content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
class Example(val `in`: String, val `cl ass`: String, val `valid`: Boolean) {
<caret>
} | plugins/kotlin/idea/tests/testData/codeInsight/generate/toString/singleTemplate/keepQuotes.kt | 920041699 |
fun usageOfComponent2(m: Main) {
m.component2()
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/constructorParameterFromDataClass/varWithJvmField/WrongUsageOfComponent2.kt | 3090118744 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("GitTestUtil")
package git4idea.test
import com.intellij.dvcs.push.PushSpec
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.HeavyPlatformTestCase
import com.intellij.util.io.write
import com.intellij.vcs.log.VcsLogObjectsFactory
import com.intellij.vcs.log.VcsLogProvider
import com.intellij.vcs.log.VcsRef
import com.intellij.vcs.log.VcsUser
import git4idea.GitRemoteBranch
import git4idea.GitStandardRemoteBranch
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.config.GitVersionSpecialty
import git4idea.log.GitLogProvider
import git4idea.push.GitPushSource
import git4idea.push.GitPushTarget
import git4idea.repo.GitRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assume.assumeTrue
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
const val USER_NAME = "John Doe"
const val USER_EMAIL = "[email protected]"
/**
*
* Creates file structure for given paths. Path element should be a relative (from project root)
* path to a file or a directory. All intermediate paths will be created if needed.
* To create a dir without creating a file pass "dir/" as a parameter.
*
* Usage example:
* `createFileStructure("a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt", "anotherdir/");`
*
* This will create files a.txt and b.txt in the project dir, create directories dir, dir/subdir and anotherdir,
* and create file c.txt in dir and d.txt in dir/subdir.
*
* Note: use forward slash to denote directories, even if it is backslash that separates dirs in your system.
*
* All files are populated with "initial content" string.
*/
fun createFileStructure(rootDir: VirtualFile, vararg paths: String) {
val parent = rootDir.toNioPath()
for (path in paths) {
val file = parent.resolve(path)
if (path.endsWith('/')) {
Files.createDirectories(file)
}
else {
file.write("initial_content_in_{$path}")
}
}
rootDir.refresh(false, true)
}
internal fun initRepo(project: Project, repoRoot: Path, makeInitialCommit: Boolean) {
Files.createDirectories(repoRoot)
cd(repoRoot.toString())
git(project, "init")
setupDefaultUsername(project)
setupLocalIgnore(repoRoot)
if (makeInitialCommit) {
touch("initial.txt")
git(project, "add initial.txt")
git(project, "commit -m initial")
}
}
private fun setupLocalIgnore(repoRoot: Path) {
repoRoot.resolve(".git/info/exclude").write(".shelf")
}
fun GitPlatformTest.cloneRepo(source: String, destination: String, bare: Boolean) {
cd(source)
if (bare) {
git("clone --bare -- . $destination")
}
else {
git("clone -- . $destination")
}
cd(destination)
setupDefaultUsername()
}
internal fun setupDefaultUsername(project: Project) {
setupUsername(project, USER_NAME, USER_EMAIL)
}
internal fun GitPlatformTest.setupDefaultUsername() {
setupDefaultUsername(project)
}
internal fun setupUsername(project: Project, name: String, email: String) {
assertFalse("Can not set empty user name ", name.isEmpty())
assertFalse("Can not set empty user email ", email.isEmpty())
git(project, "config user.name '$name'")
git(project, "config user.email '$email'")
}
private fun disableGitGc(project: Project) {
git(project, "config gc.auto 0")
}
/**
* Creates a Git repository in the given root directory;
* registers it in the Settings;
* return the [GitRepository] object for this newly created repository.
*/
fun createRepository(project: Project, root: String) = createRepository(project, Paths.get(root), true)
internal fun createRepository(project: Project, root: Path, makeInitialCommit: Boolean): GitRepository {
initRepo(project, root, makeInitialCommit)
LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root.resolve(GitUtil.DOT_GIT))!!
return registerRepo(project, root)
}
internal fun GitRepository.createSubRepository(name: String): GitRepository {
val childRoot = File(this.root.path, name)
HeavyPlatformTestCase.assertTrue(childRoot.mkdir())
val repo = createRepository(this.project, childRoot.path)
this.tac(".gitignore", name)
return repo
}
internal fun registerRepo(project: Project, root: Path): GitRepository {
val vcsManager = ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl
vcsManager.setDirectoryMapping(root.toString(), GitVcs.NAME)
Files.createDirectories(root)
val file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root)
assertFalse("There are no VCS roots. Active VCSs: ${vcsManager.allActiveVcss}", vcsManager.allVcsRoots.isEmpty())
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(file)
assertThat(repository).describedAs("Couldn't find repository for root $root").isNotNull()
cd(root)
disableGitGc(project)
return repository!!
}
fun assumeSupportedGitVersion(vcs: GitVcs) {
val version = vcs.version
assumeTrue("Unsupported Git version: $version", version.isSupported)
}
fun GitPlatformTest.readAllRefs(root: VirtualFile, objectsFactory: VcsLogObjectsFactory): Set<VcsRef> {
val refs = git("log --branches --tags --no-walk --format=%H%d --decorate=full").lines()
val result = mutableSetOf<VcsRef>()
for (ref in refs) {
result.addAll(RefParser(objectsFactory).parseCommitRefs(ref, root))
}
return result
}
fun GitPlatformTest.makeCommit(file: String): String {
append(file, "some content")
addCommit("some message")
return last()
}
fun GitPlatformTest.makeCommit(author: VcsUser, file: String): String {
setupUsername(project, author.name, author.email)
val commit = modify(file)
setupDefaultUsername(project)
return commit
}
fun findGitLogProvider(project: Project): GitLogProvider {
val providers = VcsLogProvider.LOG_PROVIDER_EP.getExtensions(project)
.filter { provider -> provider.supportedVcs == GitVcs.getKey() }
assertEquals("Incorrect number of GitLogProviders", 1, providers.size)
return providers[0] as GitLogProvider
}
internal fun makePushSpec(repository: GitRepository, from: String, to: String): PushSpec<GitPushSource, GitPushTarget> {
val source = repository.branches.findLocalBranch(from)!!
var target: GitRemoteBranch? = repository.branches.findBranchByName(to) as GitRemoteBranch?
val newBranch: Boolean
if (target == null) {
val firstSlash = to.indexOf('/')
val remote = GitUtil.findRemoteByName(repository, to.substring(0, firstSlash))!!
target = GitStandardRemoteBranch(remote, to.substring(firstSlash + 1))
newBranch = true
}
else {
newBranch = false
}
return PushSpec(GitPushSource.create(source), GitPushTarget(target, newBranch))
}
internal fun GitRepository.resolveConflicts() {
cd(this)
this.git("add -u .")
}
internal fun getPrettyFormatTagForFullCommitMessage(project: Project): String {
return if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) "%B" else "%s%n%n%-b"
}
| plugins/git4idea/tests/git4idea/test/GitTestUtil.kt | 1082462747 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
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 org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
interface ModuleTestEntity : WorkspaceEntityWithPersistentId {
val name: String
val contentRoots: List<@Child ContentRootTestEntity>
val facets: List<@Child FacetTestEntity>
override val persistentId: PersistentEntityId<WorkspaceEntityWithPersistentId>
get() = ModuleTestEntityPersistentId(name)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ModuleTestEntity, ModifiableWorkspaceEntity<ModuleTestEntity>, ObjBuilder<ModuleTestEntity> {
override var entitySource: EntitySource
override var name: String
override var contentRoots: List<ContentRootTestEntity>
override var facets: List<FacetTestEntity>
}
companion object : Type<ModuleTestEntity, Builder>() {
operator fun invoke(name: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleTestEntity {
val builder = builder()
builder.name = name
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ModuleTestEntity, modification: ModuleTestEntity.Builder.() -> Unit) = modifyEntity(
ModuleTestEntity.Builder::class.java, entity, modification)
//endregion
interface ContentRootTestEntity : WorkspaceEntity {
val module: ModuleTestEntity
val sourceRootOrder: @Child SourceRootTestOrderEntity?
val sourceRoots: List<@Child SourceRootTestEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ContentRootTestEntity, ModifiableWorkspaceEntity<ContentRootTestEntity>, ObjBuilder<ContentRootTestEntity> {
override var entitySource: EntitySource
override var module: ModuleTestEntity
override var sourceRootOrder: SourceRootTestOrderEntity?
override var sourceRoots: List<SourceRootTestEntity>
}
companion object : Type<ContentRootTestEntity, Builder>() {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ContentRootTestEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ContentRootTestEntity, modification: ContentRootTestEntity.Builder.() -> Unit) = modifyEntity(
ContentRootTestEntity.Builder::class.java, entity, modification)
//endregion
interface SourceRootTestOrderEntity : WorkspaceEntity {
val data: String
val contentRoot: ContentRootTestEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SourceRootTestOrderEntity, ModifiableWorkspaceEntity<SourceRootTestOrderEntity>, ObjBuilder<SourceRootTestOrderEntity> {
override var entitySource: EntitySource
override var data: String
override var contentRoot: ContentRootTestEntity
}
companion object : Type<SourceRootTestOrderEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootTestOrderEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SourceRootTestOrderEntity,
modification: SourceRootTestOrderEntity.Builder.() -> Unit) = modifyEntity(
SourceRootTestOrderEntity.Builder::class.java, entity, modification)
//endregion
interface SourceRootTestEntity : WorkspaceEntity {
val data: String
val contentRoot: ContentRootTestEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SourceRootTestEntity, ModifiableWorkspaceEntity<SourceRootTestEntity>, ObjBuilder<SourceRootTestEntity> {
override var entitySource: EntitySource
override var data: String
override var contentRoot: ContentRootTestEntity
}
companion object : Type<SourceRootTestEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootTestEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SourceRootTestEntity, modification: SourceRootTestEntity.Builder.() -> Unit) = modifyEntity(
SourceRootTestEntity.Builder::class.java, entity, modification)
//endregion
data class ModuleTestEntityPersistentId(val name: String) : PersistentEntityId<ModuleTestEntity> {
override val presentableName: String
get() = name
}
data class FacetTestEntityPersistentId(val name: String) : PersistentEntityId<FacetTestEntity> {
override val presentableName: String
get() = name
}
interface FacetTestEntity : WorkspaceEntityWithPersistentId {
val data: String
val moreData: String
val module: ModuleTestEntity
override val persistentId: PersistentEntityId<WorkspaceEntityWithPersistentId>
get() = FacetTestEntityPersistentId(data)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetTestEntity, ModifiableWorkspaceEntity<FacetTestEntity>, ObjBuilder<FacetTestEntity> {
override var entitySource: EntitySource
override var data: String
override var moreData: String
override var module: ModuleTestEntity
}
companion object : Type<FacetTestEntity, Builder>() {
operator fun invoke(data: String, moreData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetTestEntity {
val builder = builder()
builder.data = data
builder.moreData = moreData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetTestEntity, modification: FacetTestEntity.Builder.() -> Unit) = modifyEntity(
FacetTestEntity.Builder::class.java, entity, modification)
//endregion
| platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/JpsLike.kt | 1452510642 |
package com.quran.labs.androidquran.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.text.TextPaint
import androidx.core.content.ContextCompat
import com.quran.labs.androidquran.R
class JuzView(
context: Context,
type: Int,
private val overlayText: String?
) : Drawable() {
private var radius = 0
private var circleY = 0
private val percentage: Int
private var textOffset = 0f
private lateinit var circleRect: RectF
private val circlePaint = Paint()
private var overlayTextPaint: TextPaint? = null
private val circleBackgroundPaint = Paint()
init {
val resources = context.resources
val circleColor = ContextCompat.getColor(context, R.color.accent_color)
val circleBackground = ContextCompat.getColor(context, R.color.accent_color_dark)
circlePaint.apply {
style = Paint.Style.FILL
color = circleColor
isAntiAlias = true
}
circleBackgroundPaint.apply {
style = Paint.Style.FILL
color = circleBackground
isAntiAlias = true
}
if (!overlayText.isNullOrEmpty()) {
val textPaintColor = ContextCompat.getColor(context, R.color.header_background)
val textPaintSize = resources.getDimensionPixelSize(R.dimen.juz_overlay_text_size)
overlayTextPaint = TextPaint()
overlayTextPaint?.apply {
isAntiAlias = true
color = textPaintColor
textSize = textPaintSize.toFloat()
textAlign = Paint.Align.CENTER
}
overlayTextPaint?.let { textPaint ->
val textHeight = textPaint.descent() - textPaint.ascent()
textOffset = textHeight / 2 - textPaint.descent()
}
}
this.percentage = when (type) {
TYPE_JUZ -> 100
TYPE_THREE_QUARTERS -> 75
TYPE_HALF -> 50
TYPE_QUARTER -> 25
else -> 0
}
}
override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) {
super.setBounds(left, top, right, bottom)
radius = (right - left) / 2
val yOffset = (bottom - top - 2 * radius) / 2
circleY = radius + yOffset
circleRect = RectF(
left.toFloat(), (top + yOffset).toFloat(),
right.toFloat(), (top + yOffset + 2 * radius).toFloat()
)
}
override fun draw(canvas: Canvas) {
canvas.drawCircle(radius.toFloat(), circleY.toFloat(), radius.toFloat(), circleBackgroundPaint)
canvas.drawArc(
circleRect, -90f,
(3.6 * percentage).toFloat(), true, circlePaint
)
overlayTextPaint?.let { textPaint ->
if (overlayText != null) {
canvas.drawText(
overlayText, circleRect.centerX(),
circleRect.centerY() + textOffset, textPaint
)
}
}
}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(cf: ColorFilter?) {}
companion object {
const val TYPE_JUZ = 1
const val TYPE_QUARTER = 2
const val TYPE_HALF = 3
const val TYPE_THREE_QUARTERS = 4
}
}
| app/src/main/java/com/quran/labs/androidquran/view/JuzView.kt | 570794457 |
package pl.srw.billcalculator.form.fragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import pl.srw.billcalculator.bill.save.BillSaver
import pl.srw.billcalculator.bill.save.model.NewBillInput
import pl.srw.billcalculator.form.FormVM
import pl.srw.billcalculator.form.FormValueValidator
import pl.srw.billcalculator.form.FormValueValidator.isDatesOrderCorrect
import pl.srw.billcalculator.form.FormValueValidator.isValueFilled
import pl.srw.billcalculator.form.FormValueValidator.isValueOrderCorrect
import pl.srw.billcalculator.type.Provider
import pl.srw.billcalculator.type.Provider.PGNIG
import pl.srw.billcalculator.util.analytics.Analytics
import pl.srw.billcalculator.util.analytics.EventType
import timber.log.Timber
class FormPresenter(
private val view: FormView,
private val provider: Provider,
private val billSaver: BillSaver,
private val historyUpdater: HistoryChangeListener
) {
fun closeButtonClicked() {
Timber.i("Form: Close clicked")
view.hideForm()
}
fun calculateButtonClicked(vm: FormVM) {
Timber.i("Form: Calculate clicked")
view.cleanErrorsOnFields()
val singleReadings = provider == PGNIG || vm.isSingleReadingsProcessing()
val validInput = if (singleReadings) {
isSingleReadingsFormValid(
vm.readingFrom, vm.readingTo,
vm.dateFrom, vm.dateTo
)
} else {
isDoubleReadingsFormValid(
vm.readingDayFrom, vm.readingDayTo,
vm.readingNightFrom, vm.readingNightTo,
vm.dateFrom, vm.dateTo
)
}
if (!validInput) return
billSaver.storeBill(NewBillInput.from(vm, singleReadings))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
historyUpdater.onHistoryChanged()
with(view) {
startBillActivity(provider)
hideForm()
}
}
Analytics.event(EventType.CALCULATE, "provider", provider)
}
private fun isSingleReadingsFormValid(
readingFrom: String, readingTo: String,
dateFrom: String, dateTo: String
): Boolean {
return (isValueFilled(readingFrom, onErrorCallback(FormView.Field.READING_FROM))
&& isValueFilled(readingTo, onErrorCallback(FormView.Field.READING_TO))
&& isValueOrderCorrect(readingFrom, readingTo, onErrorCallback(FormView.Field.READING_TO))
&& isDatesOrderCorrect(dateFrom, dateTo, onDateErrorCallback()))
}
private fun isDoubleReadingsFormValid(
readingDayFrom: String, readingDayTo: String,
readingNightFrom: String, readingNightTo: String,
dateFrom: String, dateTo: String
): Boolean {
return (isValueFilled(readingDayFrom, onErrorCallback(FormView.Field.READING_DAY_FROM))
&& isValueFilled(readingDayTo, onErrorCallback(FormView.Field.READING_DAY_TO))
&& isValueFilled(readingNightFrom, onErrorCallback(FormView.Field.READING_NIGHT_FROM))
&& isValueFilled(readingNightTo, onErrorCallback(FormView.Field.READING_NIGHT_TO))
&& isValueOrderCorrect(readingDayFrom, readingDayTo, onErrorCallback(FormView.Field.READING_DAY_TO))
&& isValueOrderCorrect(readingNightFrom, readingNightTo, onErrorCallback(FormView.Field.READING_NIGHT_TO))
&& isDatesOrderCorrect(dateFrom, dateTo, onDateErrorCallback()))
}
private fun onErrorCallback(field: FormView.Field) = FormValueValidator.OnErrorCallback { view.showReadingFieldError(field, it) }
private fun onDateErrorCallback() = FormValueValidator.OnErrorCallback(view::showDateFieldError)
interface FormView {
fun showProviderSettings(provider: Provider)
fun hideForm()
fun showReadingFieldError(field: Field, errorMsgRes: Int)
fun showDateFieldError(errorMsgRes: Int)
fun cleanErrorsOnFields()
fun startBillActivity(provider: Provider)
enum class Field {
READING_FROM, READING_TO,
READING_DAY_FROM, READING_DAY_TO,
READING_NIGHT_FROM, READING_NIGHT_TO
}
}
interface HistoryChangeListener {
fun onHistoryChanged()
}
}
| app/src/main/java/pl/srw/billcalculator/form/fragment/FormPresenter.kt | 28261965 |
package pl.ches.citybikes.testing.extensions
import org.hamcrest.BaseMatcher
import org.hamcrest.Description
class ArgThat<T>(val predicate: T.() -> Boolean) : BaseMatcher<T>() {
override fun describeTo(description: Description) {
description.appendText("argThat matcher not satisfied")
}
@Suppress("UNCHECKED_CAST")
override fun matches(it: Any): Boolean {
return (it as T).predicate()
}
} | app/src/test/kotlin/pl/ches/citybikes/testing/extensions/ArgThat.kt | 4088338968 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
class UnusedDataClassCopyResultInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val callee = call.calleeExpression ?: return
if (callee.text != "copy") return
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val descriptor = call.getResolvedCall(context)?.resultingDescriptor ?: return
val receiver = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter ?: return
if ((receiver.value as? ImplicitClassReceiver)?.classDescriptor?.isData != true) return
if (call.getQualifiedExpressionForSelectorOrThis().isUsedAsExpression(context)) return
holder.registerProblem(callee, KotlinBundle.message("inspection.unused.result.of.data.class.copy"))
})
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedDataClassCopyResultInspection.kt | 2745615186 |
fun x() {
while(x.fd<caret>fd){
}
// EXPECTED_TYPE: kotlin/Boolean | plugins/kotlin/frontend-fir/testData/components/expectedExpressionType/whileConditionQualified.kt | 1496873194 |
@file:Suppress("RedundantVisibilityModifier")
package co.zsmb.materialdrawerkt.draweritems
import android.graphics.drawable.Drawable
import co.zsmb.materialdrawerkt.DrawerMarker
import co.zsmb.materialdrawerkt.draweritems.badgeable.BadgeableKt
import co.zsmb.materialdrawerkt.nonReadable
import com.mikepenz.materialdrawer.holder.BadgeStyle
import com.mikepenz.materialdrawer.holder.DimenHolder
import com.mikepenz.materialdrawer.holder.StringHolder
/**
* Adds a badge with the given [text].
*/
@Suppress("DEPRECATION")
public fun BadgeableKt.badge(text: String = "", setup: BadgeKt.() -> Unit = {}) {
val badge = BadgeKt(text)
badge.setup()
this.badgeHolder = badge.holder
this.badgeStyle = badge.style
}
@DrawerMarker
public class BadgeKt(text: String) {
//region Builder basics
internal val style = BadgeStyle()
internal var holder = StringHolder(text)
//endregion
//region BadgeStyle methods
/**
* The background of the badge as a Drawable.
*
* Non-readable property. Wraps the [BadgeStyle.withBadgeBackground] method.
*/
public var backgroundDrawable: Drawable
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withBadgeBackground(value)
}
/**
* The color of the badge, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withColor] method.
*/
public var color: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColor(value.toInt())
}
/**
* The color of the badge when it's tapped, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withColorPressed] method.
*/
public var colorPressed: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorPressed(value.toInt())
}
/**
* The color of the badge when it's tapped, as a a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withColorPressedRes] method.
*/
public var colorPressedRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorPressedRes(value)
}
/**
* The color of the badge, as a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withColor] method.
*/
public var colorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withColorRes(value)
}
/**
* The corner radius of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withCornersDp] method.
*/
public var cornersDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCornersDp(value)
}
/**
* The corner radius of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withCorners] method.
*/
public var cornersPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCorners(value)
}
/**
* The corner radius of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withCorners] method.
*/
public var cornersRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withCorners(DimenHolder.fromResource(value))
}
/**
* The background of the badge as a GradientDrawable resource.
*
* Non-readable property. Wraps the [BadgeStyle.withGradientDrawable] method.
*/
public var gradientDrawableRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withGradientDrawable(value)
}
/**
* The minimum width of the badge (more precisely, the badge's text), in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(DimenHolder.fromDp(value))
}
/**
* The minimum width of the badge (more precisely, the badge's text), in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(value)
}
/**
* The minimum width of the badge (more precisely, the badge's text), as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withMinWidth] method.
*/
public var minWidthRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withMinWidth(DimenHolder.fromResource(value))
}
/**
* The padding of all sides of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
paddingHorizontalDp = value
paddingVerticalDp = value
}
/**
* The horizontal padding of the badge, in dps.
*
* Replacement for paddingLeftRightDp.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightDp] method.
*/
public var paddingHorizontalDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightDp(value)
}
/**
* The horizontal padding of the badge, in pixels.
*
* Replacement for paddingLeftRightPx.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightPx] method.
*/
public var paddingHorizontalPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightPx(value)
}
/**
* The horizontal padding of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightRes] method.
*/
public var paddingHorizontalRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightRes(value)
}
/**
* The padding of the left and right sides of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightDp] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingHorizontalDp"),
message = "Use paddingHorizontalDp instead")
public var paddingLeftRightDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightDp(value)
}
/**
* The padding of the left and right sides of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingLeftRightPx] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingHorizontalPx"),
message = "Use paddingHorizontalPx instead")
public var paddingLeftRightPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingLeftRightPx(value)
}
/**
* The padding of all sides of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPadding(value)
}
/**
* The padding of all sides of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPadding] method.
*/
public var paddingRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
paddingHorizontalRes = value
paddingVerticalRes = value
}
/**
* The padding of the top and bottom of the badge, in dps.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomDp] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingVerticalDp"),
message = "Use paddingVerticalDp instead")
public var paddingTopBottomDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomDp(value)
}
/**
* The padding of the top and bottom of the badge, in pixels.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomPx] method.
*/
@Deprecated(level = DeprecationLevel.WARNING,
replaceWith = ReplaceWith("paddingVerticalPx"),
message = "Use paddingVerticalPx instead")
public var paddingTopBottomPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomPx(value)
}
/**
* The vertical padding of the badge, in dps.
*
* Replacement for paddingTopBottomDp.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomDp] method.
*/
public var paddingVerticalDp: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomDp(value)
}
/**
* The vertical padding of the badge, in pixels.
*
* Replacement for paddingTopBottomPx.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomPx] method.
*/
public var paddingVerticalPx: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomPx(value)
}
/**
* The vertical padding of the badge, as a dimension resource.
*
* Non-readable property. Wraps the [BadgeStyle.withPaddingTopBottomRes] method.
*/
public var paddingVerticalRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withPaddingTopBottomRes(value)
}
/**
* The text of the badge as a String.
*
* Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method.
*/
public var text: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
holder = StringHolder(value)
}
/**
* The color of the badge's text, as an argb Long.
*
* Non-readable property. Wraps the [BadgeStyle.withTextColor] method.
*/
public var textColor: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withTextColor(value.toInt())
}
/**
* The color of the badge's text, as a color resource.
*
* Non-readable property. Wraps the [BadgeStyle.withTextColorRes] method.
*/
public var textColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
style.withTextColorRes(value)
}
/**
* The text of the badge as a String resource.
*
* Non-readable property. Wraps the [com.mikepenz.materialdrawer.model.interfaces.Badgeable.withBadge] method.
*/
public var textRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
holder.textRes = value
}
//endregion
}
| library/src/main/java/co/zsmb/materialdrawerkt/draweritems/BadgeKt.kt | 1430129023 |
@file:JvmName("TextViewUtils")
package org.schabi.newpipe.ktx
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.util.Log
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.animation.addListener
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import org.schabi.newpipe.MainActivity
private const val TAG = "TextViewUtils"
/**
* Animate the text color of any view that extends [TextView] (Buttons, EditText...).
*
* @param duration the duration of the animation
* @param colorStart the text color to start with
* @param colorEnd the text color to end with
*/
fun TextView.animateTextColor(duration: Long, @ColorInt colorStart: Int, @ColorInt colorEnd: Int) {
if (MainActivity.DEBUG) {
Log.d(
TAG,
"animateTextColor() called with: " +
"view = [" + this + "], duration = [" + duration + "], " +
"colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"
)
}
val viewPropertyAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorStart, colorEnd)
viewPropertyAnimator.interpolator = FastOutSlowInInterpolator()
viewPropertyAnimator.duration = duration
viewPropertyAnimator.addUpdateListener { setTextColor(it.animatedValue as Int) }
viewPropertyAnimator.addListener(onCancel = { setTextColor(colorEnd) }, onEnd = { setTextColor(colorEnd) })
viewPropertyAnimator.start()
}
| app/src/main/java/org/schabi/newpipe/ktx/TextView.kt | 3072916643 |
// WITH_RUNTIME
// DISABLE-ERRORS
package foo.www.ddd
class Check {
class BBD {
class Bwd {
fun dad() {
class Bwd
val a = foo.www.ddd.<caret>Check.BBD.Bwd::class.java.annotatedInterfaces.size
}
}
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantQualifierName/classLiteral5.kt | 2277541998 |
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.packaging
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.WriteProperties
import org.gradle.internal.classloader.ClassLoaderFactory
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.build.ReproduciblePropertiesWriter
import com.thoughtworks.qdox.JavaProjectBuilder
import com.thoughtworks.qdox.library.SortedClassLibraryBuilder
import com.thoughtworks.qdox.model.JavaMethod
import accessors.java
import org.gradle.kotlin.dsl.*
import org.gradle.kotlin.dsl.support.serviceOf
import java.net.URLClassLoader
open class ApiMetadataExtension(project: Project) {
val sources = project.files()
val includes = project.objects.listProperty<String>()
val excludes = project.objects.listProperty<String>()
val classpath = project.files()
init {
includes.set(listOf())
excludes.set(listOf())
}
}
/**
* Generates Gradle API metadata resources.
*
* Include and exclude patterns for the Gradle API.
* Parameter names for the Gradle API.
*/
open class ApiMetadataPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val extension =
extensions.create("apiMetadata", ApiMetadataExtension::class, project)
val apiDeclarationTask =
tasks.register("apiDeclarationResource", WriteProperties::class) {
property("includes", extension.includes.get().joinToString(":"))
property("excludes", extension.excludes.get().joinToString(":"))
outputFile = generatedPropertiesFileFor(apiDeclarationFilename).get().asFile
}
val apiParameterNamesTask =
tasks.register("apiParameterNamesResource", ParameterNamesResourceTask::class) {
sources.from(extension.sources.asFileTree.matching {
include(extension.includes.get())
exclude(extension.excludes.get())
})
classpath.from(extension.classpath)
destinationFile.set(generatedPropertiesFileFor(apiParametersFilename))
}
mapOf(
apiDeclarationTask to generatedDirFor(apiDeclarationFilename),
apiParameterNamesTask to generatedDirFor(apiParametersFilename)
).forEach { task, dir ->
java.sourceSets["main"].output.dir(mapOf("builtBy" to task), dir)
}
}
private
fun Project.generatedDirFor(name: String) =
layout.buildDirectory.dir("generated-resources/$name")
private
fun Project.generatedPropertiesFileFor(name: String) =
layout.buildDirectory.file("generated-resources/$name/$name.properties")
}
private
const val apiDeclarationFilename = "gradle-api-declaration"
private
const val apiParametersFilename = "gradle-api-parameter-names"
@CacheableTask
open class ParameterNamesResourceTask : DefaultTask() {
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
val sources = project.files()
@InputFiles
@Classpath
val classpath = project.files()
@OutputFile
@PathSensitive(PathSensitivity.NONE)
val destinationFile = project.objects.fileProperty()
@TaskAction
fun generate() {
isolatedClassLoaderFor(classpath).use { loader ->
val qdoxBuilder = JavaProjectBuilder(sortedClassLibraryBuilderWithClassLoaderFor(loader))
val qdoxSources = sources.asSequence().mapNotNull { qdoxBuilder.addSource(it) }
val properties = qdoxSources
.flatMap { it.classes.asSequence().filter { it.isPublic } }
.flatMap { it.methods.asSequence().filter { it.isPublic && it.parameterTypes.isNotEmpty() } }
.map { method ->
fullyQualifiedSignatureOf(method) to commaSeparatedParameterNamesOf(method)
}.toMap(linkedMapOf())
write(properties)
}
}
private
fun write(properties: LinkedHashMap<String, String>) {
destinationFile.get().asFile.let { file ->
file.parentFile.mkdirs()
ReproduciblePropertiesWriter.store(properties, file)
}
}
private
fun fullyQualifiedSignatureOf(method: JavaMethod): String =
"${method.declaringClass.binaryName}.${method.name}(${signatureOf(method)})"
private
fun signatureOf(method: JavaMethod): String =
method.parameters.joinToString(separator = ",") { p ->
if (p.isVarArgs || p.javaClass.isArray) "${p.type.binaryName}[]"
else p.type.binaryName
}
private
fun commaSeparatedParameterNamesOf(method: JavaMethod) =
method.parameters.joinToString(separator = ",") { it.name }
private
fun sortedClassLibraryBuilderWithClassLoaderFor(loader: ClassLoader): SortedClassLibraryBuilder =
SortedClassLibraryBuilder().apply {
appendClassLoader(loader)
}
private
fun isolatedClassLoaderFor(classpath: FileCollection) =
classLoaderFactory.createIsolatedClassLoader("parameter names", DefaultClassPath.of(classpath.files)) as URLClassLoader
private
val classLoaderFactory
get() = project.serviceOf<ClassLoaderFactory>()
}
| buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ApiMetadataPlugin.kt | 3408115948 |
package pl.srw.billcalculator.bill.calculation
import org.threeten.bp.LocalDate
import pl.srw.billcalculator.pojo.IPgePrices
class PgeG11CalculatedBill(
readingFrom: Int,
readingTo: Int,
dateFrom: LocalDate,
dateTo: LocalDate,
prices: IPgePrices
) : CalculatedEnergyBill(
dateFrom,
dateTo,
prices.oplataAbonamentowa,
prices.oplataPrzejsciowa,
prices.oplataStalaZaPrzesyl,
prices
) {
override val totalConsumption = readingTo - readingFrom
val consumptionFromJuly16 = countConsumptionPartFromJuly16(dateFrom, dateTo, totalConsumption)
val zaEnergieCzynnaNetCharge = countNetAndAddToSum(prices.zaEnergieCzynna, totalConsumption)
val skladnikJakosciowyNetCharge = countNetAndAddToSum(prices.skladnikJakosciowy, totalConsumption)
val oplataSieciowaNetCharge = countNetAndAddToSum(prices.oplataSieciowa, totalConsumption)
val oplataOzeNetCharge = countNetAndAddToSum(prices.oplataOze, (consumptionFromJuly16 * 0.001).toString())
val zaEnergieCzynnaVatCharge = countVatAndAddToSum(zaEnergieCzynnaNetCharge)
val skladnikJakosciowyVatCharge = countVatAndAddToSum(skladnikJakosciowyNetCharge)
val oplataSieciowaVatCharge = countVatAndAddToSum(oplataSieciowaNetCharge)
val oplataOzeVatCharge = countVatAndAddToSum(oplataOzeNetCharge)
}
| app/src/main/java/pl/srw/billcalculator/bill/calculation/PgeG11CalculatedBill.kt | 2910816656 |
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.entitystore.iterate.binop
import jetbrains.exodus.entitystore.EntityId
import jetbrains.exodus.entitystore.EntityIterator
import java.util.*
internal fun toEntityIdIterator(it: EntityIterator): Iterator<EntityId?> {
return object : Iterator<EntityId?> {
override fun hasNext() = it.hasNext()
override fun next() = it.nextId()
}
}
internal fun toSortedEntityIdIterator(it: EntityIterator): Iterator<EntityId?> {
var array = arrayOfNulls<EntityId>(8)
var size = 0
while (it.hasNext()) {
if (size == array.size) {
array = array.copyOf(size * 2)
}
array[size++] = it.nextId()
}
if (size > 1) {
Arrays.sort(array, 0, size) { o1, o2 ->
when {
o1 == null -> 1
o2 == null -> -1
else -> o1.compareTo(o2)
}
}
}
return object : Iterator<EntityId?> {
var i = 0
override fun hasNext() = i < size
override fun next() = array[i++]
}
} | entity-store/src/main/kotlin/jetbrains/exodus/entitystore/iterate/binop/SortedIterator.kt | 3565208364 |
// 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.jps.build
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.LightVirtualFile
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.io.Decompressor
import com.intellij.util.io.ZipUtil
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.api.CanceledStatus
import org.jetbrains.jps.builders.BuildResult
import org.jetbrains.jps.builders.CompileScopeTestBuilder
import org.jetbrains.jps.builders.TestProjectBuilderLogger
import org.jetbrains.jps.builders.impl.BuildDataPathsImpl
import org.jetbrains.jps.builders.logging.BuildLoggingManager
import org.jetbrains.jps.cmdline.ProjectDescriptor
import org.jetbrains.jps.devkit.model.JpsPluginModuleType
import org.jetbrains.jps.incremental.BuilderRegistry
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.IncProjectBuilder
import org.jetbrains.jps.incremental.ModuleLevelBuilder
import org.jetbrains.jps.incremental.messages.BuildMessage
import org.jetbrains.jps.incremental.messages.CompilerMessage
import org.jetbrains.jps.model.JpsModuleRootModificationUtil
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaDependencyScope
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import org.jetbrains.kotlin.cli.common.Usage
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.JvmCodegenUtil
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.KotlinCompilerVersion.TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.jps.build.KotlinJpsBuildTestBase.LibraryDependency.*
import org.jetbrains.kotlin.jps.incremental.CacheAttributesDiff
import org.jetbrains.kotlin.jps.model.kotlinCommonCompilerArguments
import org.jetbrains.kotlin.jps.model.kotlinCompilerArguments
import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.junit.Assert
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.net.URLClassLoader
import java.util.*
import java.util.zip.ZipOutputStream
open class KotlinJpsBuildTest : KotlinJpsBuildTestBase() {
companion object {
private const val ADDITIONAL_MODULE_NAME = "module2"
private val EXCLUDE_FILES = arrayOf("Excluded.class", "YetAnotherExcluded.class")
private val NOTHING = arrayOf<String>()
private const val KOTLIN_JS_LIBRARY = "jslib-example"
private const val KOTLIN_JS_LIBRARY_JAR = "$KOTLIN_JS_LIBRARY.jar"
private val PATH_TO_KOTLIN_JS_LIBRARY =
TEST_DATA_PATH + "general/KotlinJavaScriptProjectWithDirectoryAsLibrary/" + KOTLIN_JS_LIBRARY
private fun getMethodsOfClass(classFile: File): Set<String> {
val result = TreeSet<String>()
ClassReader(FileUtil.loadFileBytes(classFile)).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<String>?
): MethodVisitor? {
result.add(name)
return null
}
}, 0)
return result
}
@JvmStatic
protected fun klass(moduleName: String, classFqName: String): String {
val outputDirPrefix = "out/production/$moduleName/"
return outputDirPrefix + classFqName.replace('.', '/') + ".class"
}
@JvmStatic
protected fun module(moduleName: String): String {
return "out/production/$moduleName/${JvmCodegenUtil.getMappingFileName(moduleName)}"
}
}
protected fun doTest() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
}
protected fun doTestWithRuntime() {
initProject(JVM_FULL_RUNTIME)
buildAllModules().assertSuccessful()
}
protected fun doTestWithKotlinJavaScriptLibrary() {
initProject(JS_STDLIB)
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
buildAllModules().assertSuccessful()
}
fun testKotlinProject() {
doTest()
checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "Test1Kt"))
}
fun testSourcePackagePrefix() {
doTest()
}
fun testSourcePackageLongPrefix() {
initProject(JVM_MOCK_RUNTIME)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about invalid package prefix in module 2 is expected: $warnings", 1, warnings.size)
assertEquals("Invalid package prefix name is ignored: invalid-prefix.test", warnings.first().messageText)
}
fun testSourcePackagePrefixWithInnerClasses() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProject() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, pathsToDelete = k2jsOutput(PROJECT_NAME))
}
private fun k2jsOutput(vararg moduleNames: String): Array<String> {
val moduleNamesSet = moduleNames.toSet()
val list = mutableListOf<String>()
myProject.modules.forEach { module ->
if (module.name in moduleNamesSet) {
val outputDir = module.productionBuildTarget.outputDir!!
list.add(toSystemIndependentName(File("$outputDir/${module.name}.js").relativeTo(workDir).path))
list.add(toSystemIndependentName(File("$outputDir/${module.name}.meta.js").relativeTo(workDir).path))
val kjsmFiles = outputDir.walk().filter { it.isFile && it.extension.equals("kjsm", ignoreCase = true) }
list.addAll(kjsmFiles.map { toSystemIndependentName(it.relativeTo(workDir).path) })
}
}
return list.toTypedArray()
}
fun testKotlinJavaScriptProjectNewSourceRootTypes() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
}
fun testKotlinJavaScriptProjectWithCustomOutputPaths() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList(File(workDir, "target"))
}
fun testKotlinJavaScriptProjectWithSourceMap() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText()
val expectedPath = "prefix-dir/src/pkg/test1.kt"
assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\""))
val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map")
assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists())
}
fun testKotlinJavaScriptProjectWithSourceMapRelativePaths() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText()
val expectedPath = "../../../src/pkg/test1.kt"
assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\""))
val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map")
assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists())
}
fun testKotlinJavaScriptProjectWithTwoModules() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
checkWhen(touch("module2/src/module2.kt"), null, k2jsOutput(ADDITIONAL_MODULE_NAME))
checkWhen(arrayOf(touch("src/test1.kt"), touch("module2/src/module2.kt")), null, k2jsOutput(PROJECT_NAME, ADDITIONAL_MODULE_NAME))
}
@WorkingDir("KotlinJavaScriptProjectWithTwoModules")
fun testKotlinJavaScriptProjectWithTwoModulesAndWithLibrary() {
initProject()
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
addKotlinJavaScriptStdlibDependency()
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithDirectoryAsStdlib() {
initProject()
val jslibJar = KotlinArtifacts.instance.kotlinStdlibJs
val jslibDir = File(workDir, "KotlinJavaScript")
try {
Decompressor.Zip(jslibJar).extract(jslibDir.toPath())
} catch (ex: IOException) {
throw IllegalStateException(ex.message)
}
addDependency("KotlinJavaScript", jslibDir)
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithDirectoryAsLibrary() {
initProject(JS_STDLIB)
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY))
buildAllModules().assertSuccessful()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibrary() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryCustomOutputDir() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryNoCopy() {
doTestWithKotlinJavaScriptLibrary()
checkOutputFilesList()
checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME))
}
fun testKotlinJavaScriptProjectWithLibraryAndErrors() {
initProject(JS_STDLIB)
createKotlinJavaScriptLibraryArchive()
addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR))
buildAllModules().assertFailed()
checkOutputFilesList()
}
fun testKotlinJavaScriptProjectWithEmptyDependencies() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptInternalFromSpecialRelatedModule() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTests() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTestsAndSeparateTestAndSrcModuleDependencies() {
initProject(JS_STDLIB)
buildAllModules().assertSuccessful()
}
fun testKotlinJavaScriptProjectWithTestsAndTestAndSrcModuleDependency() {
initProject(JS_STDLIB)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size)
}
fun testKotlinJavaScriptProjectWithTwoSrcModuleDependency() {
initProject(JS_STDLIB)
val buildResult = buildAllModules()
buildResult.assertSuccessful()
val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING)
assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size)
}
fun testExcludeFolderInSourceRoot() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
checkWhen(
touch("src/foo.kt"), null,
arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject"))
)
}
fun testExcludeModuleFolderInSourceRootOfAnotherModule() {
doTest()
for (module in myProject.modules) {
assertFilesExistInOutput(module, "Foo.class")
}
checkWhen(
touch("src/foo.kt"), null,
arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject"))
)
checkWhen(
touch("src/module2/src/foo.kt"), null,
arrayOf(klass("module2", "Foo"), module("module2"))
)
}
fun testExcludeFileUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
}
checkWhen(touch("src/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/dir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testExcludeFolderNonRecursivelyUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
checkWhen(touch("src/dir/subdir/bar.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Bar")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
checkWhen(touch("src/dir/subdir/bar.kt"), null, allClasses)
}
checkWhen(touch("src/dir/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/dir/subdir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testExcludeFolderRecursivelyUsingCompilerSettings() {
doTest()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "Foo.class", "Bar.class")
assertFilesNotExistInOutput(module, *EXCLUDE_FILES)
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo")))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/foo.kt"), null, allClasses)
}
checkWhen(touch("src/exclude/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/YetAnotherExcluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/subdir/Excluded.kt"), null, NOTHING)
checkWhen(touch("src/exclude/subdir/YetAnotherExcluded.kt"), null, NOTHING)
}
fun testKotlinProjectTwoFilesInOnePackage() {
doTest()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "_DefaultPackage"))
checkWhen(touch("src/test2.kt"), null, packageClasses("kotlinProject", "src/test2.kt", "_DefaultPackage"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/test1.kt"), null, allClasses)
checkWhen(touch("src/test2.kt"), null, allClasses)
}
checkWhen(
arrayOf(del("src/test1.kt"), del("src/test2.kt")), NOTHING,
arrayOf(
packagePartClass("kotlinProject", "src/test1.kt", "_DefaultPackage"),
packagePartClass("kotlinProject", "src/test2.kt", "_DefaultPackage"),
module("kotlinProject")
)
)
assertFilesNotExistInOutput(myProject.modules[0], "_DefaultPackage.class")
}
fun testDefaultLanguageVersionCustomApiVersion() {
initProject(JVM_FULL_RUNTIME)
buildAllModules().assertFailed()
assertEquals(1, myProject.modules.size)
val module = myProject.modules.first()
val args = module.kotlinCompilerArguments
args.apiVersion = "1.4"
myProject.kotlinCommonCompilerArguments = args
buildAllModules().assertSuccessful()
}
fun testKotlinJavaProject() {
doTestWithRuntime()
}
fun testJKJProject() {
doTestWithRuntime()
}
fun testKJKProject() {
doTestWithRuntime()
}
fun testKJCircularProject() {
doTestWithRuntime()
}
fun testJKJInheritanceProject() {
doTestWithRuntime()
}
fun testKJKInheritanceProject() {
doTestWithRuntime()
}
fun testCircularDependenciesNoKotlinFiles() {
doTest()
}
fun testCircularDependenciesDifferentPackages() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
// Check that outputs are located properly
assertFilesExistInOutput(findModule("module2"), "kt1/Kt1Kt.class")
assertFilesExistInOutput(findModule("kotlinProject"), "kt2/Kt2Kt.class")
result.assertSuccessful()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/kt2.kt"), null, packageClasses("kotlinProject", "src/kt2.kt", "kt2.Kt2Kt"))
checkWhen(touch("module2/src/kt1.kt"), null, packageClasses("module2", "module2/src/kt1.kt", "kt1.Kt1Kt"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("src/kt2.kt"), null, allClasses)
checkWhen(touch("module2/src/kt1.kt"), null, allClasses)
}
}
fun testCircularDependenciesSamePackage() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
// Check that outputs are located properly
val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class")
val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "<clinit>", "a", "getA")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "<clinit>", "b", "getB", "setB")
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage"))
checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage"))
} else {
val allClasses = myProject.outputPaths()
checkWhen(touch("module1/src/a.kt"), null, allClasses)
checkWhen(touch("module2/src/b.kt"), null, allClasses)
}
}
fun testCircularDependenciesSamePackageWithTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
// Check that outputs are located properly
val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class")
val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "<clinit>", "a", "funA", "getA")
UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "<clinit>", "b", "funB", "getB", "setB")
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage"))
checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage"))
} else {
val allProductionClasses = myProject.outputPaths(tests = false)
checkWhen(touch("module1/src/a.kt"), null, allProductionClasses)
checkWhen(touch("module2/src/b.kt"), null, allProductionClasses)
}
}
fun testInternalFromAnotherModule() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testInternalFromSpecialRelatedModule() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val classpath = listOf("out/production/module1", "out/test/module2").map { File(workDir, it).toURI().toURL() }.toTypedArray()
val clazz = URLClassLoader(classpath).loadClass("test2.BarKt")
clazz.getMethod("box").invoke(null)
}
fun testCircularDependenciesInternalFromAnotherModule() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testCircularDependenciesWrongInternalFromTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testCircularDependencyWithReferenceToOldVersionLib() {
initProject(JVM_MOCK_RUNTIME)
val sources = listOf(File(workDir, "oldModuleLib/src"))
val libraryJar = KotlinCompilerStandalone(sources).compile()
addDependency(
JpsJavaDependencyScope.COMPILE,
listOf(findModule("module1"), findModule("module2")),
false,
"module-lib",
libraryJar,
)
val result = buildAllModules()
result.assertSuccessful()
}
fun testDependencyToOldKotlinLib() {
initProject()
val sources = listOf(File(workDir, "oldModuleLib/src"))
val libraryJar = KotlinCompilerStandalone(sources).compile()
addDependency(JpsJavaDependencyScope.COMPILE, listOf(findModule("module")), false, "module-lib", libraryJar)
addKotlinStdlibDependency()
val result = buildAllModules()
result.assertSuccessful()
}
fun testDevKitProject() {
initProject(JVM_MOCK_RUNTIME)
val module = myProject.modules.single()
assertEquals(module.moduleType, JpsPluginModuleType.INSTANCE)
buildAllModules().assertSuccessful()
assertFilesExistInOutput(module, "TestKt.class")
}
fun testAccessToInternalInProductionFromTests() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertSuccessful()
}
private fun createKotlinJavaScriptLibraryArchive() {
val jarFile = File(workDir, KOTLIN_JS_LIBRARY_JAR)
try {
val zip = ZipOutputStream(FileOutputStream(jarFile))
ZipUtil.addDirToZipRecursively(zip, jarFile, File(PATH_TO_KOTLIN_JS_LIBRARY), "", null, null)
zip.close()
} catch (ex: FileNotFoundException) {
throw IllegalStateException(ex.message)
} catch (ex: IOException) {
throw IllegalStateException(ex.message)
}
}
protected fun checkOutputFilesList(outputDir: File = productionOutputDir) {
if (!expectedOutputFile.exists()) {
expectedOutputFile.writeText("")
throw IllegalStateException("$expectedOutputFile did not exist. Created empty file.")
}
val sb = StringBuilder()
val p = Printer(sb, " ")
outputDir.printFilesRecursively(p)
UsefulTestCase.assertSameLinesWithFile(expectedOutputFile.canonicalPath, sb.toString(), true)
}
private fun File.printFilesRecursively(p: Printer) {
val files = listFiles() ?: return
for (file in files.sortedBy { it.name }) {
when {
file.isFile -> {
p.println(file.name)
}
file.isDirectory -> {
p.println(file.name + "/")
p.pushIndent()
file.printFilesRecursively(p)
p.popIndent()
}
}
}
}
private val productionOutputDir
get() = File(workDir, "out/production")
private fun getOutputDir(moduleName: String): File = File(productionOutputDir, moduleName)
fun testReexportedDependency() {
initProject()
addKotlinStdlibDependency(myProject.modules.filter { module -> module.name == "module2" }, true)
buildAllModules().assertSuccessful()
}
fun testCheckIsCancelledIsCalledOftenEnough() {
val classCount = 30
val methodCount = 30
fun generateFiles() {
val srcDir = File(workDir, "src")
srcDir.mkdirs()
for (i in 0..classCount) {
val code = buildString {
appendLine("package foo")
appendLine("class Foo$i {")
for (j in 0..methodCount) {
appendLine(" fun get${j * j}(): Int = square($j)")
}
appendLine("}")
}
File(srcDir, "Foo$i.kt").writeText(code)
}
}
generateFiles()
initProject(JVM_MOCK_RUNTIME)
var checkCancelledCalledCount = 0
val countingCancelledStatus = CanceledStatus {
checkCancelledCalledCount++
false
}
val logger = TestProjectBuilderLogger()
val buildResult = BuildResult()
buildCustom(countingCancelledStatus, logger, buildResult)
buildResult.assertSuccessful()
assert(checkCancelledCalledCount > classCount) {
"isCancelled should be called at least once per class. Expected $classCount, but got $checkCancelledCalledCount"
}
}
fun testCancelKotlinCompilation() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val module = myProject.modules[0]
assertFilesExistInOutput(module, "foo/Bar.class")
val buildResult = BuildResult()
val canceledStatus = object : CanceledStatus {
var checkFromIndex = 0
override fun isCanceled(): Boolean {
val messages = buildResult.getMessages(BuildMessage.Kind.INFO)
for (i in checkFromIndex until messages.size) {
if (messages[i].messageText.matches("kotlinc-jvm .+ \\(JRE .+\\)".toRegex())) {
return true
}
}
checkFromIndex = messages.size
return false
}
}
touch("src/Bar.kt").apply()
buildCustom(canceledStatus, TestProjectBuilderLogger(), buildResult)
assertCanceled(buildResult)
}
fun testFileDoesNotExistWarning() {
fun absoluteFiles(vararg paths: String): Array<File> =
paths.map { File(it).absoluteFile }.toTypedArray()
initProject(JVM_MOCK_RUNTIME)
val filesToBeReported = absoluteFiles("badroot.jar", "some/test.class")
val otherFiles = absoluteFiles("test/other/file.xml", "some/other/baddir")
addDependency(
JpsJavaDependencyScope.COMPILE,
listOf(findModule("module")),
false,
"LibraryWithBadRoots",
*(filesToBeReported + otherFiles),
)
val result = buildAllModules()
result.assertSuccessful()
val actualWarnings = result.getMessages(BuildMessage.Kind.WARNING).map { it.messageText }
val expectedWarnings = filesToBeReported.map { "Classpath entry points to a non-existent location: $it" }
val expectedText = expectedWarnings.sorted().joinToString("\n")
val actualText = actualWarnings.sorted().joinToString("\n")
Assert.assertEquals(expectedText, actualText)
}
fun testHelp() {
initProject()
val result = buildAllModules()
result.assertSuccessful()
val warning = result.getMessages(BuildMessage.Kind.WARNING).single()
val expectedText = StringUtil.convertLineSeparators(Usage.render(K2JVMCompiler(), K2JVMCompilerArguments()))
Assert.assertEquals(expectedText, warning.messageText)
}
fun testWrongArgument() {
initProject()
val result = buildAllModules()
result.assertFailed()
val errors = result.getMessages(BuildMessage.Kind.ERROR).joinToString("\n\n") { it.messageText }
Assert.assertEquals("Invalid argument: -abcdefghij-invalid-argument", errors)
}
fun testCodeInKotlinPackage() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
val errors = result.getMessages(BuildMessage.Kind.ERROR)
Assert.assertEquals("Only the Kotlin standard library is allowed to use the 'kotlin' package", errors.single().messageText)
}
fun testDoNotCreateUselessKotlinIncrementalCaches() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot
assertFalse(File(storageRoot, "targets/java-test/kotlinProject/kotlin").exists())
assertFalse(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists())
}
fun testDoNotCreateUselessKotlinIncrementalCachesForDependentTargets() {
initProject(JVM_MOCK_RUNTIME)
buildAllModules().assertSuccessful()
if (IncrementalCompilation.isEnabledForJvm()) {
checkWhen(touch("src/utils.kt"), null, packageClasses("kotlinProject", "src/utils.kt", "_DefaultPackage"))
} else {
val allClasses = findModule("kotlinProject").outputFilesPaths()
checkWhen(touch("src/utils.kt"), null, allClasses.toTypedArray())
}
val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot
assertFalse(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists())
assertFalse(File(storageRoot, "targets/java-production/module2/kotlin").exists())
}
fun testKotlinProjectWithEmptyProductionOutputDir() {
initProject(JVM_MOCK_RUNTIME)
val result = buildAllModules()
result.assertFailed()
result.checkErrors()
}
fun testKotlinProjectWithEmptyTestOutputDir() {
doTest()
}
fun testKotlinProjectWithEmptyProductionOutputDirWithoutSrcDir() {
doTest()
}
fun testKotlinProjectWithEmptyOutputDirInSomeModules() {
doTest()
}
fun testEAPToReleaseIC() {
fun setPreRelease(value: Boolean) {
System.setProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY, value.toString())
}
try {
withIC {
initProject(JVM_MOCK_RUNTIME)
setPreRelease(true)
buildAllModules().assertSuccessful()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt")
touch("src/Foo.kt").apply()
buildAllModules()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Foo.kt")
setPreRelease(false)
touch("src/Foo.kt").apply()
buildAllModules().assertSuccessful()
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt")
}
} finally {
System.clearProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY)
}
}
fun testGetDependentTargets() {
fun addModuleWithSourceAndTestRoot(name: String): JpsModule {
return addModule(name, "src/").apply {
contentRootsList.addUrl(JpsPathUtil.pathToUrl("test/"))
addSourceRoot(JpsPathUtil.pathToUrl("test/"), JavaSourceRootType.TEST_SOURCE)
}
}
// c -> b -exported-> a
// c2 -> b2 ------------^
val a = addModuleWithSourceAndTestRoot("a")
val b = addModuleWithSourceAndTestRoot("b")
val c = addModuleWithSourceAndTestRoot("c")
val b2 = addModuleWithSourceAndTestRoot("b2")
val c2 = addModuleWithSourceAndTestRoot("c2")
JpsModuleRootModificationUtil.addDependency(b, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ true)
JpsModuleRootModificationUtil.addDependency(c, b, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
JpsModuleRootModificationUtil.addDependency(b2, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
JpsModuleRootModificationUtil.addDependency(c2, b2, JpsJavaDependencyScope.COMPILE, /*exported =*/ false)
val actual = StringBuilder()
buildCustom(CanceledStatus.NULL, TestProjectBuilderLogger(), BuildResult()) {
project.setTestingContext(TestingContext(LookupTracker.DO_NOTHING, object : TestingBuildLogger {
override fun chunkBuildStarted(context: CompileContext, chunk: ModuleChunk) {
actual.append("Targets dependent on ${chunk.targets.joinToString()}:\n")
val dependentRecursively = mutableSetOf<KotlinChunk>()
context.kotlin.getChunk(chunk)!!.collectDependentChunksRecursivelyExportedOnly(dependentRecursively)
dependentRecursively.asSequence().map { it.targets.joinToString() }.sorted().joinTo(actual, "\n")
actual.append("\n---------\n")
}
override fun afterChunkBuildStarted(context: CompileContext, chunk: ModuleChunk) {}
override fun invalidOrUnusedCache(
chunk: KotlinChunk?,
target: KotlinModuleBuildTarget<*>?,
attributesDiff: CacheAttributesDiff<*>
) {
}
override fun addCustomMessage(message: String) {}
override fun buildFinished(exitCode: ModuleLevelBuilder.ExitCode) {}
override fun markedAsDirtyBeforeRound(files: Iterable<File>) {}
override fun markedAsDirtyAfterRound(files: Iterable<File>) {}
}))
}
val expectedFile = File(getCurrentTestDataRoot(), "expected.txt")
KotlinTestUtils.assertEqualsToFile(expectedFile, actual.toString())
}
fun testCustomDestination() {
loadProject(workDir.absolutePath + File.separator + PROJECT_NAME + ".ipr")
addKotlinStdlibDependency()
buildAllModules().apply {
assertSuccessful()
val aClass = File(workDir, "customOut/A.class")
assert(aClass.exists()) { "$aClass does not exist!" }
val warnings = getMessages(BuildMessage.Kind.WARNING)
assert(warnings.isEmpty()) { "Unexpected warnings: \n${warnings.joinToString("\n")}" }
}
}
private fun BuildResult.checkErrors() {
val actualErrors = getMessages(BuildMessage.Kind.ERROR)
.map { it as CompilerMessage }
.map { "${it.messageText} at line ${it.line}, column ${it.column}" }.sorted().joinToString("\n")
val expectedFile = File(getCurrentTestDataRoot(), "errors.txt")
KotlinTestUtils.assertEqualsToFile(expectedFile, actualErrors)
}
private fun getCurrentTestDataRoot() = File(TEST_DATA_PATH + "general/" + getTestName(false))
private fun buildCustom(
canceledStatus: CanceledStatus,
logger: TestProjectBuilderLogger,
buildResult: BuildResult,
setupProject: ProjectDescriptor.() -> Unit = {}
) {
val scopeBuilder = CompileScopeTestBuilder.make().allModules()
val descriptor = this.createProjectDescriptor(BuildLoggingManager(logger))
descriptor.setupProject()
try {
val builder = IncProjectBuilder(descriptor, BuilderRegistry.getInstance(), this.myBuildParams, canceledStatus, true)
builder.addMessageHandler(buildResult)
builder.build(scopeBuilder.build(), false)
} finally {
descriptor.dataManager.flush(false)
descriptor.release()
}
}
private fun assertCanceled(buildResult: BuildResult) {
val list = buildResult.getMessages(BuildMessage.Kind.INFO)
assertTrue("The build has been canceled" == list.last().messageText)
}
private fun findModule(name: String): JpsModule {
for (module in myProject.modules) {
if (module.name == name) {
return module
}
}
throw IllegalStateException("Couldn't find module $name")
}
protected fun checkWhen(action: Action, pathsToCompile: Array<String>?, pathsToDelete: Array<String>?) {
checkWhen(arrayOf(action), pathsToCompile, pathsToDelete)
}
protected fun checkWhen(actions: Array<Action>, pathsToCompile: Array<String>?, pathsToDelete: Array<String>?) {
for (action in actions) {
action.apply()
}
buildAllModules().assertSuccessful()
if (pathsToCompile != null) {
assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, *pathsToCompile)
}
if (pathsToDelete != null) {
assertDeleted(*pathsToDelete)
}
}
protected fun packageClasses(moduleName: String, fileName: String, packageClassFqName: String): Array<String> {
return arrayOf(module(moduleName), packagePartClass(moduleName, fileName, packageClassFqName))
}
protected fun packagePartClass(moduleName: String, fileName: String, packageClassFqName: String): String {
val path = FileUtilRt.toSystemIndependentName(File(workDir, fileName).absolutePath)
val fakeVirtualFile = object : LightVirtualFile(path.substringAfterLast('/')) {
override fun getPath(): String {
// strip extra "/" from the beginning
return path.substring(1)
}
}
val packagePartFqName = PackagePartClassUtils.getDefaultPartFqName(FqName(packageClassFqName), fakeVirtualFile)
return klass(moduleName, AsmUtil.internalNameByFqNameWithoutInnerClasses(packagePartFqName))
}
private fun JpsProject.outputPaths(production: Boolean = true, tests: Boolean = true) =
modules.flatMap { it.outputFilesPaths(production = production, tests = tests) }.toTypedArray()
private fun JpsModule.outputFilesPaths(production: Boolean = true, tests: Boolean = true): List<String> {
val outputFiles = arrayListOf<File>()
if (production) {
prodOut.walk().filterTo(outputFiles) { it.isFile }
}
if (tests) {
testsOut.walk().filterTo(outputFiles) { it.isFile }
}
return outputFiles.map { FileUtilRt.toSystemIndependentName(it.relativeTo(workDir).path) }
}
private val JpsModule.prodOut: File
get() = outDir(forTests = false)
private val JpsModule.testsOut: File
get() = outDir(forTests = true)
private fun JpsModule.outDir(forTests: Boolean) =
JpsJavaExtensionService.getInstance().getOutputDirectory(this, forTests)!!
protected enum class Operation {
CHANGE,
DELETE
}
protected fun touch(path: String): Action = Action(Operation.CHANGE, path)
protected fun del(path: String): Action = Action(Operation.DELETE, path)
// TODO inline after KT-3974 will be fixed
protected fun touch(file: File): Unit = change(file.absolutePath)
protected inner class Action constructor(private val operation: Operation, private val path: String) {
fun apply() {
val file = File(workDir, path)
when (operation) {
Operation.CHANGE ->
touch(file)
Operation.DELETE ->
assertTrue("Can not delete file \"" + file.absolutePath + "\"", file.delete())
}
}
}
}
private inline fun <R> withIC(enabled: Boolean = true, fn: () -> R): R {
val isEnabledBackup = IncrementalCompilation.isEnabledForJvm()
IncrementalCompilation.setIsEnabledForJvm(enabled)
try {
return fn()
} finally {
IncrementalCompilation.setIsEnabledForJvm(isEnabledBackup)
}
} | plugins/kotlin/jps/jps-plugin/tests/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt | 2547366927 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.stash.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAwareAction
import git4idea.stash.GitStashTracker
class GitRefreshStashesAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null || !isStashToolWindowEnabled(project)) {
e.presentation.isEnabledAndVisible = false
}
}
override fun actionPerformed(e: AnActionEvent) {
e.project!!.service<GitStashTracker>().scheduleRefresh()
}
} | plugins/git4idea/src/git4idea/stash/ui/GitRefreshStashesAction.kt | 3557858816 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.test
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinJdkAndLibraryProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
abstract class AbstractJvmBasicCompletionTest : KotlinFixtureCompletionBaseTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = object : KotlinJdkAndLibraryProjectDescriptor(
libraryFiles = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE.libraryFiles,
librarySourceFiles = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE.librarySourceFiles,
) {
override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk16()
}
override fun getPlatform() = JvmPlatforms.jvm6
override fun defaultCompletionType() = CompletionType.BASIC
override fun configureFixture(testPath: String) {
// those classes are missing in mockJDK-1.7
with(myFixture) {
addCharacterCodingException()
addAppendable()
addHashSet()
addLinkedHashSet()
}
super.configureFixture(testPath)
}
} | plugins/kotlin/completion/tests/test/org/jetbrains/kotlin/idea/completion/test/AbstractJvmBasicCompletionTest.kt | 2401433929 |
package com.github.kerubistan.kerub
import com.github.kerubistan.kerub.utils.getLogger
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.nio.charset.Charset
import kotlin.reflect.KClass
import kotlin.test.assertEquals
import kotlin.test.fail
val logger = getLogger("test-utils")
fun <T : Exception> expect(message : String? = null, clazz: KClass<T>, action: () -> Unit, check: (T) -> Unit) {
try {
action()
fail("${message ?: "" } \nexpected exception: $clazz")
} catch (e: Exception) {
if (clazz == e.javaClass.kotlin) {
check(e as T)
} else {
logger.error(e.message, e)
fail("expected $clazz got $e")
}
}
}
fun <T : Exception> expect(clazz: KClass<T>, action: () -> Unit, check: (T) -> Unit) {
expect(null, clazz, action, check)
}
fun String.toInputStream(charset: Charset = Charsets.UTF_8): InputStream
= ByteArrayInputStream(this.toByteArray(charset))
fun assertSerializeNicely(instance: Any) {
val serialized = ByteArrayOutputStream().use {
ObjectOutputStream(it).use { objectOutputStream ->
objectOutputStream.writeObject(instance)
}
it.toByteArray()
}
val deserialized = ByteArrayInputStream(serialized).use {
ObjectInputStream(it).use { inputStream ->
inputStream.readObject()
}
}
assertEquals(instance, deserialized)
} | src/test/kotlin/com/github/kerubistan/kerub/TestUtils.kt | 417285887 |
package com.github.kerubistan.kerub.planner.steps.storage.gvinum.create
import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao
import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao
import com.github.kerubistan.kerub.host.HostCommandExecutor
import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.SimpleStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageGvinumAllocation
import com.github.kerubistan.kerub.model.dynamic.gvinum.ConcatenatedGvinumConfiguration
import com.github.kerubistan.kerub.model.dynamic.gvinum.MirroredGvinumConfiguration
import com.github.kerubistan.kerub.model.dynamic.gvinum.SimpleGvinumConfiguration
import com.github.kerubistan.kerub.model.dynamic.gvinum.StripedGvinumConfiguration
import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor
import com.github.kerubistan.kerub.utils.junix.storagemanager.gvinum.GVinum
import com.github.kerubistan.kerub.utils.junix.storagemanager.gvinum.GvinumDrive
import com.github.kerubistan.kerub.utils.update
import io.github.kerubistan.kroki.numbers.sumBy
class CreateGvinumVolumeExecutor(
private val hostCommandExecutor: HostCommandExecutor,
private val virtualDiskDynDao: VirtualStorageDeviceDynamicDao,
private val hostDynamicDao: HostDynamicDao
) : AbstractStepExecutor<CreateGvinumVolume, Unit>() {
override fun update(step: CreateGvinumVolume, updates: Unit) {
virtualDiskDynDao.update(id = step.disk.id, retrieve = {
virtualDiskDynDao[step.disk.id] ?: VirtualStorageDeviceDynamic(
id = step.disk.id,
allocations = listOf()
)
}, change = {
transformVirtualStorageDynamic(it, step)
})
hostCommandExecutor.execute(step.host) { session ->
val updatedDisks = GVinum.listDrives(session).filter { drive ->
when (step.config) {
is SimpleGvinumConfiguration -> step.config.diskName == drive.name
is ConcatenatedGvinumConfiguration -> drive.name in step.config.disks.keys
is MirroredGvinumConfiguration -> drive.name in step.config.disks
is StripedGvinumConfiguration -> drive.name in step.config.disks
else -> TODO("Not handled gvinum configuration type: ${step.config}")
}
}
val updatedDisksByName by lazy { updatedDisks.associateBy { it.name } }
hostDynamicDao.update(step.host.id) {
it.copy(
storageStatus = it.storageStatus.update(
selector = { deviceDynamic -> deviceDynamic.id == step.capability.id },
map = { deviceDynamic ->
when (deviceDynamic) {
is SimpleStorageDeviceDynamic -> deviceDynamic.copy(
freeCapacity = updatedDisks.sumBy(GvinumDrive::available)
)
is CompositeStorageDeviceDynamic -> deviceDynamic.copy(
items = deviceDynamic.items.update(
selector = { item ->
updatedDisksByName.containsKey(item.name)
},
map = { item ->
item.copy(
freeCapacity =
requireNotNull(updatedDisksByName[item.name])
.available
)
}
)
)
else -> TODO("Not handled deviceDynamic type: $deviceDynamic")
}
}
)
)
}
}
}
fun transformVirtualStorageDynamic(
dynamic: VirtualStorageDeviceDynamic,
step: CreateGvinumVolume
): VirtualStorageDeviceDynamic =
dynamic.copy(
allocations = dynamic.allocations + VirtualStorageGvinumAllocation(
hostId = step.host.id,
actualSize = step.disk.size,
configuration = step.config,
capabilityId = step.capability.id
)
)
override fun perform(step: CreateGvinumVolume) {
hostCommandExecutor.execute(step.host) { session ->
when (step.config) {
is ConcatenatedGvinumConfiguration -> {
GVinum.createConcatenatedVolume(
session = session,
volName = step.disk.id.toString(),
disks = step.config.disks
)
}
is SimpleGvinumConfiguration -> {
GVinum.createSimpleVolume(
session = session,
volName = step.disk.id.toString(),
disk = step.config.diskName,
size = step.disk.size)
}
else -> {
TODO("gvinum configuration not implemented by executor: ${step.config}")
}
}
}
}
} | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/gvinum/create/CreateGvinumVolumeExecutor.kt | 2320401325 |
package com.github.kerubistan.kerub.planner.steps.storage.block.copy
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.collection.VirtualStorageDataCollection
import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation
import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import com.github.kerubistan.kerub.planner.steps.storage.gvinum.create.CreateGvinumVolumeFactory
import com.github.kerubistan.kerub.planner.steps.storage.lvm.create.CreateLvFactory
import io.github.kerubistan.kroki.collections.update
import kotlin.reflect.KClass
abstract class AbstractBlockCopyFactory<T : AbstractBlockCopy> : AbstractOperationalStepFactory<T>() {
protected val allocationFactories = listOf(CreateLvFactory, CreateGvinumVolumeFactory)
protected fun createUnallocatedState(state: OperationalState, targetStorage: VirtualStorageDataCollection) =
state.copy(
vStorage = state.vStorage.update(targetStorage.id) { targetStorageColl ->
targetStorageColl.copy(
stat = targetStorageColl.stat.copy(
expectations = listOf(StorageAvailabilityExpectation())
)
)
}
)
final override val expectationHints: Set<KClass<out Expectation>>
get() = setOf(CloneOfStorageExpectation::class)
final override val problemHints: Set<KClass<out Problem>>
get() = setOf()
} | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/AbstractBlockCopyFactory.kt | 667321317 |
package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTWrapperPsiElement
import org.jetbrains.cabal.parser.*
import org.jetbrains.cabal.psi.PropertyValue
class TestSuiteType(node: ASTNode) : PropertyValue(node), RangedValue {
override fun getAvailableValues(): List<String> {
return TS_TYPE_VALS
}
}
| plugin/src/org/jetbrains/cabal/psi/TestSuiteType.kt | 2628949166 |
package li.ruoshi.nextday.models
/**
* Created by ruoshili on 1/11/15.
*/
class DailyInfo(val author: Author?,
val dateKey: Int,
val colors: Colors,
val images: Images,
val music: Music?,
val text: Text,
val video: Video?,
val event: String,
val geo: Geo,
val thumbnail: Thumbnail?,
val modifiedAt: String) {
}
| app/src/main/kotlin/li/ruoshi/nextday/models/DailyInfo.kt | 2644043302 |
package com.intellij.remoteDev.downloader
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileSystemUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.remoteDev.RemoteDevSystemSettings
import com.intellij.remoteDev.RemoteDevUtilBundle
import com.intellij.remoteDev.connection.CodeWithMeSessionInfoProvider
import com.intellij.remoteDev.connection.StunTurnServerInfo
import com.intellij.remoteDev.util.*
import com.intellij.util.PlatformUtils
import com.intellij.util.application
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.EdtScheduledExecutorService
import com.intellij.util.io.*
import com.intellij.util.io.HttpRequests.HttpStatusException
import com.intellij.util.system.CpuArch
import com.intellij.util.text.VersionComparatorUtil
import com.intellij.util.withFragment
import com.intellij.util.withQuery
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants
import com.jetbrains.infra.pgpVerifier.JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifier
import com.jetbrains.infra.pgpVerifier.PgpSignaturesVerifierLogger
import com.jetbrains.infra.pgpVerifier.Sha256ChecksumSignatureVerifier
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.fire
import com.sun.jna.platform.win32.Kernel32
import com.sun.jna.platform.win32.WinBase
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.ptr.IntByReference
import org.jetbrains.annotations.ApiStatus
import java.io.ByteArrayInputStream
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.*
import java.nio.file.attribute.FileTime
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.io.path.*
import kotlin.math.min
@ApiStatus.Experimental
object CodeWithMeClientDownloader {
private val LOG = logger<CodeWithMeClientDownloader>()
private const val extractDirSuffix = ".ide.d"
private val config get () = service<JetBrainsClientDownloaderConfigurationProvider>()
private fun isJbrSymlink(file: Path): Boolean = file.name == "jbr" && isSymlink(file)
private fun isSymlink(file: Path): Boolean = FileSystemUtil.getAttributes(file.toFile())?.isSymLink == true
val cwmJbrManifestFilter: (Path) -> Boolean = { !it.isDirectory() || isSymlink(it) }
fun getJetBrainsClientManifestFilter(clientBuildNumber: String): (Path) -> Boolean {
if (isClientWithBundledJre(clientBuildNumber)) {
return { !it.isDirectory() || isSymlink(it) }
} else {
return { !isJbrSymlink(it) && (!it.isDirectory() || isSymlink(it)) }
}
}
private const val minimumClientBuildWithBundledJre = "223.4374"
fun isClientWithBundledJre(clientBuildNumber: String) = VersionComparatorUtil.compare(clientBuildNumber, minimumClientBuildWithBundledJre) >= 0
@ApiStatus.Internal
class DownloadableFileData(
val fileCaption: String,
val url: URI,
val archivePath: Path,
val targetPath: Path,
val includeInManifest: (Path) -> Boolean,
val downloadFuture: CompletableFuture<Boolean> = CompletableFuture(),
val status: AtomicReference<DownloadableFileState> = AtomicReference(DownloadableFileState.Downloading),
) {
companion object {
private val prohibitedFileNameChars = Regex("[^._\\-a-zA-Z0-9]")
private fun sanitizeFileName(fileName: String) = prohibitedFileNameChars.replace(fileName, "_")
fun build(url: URI, tempDir: Path, cachesDir: Path, includeInManifest: (Path) -> Boolean): DownloadableFileData {
val urlWithoutFragment = url.withFragment(null)
val bareUrl = urlWithoutFragment.withQuery(null)
val fileNameFromUrl = sanitizeFileName(bareUrl.path.toString().substringAfterLast('/'))
val fileName = fileNameFromUrl.take(100) +
"-" +
DigestUtil.sha256Hex(urlWithoutFragment.toString().toByteArray()).substring(0, 10)
return DownloadableFileData(
fileCaption = fileNameFromUrl,
url = url,
archivePath = tempDir.resolve(fileName),
targetPath = cachesDir / (fileName + extractDirSuffix),
includeInManifest = includeInManifest,
)
}
}
override fun toString(): String {
return "DownloadableFileData(fileCaption='$fileCaption', url=$url, archivePath=$archivePath, targetPath=$targetPath)"
}
enum class DownloadableFileState {
Downloading,
Extracting,
Done,
}
}
private const val buildNumberPattern = """[0-9]{3}\.(([0-9]+(\.[0-9]+)?)|SNAPSHOT)"""
val buildNumberRegex = Regex(buildNumberPattern)
private fun getClientDistributionName(clientBuildVersion: String) = when {
VersionComparatorUtil.compare(clientBuildVersion, "211.6167") < 0 -> "IntelliJClient"
VersionComparatorUtil.compare(clientBuildVersion, "213.5318") < 0 -> "CodeWithMeGuest"
else -> "JetBrainsClient"
}
fun createSessionInfo(clientBuildVersion: String, jreBuild: String?, unattendedMode: Boolean): CodeWithMeSessionInfoProvider {
val isSnapshot = "SNAPSHOT" in clientBuildVersion
if (isSnapshot) {
LOG.warn("Thin client download from sources may result in failure due to different sources on host and client, " +
"don't forget to update your locally built archive")
}
val bundledJre = isClientWithBundledJre(clientBuildVersion)
val jreBuildToDownload = if (bundledJre) {
null
}
else {
jreBuild ?: error("JRE build number must be passed for client build number < $clientBuildVersion")
}
val hostBuildNumber = buildNumberRegex.find(clientBuildVersion)!!.value
val platformSuffix = if (jreBuildToDownload != null) when {
SystemInfo.isLinux && CpuArch.isIntel64() -> "-no-jbr.tar.gz"
SystemInfo.isLinux && CpuArch.isArm64() -> "-no-jbr-aarch64.tar.gz"
SystemInfo.isWindows && CpuArch.isIntel64() -> ".win.zip"
SystemInfo.isWindows && CpuArch.isArm64() -> "-aarch64.win.zip"
SystemInfo.isMac && CpuArch.isIntel64() -> "-no-jdk.sit"
SystemInfo.isMac && CpuArch.isArm64() -> "-no-jdk-aarch64.sit"
else -> null
} else when {
SystemInfo.isLinux && CpuArch.isIntel64() -> ".tar.gz"
SystemInfo.isLinux && CpuArch.isArm64() -> "-aarch64.tar.gz"
SystemInfo.isWindows && CpuArch.isIntel64() -> ".jbr.win.zip"
SystemInfo.isWindows && CpuArch.isArm64() -> "-aarch64.jbr.win.zip"
SystemInfo.isMac && CpuArch.isIntel64() -> ".sit"
SystemInfo.isMac && CpuArch.isArm64() -> "-aarch64.sit"
else -> null
} ?: error("Current platform is not supported: OS ${SystemInfo.OS_NAME} ARCH ${SystemInfo.OS_ARCH}")
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientBuildNumber = if (isSnapshot && config.downloadLatestBuildFromCDNForSnapshotHost) getLatestBuild(hostBuildNumber) else hostBuildNumber
val clientDownloadUrl = "${config.clientDownloadUrl.toString().trimEnd('/')}/$clientDistributionName-$clientBuildNumber$platformSuffix"
val jreDownloadUrl = if (jreBuildToDownload != null) {
val platformString = when {
SystemInfo.isLinux && CpuArch.isIntel64() -> "linux-x64"
SystemInfo.isLinux && CpuArch.isArm64() -> "linux-aarch64"
SystemInfo.isWindows && CpuArch.isIntel64() -> "windows-x64"
SystemInfo.isWindows && CpuArch.isArm64() -> "windows-aarch64"
SystemInfo.isMac && CpuArch.isIntel64() -> "osx-x64"
SystemInfo.isMac && CpuArch.isArm64() -> "osx-aarch64"
else -> error("Current platform is not supported")
}
val jreBuildParts = jreBuildToDownload.split("b")
require(jreBuildParts.size == 2) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
require(jreBuildParts[0].matches(Regex("^[0-9_.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
require(jreBuildParts[1].matches(Regex("^[0-9.]+$"))) { "jreBuild format should be like 12_3_45b6789.0: ${jreBuildToDownload}" }
/**
* After upgrade to JRE 17 Jetbrains Runtime Team made a couple of incompatible changes:
* 1. Java version began to contain dots in its version
* 2. Root directory was renamed from 'jbr' to 'jbr_jcef_12.3.4b1235'
*
* We decided to maintain backward compatibility with old IDEs and
* rename archives and root directories back to old format.
*/
val jdkVersion = jreBuildParts[0].replace(".", "_")
val jdkBuild = jreBuildParts[1]
val jreDownloadUrl = "${config.jreDownloadUrl.toString().trimEnd('/')}/jbr_jcef-$jdkVersion-$platformString-b${jdkBuild}.tar.gz"
jreDownloadUrl
} else null
val pgpPublicKeyUrl = if (unattendedMode) {
RemoteDevSystemSettings.getPgpPublicKeyUrl().value
} else null
val sessionInfo = object : CodeWithMeSessionInfoProvider {
override val hostBuildNumber = hostBuildNumber
override val compatibleClientUrl = clientDownloadUrl
override val isUnattendedMode = unattendedMode
override val compatibleJreUrl = jreDownloadUrl
override val hostFeaturesToEnable: Set<String>? = null
override val stunTurnServers: List<StunTurnServerInfo>? = null
override val downloadPgpPublicKeyUrl: String? = pgpPublicKeyUrl
}
LOG.info("Generated session info: $sessionInfo")
return sessionInfo
}
private fun getLatestBuild(hostBuildNumber: String): String {
val majorVersion = hostBuildNumber.substringBefore('.')
val latestBuildTxtFileName = "$majorVersion-LAST-BUILD.txt"
val latestBuildTxtUri = "${config.clientDownloadUrl.toASCIIString().trimEnd('/')}/$latestBuildTxtFileName"
val tempFile = Files.createTempFile(latestBuildTxtFileName, "")
return try {
downloadWithRetries(URI(latestBuildTxtUri), tempFile, EmptyProgressIndicator()).let {
tempFile.readText().trim()
}
}
finally {
Files.delete(tempFile)
}
}
private val currentlyDownloading = ConcurrentHashMap<Path, CompletableFuture<Boolean>>()
@ApiStatus.Experimental
fun downloadClientAndJdk(clientBuildVersion: String,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val jdkBuild = if (isClientWithBundledJre(clientBuildVersion)) null else {
// Obsolete since 2022.3. Now the client has JRE bundled in
LOG.info("Downloading Thin Client jdk-build.txt")
val jdkBuildProgressIndicator = progressIndicator.createSubProgress(0.1)
jdkBuildProgressIndicator.text = RemoteDevUtilBundle.message("thinClientDownloader.checking")
val clientDistributionName = getClientDistributionName(clientBuildVersion)
val clientJdkDownloadUrl = "${config.clientDownloadUrl}$clientDistributionName-$clientBuildVersion-jdk-build.txt"
LOG.info("Downloading from $clientJdkDownloadUrl")
val tempFile = Files.createTempFile("jdk-build", "txt")
try {
downloadWithRetries(URI(clientJdkDownloadUrl), tempFile, EmptyProgressIndicator()).let {
tempFile.readText()
}
}
finally {
Files.delete(tempFile)
}
}
val sessionInfo = createSessionInfo(clientBuildVersion, jdkBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator.createSubProgress(0.9))
}
/**
* @param clientBuildVersion format: 213.1337[.23]
* @param jreBuild format: 11_0_11b1536.1
* where 11_0_11 is jdk version, b1536.1 is the build version
* @returns Pair(path/to/thin/client, path/to/jre)
*
* Update this method (any jdk-related stuff) together with:
* `org/jetbrains/intellij/build/impl/BundledJreManager.groovy`
*/
fun downloadClientAndJdk(clientBuildVersion: String,
jreBuild: String?,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val sessionInfo = createSessionInfo(clientBuildVersion, jreBuild, true)
return downloadClientAndJdk(sessionInfo, progressIndicator)
}
/**
* @returns Pair(path/to/thin/client, path/to/jre)
*/
fun downloadClientAndJdk(sessionInfoResponse: CodeWithMeSessionInfoProvider,
progressIndicator: ProgressIndicator): ExtractedJetBrainsClientData? {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
val tempDir = FileUtil.createTempDirectory("jb-cwm-dl", null).toPath()
LOG.info("Downloading Thin Client in $tempDir...")
val clientUrl = URI(sessionInfoResponse.compatibleClientUrl)
val guestData = DownloadableFileData.build(
url = clientUrl,
tempDir = tempDir,
cachesDir = config.clientCachesDir,
includeInManifest = getJetBrainsClientManifestFilter(sessionInfoResponse.hostBuildNumber),
)
val jdkUrl = sessionInfoResponse.compatibleJreUrl?.let { URI(it) }
val jdkData = if (jdkUrl != null) {
DownloadableFileData.build(
url = jdkUrl,
tempDir = tempDir,
cachesDir = config.clientCachesDir,
includeInManifest = cwmJbrManifestFilter,
)
}
else null
val dataList = listOfNotNull(jdkData, guestData)
val activity: StructuredIdeActivity? =
if (dataList.isNotEmpty()) RemoteDevStatisticsCollector.onGuestDownloadStarted()
else null
fun updateStateText() {
val downloadList = dataList.filter { it.status.get() == DownloadableFileData.DownloadableFileState.Downloading }.joinToString(", ") { it.fileCaption }
val extractList = dataList.filter { it.status.get() == DownloadableFileData.DownloadableFileState.Extracting }.joinToString(", ") { it.fileCaption }
progressIndicator.text =
if (downloadList.isNotBlank() && extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading.and.extracting", downloadList, extractList)
else if (downloadList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.downloading", downloadList)
else if (extractList.isNotBlank()) RemoteDevUtilBundle.message("thinClientDownloader.extracting", extractList)
else RemoteDevUtilBundle.message("thinClientDownloader.ready")
}
updateStateText()
val dataProgressIndicators = MultipleSubProgressIndicator.create(progressIndicator, dataList.size)
for ((index, data) in dataList.withIndex()) {
// download
val future = data.downloadFuture
// Update only fraction via progress indicator API, text will be updated by updateStateText function
val dataProgressIndicator = dataProgressIndicators[index]
AppExecutorUtil.getAppScheduledExecutorService().execute {
try {
val existingDownloadFuture = synchronized(currentlyDownloading) {
val existingDownloadInnerFuture = currentlyDownloading[data.targetPath]
if (existingDownloadInnerFuture != null) {
existingDownloadInnerFuture
}
else {
currentlyDownloading[data.targetPath] = data.downloadFuture
null
}
}
// TODO: how to merge progress indicators in this case?
if (existingDownloadFuture != null) {
LOG.warn("Already downloading and extracting to ${data.targetPath}, will wait until download finished")
existingDownloadFuture.whenComplete { res, ex ->
if (ex != null) {
future.completeExceptionally(ex)
}
else {
future.complete(res)
}
}
return@execute
}
if (isAlreadyDownloaded(data)) {
LOG.info("Already downloaded and extracted ${data.fileCaption} to ${data.targetPath}")
data.status.set(DownloadableFileData.DownloadableFileState.Done)
dataProgressIndicator.fraction = 1.0
updateStateText()
future.complete(true)
return@execute
}
val downloadingDataProgressIndicator = dataProgressIndicator.createSubProgress(0.5)
try {
fun download(url: URI, path: Path) {
downloadWithRetries(url, path, downloadingDataProgressIndicator)
}
download(data.url, data.archivePath)
LOG.info("Signature verification is ${if (config.verifySignature) "ON" else "OFF"}")
if (config.verifySignature) {
val pgpKeyRingFile = Files.createTempFile(tempDir, "KEYS", "")
download(URI(sessionInfoResponse.downloadPgpPublicKeyUrl ?: JetBrainsPgpConstants.JETBRAINS_DOWNLOADS_PGP_SUB_KEYS_URL), pgpKeyRingFile)
val checksumPath = data.archivePath.addSuffix(SHA256_SUFFIX)
val signaturePath = data.archivePath.addSuffix(SHA256_ASC_SUFFIX)
download(data.url.addPathSuffix(SHA256_SUFFIX), checksumPath)
download(data.url.addPathSuffix(SHA256_ASC_SUFFIX), signaturePath)
val pgpVerifier = PgpSignaturesVerifier(object : PgpSignaturesVerifierLogger {
override fun info(message: String) {
LOG.info("Verifying ${data.url} PGP signature: $message")
}
})
LOG.info("Running checksum signature verifier for ${data.archivePath}")
Sha256ChecksumSignatureVerifier(pgpVerifier).verifyChecksumAndSignature(
file = data.archivePath,
detachedSignatureFile = signaturePath,
checksumFile = checksumPath,
expectedFileName = data.url.path.substringAfterLast('/'),
untrustedPublicKeyRing = ByteArrayInputStream(Files.readAllBytes(pgpKeyRingFile)),
trustedMasterKey = ByteArrayInputStream(JETBRAINS_DOWNLOADS_PGP_MASTER_PUBLIC_KEY.toByteArray()),
)
LOG.info("Signature verified for ${data.archivePath}")
}
}
catch (ex: IOException) {
future.completeExceptionally(ex)
LOG.warn(ex)
return@execute
}
// extract
dataProgressIndicator.fraction = 0.75
data.status.set(DownloadableFileData.DownloadableFileState.Extracting)
updateStateText()
// downloading a .zip file will get a VirtualFile with a path of `jar://C:/Users/ivan.pashchenko/AppData/Local/Temp/CodeWithMeGuest-212.2033-windows-x64.zip!/`
// see FileDownloaderImpl.findVirtualFiles making a call to VfsUtil.getUrlForLibraryRoot(ioFile)
val archivePath = data.archivePath
LOG.info("Extracting $archivePath to ${data.targetPath}...")
FileUtil.delete(data.targetPath)
require(data.targetPath.notExists()) { "Target path \"${data.targetPath}\" for $archivePath already exists" }
FileManifestUtil.decompressWithManifest(archivePath, data.targetPath, data.includeInManifest)
require(FileManifestUtil.isUpToDate(data.targetPath, data.includeInManifest)) {
"Manifest verification failed for archive: $archivePath -> ${data.targetPath}"
}
dataProgressIndicator.fraction = 1.0
data.status.set(DownloadableFileData.DownloadableFileState.Done)
updateStateText()
Files.delete(archivePath)
future.complete(true)
}
catch (e: Throwable) {
future.completeExceptionally(e)
LOG.warn(e)
}
finally {
synchronized(currentlyDownloading) {
currentlyDownloading.remove(data.targetPath)
}
}
}
}
try {
val guestSucceeded = guestData.downloadFuture.get()
val jdkSucceeded = jdkData?.downloadFuture?.get() ?: true
if (!guestSucceeded || !jdkSucceeded) error("Guest or jdk was not downloaded")
LOG.info("Download of guest and jdk succeeded")
return ExtractedJetBrainsClientData(clientDir = guestData.targetPath, jreDir = jdkData?.targetPath, version = sessionInfoResponse.hostBuildNumber)
}
catch(e: ProcessCanceledException) {
LOG.info("Download was canceled")
return null
}
catch (e: Throwable) {
RemoteDevStatisticsCollector.onGuestDownloadFinished(activity, isSucceeded = false)
LOG.warn(e)
if (e is ExecutionException) {
e.cause?.let { throw it }
}
throw e
}
}
private fun isAlreadyDownloaded(fileData: DownloadableFileData): Boolean {
val extractDirectory = FileManifestUtil.getExtractDirectory(fileData.targetPath, fileData.includeInManifest)
return extractDirectory.isUpToDate && !fileData.targetPath.fileName.toString().contains("SNAPSHOT")
}
private fun downloadWithRetries(url: URI, path: Path, progressIndicator: ProgressIndicator) {
require(application.isUnitTestMode || !application.isDispatchThread) { "This method should not be called on UI thread" }
@Suppress("LocalVariableName")
val MAX_ATTEMPTS = 5
@Suppress("LocalVariableName")
val BACKOFF_INITIAL_DELAY_MS = 500L
var delayMs = BACKOFF_INITIAL_DELAY_MS
for (i in 1..MAX_ATTEMPTS) {
try {
LOG.info("Downloading from $url to ${path.absolutePathString()}, attempt $i of $MAX_ATTEMPTS")
when (url.scheme) {
"http", "https" -> {
HttpRequests.request(url.toString()).saveToFile(path, progressIndicator)
}
"file" -> {
Files.copy(url.toPath(), path, StandardCopyOption.REPLACE_EXISTING)
}
else -> {
error("scheme ${url.scheme} is not supported")
}
}
LOG.info("Download from $url to ${path.absolutePathString()} succeeded on attempt $i of $MAX_ATTEMPTS")
return
}
catch (e: Throwable) {
if (e is ControlFlowException) throw e
if (e is HttpStatusException) {
if (e.statusCode in 400..499) {
LOG.warn("Received ${e.statusCode} with message ${e.message}, will not retry")
throw e
}
}
if (i < MAX_ATTEMPTS) {
LOG.warn("Attempt $i of $MAX_ATTEMPTS to download from $url to ${path.absolutePathString()} failed, retrying in $delayMs ms", e)
Thread.sleep(delayMs)
delayMs = (delayMs * 1.5).toLong()
} else {
LOG.warn("Failed to download from $url to ${path.absolutePathString()} in $MAX_ATTEMPTS attempts", e)
throw e
}
}
}
}
private fun findCwmGuestHome(guestRoot: Path): Path {
// maxDepth 2 for macOS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
if (dir.resolve("bin").exists() && dir.resolve("lib").exists()) {
return dir
}
}
}
error("JetBrains Client home is not found under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherNames: List<String>): Pair<Path, List<String>> {
val launcher = launcherNames.firstNotNullOfOrNull {
val launcherRelative = Path.of("bin", it)
val launcher = findLauncher(guestRoot, launcherRelative)
launcher?.let {
launcher to listOf(launcher.toString())
}
}
return launcher ?: error("Could not find launchers (${launcherNames.joinToString { "'$it'" }}) under $guestRoot")
}
private fun findLauncher(guestRoot: Path, launcherName: Path): Path? {
// maxDepth 2 for macOS's .app/Contents
Files.walk(guestRoot, 2).use {
for (dir in it) {
val candidate = dir.resolve(launcherName)
if (candidate.exists()) {
return candidate
}
}
}
return null
}
private fun findLauncherUnderCwmGuestRoot(guestRoot: Path): Pair<Path, List<String>> {
when {
SystemInfo.isWindows -> {
val batchLaunchers = listOf("intellij_client.bat", "jetbrains_client.bat")
val exeLaunchers = listOf("jetbrains_client64.exe", "cwm_guest64.exe", "intellij_client64.exe")
val eligibleLaunchers = if (Registry.`is`("com.jetbrains.gateway.client.use.batch.launcher", false))
batchLaunchers
else
exeLaunchers + batchLaunchers
return findLauncher(guestRoot, eligibleLaunchers)
}
SystemInfo.isUnix -> {
if (SystemInfo.isMac) {
val app = guestRoot.toFile().listFiles { file -> file.name.endsWith(".app") && file.isDirectory }!!.singleOrNull()
if (app != null) {
return app.toPath() to listOf("open", "-n", "-W", "-a", app.toString(), "--args")
}
}
val shLauncherNames = listOf("jetbrains_client.sh", "cwm_guest.sh", "intellij_client.sh")
return findLauncher(guestRoot, shLauncherNames)
}
else -> error("Unsupported OS: ${SystemInfo.OS_NAME}")
}
}
private val remoteDevYouTrackFlag = "-Dapplication.info.youtrack.url=https://youtrack.jetbrains.com/newissue?project=GTW&clearDraft=true&description=\$DESCR"
/**
* Launches client and returns process's lifetime (which will be terminated on process exit)
*/
fun runCwmGuestProcessFromDownload(
lifetime: Lifetime,
url: String,
extractedJetBrainsClientData: ExtractedJetBrainsClientData
): Lifetime {
val (executable, fullLauncherCmd) = findLauncherUnderCwmGuestRoot(extractedJetBrainsClientData.clientDir)
if (extractedJetBrainsClientData.jreDir != null) {
createSymlinkToJdkFromGuest(extractedJetBrainsClientData.clientDir, extractedJetBrainsClientData.jreDir)
}
// Update mtime on JRE & CWM Guest roots. The cleanup process will use it later.
listOfNotNull(extractedJetBrainsClientData.clientDir, extractedJetBrainsClientData.jreDir).forEach { path ->
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()))
}
val parameters = if (CodeWithMeGuestLauncher.isUnattendedModeUri(URI(url))) listOf("thinClient", url, remoteDevYouTrackFlag) else listOf("thinClient", url)
val processLifetimeDef = lifetime.createNested()
val vmOptionsFile = if (SystemInfoRt.isMac) {
// macOS stores vmoptions file inside .app file – we can't edit it
Paths.get(
PathManager.getDefaultConfigPathFor(PlatformUtils.JETBRAINS_CLIENT_PREFIX + extractedJetBrainsClientData.version),
"jetbrains_client.vmoptions"
)
} else executable.resolveSibling("jetbrains_client64.vmoptions")
service<JetBrainsClientDownloaderConfigurationProvider>().patchVmOptions(vmOptionsFile)
if (SystemInfo.isWindows) {
val hProcess = WindowsFileUtil.windowsShellExecute(
executable = executable,
workingDirectory = extractedJetBrainsClientData.clientDir,
parameters = parameters
)
@Suppress("LocalVariableName")
val STILL_ACTIVE = 259
application.executeOnPooledThread {
val exitCode = IntByReference(STILL_ACTIVE)
while (exitCode.value == STILL_ACTIVE) {
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
Thread.sleep(1000)
}
processLifetimeDef.terminate()
}
lifetime.onTerminationOrNow {
val exitCode = IntByReference(WinBase.INFINITE)
Kernel32.INSTANCE.GetExitCodeProcess(hProcess, exitCode)
if (exitCode.value == STILL_ACTIVE)
LOG.info("Terminating cwm guest process")
else return@onTerminationOrNow
if (!Kernel32.INSTANCE.TerminateProcess(hProcess, 1)) {
val error = Kernel32.INSTANCE.GetLastError()
val hResult = WinNT.HRESULT(error)
LOG.error("Failed to terminate cwm guest process, HRESULT=${"0x%x".format(hResult)}")
}
}
}
else {
// Mac gets multiple start attempts because starting it fails occasionally (CWM-2244, CWM-1733)
var attemptCount = if (SystemInfo.isMac) 5 else 1
var lastProcessStartTime: Long
fun doRunProcess() {
val commandLine = GeneralCommandLine(fullLauncherCmd + parameters)
config.modifyClientCommandLine(commandLine)
LOG.info("Starting JetBrains Client process (attempts left: $attemptCount): ${commandLine}")
attemptCount--
lastProcessStartTime = System.currentTimeMillis()
val processHandler = object : OSProcessHandler(commandLine) {
override fun readerOptions(): BaseOutputReader.Options = BaseOutputReader.Options.forMostlySilentProcess()
}
val listener = object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
super.onTextAvailable(event, outputType)
LOG.info("GUEST OUTPUT: ${event.text}")
}
override fun processTerminated(event: ProcessEvent) {
super.processTerminated(event)
LOG.info("Guest process terminated, exit code " + event.exitCode)
if (event.exitCode == 0) {
application.invokeLater {
processLifetimeDef.terminate()
}
} else {
// if process exited abnormally but took longer than 10 seconds, it's likely to be an issue with connection instead of Mac-specific bug
if ((System.currentTimeMillis() - lastProcessStartTime) < 10_000 ) {
if (attemptCount > 0) {
LOG.info("Previous attempt to start guest process failed, will try again in one second")
EdtScheduledExecutorService.getInstance().schedule({ doRunProcess() }, ModalityState.any(), 1, TimeUnit.SECONDS)
}
else {
LOG.warn("Running client process failed after specified number of attempts")
application.invokeLater {
processLifetimeDef.terminate()
}
}
}
}
}
}
processHandler.addProcessListener(listener)
processHandler.startNotify()
config.clientLaunched.fire()
lifetime.onTerminationOrNow {
processHandler.process.children().forEach {
it.destroyForcibly()
}
processHandler.process.destroyForcibly()
}
}
doRunProcess()
}
return processLifetimeDef.lifetime
}
fun createSymlinkToJdkFromGuest(guestRoot: Path, jdkRoot: Path): Path {
val linkTarget = getJbrDirectory(jdkRoot)
val guestHome = findCwmGuestHome(guestRoot)
val link = guestHome / "jbr"
createSymlink(link, linkTarget)
return link
}
private fun createSymlink(link: Path, target: Path) {
val targetRealPath = target.toRealPath()
val linkExists = true
val linkRealPath = if (link.exists(LinkOption.NOFOLLOW_LINKS)) link.toRealPath() else null
val isSymlink = FileSystemUtil.getAttributes(link.toFile())?.isSymLink == true
LOG.info("$link: exists=$linkExists, realPath=$linkRealPath, isSymlink=$isSymlink")
if (linkExists && isSymlink && linkRealPath == targetRealPath) {
LOG.info("Symlink/junction '$link' is UP-TO-DATE and points to '$target'")
}
else {
FileUtil.deleteWithRenamingIfExists(link)
LOG.info("Creating symlink/junction '$link' -> '$target'")
try {
if (SystemInfo.isWindows) {
WindowsFileUtil.createJunction(junctionFile = link, targetFile = target.absolute())
}
else {
Files.createSymbolicLink(link, target.absolute())
}
}
catch (e: IOException) {
if (link.exists() && link.toRealPath() == targetRealPath) {
LOG.warn("Creating symlink/junction to already existing target. '$link' -> '$target'")
}
else {
throw e
}
}
try {
val linkRealPath2 = link.toRealPath()
if (linkRealPath2 != targetRealPath) {
LOG.error("Symlink/junction '$link' should point to '$targetRealPath', but points to '$linkRealPath2' instead")
}
}
catch (e: Throwable) {
LOG.error(e)
throw e
}
}
}
private fun getJbrDirectory(root: Path): Path =
tryGetMacOsJbrDirectory(root) ?: tryGetJdkRoot(root) ?: error("Unable to detect jdk content directory in path: '$root'")
private fun tryGetJdkRoot(jdkDownload: Path): Path? {
jdkDownload.toFile().walk(FileWalkDirection.TOP_DOWN).forEach { file ->
if (File(file, "bin").isDirectory && File(file, "lib").isDirectory) {
return file.toPath()
}
}
return null
}
private fun tryGetMacOsJbrDirectory(root: Path): Path? {
if (!SystemInfo.isMac) {
return null
}
val jbrDirectory = root.listDirectoryEntries().find { it.nameWithoutExtension.startsWith("jbr") }
LOG.debug { "JBR directory: $jbrDirectory" }
return jbrDirectory
}
fun versionsMatch(hostBuildNumberString: String, localBuildNumberString: String): Boolean {
try {
val hostBuildNumber = BuildNumber.fromString(hostBuildNumberString)!!
val localBuildNumber = BuildNumber.fromString(localBuildNumberString)!!
// Any guest in that branch compatible with SNAPSHOT version (it's used by IDEA developers mostly)
if ((localBuildNumber.isSnapshot || hostBuildNumber.isSnapshot) && hostBuildNumber.baselineVersion == localBuildNumber.baselineVersion) {
return true
}
return hostBuildNumber.asStringWithoutProductCode() == localBuildNumber.asStringWithoutProductCode()
}
catch (t: Throwable) {
LOG.error("Error comparing versions $hostBuildNumberString and $localBuildNumberString: ${t.message}", t)
return false
}
}
private fun Path.addSuffix(suffix: String) = resolveSibling(fileName.toString() + suffix)
private const val SHA256_SUFFIX = ".sha256"
private const val SHA256_ASC_SUFFIX = ".sha256.asc"
private val urlAllowedChars = Regex("^[._\\-a-zA-Z0-9:/]+$")
fun isValidDownloadUrl(url: String): Boolean {
return urlAllowedChars.matches(url) && !url.contains("..")
}
private class MultipleSubProgressIndicator(parent: ProgressIndicator,
private val onFractionChange: () -> Unit) : SubProgressIndicatorBase(parent) {
companion object {
fun create(parent: ProgressIndicator, count: Int): List<MultipleSubProgressIndicator> {
val result = mutableListOf<MultipleSubProgressIndicator>()
val parentBaseFraction = parent.fraction
for (i in 0..count) {
val element = MultipleSubProgressIndicator(parent) {
val subFraction = result.sumOf { it.subFraction }
parent.fraction = min(parentBaseFraction + subFraction * (1.0 / count), 1.0)
}
result.add(element)
}
return result
}
}
private var subFraction = 0.0
override fun getFraction() = subFraction
override fun setFraction(fraction: Double) {
subFraction = fraction
onFractionChange()
}
}
} | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/CodeWithMeClientDownloader.kt | 2445870620 |
fun test(list: List<String>?) {
list.for
} | plugins/kotlin/code-insight/postfix-templates/testData/expansion/for/nullable.after.kt | 1074121011 |
expect class <!LINE_MARKER("descr='Has actuals in [iosX64, sharedLinux] module'")!>ActualizedInSharedAndLeaf<!>
expect class <!LINE_MARKER("descr='Has actuals in [linuxArm64, iosX64, linuxX64] module'")!>ActualizedInLeaves<!>
| plugins/kotlin/idea/tests/testData/multiplatform/expectActualLineMarkers/common/common.kt | 1973588719 |
/*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* TachiyomiEX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package eu.kanade.tachiyomi.data.source.online.english
import android.content.Context
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.network.GET
import eu.kanade.tachiyomi.data.network.POST
import eu.kanade.tachiyomi.data.source.EN
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.regex.Pattern
class Kissmanga(override val source: Sources) : ParsedOnlineSource() {
override val baseUrl = "http://kissmanga.com"
override val lang: Language get() = EN
override fun supportsLatest() = true
override val client: OkHttpClient = network.cloudflareClient
override fun popularMangaInitialUrl() = "$baseUrl/MangaList/MostPopular"
override fun latestUpdatesInitialUrl() = "http://kissmanga.com/MangaList/LatestUpdate"
override fun popularMangaSelector() = "table.listing tr:gt(1)"
override fun popularMangaFromElement(element: Element, manga: Manga) {
element.select("td a:eq(0)").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
}
override fun popularMangaNextPageSelector() = "li > a:contains(› Next)"
override fun searchMangaRequest(page: MangasPage, query: String, filters: List<Filter>): Request {
if (page.page == 1) {
page.url = searchMangaInitialUrl(query, filters)
}
val form = FormBody.Builder().apply {
add("authorArtist", "")
add("mangaName", query)
add("status", "")
[email protected] { filter ->
add("genres", if (filter in filters) "1" else "0")
}
}
return POST(page.url, headers, form.build())
}
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/AdvanceSearch"
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element, manga: Manga) {
popularMangaFromElement(element, manga)
}
override fun searchMangaNextPageSelector() = null
override fun mangaDetailsParse(document: Document, manga: Manga) {
val infoElement = document.select("div.barContent").first()
manga.author = infoElement.select("p:has(span:contains(Author:)) > a").first()?.text()
manga.genre = infoElement.select("p:has(span:contains(Genres:)) > *:gt(0)").text()
manga.description = infoElement.select("p:has(span:contains(Summary:)) ~ p").text()
manga.status = infoElement.select("p:has(span:contains(Status:))").first()?.text().orEmpty().let { parseStatus(it) }
manga.thumbnail_url = document.select(".rightBox:eq(0) img").first()?.attr("src")
}
fun parseStatus(status: String) = when {
status.contains("Ongoing") -> Manga.ONGOING
status.contains("Completed") -> Manga.COMPLETED
else -> Manga.UNKNOWN
}
override fun chapterListSelector() = "table.listing tr:gt(1)"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("a").first()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let {
SimpleDateFormat("MM/dd/yyyy").parse(it).time
} ?: 0
}
override fun pageListRequest(chapter: Chapter) = POST(baseUrl + chapter.url, headers)
override fun pageListParse(response: Response, pages: MutableList<Page>) {
//language=RegExp
val p = Pattern.compile("""lstImages.push\("(.+?)"""")
val m = p.matcher(response.body().string())
var i = 0
while (m.find()) {
pages.add(Page(i++, "", m.group(1)))
}
}
// Not used
override fun pageListParse(document: Document, pages: MutableList<Page>) {
}
override fun imageUrlRequest(page: Page) = GET(page.url)
override fun imageUrlParse(document: Document) = ""
// $("select[name=\"genres\"]").map((i,el) => `Filter("${i}", "${$(el).next().text().trim()}")`).get().join(',\n')
// on http://kissmanga.com/AdvanceSearch
override fun getFilterList(): List<Filter> = listOf(
Filter("0", "Action"),
Filter("1", "Adult"),
Filter("2", "Adventure"),
Filter("3", "Comedy"),
Filter("4", "Comic"),
Filter("5", "Cooking"),
Filter("6", "Doujinshi"),
Filter("7", "Drama"),
Filter("8", "Ecchi"),
Filter("9", "Fantasy"),
Filter("10", "Gender Bender"),
Filter("11", "Harem"),
Filter("12", "Historical"),
Filter("13", "Horror"),
Filter("14", "Josei"),
Filter("15", "Lolicon"),
Filter("16", "Manga"),
Filter("17", "Manhua"),
Filter("18", "Manhwa"),
Filter("19", "Martial Arts"),
Filter("20", "Mature"),
Filter("21", "Mecha"),
Filter("22", "Medical"),
Filter("23", "Music"),
Filter("24", "Mystery"),
Filter("25", "One shot"),
Filter("26", "Psychological"),
Filter("27", "Romance"),
Filter("28", "School Life"),
Filter("29", "Sci-fi"),
Filter("30", "Seinen"),
Filter("31", "Shotacon"),
Filter("32", "Shoujo"),
Filter("33", "Shoujo Ai"),
Filter("34", "Shounen"),
Filter("35", "Shounen Ai"),
Filter("36", "Slice of Life"),
Filter("37", "Smut"),
Filter("38", "Sports"),
Filter("39", "Supernatural"),
Filter("40", "Tragedy"),
Filter("41", "Webtoon"),
Filter("42", "Yaoi"),
Filter("43", "Yuri")
)
} | app/src/main/java/eu/kanade/tachiyomi/data/source/online/english/Kissmanga.kt | 1050782267 |
// 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.filePrediction.features.history
import kotlin.math.max
import kotlin.math.min
class FilePredictionNGramFeatures(private val byFile: Map<String, Double>) {
private val minProbability: Double
private val maxProbability: Double
init {
var minProb = 1.0
var maxProb = 0.0
for (nGram in byFile.values) {
minProb = min(minProb, nGram)
maxProb = max(maxProb, nGram)
}
minProbability = max(minProb, 0.0001)
maxProbability = max(maxProb, 0.0001)
}
fun calculateFileFeatures(fileUrl: String): NextFileProbability? {
val probability = byFile[fileUrl]
if (probability == null) {
return null
}
val mleToMin = if (minProbability != 0.0) probability / minProbability else 0.0
val mleToMax = if (maxProbability != 0.0) probability / maxProbability else 0.0
return NextFileProbability(probability, minProbability, maxProbability, mleToMin, mleToMax)
}
} | plugins/filePrediction/src/com/intellij/filePrediction/features/history/FilePredictionNGramFeatures.kt | 2493403923 |
/*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.vmb.settings
import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.ColorInt
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import net.mm2d.android.vmb.BuildConfig
import net.mm2d.log.Logger
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class Settings private constructor(private val storage: SettingsStorage) {
var backgroundColor: Int
@ColorInt
get() = storage.readInt(Key.KEY_BACKGROUND)
set(@ColorInt color) = storage.writeInt(Key.KEY_BACKGROUND, color)
var foregroundColor: Int
@ColorInt
get() = storage.readInt(Key.KEY_FOREGROUND)
set(@ColorInt color) = storage.writeInt(Key.KEY_FOREGROUND, color)
val screenOrientation: Int
get() {
val value = storage.readString(Key.SCREEN_ORIENTATION)
if (value.isNotEmpty()) {
try {
return Integer.parseInt(value)
} catch (e: NumberFormatException) {
e.printStackTrace()
}
}
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
var useFont: Boolean
get() = storage.readBoolean(Key.USE_FONT)
set(value) = storage.writeBoolean(Key.USE_FONT, value)
var fontPath: String
get() = storage.readString(Key.FONT_PATH)
set(value) = storage.writeString(Key.FONT_PATH, value)
val fontPathToUse: String
get() = if (useFont) fontPath else ""
fun shouldUseSpeechRecognizer(): Boolean =
storage.readBoolean(Key.SPEECH_RECOGNIZER)
fun shouldShowCandidateList(): Boolean =
storage.readBoolean(Key.CANDIDATE_LIST)
fun shouldShowEditorWhenLongTap(): Boolean =
storage.readBoolean(Key.LONG_TAP_EDIT)
fun shouldShowEditorAfterSelect(): Boolean =
storage.readBoolean(Key.LIST_EDIT)
var history: Set<String>
get() = storage.readStringSet(Key.HISTORY)
set(history) = storage.writeStringSet(Key.HISTORY, history)
companion object {
private var settings: Settings? = null
private val lock: Lock = ReentrantLock()
private val condition: Condition = lock.newCondition()
/**
* Settingsのインスタンスを返す。
*
* 初期化が完了していなければブロックされる。
*/
fun get(): Settings = lock.withLock {
while (settings == null) {
if (BuildConfig.DEBUG) {
Logger.e("!!!!!!!!!! BLOCK !!!!!!!!!!")
}
if (!condition.await(1, TimeUnit.SECONDS)) {
throw IllegalStateException("Settings initialization timeout")
}
}
settings as Settings
}
/**
* アプリ起動時に一度だけコールされ、初期化を行う。
*
* @param context コンテキスト
*/
fun initialize(context: Context) {
Completable.fromAction { initializeInner(context) }
.subscribeOn(Schedulers.io())
.subscribe()
}
private fun initializeInner(context: Context) {
val storage = SettingsStorage(context)
Maintainer.maintain(storage)
lock.withLock {
settings = Settings(storage)
condition.signalAll()
}
}
}
}
| app/src/main/java/net/mm2d/android/vmb/settings/Settings.kt | 3786592905 |
class C : java.io.BufferedReader() {
override fun hashCode(): Int {
super<Buf<caret>
}
}
// INVOCATION_COUNT: 2
// ELEMENT: BufferedReader
| plugins/kotlin/completion/tests/testData/handlers/basic/SuperTypeArg.kt | 3984267186 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogProgress
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.history.FileHistoryPaths.withFileHistory
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import com.intellij.vcs.log.util.StopWatch
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference
class FileHistoryFilterer(private val logData: VcsLogData, private val logId: String) : VcsLogFilterer, Disposable {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache, logData.commitDetailsGetter, index)
private var fileHistoryTask: FileHistoryTask? = null
private val vcsLogObjectsFactory: VcsLogObjectsFactory get() = project.service()
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters)
val root = filePath?.let { VcsLogUtil.getActualRoot(project, filePath) }
val hash = getHash(filters)
if (root != null && !filePath.isDirectory) {
val result = MyWorker(root, filePath, hash).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
if (result != null) return result
}
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private fun cancelLastTask(wait: Boolean) {
fileHistoryTask?.cancel(wait)
fileHistoryTask = null
}
private fun createFileHistoryTask(vcs: AbstractVcs,
root: VirtualFile,
filePath: FilePath,
hash: Hash?,
isInitial: Boolean): FileHistoryTask {
val oldHistoryTask = fileHistoryTask
if (oldHistoryTask != null && !oldHistoryTask.isCancelled && !isInitial &&
oldHistoryTask.filePath == filePath && oldHistoryTask.hash == hash) return oldHistoryTask
cancelLastTask(false)
val factory = vcsLogObjectsFactory
val newHistoryTask = object : FileHistoryTask(vcs, filePath, hash, createProgressIndicator()) {
override fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath {
return factory.createCommitMetadataWithPath(revision as VcsFileRevisionEx, root)
}
}
fileHistoryTask = newHistoryTask
return newHistoryTask
}
private fun VcsLogObjectsFactory.createCommitMetadataWithPath(revision: VcsFileRevisionEx,
root: VirtualFile): CommitMetadataWithPath {
val commitHash = createHash(revision.revisionNumber.asString())
val metadata = createCommitMetadata(commitHash, emptyList(), revision.revisionDate.time, root,
CommitPresentationUtil.getSubject(revision.commitMessage!!),
revision.author!!, revision.authorEmail!!,
revision.commitMessage!!,
revision.committerName!!, revision.committerEmail!!, revision.authorDate!!.time)
return CommitMetadataWithPath(storage.getCommitIndex(commitHash, root), metadata,
MaybeDeletedFilePath(revision.path, revision.isDeleted))
}
private fun createProgressIndicator(): ProgressIndicator {
return logData.progress.createProgressIndicator(VcsLogProgress.ProgressKey("file history task for $logId"))
}
override fun dispose() {
cancelLastTask(true)
}
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? {
val start = System.currentTimeMillis()
TraceManager.getTracer("vcs").spanBuilder("computing history").useWithScope { scope ->
val isInitial = commitCount == CommitCountStage.INITIAL
val indexDataGetter = index.dataGetter
scope.setAttribute("filePath", filePath.toString())
if (indexDataGetter != null && index.isIndexed(root) && dataPack.isFull) {
cancelLastTask(false)
val visiblePack = filterWithIndex(indexDataGetter, dataPack, oldVisiblePack, sortType, filters, isInitial)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index")
scope.setAttribute("type", "index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters, commitCount)
scope.setAttribute("type", "history provider")
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for computing history for $filePath with history provider")
checkNotEmpty(dataPack, visiblePack, false)
return@filter Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return null
}
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): VisiblePack {
val historyHandler = logProviders[root]?.fileHistoryHandler
val isFastStart = commitCount == CommitCountStage.INITIAL && historyHandler != null
val (revisions, isDone) = if (isFastStart) {
cancelLastTask(false)
historyHandler!!.getHistoryFast(root, filePath, hash, commitCount.count).map {
vcsLogObjectsFactory.createCommitMetadataWithPath(it, root)
} to false
}
else {
createFileHistoryTask(vcs, root, filePath, hash,
(commitCount == CommitCountStage.FIRST_STEP && historyHandler != null) ||
commitCount == CommitCountStage.INITIAL).waitForRevisions()
}
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull && !isFastStart) {
val pathsMap = revisions.associate { Pair(it.commit, it.path) }
val visibleGraph = createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(pathsMap))
.apply {
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
val commits = revisions.map { GraphCommitImpl.createCommit(it.commit, emptyList(), it.metadata.timestamp) }
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(revisions.associate { Pair(it.commit, it.path) }))
.apply {
putUserData(VisiblePack.NO_GRAPH_INFORMATION, true)
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(indexDataGetter, dataPack, filters, sortType,
oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(indexDataGetter, dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
val fileHistory = FileHistory(data.buildPathsMap())
return VisiblePack(dataPack, visibleGraph, false, filters).withFileHistory(fileHistory)
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory,
removeTrivialMerges = FileHistoryBuilder.isRemoveTrivialMerges,
refine = FileHistoryBuilder.isRefine)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters).withFileHistory(fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
TraceManager.getTracer("vcs").spanBuilder("collecting renames").useWithScope {
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull { ad ->
val parentHash = storage.getCommitId(ad.parent)!!.hash
val childHash = storage.getCommitId(ad.child)!!.hash
if (ad.isAddition) handler.getRename(root, ad.filePath, parentHash, childHash)
else handler.getRename(root, ad.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
it.setAttribute("renamesSize", renames.size.toLong())
it.setAttribute("numberOfAdditionDeletions", fileHistory.unmatchedAdditionsDeletions.size.toLong())
val result = MultiMap<UnorderedPair<Int>, Rename>()
renames.forEach { rename -> result.putValue(rename.commits, rename) }
return result
}
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = logger<FileHistoryFilterer>()
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
private fun createVisibleGraph(dataPack: DataPack,
sortType: PermanentGraph.SortType,
matchingHeads: Set<Int>?,
matchingCommits: Set<Int>?): VisibleGraph<Int> {
if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) {
return EmptyVisibleGraph.getInstance()
}
return dataPack.permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) {
return map
}
if (map.isEmpty) {
return this
}
val result = MultiMap<K, V>()
result.putAllValues(this)
result.putAllValues(map)
return result
}
private data class CommitMetadataWithPath(val commit: Int, val metadata: VcsCommitMetadata, val path: MaybeDeletedFilePath)
private abstract class FileHistoryTask(val vcs: AbstractVcs, val filePath: FilePath, val hash: Hash?, val indicator: ProgressIndicator) {
private val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
private val future: Future<*>
private val _revisions = ConcurrentLinkedQueue<CommitMetadataWithPath>()
private val exception = AtomicReference<VcsException>()
@Volatile
private var lastSize = 0
val isCancelled get() = indicator.isCanceled
init {
future = AppExecutorUtil.getAppExecutorService().submit {
ProgressManager.getInstance().runProcess(Runnable {
try {
VcsCachingHistory.collect(vcs, filePath, revisionNumber) { revision ->
_revisions.add(createCommitMetadataWithPath(revision))
}
}
catch (e: VcsException) {
exception.set(e)
}
}, indicator)
}
}
protected abstract fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath
@Throws(VcsException::class)
fun waitForRevisions(): Pair<List<CommitMetadataWithPath>, Boolean> {
throwOnError()
while (_revisions.size == lastSize) {
try {
future.get(100, TimeUnit.MILLISECONDS)
ProgressManager.checkCanceled()
throwOnError()
return Pair(getRevisionsSnapshot(), true)
}
catch (_: TimeoutException) {
}
}
return Pair(getRevisionsSnapshot(), false)
}
private fun getRevisionsSnapshot(): List<CommitMetadataWithPath> {
val list = _revisions.toList()
lastSize = list.size
return list
}
@Throws(VcsException::class)
private fun throwOnError() {
if (exception.get() != null) throw VcsException(exception.get())
}
fun cancel(wait: Boolean) {
indicator.cancel()
if (wait) {
try {
future.get(20, TimeUnit.MILLISECONDS)
}
catch (_: Throwable) {
}
}
}
}
| platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt | 3471944160 |
// 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.actions
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.RightGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.usageView.UsageViewBundle
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.JBUI
import com.intellij.xml.util.XmlStringUtil
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import javax.swing.JLabel
internal class ShowUsagesHeader(pinButton: JComponent, @NlsContexts.PopupTitle title: String) {
@JvmField
val panel: DialogPanel
private lateinit var titleLabel: JLabel
private lateinit var processIcon: AsyncProcessIcon
private lateinit var statusLabel: JLabel
init {
panel = panel {
customizeSpacingConfiguration(spacingConfiguration = object : IntelliJSpacingConfiguration() {
// Remove default vertical gap around cells, so the header can be smaller
override val verticalComponentGap: Int
get() = 0
}) {
row {
// Don't use Row.label method: it processes mnemonics and breaks symbol &
val titleCell = cell(JLabel(XmlStringUtil.wrapInHtml("<body><nobr>$title</nobr></body>")))
.resizableColumn()
.gap(RightGap.SMALL)
titleLabel = titleCell.component
processIcon = cell(AsyncProcessIcon("xxx"))
.gap(RightGap.SMALL)
.component
val statusCell = label("")
statusLabel = statusCell.component
val pinCell = cell(pinButton)
if (ExperimentalUI.isNewUI()) {
val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets()
titleCell.customize(Gaps(top = headerInsets.top, bottom = headerInsets.bottom, right = JBUI.scale(12)))
statusCell.component.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND
statusCell.customize(JBGaps(right = 8))
// Fix vertical alignment for the pin icon
pinCell.customize(JBGaps(top = 2))
}
else {
statusCell.gap(RightGap.SMALL)
}
}
}
}
}
fun setStatusText(hasMore: Boolean, visibleCount: Int, totalCount: Int) {
statusLabel.text = getStatusString(!processIcon.isDisposed, hasMore, visibleCount, totalCount)
}
fun disposeProcessIcon() {
Disposer.dispose(processIcon)
processIcon.parent?.apply {
remove(processIcon)
repaint()
}
}
@NlsContexts.PopupTitle
fun getTitle(): String {
return titleLabel.text
}
private fun getStatusString(findUsagesInProgress: Boolean, hasMore: Boolean, visibleCount: Int, totalCount: Int): @Nls String {
return if (findUsagesInProgress || hasMore) {
UsageViewBundle.message("showing.0.usages", visibleCount - if (hasMore) 1 else 0)
}
else if (visibleCount != totalCount) {
UsageViewBundle.message("showing.0.of.1.usages", visibleCount, totalCount)
}
else {
UsageViewBundle.message("found.0.usages", totalCount)
}
}
} | platform/lang-impl/src/com/intellij/find/actions/ShowUsagesHeader.kt | 3658712052 |
import dependency.X
import dependency.Y
import dependency.Z
fun foo(s: String, x: X, y: Y, z: Z) {
if (s in <caret>)
}
// EXIST: x
// EXIST: y
// ABSENT: z
| plugins/kotlin/completion/tests/testData/smartMultiFile/NotImportedContains/NotImportedContains.kt | 41487656 |
fun foo1 (bar: Int) { print(bar.hashCode()) }
fun foo2 (bar: kotlin.Int) { print(bar.hashCode()) }
<warning descr="SSR">fun foo3 (bar: Int?) { print(bar.hashCode()) }</warning>
fun foo4 (bar: (Int) -> Int) { print(bar.hashCode()) } | plugins/kotlin/idea/tests/testData/structuralsearch/typeReference/nullableType.kt | 3101077842 |
// 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.parameterInfo
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
fun check(text: String) {
myFixture.configureByText("A.kt", text)
myFixture.testInlays()
}
fun `test insert literal arguments`() {
check(
"""
fun test(file: File) {
val testNow = System.currentTimeMillis() > 34000
val times = 1
val pi = 4.0f
val title = "Testing..."
val ch = 'q';
configure(<hint text="testNow:" />true, <hint text="times:" />555, <hint text="pii:" />3.141f, <hint text="title:" />"Huge Title", <hint text="terminate:" />'c', <hint text="file:" />null)
configure(testNow, shouldIgnoreRoots(), fourteen, pi, title, c, file)
}
fun configure(testNow: Boolean, times: Int, pii: Float, title: String, terminate: Char, file: File) {
System.out.println()
System.out.println()
}"""
)
}
fun `test do not show for Exceptions`() {
check(
"""
fun test() {
val t = IllegalStateException("crime");
}"""
)
}
fun `test single varargs hint`() {
check(
"""
fun main() {
testBooleanVarargs(<hint text="test:" />13, <hint text="...booleans:" />false)
}
fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean {
return false
}
}
"""
)
}
fun `test no hint if varargs null`() {
check(
"""
fun main() {
testBooleanVarargs(<hint text="test:" />13)
}
fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean {
return false
}
"""
)
}
fun `test multiple vararg hint`() {
check(
"""
fun main() {
testBooleanVarargs(<hint text="test:" />13, <hint text="...booleans:" />false, true, false)
}
fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean {
return false
}
"""
)
}
fun `test inline positive and negative numbers`() {
check(
"""
fun main() {
val obj = Any()
count(<hint text="test:"/>-1, obj);
count(<hint text="test:"/>+1, obj);
}
fun count(test: Int, obj: Any) {
}
}
"""
)
}
fun `test show ambiguous`() {
check(
"""
fun main() {
test(<hint text="a:"/>10, x);
}
fun test(a: Int, bS: String) {}
fun test(a: Int, bI: Int) {}
"""
)
}
fun `test show non-ambiguous overload`() {
check(
"""
fun main() {
test(<hint text="a:"/>10, <hint text="bI:"/>15);
}
fun test() {}
fun test(a: Int, bS: String) {}
fun test(a: Int, bI: Int) {}
"""
)
}
fun `test show ambiguous constructor`() {
check(
"""
fun main() {
X(<hint text="a:"/>10, x);
}
}
class X {
constructor(a: Int, bI: Int) {}
constructor(a: Int, bS: String) {}
}
"""
)
}
fun `test invoke`() {
check(
"""
fun main() {
val x = X()
x(<hint text="a:"/>10, x);
}
}
class X {
operator fun invoke(a: Int, bI: Int) {}
}
"""
)
}
fun `test annotation`() {
check(
"""
annotation class ManyArgs(val name: String, val surname: String)
@ManyArgs(<hint text="name:"/>"Ilya", <hint text="surname:"/>"Sergey") class AnnotatedMuch
"""
)
}
fun `test functional type`() {
check(
"""
fun <T> T.test(block: (T) -> Unit) = block(this)
"""
)
}
fun `test functional type with parameter name`() {
check(
"""
fun <T> T.test(block: (receiver: T, Int) -> Unit) = block(<hint text="receiver:"/>this, 0)
"""
)
}
fun `test dynamic`() {
check(
"""fun foo(x: dynamic) {
x.foo("123")
}"""
)
}
fun `test spread`() {
check(
"""fun foo(vararg x: Int) {
intArrayOf(1, 0).apply { foo(<hint text="...x:" />*this) }
}"""
)
}
fun `test line break`() {
check(
"""fun foo(vararg x: Int) {
foo(<hint text="...x:" />
1,
2,
3
) }
}"""
)
}
fun `test incomplete Pair call`() {
check("val x = Pair(1, )")
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt | 419460972 |
// WITH_STDLIB
// INTENTION_TEXT: "Replace with 'filterTo(){}'"
// IS_APPLICABLE_2: false
fun foo(list: List<String>) {
val target = createCollection()
<caret>for (s in list) {
if (s.length > 0)
target.add(s)
}
}
fun createCollection() = java.util.ArrayList<String>() | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/filter/filterTo2.kt | 2329298408 |
// 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.stackFrame
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.xdebugger.frame.XStackFrame
import com.sun.jdi.Location
import com.sun.jdi.Method
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.getBorders
import org.jetbrains.kotlin.load.java.JvmAbi
object InlineStackTraceCalculator {
fun calculateInlineStackTrace(frameProxy: StackFrameProxyImpl): List<XStackFrame> {
val location = frameProxy.safeLocation() ?: return emptyList()
val method = location.safeMethod() ?: return emptyList()
val inlineStackFramesInfo = method.getInlineStackFramesInfo(location)
if (inlineStackFramesInfo.isEmpty()) {
return emptyList()
}
val allLocations = method.safeAllLineLocations()
if (allLocations.isEmpty()) {
return emptyList()
}
inlineStackFramesInfo.fetchDepths()
val newFrameProxyLocation = inlineStackFramesInfo.fetchLocationsAndGetNewFrameProxyLocation(allLocations, location)
return createInlineStackFrames(inlineStackFramesInfo, frameProxy, newFrameProxyLocation)
}
private fun createInlineStackFrames(
inlineStackFramesInfo: List<InlineStackFrameInfo>,
frameProxy: StackFrameProxyImpl,
frameProxyLocation: Location
): MutableList<KotlinStackFrame> {
val stackFrames = mutableListOf<KotlinStackFrame>()
var variableHolder: InlineStackFrameVariableHolder? =
InlineStackFrameVariableHolder.fromStackFrame(frameProxy)
for (info in inlineStackFramesInfo.asReversed()) {
stackFrames.add(
info.toInlineStackFrame(
frameProxy,
variableHolder.getVisibleVariables()
)
)
variableHolder = variableHolder?.parentFrame
}
val originalFrame = KotlinStackFrameWithProvidedVariables(
safeInlineStackFrameProxy(frameProxyLocation, 0, frameProxy),
variableHolder.getVisibleVariables()
)
stackFrames.add(originalFrame)
return stackFrames
}
private fun Method.getInlineStackFramesInfo(location: Location) =
getInlineFunctionInfos()
.filter { it.contains(location) }
.sortedBy { it.borders.start }
.map { InlineStackFrameInfo(it, location, 0) }
private fun Method.getInlineFunctionInfos(): List<AbstractInlineFunctionInfo> {
val localVariables = safeVariables() ?: return emptyList()
val inlineFunctionInfos = mutableListOf<AbstractInlineFunctionInfo>()
for (variable in localVariables) {
val borders = variable.getBorders() ?: continue
val variableName = variable.name()
if (variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
inlineFunctionInfos.add(InlineFunctionInfo(variableName, borders))
} else if (variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT)) {
inlineFunctionInfos.add(InlineLambdaInfo(variableName, borders))
}
}
return inlineFunctionInfos
}
// Consider the following example:
// inline fun baz() = 1 // Breakpoint
// inline fun bar(f: () -> Unit) = f()
// inline fun foo(f: () -> Unit) = bar { f() }
// fun main() = foo { baz() }
// The depth of an inline lambda is equal to the depth of a method where it was declared.
// Inline function infos should be listed according to the function call order,
// so that depths of inline lambdas could be calculated correctly.
// The method will produce the following depths:
// foo -> 1
// bar -> 2
// $i$a$-bar-MainKt$foo$1$iv -> 1
// $i$a$-foo-MainKt$main$1 -> 0
// baz -> 1
private fun List<InlineStackFrameInfo>.fetchDepths() {
var currentDepth = 0
val depths = mutableMapOf<String, Int>()
for (inlineStackFrameInfo in this) {
val inlineFunctionInfo = inlineStackFrameInfo.inlineFunctionInfo
val calculatedDepth =
if (inlineFunctionInfo is InlineLambdaInfo) {
inlineFunctionInfo.getDeclarationFunctionName()
?.let { depths[it] }
?: 0 // The lambda was declared in the top frame
} else {
currentDepth + 1
}
depths[inlineFunctionInfo.name] = calculatedDepth
inlineStackFrameInfo.depth = calculatedDepth
currentDepth = calculatedDepth
}
}
private fun List<InlineStackFrameInfo>.fetchLocationsAndGetNewFrameProxyLocation(
allLocations: List<Location>,
originalLocation: Location
): Location {
val iterator = allLocations.iterator()
val newFrameProxyLocation =
iterator.getInlineFunctionCallLocation(first().inlineFunctionInfo)
?: originalLocation
var inlineStackFrameIndex = 1
var prevLocation = originalLocation
for (location in iterator) {
if (inlineStackFrameIndex > lastIndex) {
break
}
if (this[inlineStackFrameIndex].inlineFunctionInfo.contains(location)) {
this[inlineStackFrameIndex - 1].location = prevLocation
inlineStackFrameIndex++
}
prevLocation = location
}
last().location = originalLocation
return newFrameProxyLocation
}
private fun Iterator<Location>.getInlineFunctionCallLocation(inlineFunctionInfo: AbstractInlineFunctionInfo): Location? {
var prevLocation: Location? = null
for (location in this) {
if (inlineFunctionInfo.contains(location)) {
return prevLocation
}
prevLocation = location
}
return null
}
private fun InlineStackFrameVariableHolder?.getVisibleVariables() =
this?.visibleVariables.orEmpty()
}
private data class InlineStackFrameInfo(val inlineFunctionInfo: AbstractInlineFunctionInfo, var location: Location, var depth: Int) {
fun toInlineStackFrame(
frameProxy: StackFrameProxyImpl,
visibleVariables: List<LocalVariableProxyImpl>
) =
InlineStackFrame(
location,
inlineFunctionInfo.getDisplayName(),
frameProxy,
depth,
visibleVariables
)
}
private abstract class AbstractInlineFunctionInfo(val name: String, val borders: ClosedRange<Location>) {
abstract fun getDisplayName(): String
fun contains(location: Location) =
location in borders
}
private class InlineFunctionInfo(
name: String,
borders: ClosedRange<Location>
) : AbstractInlineFunctionInfo(
name.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION),
borders
) {
override fun getDisplayName() = name
}
private class InlineLambdaNameWrapper(name: String) {
companion object {
private val inlineLambdaRegex =
"${JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT.replace("$", "\\$")}-(.+)-[^\$]+\\$([^\$]+)\\$.*"
.toRegex()
}
private val groupValues = inlineLambdaRegex.matchEntire(name)?.groupValues
val lambdaName = groupValues?.getOrNull(1)
val declarationFunctionName = groupValues?.getOrNull(2)
fun isValid() =
groupValues != null
}
private class InlineLambdaInfo(name: String, borders: ClosedRange<Location>) : AbstractInlineFunctionInfo(name, borders) {
private val nameWrapper = InlineLambdaNameWrapper(name)
override fun getDisplayName(): String {
if (!nameWrapper.isValid()) {
return name
}
return "lambda '${nameWrapper.lambdaName}' in '${nameWrapper.declarationFunctionName}'"
}
fun getDeclarationFunctionName(): String? =
nameWrapper.declarationFunctionName
}
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stackFrame/InlineStackTraceCalculator.kt | 1597054948 |
package a
import a.A.X
fun bar(s: String) {
val t: X = A().X { s }
} | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveInnerToTop/moveNestedClassToTopLevelInTheSamePackageAndAddOuterInstanceWithLambda/before/a/specificImport.kt | 2238720889 |
// SET_TRUE: ALIGN_MULTILINE_EXTENDS_LIST
enum class EnumTest(val value: Int) {
VALUE_1(
value = 0
)
}
| plugins/kotlin/idea/tests/testData/formatter/ExtendsListAlignEnum.after.kt | 3502759356 |
package extractVariablesFromCall
fun main(args: Array<String>) {
val a = 1
val s = "str"
val klass = MyClass()
//Breakpoint!
val c = 0
}
fun f1(i: Int, s: String) = i + s.length
infix fun Int.f2(s: String) = this + s.length
class MyClass {
fun f1(i: Int, s: String) = i + s.length
}
// EXPRESSION: f1(a, s)
// RESULT: 4: I
// EXPRESSION: a.f2(s)
// RESULT: 4: I
// EXPRESSION: a f2 s
// RESULT: 4: I
// EXPRESSION: klass.f1(a, s)
// RESULT: 4: I
| plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/extractVariablesFromCall.kt | 328423362 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.protocolReader
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
const val TYPE_FACTORY_NAME_PREFIX: Char = 'F'
const val READER_NAME: String = "reader"
const val PENDING_INPUT_READER_NAME: String = "inputReader"
const val JSON_READER_CLASS_NAME: String = "JsonReaderEx"
val JSON_READER_PARAMETER_DEF: String = "$READER_NAME: $JSON_READER_CLASS_NAME"
/**
* Generate Java type name of the passed type. Type may be parameterized.
*/
internal fun writeJavaTypeName(arg: Type, out: TextOutput) {
if (arg is Class<*>) {
val name = arg.canonicalName
out.append(
if (name == "java.util.List") "List"
else if (name == "java.lang.String") "String?"
else name
)
}
else if (arg is ParameterizedType) {
writeJavaTypeName(arg.rawType, out)
out.append('<')
val params = arg.actualTypeArguments
for (i in params.indices) {
if (i != 0) {
out.comma()
}
writeJavaTypeName(params[i], out)
}
out.append('>')
}
else if (arg is WildcardType) {
val upperBounds = arg.upperBounds!!
if (upperBounds.size != 1) {
throw RuntimeException()
}
out.append("? extends ")
writeJavaTypeName(upperBounds.first(), out)
}
else {
out.append(arg.toString())
}
} | platform/script-debugger/protocol/protocol-reader/src/Util.kt | 792281055 |
// "Wrap element with 'sequenceOf()' call" "true"
// WITH_STDLIB
fun foo(a: String) {
bar(a<caret>)
}
fun bar(a: Sequence<String>) {}
| plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/toSequence.kt | 665037710 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.dsl
import com.intellij.codeInsight.documentation.DocumentationComponent
import com.intellij.codeInsight.documentation.DocumentationEditorPane
import com.intellij.codeInsight.documentation.QuickDocUtil.isDocumentationV2Enabled
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.WindowStateService
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.TextWithMnemonic
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.ui.ScreenUtil
import com.intellij.ui.content.Content
import com.intellij.ui.tabs.impl.JBTabsImpl
import com.intellij.usageView.UsageViewContentManager
import com.intellij.util.messages.Topic
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebuggerManager
import org.assertj.swing.timing.Timeout
import org.jetbrains.annotations.Nls
import training.dsl.LessonUtil.checkExpectedStateOfEditor
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.ui.*
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.getActionById
import training.util.learningToolWindow
import java.awt.*
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import javax.swing.JList
import javax.swing.KeyStroke
object LessonUtil {
val productName: String get() {
return ApplicationNamesInfo.getInstance().fullProductName
}
fun getHelpLink(topic: String): String = getHelpLink(null, topic)
fun getHelpLink(ide: String?, topic: String): String {
val helpIdeName: String = ide ?: when (val name = ApplicationNamesInfo.getInstance().productName) {
"GoLand" -> "go"
"RubyMine" -> "ruby"
"AppCode" -> "objc"
else -> name.lowercase(Locale.ENGLISH)
}
return "https://www.jetbrains.com/help/$helpIdeName/$topic"
}
fun hideStandardToolwindows(project: Project) {
val windowManager = ToolWindowManager.getInstance(project)
for (id in windowManager.toolWindowIds) {
if (id != LearnToolWindowFactory.LEARN_TOOL_WINDOW) {
windowManager.getToolWindow(id)?.hide()
}
}
}
fun insertIntoSample(sample: LessonSample, inserted: String): String {
return sample.text.substring(0, sample.startOffset) + inserted + sample.text.substring(sample.startOffset)
}
/**
* Checks that user edited sample text, moved caret to any place of editor or changed selection
*/
fun TaskContext.restoreIfModifiedOrMoved(sample: LessonSample? = null) {
proposeRestore {
checkPositionOfEditor(sample ?: previous.sample)
}
}
/**
* Checks that user edited sample text, moved caret to any place of editor or changed selection
*/
fun TaskContext.restoreIfModified(sample: LessonSample? = null) {
proposeRestore {
checkExpectedStateOfEditor(sample ?: previous.sample, false)
}
}
/**
* Checks that user edited sample text or moved caret outside of [possibleCaretArea] text
*/
fun TaskContext.restoreIfModifiedOrMovedIncorrectly(possibleCaretArea: String, sample: LessonSample? = null) {
proposeRestore {
checkPositionOfEditor(sample ?: previous.sample) {
checkCaretOnText(possibleCaretArea)
}
}
}
fun TaskRuntimeContext.checkPositionOfEditor(sample: LessonSample,
checkCaret: TaskRuntimeContext.(LessonSample) -> Boolean = { checkCaretValid(it) }
): TaskContext.RestoreNotification? {
return checkExpectedStateOfEditor(sample, false)
?: if (!checkCaret(sample)) sampleRestoreNotification(TaskContext.CaretRestoreProposal, sample) else null
}
private fun TaskRuntimeContext.checkCaretValid(sample: LessonSample): Boolean {
val selection = sample.selection
val currentCaret = editor.caretModel.currentCaret
return if (selection != null && selection.first != selection.second) {
currentCaret.selectionStart == selection.first && currentCaret.selectionEnd == selection.second
}
else currentCaret.offset == sample.startOffset
}
private fun TaskRuntimeContext.checkCaretOnText(text: String): Boolean {
val caretOffset = editor.caretModel.offset
val textStartOffset = editor.document.charsSequence.indexOf(text)
if (textStartOffset == -1) return false
val textEndOffset = textStartOffset + text.length
return caretOffset in textStartOffset..textEndOffset
}
fun TaskRuntimeContext.checkExpectedStateOfEditor(sample: LessonSample,
checkPosition: Boolean = true,
checkModification: (String) -> Boolean = { it.isEmpty() }): TaskContext.RestoreNotification? {
val prefix = sample.text.substring(0, sample.startOffset)
val postfix = sample.text.substring(sample.startOffset)
val docText = editor.document.charsSequence
val message = if (docText.startsWith(prefix) && docText.endsWith(postfix)) {
val middle = docText.subSequence(prefix.length, docText.length - postfix.length).toString()
if (checkModification(middle)) {
val offset = editor.caretModel.offset
if (!checkPosition || (prefix.length <= offset && offset <= prefix.length + middle.length)) {
null
}
else {
TaskContext.CaretRestoreProposal
}
}
else {
TaskContext.ModificationRestoreProposal
}
}
else {
TaskContext.ModificationRestoreProposal
}
return if (message != null) sampleRestoreNotification(message, sample) else null
}
fun TaskRuntimeContext.sampleRestoreNotification(@Nls message: String, sample: LessonSample) =
TaskContext.RestoreNotification(message) { setSample(sample) }
fun findItem(ui: JList<*>, checkList: (item: Any) -> Boolean): Int? {
for (i in 0 until ui.model.size) {
val elementAt = ui.model.getElementAt(i)
if (elementAt != null && checkList(elementAt)) {
return i
}
}
return null
}
fun setEditorReadOnly(editor: Editor) {
if (editor !is EditorEx) return
editor.isViewer = true
EditorModificationUtil.setReadOnlyHint(editor, LearnBundle.message("learn.task.read.only.hint"))
}
fun actionName(actionId: String): @NlsActions.ActionText String {
val name = getActionById(actionId).templatePresentation.text?.replace("...", "")
return "<strong>${name}</strong>"
}
/**
* Use constants from [java.awt.event.KeyEvent] as keyCode.
* For example: rawKeyStroke(KeyEvent.VK_SHIFT)
*/
fun rawKeyStroke(keyCode: Int): String = rawKeyStroke(KeyStroke.getKeyStroke(keyCode, 0))
fun rawKeyStroke(keyStroke: KeyStroke): String {
return " <raw_shortcut>$keyStroke</raw_shortcut> "
}
fun rawEnter(): String = rawKeyStroke(KeyEvent.VK_ENTER)
fun rawCtrlEnter(): String {
return if (SystemInfo.isMac) {
rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.META_DOWN_MASK))
}
else {
rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK))
}
}
fun checkToolbarIsShowing(ui: ActionButton): Boolean {
// Some buttons are duplicated to several tab-panels. It is a way to find an active one.
val parentOfType = UIUtil.getParentOfType(JBTabsImpl.Toolbar::class.java, ui)
val location = parentOfType?.location
val x = location?.x
return x != 0
}
val breakpointXRange: (width: Int) -> IntRange = { IntRange(20, it - 27) }
fun LessonContext.highlightBreakpointGutter(xRange: (width: Int) -> IntRange = breakpointXRange,
logicalPosition: () -> LogicalPosition
) {
task {
triggerByPartOfComponent<EditorGutterComponentEx> l@{ ui ->
if (CommonDataKeys.EDITOR.getData(ui as DataProvider) != editor) return@l null
val y = editor.visualLineToY(editor.logicalToVisualPosition(logicalPosition()).line)
val range = xRange(ui.width)
return@l Rectangle(range.first, y, range.last - range.first + 1, editor.lineHeight)
}
}
}
/**
* Should be called after task with detection of UI element inside desired window to adjust
* @return location of window before adjustment
*/
fun TaskRuntimeContext.adjustPopupPosition(windowKey: String): Point? {
val window = UIUtil.getWindow(previous.ui) ?: return null
val previousWindowLocation = WindowStateService.getInstance(project).getLocation(windowKey)
return if (adjustPopupPosition(project, window)) previousWindowLocation else null
}
fun restorePopupPosition(project: Project, windowKey: String, savedLocation: Point?) {
if (savedLocation != null) invokeLater {
WindowStateService.getInstance(project).putLocation(windowKey, savedLocation)
}
}
fun adjustPopupPosition(project: Project, popupWindow: Window): Boolean {
val learningToolWindow = learningToolWindow(project) ?: return false
val learningComponent = learningToolWindow.component
val learningRectangle = Rectangle(learningComponent.locationOnScreen, learningToolWindow.component.size)
val popupBounds = popupWindow.bounds
val screenRectangle = ScreenUtil.getScreenRectangle(learningComponent)
if (!learningRectangle.intersects(popupBounds)) return false // ok, no intersection
if (!screenRectangle.contains(learningRectangle)) return false // we can make some strange moves in this case
if (learningRectangle.width + popupBounds.width > screenRectangle.width) return false // some huge sizes
when (learningToolWindow.anchor) {
ToolWindowAnchor.LEFT -> {
val rightScreenBorder = screenRectangle.x + screenRectangle.width
val expectedRightPopupBorder = learningRectangle.x + learningRectangle.width + popupBounds.width
if (expectedRightPopupBorder > rightScreenBorder) {
val mainWindow = UIUtil.getParentOfType(IdeFrameImpl::class.java, learningComponent) ?: return false
mainWindow.location = Point(mainWindow.location.x - (expectedRightPopupBorder - rightScreenBorder), mainWindow.location.y)
popupWindow.location = Point(rightScreenBorder - popupBounds.width, popupBounds.y)
}
else {
popupWindow.location = Point(learningRectangle.x + learningRectangle.width, popupBounds.y)
}
}
ToolWindowAnchor.RIGHT -> {
val learningScreenOffset = learningRectangle.x - screenRectangle.x
if (popupBounds.width > learningScreenOffset) {
val mainWindow = UIUtil.getParentOfType(IdeFrameImpl::class.java, learningComponent) ?: return false
mainWindow.location = Point(mainWindow.location.x + (popupBounds.width - learningScreenOffset), mainWindow.location.y)
popupWindow.location = Point(screenRectangle.x, popupBounds.y)
}
else {
popupWindow.location = Point(learningRectangle.x - popupBounds.width, popupBounds.y)
}
}
else -> return false
}
return true
}
inline fun<reified T: Component> findUiParent(start: Component, predicate: (Component) -> Boolean): T? {
if (start is T && predicate(start)) return start
var ui: Container? = start.parent
while (ui != null) {
if (ui is T && predicate(ui)) {
return ui
}
ui = ui.parent
}
return null
}
fun returnToWelcomeScreenRemark(): String {
val isSingleProject = ProjectManager.getInstance().openProjects.size == 1
return if (isSingleProject) LessonsBundle.message("onboarding.return.to.welcome.remark") else ""
}
fun showFeedbackNotification(lesson: Lesson, project: Project) {
invokeLater {
if (project.isDisposed) {
return@invokeLater
}
lesson.module.primaryLanguage?.let { langSupport ->
// exit link will show notification directly and reset this field to null
langSupport.onboardingFeedbackData?.let {
showOnboardingFeedbackNotification(project, it)
}
langSupport.onboardingFeedbackData = null
}
}
}
}
fun LessonContext.firstLessonCompletedMessage() {
text(LessonsBundle.message("goto.action.propose.to.go.next.new.ui", LessonUtil.rawEnter()))
}
fun LessonContext.highlightDebugActionsToolbar() {
task {
before {
LearningUiHighlightingManager.clearHighlights()
}
highlightToolbarWithAction(ActionPlaces.DEBUGGER_TOOLBAR, "Resume", clearPreviousHighlights = false)
if (!Registry.`is`("debugger.new.tool.window.layout")) {
highlightToolbarWithAction(ActionPlaces.DEBUGGER_TOOLBAR, "ShowExecutionPoint", clearPreviousHighlights = false)
}
}
}
private fun TaskContext.highlightToolbarWithAction(place: String, actionId: String, clearPreviousHighlights: Boolean = true) {
val needAction = getActionById(actionId)
triggerByUiComponentAndHighlight(usePulsation = true, clearPreviousHighlights = clearPreviousHighlights) { ui: ActionToolbarImpl ->
if (ui.size.let { it.width > 0 && it.height > 0 } && ui.place == place) {
ui.components.filterIsInstance<ActionButton>().any { it.action == needAction }
}
else false
}
}
fun TaskContext.proceedLink(additionalAbove: Int = 0) {
val gotIt = CompletableFuture<Boolean>()
runtimeText {
removeAfterDone = true
textProperties = TaskTextProperties(UISettings.instance.taskInternalParagraphAbove + additionalAbove, 12)
LessonsBundle.message("proceed.to.the.next.step", LearningUiManager.addCallback { gotIt.complete(true) })
}
addStep(gotIt)
test {
clickLessonMessagePaneLink("Click to proceed")
}
}
/**
* Will click on the first occurrence of [linkText] in the [LessonMessagePane]
*/
fun TaskTestContext.clickLessonMessagePaneLink(linkText: String) {
ideFrame {
val lessonMessagePane = findComponentWithTimeout(defaultTimeout) { _: LessonMessagePane -> true }
val offset = lessonMessagePane.text.indexOf(linkText)
if (offset == -1) error("Not found '$linkText' in the LessonMessagePane")
val rect = lessonMessagePane.modelToView2D(offset + linkText.length / 2)
robot.click(lessonMessagePane, Point(rect.centerX.toInt(), rect.centerY.toInt()))
}
}
fun TaskContext.proposeRestoreForInvalidText(needToType: String) {
proposeRestore {
checkExpectedStateOfEditor(previous.sample) {
needToType.contains(it.replace(" ", ""))
}
}
}
fun TaskContext.checkToolWindowState(toolWindowId: String, isShowing: Boolean) {
addFutureStep {
subscribeForMessageBus(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
val toolWindow = toolWindowManager.getToolWindow(toolWindowId)
if (toolWindow == null && !isShowing || toolWindow?.isVisible == isShowing) {
completeStep()
}
}
})
}
}
fun <L : Any> TaskRuntimeContext.subscribeForMessageBus(topic: Topic<L>, handler: L) {
project.messageBus.connect(taskDisposable).subscribe(topic, handler)
}
fun TaskRuntimeContext.lineWithBreakpoints(): Set<Int> {
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
return breakpointManager.allBreakpoints.filter {
val file = FileDocumentManager.getInstance().getFile(editor.document)
it.sourcePosition?.file == file
}.mapNotNull {
it.sourcePosition?.line
}.toSet()
}
val defaultRestoreDelay: Int
get() = Registry.intValue("ift.default.restore.delay")
/**
* @param [restoreId] where to restore, `null` means the previous task
* @param [restoreRequired] returns true iff restore is needed
*/
fun TaskContext.restoreAfterStateBecomeFalse(restoreId: TaskContext.TaskId? = null,
restoreRequired: TaskRuntimeContext.() -> Boolean) {
var restoreIsPossible = false
restoreState(restoreId) {
val required = restoreRequired()
(restoreIsPossible && required).also { restoreIsPossible = restoreIsPossible || !required }
}
}
fun TaskRuntimeContext.closeAllFindTabs() {
val usageViewManager = UsageViewContentManager.getInstance(project)
var selectedContent: Content?
while (usageViewManager.selectedContent.also { selectedContent = it } != null) {
usageViewManager.closeContent(selectedContent!!)
}
}
fun @Nls String.dropMnemonic(): @Nls String {
return TextWithMnemonic.parse(this).dropMnemonic(true).text
}
fun TaskContext.waitSmartModeStep() {
val future = CompletableFuture<Boolean>()
addStep(future)
DumbService.getInstance(project).runWhenSmart {
future.complete(true)
}
}
private val seconds01 = Timeout.timeout(1, TimeUnit.SECONDS)
fun LessonContext.showWarningIfInplaceRefactoringsDisabled() {
task {
val step = stateCheck {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled
}
val callbackId = LearningUiManager.addCallback {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled = true
step.complete(true)
}
showWarning(LessonsBundle.message("refactorings.change.settings.warning.message", action("ShowSettings"),
strong(OptionsBundle.message("configurable.group.editor.settings.display.name")),
strong(ApplicationBundle.message("title.code.editing")),
strong(ApplicationBundle.message("radiobutton.rename.local.variables.inplace")),
strong(ApplicationBundle.message("radiogroup.rename.local.variables").dropLast(1)),
callbackId)
) {
!EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled
}
}
}
fun LessonContext.restoreRefactoringOptionsInformer() {
if (EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled) return
restoreChangedSettingsInformer {
EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled = false
}
}
fun LessonContext.restoreChangedSettingsInformer(restoreSettings: () -> Unit) {
task {
runtimeText {
val newMessageIndex = LessonManager.instance.messagesNumber()
val callbackId = LearningUiManager.addCallback {
restoreSettings()
LessonManager.instance.removeMessageAndRepaint(newMessageIndex)
}
LessonsBundle.message("restore.settings.informer", callbackId)
}
}
}
fun LessonContext.highlightButtonById(actionId: String, clearHighlights: Boolean = true): CompletableFuture<Boolean> {
val feature: CompletableFuture<Boolean> = CompletableFuture()
val needToFindButton = getActionById(actionId)
prepareRuntimeTask {
if (clearHighlights) {
LearningUiHighlightingManager.clearHighlights()
}
invokeInBackground {
val result = try {
LearningUiUtil.findAllShowingComponentWithTimeout(project, ActionButton::class.java, seconds01) { ui ->
ui.action == needToFindButton && LessonUtil.checkToolbarIsShowing(ui)
}
}
catch (e: Throwable) {
// Just go to the next step if we cannot find needed button (when this method is used as pass trigger)
feature.complete(false)
throw IllegalStateException("Cannot find button for $actionId", e)
}
taskInvokeLater {
feature.complete(result.isNotEmpty())
for (button in result) {
val options = LearningUiHighlightingManager.HighlightingOptions(usePulsation = true, clearPreviousHighlights = false)
LearningUiHighlightingManager.highlightComponent(button, options)
}
}
}
}
return feature
}
inline fun <reified ComponentType : Component> LessonContext.highlightAllFoundUi(
clearPreviousHighlights: Boolean = true,
highlightInside: Boolean = true,
usePulsation: Boolean = false,
crossinline finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean
) {
val componentClass = ComponentType::class.java
@Suppress("DEPRECATION")
highlightAllFoundUiWithClass(componentClass, clearPreviousHighlights, highlightInside, usePulsation) {
finderFunction(it)
}
}
@Deprecated("Use inline form instead")
fun <ComponentType : Component> LessonContext.highlightAllFoundUiWithClass(componentClass: Class<ComponentType>,
clearPreviousHighlights: Boolean,
highlightInside: Boolean,
usePulsation: Boolean,
finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) {
prepareRuntimeTask {
if (clearPreviousHighlights) LearningUiHighlightingManager.clearHighlights()
invokeInBackground {
val result =
LearningUiUtil.findAllShowingComponentWithTimeout(project, componentClass, seconds01) { ui ->
finderFunction(ui)
}
taskInvokeLater {
for (ui in result) {
val options = LearningUiHighlightingManager.HighlightingOptions(clearPreviousHighlights = false,
highlightInside = highlightInside,
usePulsation = usePulsation)
LearningUiHighlightingManager.highlightComponent(ui, options)
}
}
}
}
}
fun TaskContext.triggerOnQuickDocumentationPopup() {
if (isDocumentationV2Enabled()) {
triggerByUiComponentAndHighlight(false, false) { _: DocumentationEditorPane -> true }
}
else {
triggerByUiComponentAndHighlight(false, false) { _: DocumentationComponent -> true }
}
}
| plugins/ide-features-trainer/src/training/dsl/LessonUtil.kt | 3274409217 |
package org.craftsmenlabs.gareth.validator.mongo
import org.craftsmenlabs.gareth.validator.model.ExperimentTemplateCreateDTO
import org.craftsmenlabs.gareth.validator.model.ExperimentTemplateDTO
import org.craftsmenlabs.gareth.validator.model.Gluelines
import org.craftsmenlabs.gareth.validator.time.TimeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ExperimentTemplateConverter @Autowired constructor(val timeService: TimeService) {
fun toEntity(dto: ExperimentTemplateCreateDTO): ExperimentTemplateEntity {
val entity = ExperimentTemplateEntity()
entity.name = dto.name
entity.projectId = dto.projectid
entity.dateCreated = timeService.now()
entity.baseline = dto.glueLines.baseline
entity.assume = dto.glueLines.assume
entity.success = dto.glueLines.success
entity.failure = dto.glueLines.failure
entity.timeline = dto.glueLines.time
entity.projectId = dto.projectid
entity.interval = dto.interval
return entity
}
fun toDTO(entity: ExperimentTemplateEntity): ExperimentTemplateDTO {
val glueLines = Gluelines(
assume = entity.assume,
baseline = entity.baseline,
success = entity.success,
failure = entity.failure,
time = entity.timeline)
return ExperimentTemplateDTO(id = entity.id ?: throw IllegalStateException("Cannot convert ExperimentTemplate with null ID to DTO"),
name = entity.name,
projectId = entity.projectId,
created = entity.dateCreated,
ready = entity.ready,
archived = entity.archived,
interval = entity.interval,
glueLines = glueLines
)
}
} | gareth-core/src/main/kotlin/org/craftsmenlabs/gareth/validator/mongo/ExperimentTemplateConverter.kt | 1413273992 |
// IS_APPLICABLE: false
// WITH_STDLIB
import java.io.File
import java.io.IOException
fun main(args: Array<String>) {
val reader = File("hello-world.txt").bufferedReader()
<caret>try {
reader.readLine()
}
catch (e: IOException) {
}
finally {
reader.close()
}
} | plugins/kotlin/idea/tests/testData/intentions/convertTryFinallyToUseCall/catch.kt | 854346395 |
package net.benwoodworth.fastcraft
interface FastCraftFactory {
fun createFastCraft(): FastCraft
}
| fastcraft-core/src/main/kotlin/net/benwoodworth/fastcraft/FastCraftFactory.kt | 2935265819 |
package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.Before
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.decisiontables.BeforeRow
import org.livingdoc.api.fixtures.decisiontables.Check
import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture
import org.livingdoc.api.fixtures.decisiontables.Input
import org.livingdoc.api.fixtures.scenarios.Binding
import org.livingdoc.api.fixtures.scenarios.ScenarioFixture
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.api.tagging.Tag
/**
* [ExecutableDocuments][ExecutableDocument] can also be specified in Markdown
*
* @see ExecutableDocument
*/
@Tag("markdown")
@ExecutableDocument("local://Calculator.md")
class CalculatorDocumentMd {
@DecisionTableFixture(parallel = true)
class CalculatorDecisionTableFixture {
private lateinit var sut: Calculator
@Input("a")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("b")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
@ScenarioFixture
class CalculatorScenarioFixture {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
@Step("adding {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} and {bb} and {cc} and {dd} and {ee} and {ff} and {gg} equals {hh}")
fun addMultiple(
@Binding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") a: Float,
@Binding("bb") b: Float,
@Binding("cc") c: Float,
@Binding("dd") d: Float,
@Binding("ee") e: Float,
@Binding("ff") f: Float,
@Binding("gg") g: Float,
@Binding("hh") h: Float
) {
assertThat(a + b + c + d + e + f + g).isEqualTo(h)
}
@Step("subtraction {b} form {a} equals {c}")
fun subtract(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.diff(a, b)
assertThat(result).isEqualTo(c)
}
@Step("multiplying {a} and {b} equals {c}")
fun multiply(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.multiply(a, b)
assertThat(result).isEqualTo(c)
}
@Step("dividing {a} by {b} equals {c}")
fun divide(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.divide(a, b)
assertThat(result).isEqualTo(c)
}
@Step("add {a} to itself and you get {b}")
fun selfadd(
@Binding("a") a: Float,
@Binding("b") b: Float
) {
val result = sut.sum(a, a)
assertThat(result).isEqualTo(b)
}
}
@ScenarioFixture
class CalculatorScenarioFixture2 {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
}
}
| livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorDocumentMd.kt | 1356759687 |
package io.sentry.protocol
import java.util.Collections
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNotSame
import kotlin.test.assertNull
class UserTest {
@Test
fun `copying user wont have the same references`() {
val user = createUser()
val clone = User(user)
assertNotNull(clone)
assertNotSame(user, clone)
assertNotSame(user.others, clone.others)
assertNotSame(user.unknown, clone.unknown)
}
@Test
fun `copying user will have the same values`() {
val user = createUser()
val clone = User(user)
assertEquals("[email protected]", clone.email)
assertEquals("123", clone.id)
assertEquals("123.x", clone.ipAddress)
assertEquals("userName", clone.username)
assertEquals("others", clone.others!!["others"])
assertEquals("unknown", clone.unknown!!["unknown"])
}
@Test
fun `copying user and changing the original values wont change the clone values`() {
val user = createUser()
val clone = User(user)
user.email = "[email protected]"
user.id = "456"
user.ipAddress = "456.x"
user.username = "newUserName"
user.others!!["others"] = "newOthers"
user.others!!["anotherOne"] = "anotherOne"
val newUnknown = mapOf(Pair("unknown", "newUnknown"), Pair("otherUnknown", "otherUnknown"))
user.acceptUnknownProperties(newUnknown)
assertEquals("[email protected]", clone.email)
assertEquals("123", clone.id)
assertEquals("123.x", clone.ipAddress)
assertEquals("userName", clone.username)
assertEquals("others", clone.others!!["others"])
assertEquals(1, clone.others!!.size)
assertEquals("unknown", clone.unknown!!["unknown"])
assertEquals(1, clone.unknown!!.size)
}
@Test
fun `setting null others do not crash`() {
val user = createUser()
user.others = null
assertNull(user.others)
}
@Test
fun `when setOther receives immutable map as an argument, its still possible to add more others to the user`() {
val user = User().apply {
others = Collections.unmodifiableMap(mapOf("key1" to "value1"))
others!!["key2"] = "value2"
}
assertNotNull(user.others) {
assertEquals(mapOf("key1" to "value1", "key2" to "value2"), it)
}
}
private fun createUser(): User {
return User().apply {
email = "[email protected]"
id = "123"
ipAddress = "123.x"
username = "userName"
val others = mutableMapOf(Pair("others", "others"))
setOthers(others)
val unknown = mapOf(Pair("unknown", "unknown"))
acceptUnknownProperties(unknown)
}
}
}
| sentry/src/test/java/io/sentry/protocol/UserTest.kt | 3169507750 |
package me.kirimin.mitsumine.feed.read
import android.os.Bundle
import me.kirimin.mitsumine.feed.AbstractFeedFragment
import me.kirimin.mitsumine.feed.FeedPresenter
class ReadFeedFragment : AbstractFeedFragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
presenter.view = this
presenter.onCreate(FeedPresenter.FeedMethod.Read())
}
}
| app/src/main/java/me/kirimin/mitsumine/feed/read/ReadFeedFragment.kt | 3551462322 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.configurationStore.ApplicationStoreImpl
import com.intellij.configurationStore.write
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.vcs.merge.MergeSession
import com.intellij.testFramework.file
import com.intellij.testFramework.writeChild
import com.intellij.util.PathUtilRt
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.jgit.dirCache.deletePath
import org.jetbrains.jgit.dirCache.writePath
import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode
import org.jetbrains.settingsRepository.SyncType
import org.jetbrains.settingsRepository.conflictResolver
import org.jetbrains.settingsRepository.copyLocalConfig
import org.jetbrains.settingsRepository.git.commit
import org.jetbrains.settingsRepository.git.computeIndexDiff
import org.junit.Test
import java.nio.charset.StandardCharsets
import java.util.*
// kotlin bug, cannot be val (.NoSuchMethodError: org.jetbrains.settingsRepository.SettingsRepositoryPackage.getMARKER_ACCEPT_MY()[B)
internal object AM {
val MARKER_ACCEPT_MY: ByteArray = "__accept my__".toByteArray()
val MARKER_ACCEPT_THEIRS: ByteArray = "__accept theirs__".toByteArray()
}
internal class GitTest : GitTestCase() {
init {
conflictResolver = { files, mergeProvider ->
val mergeSession = mergeProvider.createMergeSession(files)
for (file in files) {
val mergeData = mergeProvider.loadRevisions(file)
if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_THEIRS)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours)
}
else if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs)
}
else if (Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) {
file.setBinaryContent(mergeData.LAST!!)
mergeProvider.conflictResolvedForFile(file)
}
else {
throw CannotResolveConflictInTestMode()
}
}
}
}
@Test fun add() {
provider.write(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isTrue()
assertThat(diff.added).containsOnly(SAMPLE_FILE_NAME)
assertThat(diff.changed).isEmpty()
assertThat(diff.removed).isEmpty()
assertThat(diff.modified).isEmpty()
assertThat(diff.untracked).isEmpty()
assertThat(diff.untrackedFolders).isEmpty()
}
@Test fun addSeveral() {
val addedFile = "foo.xml"
val addedFile2 = "bar.xml"
provider.write(addedFile, "foo")
provider.write(addedFile2, "bar")
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isTrue()
assertThat(diff.added).containsOnly(addedFile, addedFile2)
assertThat(diff.changed).isEmpty()
assertThat(diff.removed).isEmpty()
assertThat(diff.modified).isEmpty()
assertThat(diff.untracked).isEmpty()
assertThat(diff.untrackedFolders).isEmpty()
}
@Test fun delete() {
fun delete(directory: Boolean) {
val dir = "dir"
val fullFileSpec = "$dir/file.xml"
provider.write(fullFileSpec, SAMPLE_FILE_CONTENT)
provider.delete(if (directory) dir else fullFileSpec)
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isFalse()
assertThat(diff.added).isEmpty()
assertThat(diff.changed).isEmpty()
assertThat(diff.removed).isEmpty()
assertThat(diff.modified).isEmpty()
assertThat(diff.untracked).isEmpty()
assertThat(diff.untrackedFolders).isEmpty()
}
delete(false)
delete(true)
}
@Test fun `set upstream`() {
val url = "https://github.com/user/repo.git"
repositoryManager.setUpstream(url)
assertThat(repositoryManager.getUpstream()).isEqualTo(url)
}
@Test
public fun pullToRepositoryWithoutCommits() {
doPullToRepositoryWithoutCommits(null)
}
@Test fun pullToRepositoryWithoutCommitsAndCustomRemoteBranchName() {
doPullToRepositoryWithoutCommits("customRemoteBranchName")
}
private fun doPullToRepositoryWithoutCommits(remoteBranchName: String?) {
createLocalAndRemoteRepositories(remoteBranchName)
repositoryManager.pull()
compareFiles(repository.workTree, remoteRepository.workTree)
}
@Test fun pullToRepositoryWithCommits() {
doPullToRepositoryWithCommits(null)
}
@Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() {
doPullToRepositoryWithCommits("customRemoteBranchName")
}
private fun doPullToRepositoryWithCommits(remoteBranchName: String?) {
createLocalAndRemoteRepositories(remoteBranchName)
val file = addAndCommit("local.xml")
repositoryManager.commit()
repositoryManager.pull()
assertThat(repository.workTree.resolve(file.name)).hasBinaryContent(file.data)
compareFiles(repository.workTree, remoteRepository.workTree, PathUtilRt.getFileName(file.name))
}
// never was merged. we reset using "merge with strategy "theirs", so, we must test - what's happen if it is not first merge? - see next test
@Test fun resetToTheirsIfFirstMerge() {
createLocalAndRemoteRepositories(initialCommit = true)
sync(SyncType.OVERWRITE_LOCAL)
fs
.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.compare()
}
@Test fun `overwrite local: second merge is null`() {
createLocalAndRemoteRepositories(initialCommit = true)
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fun testRemote() {
fs
.file("local.xml", """<file path="local.xml" />""")
.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.compare()
}
testRemote()
addAndCommit("_mac/local2.xml")
sync(SyncType.OVERWRITE_LOCAL)
fs.compare()
// test: merge and push to remote after such reset
sync(SyncType.MERGE)
restoreRemoteAfterPush()
testRemote()
}
@Test fun `merge - resolve conflicts to my`() {
createLocalAndRemoteRepositories()
val data = AM.MARKER_ACCEPT_MY
provider.write(SAMPLE_FILE_NAME, data)
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs.file(SAMPLE_FILE_NAME, data.toString(StandardCharsets.UTF_8)).compare()
}
@Test fun `merge - theirs file deleted, my modified, accept theirs`() {
createLocalAndRemoteRepositories()
sync(SyncType.MERGE)
val data = AM.MARKER_ACCEPT_THEIRS
provider.write(SAMPLE_FILE_NAME, data)
repositoryManager.commit()
remoteRepository.deletePath(SAMPLE_FILE_NAME)
remoteRepository.commit("delete $SAMPLE_FILE_NAME")
sync(SyncType.MERGE)
fs.compare()
}
@Test fun `merge - my file deleted, theirs modified, accept my`() {
createLocalAndRemoteRepositories()
sync(SyncType.MERGE)
provider.delete(SAMPLE_FILE_NAME)
repositoryManager.commit()
remoteRepository.writePath(SAMPLE_FILE_NAME, AM.MARKER_ACCEPT_THEIRS)
remoteRepository.commit("")
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs.compare()
}
@Test fun `commit if unmerged`() {
createLocalAndRemoteRepositories()
val data = "<foo />"
provider.write(SAMPLE_FILE_NAME, data)
try {
sync(SyncType.MERGE)
}
catch (e: CannotResolveConflictInTestMode) {
}
// repository in unmerged state
conflictResolver = {files, mergeProvider ->
assertThat(files).hasSize(1)
assertThat(files.first().path).isEqualTo(SAMPLE_FILE_NAME)
val mergeSession = mergeProvider.createMergeSession(files)
mergeSession.conflictResolvedForFile(files.first(), MergeSession.Resolution.AcceptedTheirs)
}
sync(SyncType.MERGE)
fs.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare()
}
// remote is uninitialized (empty - initial commit is not done)
@Test fun `merge with uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.MERGE)
}
@Test fun `overwrite remote: uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE)
}
@Test fun `overwrite local - uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL)
}
@Test fun gitignore() {
createLocalAndRemoteRepositories()
provider.write(".gitignore", "*.html")
sync(SyncType.MERGE)
val filePaths = listOf("bar.html", "i/am/a/long/path/to/file/foo.html")
for (path in filePaths) {
provider.write(path, path)
}
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isFalse()
assertThat(diff.added).isEmpty()
assertThat(diff.changed).isEmpty()
assertThat(diff.removed).isEmpty()
assertThat(diff.modified).isEmpty()
assertThat(diff.untracked).isEmpty()
assertThat(diff.untrackedFolders).isEmpty()
for (path in filePaths) {
assertThat(provider.read(path)).isNull()
}
}
@Test fun `initial copy to repository: no local files`() {
createRemoteRepository(initialCommit = false)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(false)
}
@Test fun `initial copy to repository: some local files`() {
createRemoteRepository(initialCommit = false)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(true)
}
@Test fun `initial copy to repository: remote files removed`() {
createRemoteRepository(initialCommit = true)
// check error during findRemoteRefUpdatesFor (no master ref)
testInitialCopy(true, SyncType.OVERWRITE_REMOTE)
}
private fun testInitialCopy(addLocalFiles: Boolean, syncType: SyncType = SyncType.MERGE) {
repositoryManager.createRepositoryIfNeed()
repositoryManager.setUpstream(remoteRepository.getWorkTree().absolutePath)
val store = ApplicationStoreImpl(ApplicationManager.getApplication()!!)
val localConfigPath = tempDirManager.newPath("local_config")
val lafData = """<application>
<component name="UISettings">
<option name="HIDE_TOOL_STRIPES" value="false" />
</component>
</application>"""
if (addLocalFiles) {
localConfigPath.writeChild("options/ui.lnf.xml", lafData)
}
store.setPath(localConfigPath.toString())
store.storageManager.streamProvider = provider
icsManager.sync(syncType, GitTestCase.projectRule.project, { copyLocalConfig(store.storageManager) })
if (addLocalFiles) {
assertThat(localConfigPath).isDirectory()
fs
.file("ui.lnf.xml", lafData)
restoreRemoteAfterPush()
}
else {
assertThat(localConfigPath).doesNotExist()
}
fs.compare()
}
private fun doSyncWithUninitializedUpstream(syncType: SyncType) {
createRemoteRepository(initialCommit = false)
repositoryManager.setUpstream(remoteRepository.getWorkTree().absolutePath)
val path = "local.xml"
val data = "<application />"
provider.write(path, data)
sync(syncType)
if (syncType != SyncType.OVERWRITE_LOCAL) {
fs.file(path, data)
}
restoreRemoteAfterPush();
fs.compare()
}
} | plugins/settings-repository/testSrc/GitTest.kt | 1802849342 |
/**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 8/12/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.security.keystore.UserNotAuthenticatedException
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_UNLOCKED
import androidx.lifecycle.lifecycleScope
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import com.breadwallet.BuildConfig
import com.breadwallet.R
import com.breadwallet.app.BreadApp
import com.breadwallet.logger.logDebug
import com.breadwallet.tools.animation.BRDialog
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.auth.AuthenticationController
import com.breadwallet.ui.disabled.DisabledController
import com.breadwallet.ui.keystore.KeyStoreController
import com.breadwallet.ui.login.LoginController
import com.breadwallet.ui.migrate.MigrateController
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.ui.navigation.Navigator
import com.breadwallet.ui.navigation.OnCompleteAction
import com.breadwallet.ui.navigation.RouterNavigator
import com.breadwallet.ui.onboarding.IntroController
import com.breadwallet.ui.onboarding.OnBoardingController
import com.breadwallet.ui.pin.InputPinController
import com.breadwallet.ui.recovery.RecoveryKey
import com.breadwallet.ui.recovery.RecoveryKeyController
import com.breadwallet.ui.settings.SettingsController
import com.breadwallet.ui.settings.SettingsSection
import com.breadwallet.util.ControllerTrackingListener
import com.breadwallet.util.errorHandler
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.dropWhile
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.kodein.di.KodeinAware
import org.kodein.di.android.closestKodein
import org.kodein.di.android.retainedSubKodein
import org.kodein.di.erased.bind
import org.kodein.di.erased.instance
import org.kodein.di.erased.singleton
// String extra containing a recovery phrase to bootstrap the recovery process. (debug only)
private const val EXTRA_RECOVER_PHRASE = "RECOVER_PHRASE"
/**
* The main user entrypoint into the app.
*
* This activity serves as a Conductor router host and translates
* platform events into Mobius events.
*/
@Suppress("TooManyFunctions")
class MainActivity : AppCompatActivity(), KodeinAware {
companion object {
const val EXTRA_DATA = "com.breadwallet.ui.MainActivity.EXTRA_DATA"
const val EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID =
"com.breadwallet.ui.MainActivity.EXTRA_PUSH_CAMPAIGN_ID"
}
override val kodein by retainedSubKodein(closestKodein()) {
val router = router
bind<Navigator>() with singleton {
RouterNavigator { router }
}
}
private val userManager by instance<BrdUserManager>()
lateinit var router: Router
private var trackingListener: ControllerTrackingListener? = null
// NOTE: Used only to centralize deep link navigation handling.
private val navigator by instance<Navigator>()
private val resumedScope = CoroutineScope(
Default + SupervisorJob() + errorHandler("resumedScope")
)
private var closeDebugDrawer = { false }
private var launchedWithInvalidState = false
@Suppress("ComplexMethod", "LongMethod")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// The view of this activity is nothing more than a Controller host with animation support
val root = ChangeHandlerFrameLayout(this).also { view ->
router = Conductor.attachRouter(this, view, savedInstanceState)
}
setContentView(if (BuildConfig.DEBUG) createDebugLayout(root, savedInstanceState) else root)
trackingListener = ControllerTrackingListener(this).also(router::addChangeListener)
BreadApp.applicationScope.launch(Main) {
try {
userManager.checkAccountInvalidated()
} catch (e: UserNotAuthenticatedException) {
finish()
return@launch
}
val userState = userManager.getState()
if (userState is BrdUserState.KeyStoreInvalid) {
processUserState(userState)
return@launch
}
userManager.lock()
// Allow launching with a phrase to recover automatically
val hasWallet = userManager.isInitialized()
if (BuildConfig.DEBUG && intent.hasExtra(EXTRA_RECOVER_PHRASE) && !hasWallet) {
val phrase = intent.getStringExtra(EXTRA_RECOVER_PHRASE)!!
if (phrase.isNotBlank() && phrase.split(" ").size == RecoveryKey.M.RECOVERY_KEY_WORDS_COUNT) {
val controller = RecoveryKeyController(RecoveryKey.Mode.RECOVER, phrase)
router.setRoot(RouterTransaction.with(controller))
return@launch
}
}
// The app is launched, no screen to be restored
if (!router.hasRootController()) {
val rootController = when {
userManager.isMigrationRequired() -> MigrateController()
else -> when (userManager.getState()) {
is BrdUserState.Disabled -> DisabledController()
is BrdUserState.Uninitialized -> IntroController()
else -> if (userManager.hasPinCode()) {
val intentUrl = processIntentData(intent)
LoginController(intentUrl)
} else {
InputPinController(OnCompleteAction.GO_HOME)
}
}
}
router.setRoot(
RouterTransaction.with(rootController)
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
)
}
}
if (BuildConfig.DEBUG) {
Utils.printPhoneSpecs(this@MainActivity)
}
}
override fun onDestroy() {
super.onDestroy()
closeDebugDrawer = { false }
trackingListener?.run(router::removeChangeListener)
trackingListener = null
resumedScope.cancel()
}
override fun onResume() {
super.onResume()
BreadApp.setBreadContext(this)
userManager.stateChanges()
.dropWhile { router.backstackSize == 0 }
.map { processUserState(it) }
.flowOn(Main)
.launchIn(resumedScope)
}
override fun onPause() {
super.onPause()
BreadApp.setBreadContext(null)
resumedScope.coroutineContext.cancelChildren()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
router.onActivityResult(requestCode, resultCode, data)
userManager.onActivityResult(requestCode, resultCode)
}
override fun onBackPressed() {
// Defer to controller back-press control before exiting.
if (!closeDebugDrawer() && !router.handleBack()) {
super.onBackPressed()
}
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return checkOverlayAndDispatchTouchEvent(ev)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent ?: return
val data = processIntentData(intent) ?: ""
if (data.isNotBlank() && userManager.isInitialized()) {
val hasRoot = router.hasRootController()
val isTopLogin = router.backstack.lastOrNull()?.controller is LoginController
val isAuthenticated = !isTopLogin && hasRoot
navigator.navigateTo(NavigationTarget.DeepLink(data, isAuthenticated))
}
}
@SuppressLint("RtlHardcoded")
private fun createDebugLayout(root: View, bundle: Bundle?): View {
val drawerDirection = Gravity.RIGHT
val controller = SettingsController(SettingsSection.DEVELOPER_OPTION)
return DrawerLayout(this).apply {
lifecycleScope.launchWhenCreated {
userManager.stateChanges().collect { state ->
val mode = if (state is BrdUserState.Enabled) {
LOCK_MODE_UNLOCKED
} else {
LOCK_MODE_LOCKED_CLOSED
}
setDrawerLockMode(mode, drawerDirection)
}
}
closeDebugDrawer = {
isDrawerOpen(drawerDirection).also {
closeDrawer(drawerDirection)
}
}
addView(root, DrawerLayout.LayoutParams(
DrawerLayout.LayoutParams.MATCH_PARENT,
DrawerLayout.LayoutParams.MATCH_PARENT
))
addView(NavigationView(context).apply {
addView(ChangeHandlerFrameLayout(context).apply {
id = R.id.drawer_layout_id
Conductor.attachRouter(this@MainActivity, this, bundle)
.setRoot(RouterTransaction.with(controller))
}, FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.MATCH_PARENT
))
}, DrawerLayout.LayoutParams(
DrawerLayout.LayoutParams.WRAP_CONTENT,
DrawerLayout.LayoutParams.MATCH_PARENT
).apply {
gravity = drawerDirection
})
}
}
/** Process the new intent and return the url to browse if available */
private fun processIntentData(intent: Intent): String? {
if (intent.hasExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)) {
val campaignId = intent.getStringExtra(EXTRA_PUSH_NOTIFICATION_CAMPAIGN_ID)!!
val attributes = mapOf(EventUtils.EVENT_ATTRIBUTE_CAMPAIGN_ID to campaignId)
EventUtils.pushEvent(EventUtils.EVENT_MIXPANEL_APP_OPEN, attributes)
EventUtils.pushEvent(EventUtils.EVENT_PUSH_NOTIFICATION_OPEN)
}
val data = intent.getStringExtra(EXTRA_DATA)
return if (data.isNullOrBlank()) {
intent.dataString
} else data
}
private fun processUserState(userState: BrdUserState) {
if (userState is BrdUserState.KeyStoreInvalid) {
launchedWithInvalidState = true
logDebug("Device state is invalid, $userState")
val needsKeyStoreController = router.backstack
.map(RouterTransaction::controller)
.filterIsInstance<KeyStoreController>()
.none()
if (needsKeyStoreController) {
router.setRoot(RouterTransaction.with(KeyStoreController()))
}
} else if (launchedWithInvalidState) {
logDebug("Device state is now valid, recreating activity.")
router.setBackstack(emptyList(), null)
recreate()
} else {
if (userManager.isInitialized() && router.hasRootController()) {
when (userState) {
BrdUserState.Locked -> lockApp()
is BrdUserState.Disabled -> disableApp()
}
}
}
}
private fun isBackstackDisabled() = router.backstack
.map(RouterTransaction::controller)
.filterIsInstance<DisabledController>()
.any()
private fun isBackstackLocked() =
router.backstack.lastOrNull()?.controller
?.let {
// Backstack is locked or requires a pin
it is LoginController || it is InputPinController ||
it is AuthenticationController ||
// Backstack is initialization flow
it is OnBoardingController || it is RecoveryKeyController ||
it is MigrateController
} ?: false
private fun disableApp() {
if (isBackstackDisabled()) return
logDebug("Disabling backstack.")
router.pushController(
RouterTransaction.with(DisabledController())
.pushChangeHandler(FadeChangeHandler())
.popChangeHandler(FadeChangeHandler())
)
}
private fun lockApp() {
if (isBackstackDisabled() || isBackstackLocked()) return
val controller = when {
userManager.hasPinCode() ->
LoginController(showHome = router.backstackSize == 0)
else -> InputPinController(
onComplete = OnCompleteAction.GO_HOME,
skipWriteDown = BRSharedPrefs.phraseWroteDown
)
}
logDebug("Locking with controller=$controller")
router.pushController(
RouterTransaction.with(controller)
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
)
}
/**
* Check if there is an overlay view over the screen, if an
* overlay view is found the event won't be dispatched and
* a dialog with a warning will be shown.
*
* @param event The touch screen event.
* @return boolean Return true if this event was consumed or if an overlay view was found.
*/
private fun checkOverlayAndDispatchTouchEvent(event: MotionEvent): Boolean {
// Filter obscured touches by consuming them.
if (event.flags and MotionEvent.FLAG_WINDOW_IS_OBSCURED != 0) {
if (event.action == MotionEvent.ACTION_UP) {
BRDialog.showSimpleDialog(
this, getString(R.string.Android_screenAlteringTitle),
getString(R.string.Android_screenAlteringMessage)
)
}
return true
}
return super.dispatchTouchEvent(event)
}
}
| app/src/main/java/com/breadwallet/ui/MainActivity.kt | 2532501246 |
package com.quran.data.page.provider
import com.quran.common.upgrade.LocalDataUpgrade
import com.quran.common.upgrade.PreferencesUpgrade
import com.quran.data.page.provider.madani.MadaniPageProvider
import com.quran.data.pageinfo.mapper.AyahMapper
import com.quran.data.pageinfo.mapper.IdentityAyahMapper
import com.quran.data.source.PageProvider
import com.quran.page.common.draw.ImageDrawHelper
import com.quran.page.common.factory.PageViewFactoryProvider
import dagger.Module
import dagger.Provides
import dagger.Reusable
import dagger.multibindings.ElementsIntoSet
import dagger.multibindings.IntoMap
import dagger.multibindings.StringKey
@Module
object QuranDataModule {
@Provides
fun providePageViewFactoryProvider(): PageViewFactoryProvider {
return PageViewFactoryProvider { null }
}
@JvmStatic
@Provides
@IntoMap
@StringKey("madani")
fun provideMadaniPageSet(): PageProvider {
return MadaniPageProvider()
}
@JvmStatic
@Provides
@ElementsIntoSet
fun provideImageDrawHelpers(): Set<ImageDrawHelper> {
return emptySet()
}
@JvmStatic
@Provides
fun provideLocalDataUpgrade(): LocalDataUpgrade = object : LocalDataUpgrade { }
@JvmStatic
@Provides
fun providePreferencesUpgrade(): PreferencesUpgrade = PreferencesUpgrade { _, _, _ -> true }
@JvmStatic
@Reusable
@Provides
fun provideAyahMapper(): AyahMapper = IdentityAyahMapper()
}
| pages/madani/src/main/java/com/quran/data/page/provider/QuranDataModule.kt | 110275410 |
package com.quran.labs.androidquran.ui.adapter
interface DownloadedItemActionListener {
fun handleDeleteItemAction()
fun handleRankUpItemAction()
fun handleRankDownItemAction()
}
| app/src/main/java/com/quran/labs/androidquran/ui/adapter/DownloadedItemActionListener.kt | 46788050 |
package com.quran.mobile.recitation.presenter
import android.app.Activity
import com.quran.data.di.ActivityScope
import com.quran.data.di.QuranReadingScope
import com.quran.data.model.SuraAyah
import com.quran.recitation.presenter.RecitationPresenter
import com.squareup.anvil.annotations.ContributesBinding
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
@ActivityScope
@ContributesBinding(scope = QuranReadingScope::class, boundType = RecitationPresenter::class)
class RecitationPresenterImpl @Inject constructor(): RecitationPresenter {
override fun bind(what: Activity) {}
override fun unbind(what: Activity) {}
override fun isRecitationEnabled(): Boolean = false
override fun isRecitationEnabledFlow(): StateFlow<Boolean> = MutableStateFlow(false)
override fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray) {}
override fun startOrStopRecitation(startAyah: () -> SuraAyah, showModeSelection: Boolean) {}
override fun endSession() {}
}
| feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationPresenterImpl.kt | 2810085943 |
/*
* MIT License
*
* Copyright (c) 2017 Ian Cronkright
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.txuritan.mental.fish.common
import com.github.txuritan.mental.core.common.IModule
import com.github.txuritan.mental.core.common.util.References
import net.minecraftforge.common.config.Configuration
import net.minecraftforge.fml.common.ModMetadata
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent
/**
* @author Ian 'Txuritan/Captain Daro'Ma'Sohni Tavia' Cronkright
*/
object Fish : IModule {
var fishes : Fishes = Fishes
override fun setupConfig(configuration : Configuration) {
fishes.fishes.filterIsInstance<IFish>().forEach { it.setupConfig(configuration) }
}
override fun preInit(event : FMLPreInitializationEvent) {
fishes.fishes.filterIsInstance<IFish>().forEach { it.preInit(event) }
val modMetadata : ModMetadata = event.modMetadata
modMetadata.modId = References.MOD_ID
var description : String = modMetadata.description
description += "\nEnabled fishes\n"
fishes.fishes.filterIsInstance<IFish>().forEach {
description += " * ${it.FISH.replace("-"," ").capitalize()}: ${if (it.configEnabledAll !!) "§2True§f" else "§4False§f"}\n"
}
modMetadata.description = description
}
override fun init(event : FMLInitializationEvent) {
fishes.fishes.filterIsInstance<IFish>().forEach { it.init(event) }
}
override fun postInit(event : FMLPostInitializationEvent) {
fishes.fishes.filterIsInstance<IFish>().forEach { it.postInit(event) }
}
}
| src/main/kotlin/com/github/txuritan/mental/fish/common/Fish.kt | 2775735659 |
package com.github.stephanenicolas.heatcontrol.features.setting.ui
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CompoundButton.OnCheckedChangeListener
import android.widget.EditText
import android.widget.FrameLayout
import butterknife.BindView
import butterknife.ButterKnife
import com.github.stephanenicolas.heatcontrol.R
import com.github.stephanenicolas.heatcontrol.features.control.state.Host
import com.github.stephanenicolas.heatcontrol.features.control.state.SettingState
import com.github.stephanenicolas.heatcontrol.features.control.state.SettingStore
import com.github.stephanenicolas.heatcontrol.features.control.usecases.SettingController
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class SettingsView : FrameLayout {
@Inject
lateinit var settingStore: SettingStore
@Inject
lateinit var settingController: SettingController
@BindView(R.id.edit_text_api_key_value)
lateinit var apiKeyView: EditText
@BindView(R.id.recycler_hosts)
lateinit var recyclerView: RecyclerView
@BindView(R.id.reset_button)
lateinit var resetButton: Button
@BindView(R.id.save_button)
lateinit var saveButton: Button
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
LayoutInflater.from(context).inflate(R.layout.settings_view, this)
ButterKnife.bind(this)
recyclerView.layoutManager = LinearLayoutManager(context)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
settingStore.getStateObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateState)
apiKeyView.setOnFocusChangeListener { v, hasFocus -> if(!hasFocus) settingController.setApiKey(apiKeyView.text.toString()) }
resetButton.setOnClickListener { settingController.reset() }
saveButton.setOnClickListener { settingController.save(settingStore.getState()) }
}
private fun updateState(state: SettingState) {
apiKeyView.setText(state.key)
recyclerView.adapter = HostListAdapter(state.hostList, settingController)
}
}
class HostListAdapter(var hosts: List<Host>, var settingController: SettingController) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val TYPE_HOST: Int = 0
val TYPE_ADD: Int = 1
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (position < hosts.size) {
val hostViewViewHolder: HostViewViewHolder = holder as HostViewViewHolder
val host: Host = hosts[position]
hostViewViewHolder.hostView.setHost(host)
hostViewViewHolder.hostView.setSelectCallback(OnCheckedChangeListener { buttonView, isChecked -> settingController.setlectHost(position) })
hostViewViewHolder.hostView.setRenameCallBack(View.OnFocusChangeListener {
view, hasFocus ->
val name = hostViewViewHolder.hostView.getName()
if (!hasFocus) settingController.renameHost(position, name)
})
hostViewViewHolder.hostView.setChangeAddressCallBack(View.OnFocusChangeListener {
view, hasFocus ->
val address = hostViewViewHolder.hostView.getAddress()
if (!hasFocus) settingController.changeAddressHost(position, address)
})
hostViewViewHolder.hostView.setDeleteCallback(View.OnClickListener { settingController.removeHost(position) })
} else {
val addNewHostViewHolder: AddNewHostViewHolder = holder as AddNewHostViewHolder
addNewHostViewHolder.button.setOnClickListener { settingController.addHost() }
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val context: Context = parent!!.context
when (viewType) {
TYPE_HOST -> {
return HostViewViewHolder(context)
}
else -> {
return AddNewHostViewHolder(context)
}
}
}
override fun getItemCount(): Int {
return hosts.size + 1
}
override fun getItemViewType(position: Int): Int {
if (position == hosts.size) {
return TYPE_ADD
} else {
return TYPE_HOST
}
}
}
| app/src/main/java/com/github/stephanenicolas/heatcontrol/features/setting/ui/SettingView.kt | 3947078777 |
package 泛型.继承链式测试.test2
/**
* Created by fuzhipeng on 2019/3/5.
*/
class Holder3 : Holder2<Holder3>() {
override fun getReturnValue(): Holder3 = this
fun go3(): Holder3 {
return getReturnValue()
}
}
| JavaTest_Zone/src/泛型/继承链式测试/test2/Holder3.kt | 1385480074 |
package com.foo.rest.examples.spring.openapi.v3.base
import com.foo.rest.examples.spring.openapi.v3.SpringController
class BaseController : SpringController(BaseApplication::class.java) | e2e-tests/spring-rest-openapi-v3/src/test/kotlin/com/foo/rest/examples/spring/openapi/v3/base/BaseController.kt | 3456564992 |
/*
* Copyright (C) 2016/2022 Litote
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litote.kmongo.issues
import com.github.jershell.kbson.BsonEncoder
import com.github.jershell.kbson.BsonFlexibleDecoder
import com.github.jershell.kbson.Configuration
import kotlinx.serialization.Serializable
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.EmptySerializersModule
import org.bson.BsonDocument
import org.bson.BsonDocumentReader
import org.bson.BsonDocumentWriter
import org.junit.Test
import kotlin.test.assertEquals
@Serializable
sealed class Message
@Serializable
data class StringMessage(val message: String) : Message()
@Serializable
data class IntMessage(val int: Int) : Message()
@Serializable
object ObjectMessage : Message() {
val message: String = "Message"
}
@Serializable
data class ComplexObject(
val a: Int,
val m: Message,
val c: String
)
class ObjectInPolymorphicNotWorking {
@Test
fun `serialize and deserialize object in polymorphic`() {
val document = BsonDocument()
val writer = BsonDocumentWriter(document)
val encoder = BsonEncoder(writer, EmptySerializersModule, Configuration())
Message.serializer().serialize(encoder, ObjectMessage)
val expected = BsonDocument.parse("""{"___type":"ObjectMessage"}""")
assertEquals(expected, document)
val reader = BsonDocumentReader(document)
val decoder = BsonFlexibleDecoder(reader, EmptySerializersModule, Configuration())
val parsed = Message.serializer().deserialize(decoder)
assertEquals(ObjectMessage, parsed)
}
@Test
fun `serialize and deserialize class in polymorphic`(){
val message = StringMessage("msg")
val document = BsonDocument()
val writer = BsonDocumentWriter(document)
val encoder = BsonEncoder(writer, EmptySerializersModule, Configuration())
Message.serializer().serialize(encoder, message)
writer.flush()
val expected = BsonDocument.parse("""{"___type":"StringMessage", "message":"msg"}""")
assertEquals(expected, document)
val reader = BsonDocumentReader(document)
val decoder = BsonFlexibleDecoder(reader, EmptySerializersModule, Configuration())
val parsed = Message.serializer().deserialize(decoder)
assertEquals(message, parsed)
}
@Test
fun `serialize in complex object`(){
val complex = ComplexObject(3, ObjectMessage, "msg")
val document = BsonDocument()
val writer = BsonDocumentWriter(document)
val encoder = BsonEncoder(writer, EmptySerializersModule, Configuration())
ComplexObject.serializer().serialize(encoder, complex)
writer.flush()
val expected = BsonDocument.parse("""{"a":3,"m":{"___type":"ObjectMessage"},"c":"msg"}""")
assertEquals(expected, document)
val reader = BsonDocumentReader(document)
val decoder = BsonFlexibleDecoder(reader, EmptySerializersModule, Configuration())
val parsed = ComplexObject.serializer().deserialize(decoder)
assertEquals(complex, parsed)
}
} | kmongo-serialization/src/test/kotlin/ObjectInPolymorphicNotWorking.kt | 1441772326 |
package site.yanglong.promotion.config
import com.alibaba.druid.pool.DruidDataSource
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import java.sql.SQLException
import javax.sql.DataSource
/**
* package: site.yanglong.promotion.config <br/>
* functional describe: druid configuration
*
* @author DR.YangLong [[email protected]]
* @version 1.0 2017/7/12
*/
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
class DruidConfig {
private val logger: Logger = LoggerFactory.getLogger(DruidConfig::class.java)
var url: String? = null
var username: String? = null
var password: String? = null
var driverClassName: String? = null
var initialSize: Int = 0
var minIdle: Int = 0
var maxActive: Int = 0
var maxWait: Long = 0
var timeBetweenEvictionRunsMillis: Int = 0
var minEvictableIdleTimeMillis: Int = 0
var validationQuery: String? = null
var testWhileIdle: Boolean = false
var testOnBorrow: Boolean = false
var testOnReturn: Boolean = false
var poolPreparedStatements: Boolean = false
var maxPoolPreparedStatementPerConnectionSize: Int = 0
var filters: String? = null
var connectionProperties: String? = null
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
fun dataSource(): DataSource {
val datasource = DruidDataSource()
datasource.url = url
datasource.username = username
datasource.password = password
datasource.driverClassName = driverClassName
//configuration
datasource.initialSize = initialSize
datasource.minIdle = minIdle
datasource.maxActive = maxActive
datasource.maxWait = maxWait
datasource.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis.toLong()
datasource.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis.toLong()
datasource.validationQuery = validationQuery
datasource.isTestWhileIdle = testWhileIdle
datasource.isTestOnBorrow = testOnBorrow
datasource.isTestOnReturn = testOnReturn
datasource.isPoolPreparedStatements = poolPreparedStatements
datasource.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize
try {
datasource.setFilters(filters)
} catch (e: SQLException) {
logger.error("druid configuration initialization filter", e)
}
datasource.setConnectionProperties(connectionProperties)
return datasource
}
} | src/main/kotlin/site/yanglong/promotion/config/DruidConfig.kt | 684572589 |
package com.bubelov.coins.repository.synclogs
import com.bubelov.coins.data.LogEntry
import com.bubelov.coins.data.LogEntryQueries
import com.squareup.sqldelight.runtime.coroutines.asFlow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
class LogsRepository(
private val queries: LogEntryQueries
) {
fun getAll() = queries.selectAll().asFlow().map { it.executeAsList() }
fun append(tag: String = "", message: String) = runBlocking {
withContext(Dispatchers.IO) {
queries.insert(
LogEntry(
datetime = LocalDateTime.now().toString(),
tag = tag,
message = message
)
)
}
}
operator fun plusAssign(entry: LogEntry) = runBlocking {
queries.insert(entry)
}
operator fun plusAssign(message: String) {
append("", message)
}
}
fun Any.logEntry(message: String) = LogEntry(
datetime = LocalDateTime.now().toString(),
tag = this.javaClass.simpleName,
message = message
) | app/src/main/java/com/bubelov/coins/repository/synclogs/LogsRepository.kt | 551163650 |
package com.aman_arora.multi_threaded_downloader
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/com/aman_arora/multi_threaded_downloader/ExampleUnitTest.kt | 576521149 |
package com.antonioleiva.weatherapp.ui
import android.app.Application
import com.antonioleiva.weatherapp.extensions.DelegatesExt
class App : Application() {
companion object {
var instance: App by DelegatesExt.notNullSingleValue()
}
override fun onCreate() {
super.onCreate()
instance = this
}
} | app/src/main/java/com/antonioleiva/weatherapp/ui/App.kt | 405556378 |
package tonnysunm.com.acornote.ui.colortag
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.findFragment
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_note.*
import kotlinx.coroutines.launch
import tonnysunm.com.acornote.databinding.ListItemColortagHorizontalBinding
import tonnysunm.com.acornote.databinding.ListItemEditBinding
import tonnysunm.com.acornote.model.ColorTag
import tonnysunm.com.acornote.ui.HomeActivity
import tonnysunm.com.acornote.ui.note.NoteActivity
import tonnysunm.com.acornote.ui.note.NoteFragment
private const val ColorTagType = 0
private const val FooterType = 1
class ColorTagListAdapterHorizontal(
var selectedColorTagColor: String?,
var array: List<ColorTag>
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
if (viewType == ColorTagType)
ViewHolder(
ListItemColortagHorizontalBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
).apply {
itemView.setOnClickListener {
val data = array[this.absoluteAdapterPosition]
val fragment = itemView.findFragment<ColorTagListFragmentHorizontal>()
val activity = fragment.activity
if (activity is HomeActivity) {
fragment.navigateToNotesBy(data)
} else if (activity is NoteActivity) {
val noteFgm = activity.fragment_edit_note as NoteFragment
val viewModal = noteFgm.viewModel
viewModal.viewModelScope.launch {
viewModal.updateColorTag(data)
}
}
}
}
else
EditViewHolder(
ListItemEditBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
).apply {
itemView.setOnClickListener {
val fragment = it.findFragment<ColorTagListFragmentHorizontal>()
val activity = fragment.activity ?: return@setOnClickListener
val startForResult =
activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == AppCompatActivity.RESULT_OK) {
}
}
startForResult.launch(Intent(activity, ColorTagListActivity::class.java))
}
}
override fun getItemViewType(position: Int) =
if (position < array.count()) ColorTagType else FooterType
override fun getItemCount() = array.count() + 1
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ViewHolder) {
val item = array[position]
with(holder.binding) {
checked = item.color == selectedColorTagColor
data = item
executePendingBindings()
}
}
}
/* ViewHolder */
inner class ViewHolder(val binding: ListItemColortagHorizontalBinding) :
RecyclerView.ViewHolder(binding.root)
inner class EditViewHolder(binding: ListItemEditBinding) :
RecyclerView.ViewHolder(binding.root)
} | Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/colortag/ColorTagListAdapterHorizontal.kt | 2975703489 |
package com.nishtahir.fern.internal
import com.android.build.api.transform.*
import com.nishtahir.fern.DecompilerOptionsExtension
import org.gradle.api.Project
import org.gradle.api.logging.LogLevel
import java.io.File
import java.util.*
class FernTransform(private val project: Project, private val decompilerOptions: DecompilerOptionsExtension) : Transform() {
override fun getName() = "fern-android"
override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> = Collections.singleton(QualifiedContent.DefaultContentType.CLASSES)
override fun isIncremental() = false
override fun getScopes(): MutableSet<in QualifiedContent.Scope> = Collections.singleton(QualifiedContent.Scope.PROJECT)
override fun transform(invocation: TransformInvocation) {
super.transform(invocation)
invocation.context.logging.captureStandardOutput(LogLevel.INFO)
val inputs = invocation.inputs.flatMap { it.jarInputs + it.directoryInputs }
val outputs = inputs.map { input ->
val format = if (input is JarInput) Format.JAR else Format.DIRECTORY
invocation.outputProvider.getContentLocation(
input.name,
setOf(QualifiedContent.DefaultContentType.CLASSES),
EnumSet.of(QualifiedContent.Scope.PROJECT),
format
)
}
if (decompilerOptions.enabled) {
val decompiler = FernDecompiler(
sources = inputs.map { it.file },
outputPath = File("${project.buildDir}/decompiled-sources/${project.name}"),
options = decompilerOptions
)
decompiler.decompileContext()
}
inputs.zip(outputs) { input, output ->
input.file.copyRecursively(output, true)
}
}
} | src/main/kotlin/com/nishtahir/fern/internal/FernTransform.kt | 3739012379 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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 jp.nephy.penicillin.core.request.action
import jp.nephy.penicillin.core.exceptions.PenicillinException
import jp.nephy.penicillin.core.request.ApiRequest
import jp.nephy.penicillin.core.session.ApiClient
import kotlinx.coroutines.CancellationException
internal class DelegatedAction<R>(override val client: ApiClient, private val block: suspend () -> R): ApiAction<R> {
override val request: ApiRequest
get() = throw UnsupportedOperationException()
@Throws(PenicillinException::class, CancellationException::class)
override suspend operator fun invoke(): R {
return block()
}
}
| src/main/kotlin/jp/nephy/penicillin/core/request/action/DelegatedAction.kt | 3974388965 |
package com.example.examplescomposeconstraintlayout
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Wrap
@Preview(group = "flow1")
@Composable
fun FlowPad() {
val names = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#")
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom,
modifier = Modifier.fillMaxSize()
) {
ConstraintLayout(
ConstraintSet {
val keys = names.map { createRefFor(it) }.toTypedArray()
val flow = createFlow(
elements = keys,
maxElement = 3,
wrapMode = Wrap.Aligned,
verticalGap = 8.dp,
horizontalGap = 8.dp
)
constrain(flow) {
centerTo(parent)
}
},
modifier = Modifier
.background(Color(0xFFDAB539))
.padding(8.dp)
) {
names.map {
Button(
modifier = Modifier.layoutId(it), onClick = {},
) {
Text(text = it)
}
}
}
}
} | demoProjects/ExamplesComposeConstraintLayout/app/src/main/java/com/example/examplescomposeconstraintlayout/FlowKeyPad.kt | 3266612804 |
package io.github.manamiproject.manami.app.cache.populator
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock.*
import io.github.manamiproject.manami.app.cache.DefaultAnimeCache
import io.github.manamiproject.manami.app.cache.DeadEntry
import io.github.manamiproject.manami.app.cache.MetaDataProviderTestConfig
import io.github.manamiproject.manami.app.cache.TestCacheLoader
import io.github.manamiproject.modb.core.config.AnimeId
import io.github.manamiproject.modb.core.config.Hostname
import io.github.manamiproject.modb.core.config.MetaDataProviderConfig
import io.github.manamiproject.modb.test.MockServerTestCase
import io.github.manamiproject.modb.test.WireMockServerCreator
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.net.URI
import java.net.URL
internal class DeadEntriesCachePopulatorTest: MockServerTestCase<WireMockServer> by WireMockServerCreator() {
@Test
fun `successfully populate cache with dead entries`() {
// given
val testCache = DefaultAnimeCache(listOf(TestCacheLoader))
val testConfig = object: MetaDataProviderConfig by MetaDataProviderTestConfig {
override fun hostname(): Hostname = "example.org"
override fun buildAnimeLink(id: AnimeId): URI = URI("https://${hostname()}/anime/$id")
}
val animeCachePopulator = DeadEntriesCachePopulator(
config = testConfig,
url = URL("http://localhost:$port/dead-entires/all.json")
)
serverInstance.stubFor(
get(urlPathEqualTo("/dead-entires/all.json")).willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(200)
.withBody("""
{
"deadEntries": [
"12449",
"65562"
]
}
""".trimIndent())
)
)
// when
animeCachePopulator.populate(testCache)
// then
assertThat(testCache.fetch(URI("https://example.org/anime/12449"))).isInstanceOf(DeadEntry::class.java)
assertThat(testCache.fetch(URI("https://example.org/anime/65562"))).isInstanceOf(DeadEntry::class.java)
}
} | manami-app/src/test/kotlin/io/github/manamiproject/manami/app/cache/populator/DeadEntriesCachePopulatorTest.kt | 2130878764 |
/*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.api.router
/**
* Bean representing a "route" (e.g., an Apache Camel route)
*
* @author Julian Schuette ([email protected])
*/
class RouteObject {
var status: String? = null
var uptime: Long = 0
var context: String? = null
var shortName: String? = null
var dot: String? = null
var description: String? = null
var id: String? = null
constructor() {
/* Bean std c'tor */
}
constructor(
id: String?,
description: String?,
dot: String?,
shortName: String?,
context: String?,
uptime: Long,
status: String?
) {
this.id = id
this.description = description
this.dot = dot
this.shortName = shortName
this.context = context
this.uptime = uptime
this.status = status
}
}
| ids-api/src/main/java/de/fhg/aisec/ids/api/router/RouteObject.kt | 3246702689 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.util
import org.reflections.Reflections
import uk.co.nickthecoder.paratask.parameters.GroupedChoiceParameter
import uk.co.nickthecoder.tickle.scripts.ScriptManager
import java.lang.reflect.Modifier
object ClassLister {
var reflectionsMap = mutableMapOf<String, Reflections>()
private val cache = mutableMapOf<Class<*>, List<Class<*>>>()
init {
addPackage("uk.co.nickthecoder.tickle")
}
fun packages(packages: List<String>) {
reflectionsMap.clear()
packages.forEach { addPackage(it) }
}
fun addPackage(pack: String) {
cache.clear()
reflectionsMap[pack] = Reflections(pack)
}
fun subTypes(type: Class<*>): List<Class<*>> {
val cached = cache[type]
val results = mutableListOf<Class<*>>()
if (cached != null) {
results.addAll(cached)
} else {
// Find all compiled classes of the given type. i.e. NOT scripted languages.
reflectionsMap.values.forEach {
results.addAll(it.getSubTypesOf(type).filter { !it.isInterface && !Modifier.isAbstract(it.modifiers) }.sortedBy { it.name })
}
cache[type] = results.toList()
}
// Find all scripted class of the given type
results.addAll(ScriptManager.subTypes(type))
return results
}
fun setChoices(choiceParameter: GroupedChoiceParameter<Class<*>>, type: Class<*>) {
val value = choiceParameter.value
choiceParameter.clear()
subTypes(type).groupBy { it.`package` }.forEach { pack, list ->
val group = choiceParameter.group(pack?.name ?: "Top-Level")
list.forEach { klass ->
group.choice(klass.name, klass, klass.simpleName)
}
}
choiceParameter.value = value
}
fun setNullableChoices(choiceParameter: GroupedChoiceParameter<Class<*>?>, type: Class<*>) {
val value = choiceParameter.value
choiceParameter.clear()
choiceParameter.addChoice("", null, "<none>")
subTypes(type).groupBy { it.`package` }.forEach { pack, list ->
val group = choiceParameter.group(pack?.name ?: "Top-Level")
list.forEach { klass ->
group.choice(klass.name, klass, klass.simpleName)
}
}
choiceParameter.value = value
}
fun clearCache() {
cache.clear()
}
}
| tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/ClassLister.kt | 1698725323 |
package com.fuyoul.sanwenseller.configs
import com.fuyoul.sanwenseller.R
import com.lzy.okgo.OkGo
/**
* @author: chen
* @CreatDate: 2017\10\25 0025
* @Desc:
*/
object UrlInfo {
private var base = OkGo.getInstance().context.getString(R.string.baseUrl)
/**登录相关**/
val LOGIN = "$base/account/master/signIn"//登录
val SMS = "$base/account/sendVerifyCode?phone="//获取验证码
val GETTAGLIST = "$base/account/master/labelList"//获取标签
val SUBMITMASTERINFO = "$base/account/master/apply"//提交预测师申请资料
/**订单相关**/
val ORDERLIST = "$base/order/master/orderList"//获取订单列表
val APPOINTMENTLIST = "$base/masterSchedulingHandler/getMasterSchedulingHandler"//获取大师盘班表
val CHANGEAPPOINTMENT = "$base/masterSchedulingHandler/updateMasterScheduling"//更改大师排班表
val CHANGEITEMAPPOINTMENT = "$base/masterSchedulingHandler/modifyAppointmentStatus"//修改某天某个时间点的接单状态
val APPOIINTMENTINFO = "$base/masterSchedulingHandler/getAppointInfo"//获取预约信息
val FINDFLASHORDERCOUNT = "$base/order/flashOrderCount"//查询大师闪测接单数
val UPDATEFLASHORDERCOUNT = "$base/order/flashOrderUpdate"//设置当天闪测接单数
val CONFIRMORDER = "$base/order/confirmOrder"//确认订单
val ORDERREFUND = "$base/order/master/masterDealRefund"//同意/拒绝退款
val ORDERDELETE = "$base/order/user/delOrder"//删除订单
val INCOME = "$base/master/masterIncome"//收入相关
val SETTLEMENTDATE = "$base/master/getOrdersYearMonth"//收入时间节点
/**商品相关**/
val BABYLIST = "$base/goods/master/getMasterGoodsList"//获取预测师的宝贝礼拜
val BABYDELETE = "$base/goods/deleteGoods"//删除商品
val BABYDOWNTOSHOP = "$base/goods/master/soldOut"//商品下架
val BABYUPTOSHOP = "$base/goods/master/goodsPutaway"//商品上架
val BABYRELEASE = "$base/goods/master/releaseGoods"//发布商品
val BABYEDIT = "$base/goods/editGoods"//编辑商品
/**用户信息相关**/
val EDITUSERINFO = "$base/account/user/editUserInfo"//更新个人资料
/**七牛**/
val GETIMGTOKEN = "$base/qiniu/getQiniuUploadToken"//获取七牛的token
/**其他信息**/
val REWARDRULE = "$base/master/rewardRule"//奖励制度
val GETCONFIG = "$base/account/user/getSysConfig" //获取一些配置信息
} | app/src/main/java/com/fuyoul/sanwenseller/configs/UrlInfo.kt | 3087761323 |
package com.github.kittinunf.reactiveandroid.sample.view
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import com.github.kittinunf.reactiveandroid.sample.R
import kotlinx.android.synthetic.main.activity_nested_recycler_view.firstRecyclerView
import kotlinx.android.synthetic.main.activity_nested_recycler_view.secondRecyclerView
class NestedRecyclerViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nested_recycler_view)
firstRecyclerView.apply {
layoutManager = LinearLayoutManager(this@NestedRecyclerViewActivity)
// rx_itemsWith(Observable.just(listOf(1, 2, 3, 4, 5, 6, 7, 8)), { parent, viewType ->
// val v = LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false)
// ViewHolder(v)
// }, { holder, position, item ->
// holder.textView.text = item.toString()
// })
}
secondRecyclerView.apply {
layoutManager = LinearLayoutManager(this@NestedRecyclerViewActivity)
// rx_itemsWith(Observable.just(listOf(1, 2, 3, 4, 5, 6, 7, 8)), { parent, viewType ->
// val v = LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false)
// ViewHolder(v)
// }, { holder, position, item ->
// holder.textView.text = item.toString()
// })
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView by lazy { view.findViewById<TextView>(android.R.id.text1) }
}
}
| sample/src/main/kotlin/com.github.kittinunf.reactiveandroid.sample/view/NestedRecyclerViewActivity.kt | 2697126157 |
package com.zj.example.kotlin.dsl
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Created by zhengjiong
* date: 2017/10/1 19:07
*/
class MapDelegate(val map: MutableMap<String, String>) : ReadWriteProperty<Any, String> {
override fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
map[property.name] = value
}
override fun getValue(thisRef: Any, property: KProperty<*>): String {
return map[property.name] ?: ""
}
} | src/main/kotlin/com/zj/example/kotlin/dsl/MapDelegate.kt | 3327307850 |
package com.jakewharton.rxbinding4.widget
import android.widget.SearchView
data class SearchViewQueryTextEvent(
/** The view from which this event occurred. */
val view: SearchView,
val queryText: CharSequence,
val isSubmitted: Boolean
)
| rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/SearchViewQueryTextEvent.kt | 1795785800 |
//
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.app
object UndoManager : UndoManagerInterface {
var undoState: UndoState? = null
override fun addUndoState(state: UndoState) {
synchronized(this) {
undoState = state
}
}
override fun undo() {
synchronized(this) {
undoState?.undo?.run()
undoState = null
}
}
override fun clearUndoState() {
synchronized(this) {
undoState?.dismiss?.run()
undoState = null
}
}
override val canUndo: Boolean
get() = synchronized(this) {
undoState != null
}
} | app/src/main/java/com/github/quarck/calnotify/app/UndoManager.kt | 3315427422 |
package de.maibornwolff.codecharta.tools.validation
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptInput
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ParserDialogTest {
@AfterAll
fun afterTest() {
unmockkAll()
}
@Test
fun `should output correct arguments`() {
mockkStatic("com.github.kinquirer.components.InputKt")
every {
KInquirer.promptInput(any(), any(), any())
} returns "sampleFile.cc.json"
val parserArguments = ParserDialog.collectParserArgs()
Assertions.assertThat(parserArguments).isEqualTo(listOf("sampleFile.cc.json"))
}
}
| analysis/tools/ValidationTool/src/test/kotlin/de/maibornwolff/codecharta/tools/validation/ParserDialogTest.kt | 3892084935 |
package net.perfectdreams.loritta.morenitta.youtube
class YouTubeWebhook(val createdAt: Long, val lease: Int) | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/youtube/YouTubeWebhook.kt | 585381931 |
package net.perfectdreams.loritta.morenitta.utils
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.obj
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import net.perfectdreams.loritta.morenitta.dao.DonationKey
import net.perfectdreams.loritta.morenitta.tables.DonationKeys
import io.ktor.client.request.*
import io.ktor.client.statement.*
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.dao.Payment
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.payments.PaymentGateway
import net.perfectdreams.loritta.morenitta.utils.payments.PaymentReason
import java.util.*
class PerfectPaymentsClient(val url: String) {
private val logger = KotlinLogging.logger {}
/**
* Creates a payment in PerfectPayments, creates a entry in Loritta's payment table and returns the payment URL
*
* @return the payment URL
*/
suspend fun createPayment(
loritta: LorittaBot,
userId: Long,
paymentTitle: String,
amount: Long,
storedAmount: Long,
paymentReason: PaymentReason,
externalReference: String,
discount: Double? = null,
metadata: JsonObject? = null
): String {
logger.info { "Requesting PerfectPayments payment URL for $userId" }
val payments = loritta.http.post("${url}api/v1/payments") {
header("Authorization", loritta.config.loritta.perfectPayments.token)
setBody(
jsonObject(
"title" to paymentTitle,
"callbackUrl" to "${loritta.config.loritta.website.url}api/v1/callbacks/perfect-payments",
"amount" to amount,
"currencyId" to "BRL",
"externalReference" to externalReference
).toString()
)
}.bodyAsText()
val paymentResponse = JsonParser.parseString(payments)
.obj
val partialPaymentId = UUID.fromString(paymentResponse["id"].string)
val paymentUrl = paymentResponse["paymentUrl"].string
logger.info { "Payment successfully created for $userId! ID: $partialPaymentId" }
loritta.newSuspendedTransaction {
DonationKey.find {
DonationKeys.expiresAt greaterEq System.currentTimeMillis()
}
Payment.new {
this.userId = userId
this.gateway = PaymentGateway.PERFECTPAYMENTS
this.reason = paymentReason
if (discount != null)
this.discount = discount
if (metadata != null)
this.metadata = metadata
this.money = (storedAmount.toDouble() / 100).toBigDecimal()
this.createdAt = System.currentTimeMillis()
this.referenceId = partialPaymentId
}
}
return paymentUrl
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/PerfectPaymentsClient.kt | 3838714808 |
package net.perfectdreams.loritta.cinnamon.showtime.backend.utils
import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend
import org.apache.commons.codec.digest.DigestUtils
import java.util.concurrent.ConcurrentHashMap
class WebsiteAssetsHashManager(val showtime: ShowtimeBackend) {
val websiteFileHashes = ConcurrentHashMap<String, String>()
/**
* Generates a MD5 hexadecimal hash for the file in the [assetName] path, useful for cache busting
*
* After the first hash generation, the hash will be cached
*
* @param assetName the file path
* @return the asset content hashed in MD5
*/
fun getAssetHash(assetName: String): String {
return if (websiteFileHashes.containsKey(assetName)) {
websiteFileHashes[assetName]!!
} else {
val md5 = DigestUtils.md5Hex(WebsiteAssetsHashManager::class.java.getResourceAsStream("/static/v3/${assetName.removePrefix("/")}"))
websiteFileHashes[assetName] = md5
md5
}
}
} | web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/utils/WebsiteAssetsHashManager.kt | 1364099506 |
package io.innofang.builder.example.kotlin
/**
* Created by Inno Fang on 2017/8/31.
*/
fun main(args: Array<String>) {
val ferrari = Ferrari.build {
brand = "ferrari"
color = "red"
licensePlate = "B88888"
}
println(ferrari)
val audi = Audi.build {
brand = "Audi"
color = "blue"
licensePlate = "C88888"
}
println(audi)
} | src/io/innofang/builder/example/kotlin/Client.kt | 820545330 |
package net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils
object LoadingGifs {
val list = listOf(
"https://cdn.discordapp.com/emojis/957368372025262120.gif?size=160&quality=lossless",
"https://cdn.discordapp.com/emojis/958906311414796348.gif?size=160&quality=lossless",
"https://cdn.discordapp.com/emojis/959551356769820712.gif?size=160&quality=lossless",
"https://cdn.discordapp.com/emojis/959557654341103696.gif?size=160&quality=lossless",
"https://cdn.discordapp.com/emojis/985919207147470858.gif?size=160&quality=lossless"
)
} | web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/utils/LoadingGifs.kt | 4155014352 |
package com.blankj.utilcode.pkg.feature.process
import android.content.Context
import android.content.Intent
import com.blankj.common.activity.CommonActivity
import com.blankj.common.item.CommonItem
import com.blankj.common.item.CommonItemClick
import com.blankj.common.item.CommonItemTitle
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ProcessUtils
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2016/10/13
* desc : demo about ProcessUtils
* ```
*/
class ProcessActivity : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, ProcessActivity::class.java)
context.startActivity(starter)
}
}
override fun bindTitleRes(): Int {
return R.string.demo_process
}
override fun bindItems(): MutableList<CommonItem<*>> {
val set = ProcessUtils.getAllBackgroundProcesses()
return CollectionUtils.newArrayList(
CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()!!),
CommonItemTitle("getAllBackgroundProcesses -> ${set.size}", getSetItems(set)),
CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()),
CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()),
CommonItemClick(R.string.process_kill_all_background).setOnItemClickListener { _, item, _ ->
val bgSet = ProcessUtils.getAllBackgroundProcesses()
val killedSet = ProcessUtils.killAllBackgroundProcesses()
itemsView.updateItems(
CollectionUtils.newArrayList(
CommonItemTitle("getForegroundProcessName", ProcessUtils.getForegroundProcessName()),
CommonItemTitle("getAllBackgroundProcesses -> ${bgSet.size}", getSetItems(bgSet)),
CommonItemTitle("killAllBackgroundProcesses -> ${killedSet.size}", getSetItems(killedSet)),
CommonItemTitle("isMainProcess", ProcessUtils.isMainProcess().toString()),
CommonItemTitle("getCurrentProcessName", ProcessUtils.getCurrentProcessName()),
item
)
)
}
)
}
private fun getSetItems(set: Set<String>): String {
val iterator = set.iterator()
val sb = StringBuilder()
while (iterator.hasNext()) {
sb.append("\n").append(iterator.next())
}
return if (sb.isNotEmpty()) sb.deleteCharAt(0).toString() else ""
}
}
| feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/process/ProcessActivity.kt | 1036167596 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.xprank
import dev.kord.core.entity.User
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.*
import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds
class ChangeXpRankPageButtonExecutor(loritta: LorittaBot) : CinnamonButtonExecutor(loritta) {
companion object : ButtonExecutorDeclaration(ComponentExecutorIds.CHANGE_XP_RANK_PAGE_BUTTON_EXECUTOR)
override suspend fun onClick(user: User, context: ComponentContext) {
if (context !is GuildComponentContext)
return
val data = context.decodeDataFromComponentOrFromDatabaseAndRequireUserToMatch<ChangeXpRankPageData>()
// Loading Section
context.updateMessageSetLoadingState()
// TODO: Cache this somewhere
val guild = loritta.kord.getGuild(context.guildId)!!
val message = XpRankExecutor.createMessage(loritta, context, guild, data.page)
context.updateMessage {
message()
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/xprank/ChangeXpRankPageButtonExecutor.kt | 3694189078 |
package za.co.dvt.android.showcase.injection
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import timber.log.Timber
import za.co.dvt.android.showcase.ShowcaseApplication
/**
* @author rebeccafranks
* *
* @since 2017/06/07.
*/
class ShowcaseFactory(private val application: ShowcaseApplication) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val t = super.create(modelClass)
if (t is ShowcaseComponent.Injectable) {
t.inject(application.showcaseComponent)
} else {
Timber.d("item is not of type ShowcaseComponent.Injectable")
}
return t
}
}
| app/src/main/kotlin/za/co/dvt/android/showcase/injection/ShowcaseFactory.kt | 994619600 |
package com.rartworks.engine.utils
import com.badlogic.gdx.math.MathUtils
/**
* Increases the number until a max [limit].
*/
fun Float.increaseUntil(delta: Float, limit: Float): Float {
val result = this + delta
return if (result > limit) limit else result
}
/**
* Decreases the number until a min [limit].
*/
fun Float.decreaseUntil(delta: Float, limit: Float): Float {
val result = this - delta
return if (result < limit) limit else result
}
/**
* Returns if the number is equal to [another] applying a [delta] for the comparison.
*/
fun Float.isEqualWithDelta(another: Float, delta: Float): Boolean {
return Math.abs(this - another) < delta
}
/**
* Generates a random number between this and [max].
*/
fun Float.toRandom(max: Float): Float {
return this + MathUtils.random() * (max - this)
}
/**
* Generates a random number between this and [max].
*/
fun Int.toRandom(max: Int): Int {
return this.toFloat().toRandom(max.toFloat()).toInt()
}
/**
* Creates a [String] with the [Float] and [digits] trailing zeros.
*/
fun Int.addTrailingZeros(digits: Int) = java.lang.String.format("%0${digits}d", this)
| core/src/com/rartworks/engine/utils/NumberExtensions.kt | 2754869293 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.screens.settings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.google.homesampleapp.R
import com.google.homesampleapp.databinding.FragmentSettingsBinding
import timber.log.Timber
/** Shows settings and user preferences. */
class SettingsFragment : Fragment() {
private lateinit var binding: FragmentSettingsBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_settings, container, false)
setupUiElements()
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
childFragmentManager
.beginTransaction()
.replace(R.id.nested_settings_fragment, SettingsNestedFragment())
.commit()
}
private fun setupUiElements() {
binding.topAppBar.setNavigationOnClickListener {
// navigate back.
Timber.d("topAppBar.setNavigationOnClickListener")
findNavController().popBackStack()
}
}
}
| app/src/main/java/com/google/homesampleapp/screens/settings/SettingsFragment.kt | 2273588976 |
package org.fossasia.susi.ai.skills.settings
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.preference.ListPreference
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.widget.AppCompatCheckBox
import android.util.Log
import android.view.Menu
import android.view.View
import android.widget.Toast
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.login.LoginActivity
import org.fossasia.susi.ai.helper.PrefManager
import org.fossasia.susi.ai.skills.settings.contract.ISettingsPresenter
import org.fossasia.susi.ai.skills.settings.contract.ISettingsView
import org.fossasia.susi.ai.skills.SkillsActivity
/**
* The Fragment for Settings Activity
*
* Created by mayanktripathi on 10/07/17.
*/
class ChatSettingsFragment : PreferenceFragmentCompat(), ISettingsView {
lateinit var settingsPresenter: ISettingsPresenter
lateinit var rate: Preference
lateinit var server: Preference
lateinit var micSettings: Preference
lateinit var hotwordSettings: Preference
lateinit var share: Preference
lateinit var loginLogout: Preference
lateinit var resetPassword: Preference
lateinit var enterSend: Preference
lateinit var speechAlways: Preference
lateinit var speechOutput: Preference
lateinit var password: TextInputLayout
lateinit var newPassword: TextInputLayout
lateinit var conPassword: TextInputLayout
lateinit var input_url: TextInputLayout
lateinit var resetPasswordAlert: AlertDialog
lateinit var setServerAlert: AlertDialog
lateinit var querylanguage: ListPreference
var flag = true
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.pref_settings)
(activity as SkillsActivity).title = (activity as SkillsActivity).getString(R.string.action_settings)
settingsPresenter = SettingsPresenter(activity as SkillsActivity)
settingsPresenter.onAttach(this)
setHasOptionsMenu(true)
rate = preferenceManager.findPreference(Constant.RATE)
server = preferenceManager.findPreference(Constant.SELECT_SERVER)
micSettings = preferenceManager.findPreference(Constant.MIC_INPUT)
hotwordSettings = preferenceManager.findPreference(Constant.HOTWORD_DETECTION)
share = preferenceManager.findPreference(Constant.SHARE)
loginLogout = preferenceManager.findPreference(Constant.LOGIN_LOGOUT)
resetPassword = preferenceManager.findPreference(Constant.RESET_PASSWORD)
enterSend = preferenceManager.findPreference(Constant.ENTER_SEND)
speechOutput = preferenceManager.findPreference(Constant.SPEECH_OUTPUT)
speechAlways = preferenceManager.findPreference(Constant.SPEECH_ALWAYS)
querylanguage = preferenceManager.findPreference(Constant.LANG_SELECT) as ListPreference
setLanguage()
if (settingsPresenter.getAnonymity()) {
loginLogout.title = "Login"
} else {
loginLogout.title = "Logout"
}
querylanguage.setOnPreferenceChangeListener { _, newValue ->
PrefManager.putString(Constant.LANGUAGE, newValue.toString())
setLanguage()
if(!settingsPresenter.getAnonymity()) {
settingsPresenter.sendSetting(Constant.LANGUAGE, newValue.toString(), 1)
}
true
}
rate.setOnPreferenceClickListener {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName)))
true
}
share.setOnPreferenceClickListener {
try {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TEXT,
String.format(getString(R.string.promo_msg_template),
String.format(getString(R.string.app_share_url), activity.packageName)))
startActivity(shareIntent)
} catch (e: Exception) {
showToast(getString(R.string.error_msg_retry))
}
true
}
loginLogout.setOnPreferenceClickListener {
if (!settingsPresenter.getAnonymity()) {
val d = AlertDialog.Builder(activity)
d.setMessage("Are you sure ?").setCancelable(false).setPositiveButton("Yes") { _, _ ->
settingsPresenter.loginLogout()
}.setNegativeButton("No") { dialog, _ -> dialog.cancel() }
val alert = d.create()
alert.setTitle(getString(R.string.logout))
alert.show()
} else {
settingsPresenter.loginLogout()
}
true
}
if (settingsPresenter.getAnonymity()) {
server.isEnabled = true
server.setOnPreferenceClickListener {
showAlert()
true
}
} else {
server.isEnabled = false
}
if(!settingsPresenter.getAnonymity()) {
resetPassword.isEnabled = true
resetPassword.setOnPreferenceClickListener {
showResetPasswordAlert()
true
}
} else {
resetPassword.isEnabled = false
}
micSettings.isEnabled = settingsPresenter.enableMic()
hotwordSettings.isEnabled = settingsPresenter.enableHotword()
if(!settingsPresenter.getAnonymity()) {
micSettings.setOnPreferenceClickListener {
settingsPresenter.sendSetting(Constant.MIC_INPUT, (PrefManager.getBoolean(Constant.MIC_INPUT, false)).toString(), 1)
true
}
enterSend.setOnPreferenceChangeListener { _, newValue ->
settingsPresenter.sendSetting(Constant.ENTER_SEND, newValue.toString(), 1)
true
}
speechAlways.setOnPreferenceChangeListener { _, newValue ->
settingsPresenter.sendSetting(Constant.SPEECH_ALWAYS, newValue.toString(), 1)
true
}
speechOutput.setOnPreferenceChangeListener { _, newValue ->
settingsPresenter.sendSetting(Constant.SPEECH_OUTPUT, newValue.toString(), 1)
true
}
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val itemSettings = menu.findItem(R.id.menu_settings)
itemSettings.isVisible = false
val itemAbout = menu.findItem(R.id.menu_about)
itemAbout.isVisible = true
super.onPrepareOptionsMenu(menu)
}
fun setLanguage() {
val index = querylanguage.findIndexOfValue(PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT))
querylanguage.setValueIndex(index)
querylanguage.summary = querylanguage.entries[index]
}
fun showAlert() {
val builder = AlertDialog.Builder(activity)
val promptsView = activity.layoutInflater.inflate(R.layout.alert_change_server, null)
input_url = promptsView.findViewById(R.id.input_url) as TextInputLayout
val input_url_text = promptsView.findViewById(R.id.input_url_text) as TextInputEditText
val customer_server = promptsView.findViewById(R.id.customer_server) as AppCompatCheckBox
if (PrefManager.getBoolean(Constant.SUSI_SERVER, true)) {
input_url.visibility = View.GONE
flag = false
} else {
input_url.visibility = View.VISIBLE
flag = true
}
customer_server.isChecked = flag
input_url_text.setText(PrefManager.getString(Constant.CUSTOM_SERVER, null))
customer_server.setOnCheckedChangeListener { buttonView, isChecked ->
if(isChecked)
input_url.visibility = View.VISIBLE
if(!isChecked)
input_url.visibility = View.GONE
}
builder.setView(promptsView)
builder.setTitle(Constant.CHANGE_SERVER)
.setCancelable(false)
.setNegativeButton(Constant.CANCEL, null)
.setPositiveButton(activity.getString(R.string.ok), null)
setServerAlert = builder.create()
setServerAlert.show()
setServerAlert.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener {
settingsPresenter.setServer(customer_server.isChecked, input_url.editText?.text.toString())
}
}
fun showResetPasswordAlert() {
val builder = AlertDialog.Builder(activity)
val resetPasswordView = activity.layoutInflater.inflate(R.layout.alert_reset_password, null)
password = resetPasswordView.findViewById(R.id.password) as TextInputLayout
newPassword = resetPasswordView.findViewById(R.id.newpassword) as TextInputLayout
conPassword = resetPasswordView.findViewById(R.id.confirmpassword) as TextInputLayout
builder.setView(resetPasswordView)
builder.setTitle(Constant.CHANGE_PASSWORD)
.setCancelable(false)
.setNegativeButton(Constant.CANCEL, null)
.setPositiveButton(getString(R.string.ok), null)
resetPasswordAlert = builder.create()
resetPasswordAlert.show()
setupPasswordWatcher()
resetPasswordAlert.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener {
settingsPresenter.resetPassword(password.editText?.text.toString(), newPassword.editText?.text.toString(), conPassword.editText?.text.toString())
}
}
override fun micPermission(): Boolean {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
}
override fun hotWordPermission(): Boolean {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
}
override fun startLoginActivity() {
val intent = Intent(activity, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
activity.finish()
}
fun showToast(message: String) {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
}
override fun onSettingResponse(message: String) {
Log.d("settingresponse", message)
}
override fun passwordInvalid(what: String) {
when(what) {
Constant.NEW_PASSWORD -> newPassword.error = getString(R.string.pass_validation_text)
Constant.PASSWORD -> password.error = getString(R.string.pass_validation_text)
Constant.CONFIRM_PASSWORD -> conPassword.error = getString(R.string.pass_validation_text)
}
}
override fun invalidCredentials(isEmpty: Boolean, what: String) {
if(isEmpty) {
when(what) {
Constant.PASSWORD -> password.error = getString(R.string.field_cannot_be_empty)
Constant.NEW_PASSWORD -> newPassword.error = getString(R.string.field_cannot_be_empty)
Constant.CONFIRM_PASSWORD -> conPassword.error = getString(R.string.field_cannot_be_empty)
}
} else {
conPassword.error = getString(R.string.error_password_matching)
}
}
override fun onResetPasswordResponse(message: String) {
resetPasswordAlert.dismiss()
if(!message.equals("null")) {
showToast(message)
} else {
showToast(getString(R.string.wrong_password))
showResetPasswordAlert()
}
}
override fun checkUrl(isEmpty: Boolean) {
if(isEmpty) {
input_url.error = getString(R.string.field_cannot_be_empty)
} else {
input_url.error = getString(R.string.invalid_url)
}
}
override fun setServerSuccessful() {
setServerAlert.dismiss()
}
fun setupPasswordWatcher() {
password.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
password.error = null
if (!hasFocus)
settingsPresenter.checkForPassword(password.editText?.text.toString(), Constant.PASSWORD)
}
newPassword.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
newPassword.error = null
if (!hasFocus)
settingsPresenter.checkForPassword(newPassword.editText?.text.toString(), Constant.NEW_PASSWORD)
}
conPassword.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
conPassword.error = null
if (!hasFocus)
settingsPresenter.checkForPassword(conPassword.editText?.text.toString(), Constant.CONFIRM_PASSWORD)
}
}
override fun onDestroyView() {
super.onDestroyView()
settingsPresenter.onDetach()
}
} | app/src/main/java/org/fossasia/susi/ai/skills/settings/ChatSettingsFragment.kt | 148891076 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.samples.dynamiccodeloading
import android.app.Application
import android.content.Context
import android.util.Log
import java.util.ServiceLoader
/**
* An implementation of our ViewModel that uses ServiceLoader.
*
* ServiceLoader is a standard mechanism in Java that is used to load
* concrete service implementations (as defined by an interface)
* based on metadata found in META-INF/services/
*
* You can find the corresponding metadata file in the storage module
* in storage/src/serviceLoader/resources/META-INF/services
*
* Please note that by default, ServiceLoader involves disk access
* and performs slow operations, making the performance of this solution
* not optimal for use in Android apps.
*
* R8 (the new code shrinker and optimizer in Android Studio 3.4)
* introduced an optimization where for straightforward ServiceLoader uses
* it is able to replace them with straight object instantiation based
* on the same metadata from META-INF at build time,
* mitigating the performance and disk access issues.
*
* At the time of writing this sample, a specific version of R8 from master
* has to be used. The optimization should be in versions of R8 included with
* Android Gradle Plugin 3.5.0+.
*
* The ServiceLoader approach can be useful if you want to load
* multiple implementations of a service. Even though in this sample we only
* have one StorageFeature implementation, ServiceLoader.load returns an iterator
* with all registered classes.
*/
class MainViewModel(app: Application) : AbstractMainViewModel(app) {
override fun initializeStorageFeature() {
// We will need this to pass in dependencies to the StorageFeature.Provider
val dependencies: StorageFeature.Dependencies = object : StorageFeature.Dependencies {
override fun getContext(): Context = getApplication()
override fun getLogger(): Logger = MainLogger
}
// Ask ServiceLoader for concrete implementations of StorageFeature.Provider
// Explicitly use the 2-argument version of load to enable R8 optimization.
val serviceLoader = ServiceLoader.load(
StorageFeature.Provider::class.java,
StorageFeature.Provider::class.java.classLoader
)
// Explicitly ONLY use the .iterator() method on the returned ServiceLoader to enable R8 optimization.
// When these two conditions are met, R8 replaces ServiceLoader calls with direct object instantiation.
storageModule = serviceLoader.iterator().next().get(dependencies)
Log.d(TAG, "Loaded storage feature through ServiceLoader")
}
}
| DynamicCodeLoadingKotlin/app/src/serviceLoader/java/com/google/android/samples/dynamiccodeloading/MainViewModel.kt | 1872319514 |
package net.pterodactylus.sone.web.ajax
import com.fasterxml.jackson.databind.ObjectMapper
import freenet.clients.http.ToadletContext
import net.pterodactylus.sone.utils.parameters
import net.pterodactylus.sone.web.SessionProvider
import net.pterodactylus.sone.web.WebInterface
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.util.web.Page
import net.pterodactylus.util.web.Response
import java.io.ByteArrayOutputStream
import java.io.PrintStream
/**
* A JSON page is a specialized [Page] that will always return a JSON
* object to the browser, e.g. for use with AJAX or other scripting frameworks.
*/
abstract class JsonPage(protected val webInterface: WebInterface) : Page<FreenetRequest> {
private val objectMapper = ObjectMapper()
private val sessionProvider: SessionProvider = webInterface
protected val core = webInterface.core
override fun getPath() = toadletPath
override fun isPrefixPage() = false
open val needsFormPassword = true
open val requiresLogin = true
protected fun createSuccessJsonObject() = JsonReturnObject(true)
protected fun createErrorJsonObject(error: String) =
JsonErrorReturnObject(error)
protected fun getCurrentSone(toadletContext: ToadletContext) =
sessionProvider.getCurrentSone(toadletContext)
override fun handleRequest(request: FreenetRequest, response: Response): Response {
if (core.preferences.requireFullAccess && !request.toadletContext.isAllowedFullAccess) {
return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString())
}
if (needsFormPassword && request.parameters["formPassword"] != webInterface.formPassword) {
return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString())
}
if (requiresLogin && (sessionProvider.getCurrentSone(request.toadletContext) == null)) {
return response.setStatusCode(403).setStatusText("Forbidden").setContentType("application/json").write(createErrorJsonObject("auth-required").asJsonString())
}
return try {
response.setStatusCode(200).setStatusText("OK").setContentType("application/json").write(createJsonObject(request).asJsonString())
} catch (e: Exception) {
response.setStatusCode(500).setStatusText(e.message).setContentType("text/plain").write(e.dumpStackTrace())
}
}
abstract fun createJsonObject(request: FreenetRequest): JsonReturnObject
private fun JsonReturnObject.asJsonString(): String = objectMapper.writeValueAsString(this)
private fun Throwable.dumpStackTrace(): String = ByteArrayOutputStream().use {
PrintStream(it, true, "UTF-8").use {
this.printStackTrace(it)
}
it.toString("UTF-8")
}
}
| src/main/kotlin/net/pterodactylus/sone/web/ajax/JsonPage.kt | 402455874 |
package com.nlefler.glucloser.a.dataSource.jsonAdapter
import com.nlefler.glucloser.a.models.Food
import com.nlefler.glucloser.a.models.FoodEntity
import com.nlefler.glucloser.a.models.json.FoodJson
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
/**
* Created by nathan on 1/31/16.
*/
public class FoodJsonAdapter() {
@FromJson fun fromJson(json: FoodJson): Food {
val food = FoodEntity()
food.primaryID = json.primaryId
food.carbs = json.carbs
food.foodName = json.foodName
return food
}
@ToJson fun toJson(food: Food): FoodJson {
return FoodJson(
primaryId = food.primaryID,
foodName = food.foodName,
carbs = food.carbs
)
}
}
| Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/jsonAdapter/FoodJsonAdapter.kt | 898687025 |
package cz.vhromada.catalog.web.fo
import java.io.Serializable
import java.util.Objects
import javax.validation.Valid
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull
/**
* A class represents FO for song.
*
* @author Vladimir Hromada
*/
data class SongFO(
/**
* ID
*/
val id: Int?,
/**
* Name
*/
@field:NotBlank
val name: String?,
/**
* Length
*/
@field:NotNull
@field:Valid
var length: TimeFO?,
/**
* Note
*/
val note: String?,
/**
* Position
*/
val position: Int?) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return if (other !is SongFO || id == null) {
false
} else id == other.id
}
override fun hashCode(): Int {
return Objects.hashCode(id)
}
override fun toString(): String {
return String.format("SongFO [id=%d, name=%s, length=%s, note=%s, position=%d]", id, name, length, note, position)
}
}
| src/main/kotlin/cz/vhromada/catalog/web/fo/SongFO.kt | 4034764881 |
package io.particle.android.sdk.ui.devicelist
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.core.os.postDelayed
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProviders
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.ui.BaseActivity
import io.particle.android.sdk.updateUsernameWithCrashlytics
import io.particle.android.sdk.utils.SoftAPConfigRemover
import io.particle.android.sdk.utils.WifiFacade
import io.particle.android.sdk.utils.ui.Ui
import io.particle.mesh.ui.setup.MeshSetupActivity
import io.particle.sdk.app.R
class DeviceListActivity : BaseActivity() {
private var softAPConfigRemover: SoftAPConfigRemover? = null
private lateinit var filterViewModel: DeviceFilterViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
updateUsernameWithCrashlytics(ParticleCloudSDK.getCloud().loggedInUsername)
setContentView(R.layout.activity_device_list)
filterViewModel = ViewModelProviders.of(this).get(DeviceFilterViewModel::class.java)
filterViewModel.refreshDevices()
softAPConfigRemover = SoftAPConfigRemover(this, WifiFacade.get(this))
// TODO: If exposing deep links into your app, handle intents here.
if (Ui.findFrag<Fragment>(this, R.id.fragment_parent) == null) {
supportFragmentManager.commit {
add(R.id.fragment_parent, DeviceListFragment.newInstance())
}
}
onProcessIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
onProcessIntent(intent)
}
private fun onProcessIntent(intent: Intent) {
val intentUri = intent.data
// we have to do all this nonsense because Branch sends us garbage URIs
// which have *two schemes* in them.
if (intentUri != null
&& intentUri.encodedPath != null
&& (intentUri.encodedPath!!.contains("meshsetup") || intentUri.host != null && intentUri.host!!.contains(
"meshsetup"
))
) {
startActivity(Intent(this, MeshSetupActivity::class.java))
}
}
override fun onStart() {
super.onStart()
softAPConfigRemover!!.removeAllSoftApConfigs()
softAPConfigRemover!!.reenableWifiNetworks()
}
override fun onBackPressed() {
val currentFragment = Ui.findFrag<Fragment>(this, R.id.fragment_parent)
var deviceList: DeviceListFragment? = null
if (currentFragment is DeviceListFragment) {
deviceList = currentFragment
}
if (deviceList?.onBackPressed() != true) {
super.onBackPressed()
}
}
}
| app/src/main/java/io/particle/android/sdk/ui/devicelist/DeviceListActivity.kt | 3775697560 |
package com.waz.zclient.core.backend.datasources.local
import com.waz.zclient.UnitTest
import com.waz.zclient.core.extension.empty
import com.waz.zclient.eq
import com.waz.zclient.storage.pref.backend.BackendPreferences
import org.amshove.kluent.shouldBe
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
class BackendLocalDataSourceTest : UnitTest() {
private lateinit var backendPrefsDataSource: BackendLocalDataSource
@Mock
private lateinit var backendPreferences: BackendPreferences
@Before
fun setup() {
backendPrefsDataSource = BackendLocalDataSource(backendPreferences)
}
@Test
fun `when environment is called, returns backendPreferences' environment`() {
backendPrefsDataSource.environment()
verify(backendPreferences).environment
}
@Test
fun `given backendConfig is valid, when getBackendConfig is requested, then return config`() {
mockBackendPrefs(valid = true)
val response = backendPrefsDataSource.backendConfig()
response.fold({
assert(false) { "Expected a valid preference" }
}) {
assert(it == TEST_PREFERENCE) //TODO @Fernando : Does not verify with kluent: "it shouldBe TEST_PREFERENCE"
}
}
@Test
fun `given backendConfig is not valid, when getBackendConfig is requested, then return InvalidBackendConfig error`() {
mockBackendPrefs(valid = false)
val response = backendPrefsDataSource.backendConfig()
response.fold({
it shouldBe InvalidBackendConfig
}) {
assert(false) //should've got an error
}
}
@Test
fun `given url and new backend config, when update backend config is requested, then update backend preferences`() {
backendPrefsDataSource.updateBackendConfig(CONFIG_URL, TEST_PREFERENCE)
verify(backendPreferences).environment = eq(ENVIRONMENT)
verify(backendPreferences).customConfigUrl = eq(CONFIG_URL)
verify(backendPreferences).accountsUrl = eq(ACCOUNTS_URL)
verify(backendPreferences).baseUrl = eq(BASE_URL)
verify(backendPreferences).websocketUrl = eq(WEBSOCKET_URL)
verify(backendPreferences).teamsUrl = eq(TEAMS_URL)
verify(backendPreferences).websiteUrl = eq(WEBSITE_URL)
verify(backendPreferences).blacklistUrl = eq(BLACKLIST_URL)
}
private fun mockBackendPrefs(valid: Boolean) {
`when`(backendPreferences.environment).thenReturn(if (valid) ENVIRONMENT else String.empty())
`when`(backendPreferences.baseUrl).thenReturn(BASE_URL)
`when`(backendPreferences.websocketUrl).thenReturn(WEBSOCKET_URL)
`when`(backendPreferences.blacklistUrl).thenReturn(BLACKLIST_URL)
`when`(backendPreferences.teamsUrl).thenReturn(TEAMS_URL)
`when`(backendPreferences.accountsUrl).thenReturn(ACCOUNTS_URL)
`when`(backendPreferences.websiteUrl).thenReturn(WEBSITE_URL)
}
companion object {
private const val CONFIG_URL = "https://www.wire.com/config.json"
private const val ACCOUNTS_URL = "https://accounts.wire.com"
private const val ENVIRONMENT = "custom.environment.link.wire.com"
private const val BASE_URL = "https://www.wire.com"
private const val WEBSOCKET_URL = "https://websocket.wire.com"
private const val BLACKLIST_URL = "https://blacklist.wire.com"
private const val TEAMS_URL = "https://teams.wire.com"
private const val WEBSITE_URL = "https://wire.com"
private val TEST_PREFERENCE = CustomBackendPreferences(
ENVIRONMENT,
CustomBackendPrefEndpoints(
backendUrl = BASE_URL,
websocketUrl = WEBSOCKET_URL,
blacklistUrl = BLACKLIST_URL,
teamsUrl = TEAMS_URL,
accountsUrl = ACCOUNTS_URL,
websiteUrl = WEBSITE_URL
)
)
}
}
| app/src/test/kotlin/com/waz/zclient/core/backend/datasources/local/BackendLocalDataSourceTest.kt | 413596798 |
/* 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.helpers
import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import org.mozilla.focus.ext.settings
class FeatureSettingsHelper {
val context: Context = InstrumentationRegistry.getInstrumentation().targetContext
private val settings = context.settings
// saving default values of feature flags
private var shouldShowCfrForTrackingProtection: Boolean = settings.shouldShowCfrForTrackingProtection
fun setCfrForTrackingProtectionEnabled(enabled: Boolean) {
settings.shouldShowCfrForTrackingProtection = enabled
}
fun setShowStartBrowsingCfrEnabled(enabled: Boolean) {
settings.shouldShowStartBrowsingCfr = enabled
}
fun setSearchWidgetDialogEnabled(enabled: Boolean) {
if (enabled) {
settings.addClearBrowsingSessions(4)
} else {
settings.addClearBrowsingSessions(10)
}
}
// Important:
// Use this after each test if you have modified these feature settings
// to make sure the app goes back to the default state
fun resetAllFeatureFlags() {
settings.shouldShowCfrForTrackingProtection = shouldShowCfrForTrackingProtection
}
}
| app/src/androidTest/java/org/mozilla/focus/helpers/FeatureSettingsHelper.kt | 629634973 |
package com.izettle.wrench.oss.detail
import android.content.Context
import androidx.lifecycle.LiveData
import com.izettle.wrench.oss.LicenceMetadata
import com.izettle.wrench.oss.list.OssLoading
class LicenceMetadataLiveData(val context: Context, val licenceMetadata: LicenceMetadata) : LiveData<String>() {
init {
run {
postValue(OssLoading.getThirdPartyLicence(context, licenceMetadata))
}
}
}
| wrench-app/src/main/java/com/izettle/wrench/oss/detail/LicenceMetadataLiveData.kt | 2917576181 |
package jp.toastkid.yobidashi.settings.background
import androidx.annotation.StringRes
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import coil.load
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.ItemSavedImageBinding
import timber.log.Timber
import java.io.File
import java.io.IOException
/**
* Extended of [RecyclerView.ViewHolder].
*
* @param binding Binding object.
* @param preferenceApplier Preferences wrapper.
* @param onRemoved Action on removed.
*
* @author toastkidjp
*/
internal class ViewHolder(
private val binding: ItemSavedImageBinding,
private val preferenceApplier: PreferenceApplier,
private val onRemoved: () -> Unit
) : RecyclerView.ViewHolder(binding.root) {
/**
* Apply file content.
*
* @param f background image file
*/
fun applyContent(f: File?) {
if (f == null) {
return
}
binding.image.load(f)
binding.text.text = f.nameWithoutExtension
binding.remove.setOnClickListener { removeSetImage(f) }
binding.root.setOnClickListener {
preferenceApplier.backgroundImagePath = f.path
snack(R.string.message_change_background_image)
}
binding.root.setOnLongClickListener { v ->
try {
val context = v.context
if (context is FragmentActivity) {
ImageDialogFragment.withUrl(f.toURI().toString())
.show(
context.supportFragmentManager,
ImageDialogFragment::class.java.simpleName
)
}
} catch (e: IOException) {
Timber.e(e)
}
true
}
}
/**
* Remove set image.
*
* @param file Image file
*/
private fun removeSetImage(file: File?) {
if (file == null || !file.exists()) {
snack(R.string.message_cannot_found_image)
return
}
val successRemove = file.delete()
if (!successRemove) {
snack(R.string.message_failed_image_removal)
return
}
snack(R.string.message_success_image_removal)
onRemoved()
}
/**
* Show [Snackbar] with specified message resource.
*
* @param messageId Message ID
*/
private fun snack(@StringRes messageId: Int) {
(binding.root.context as? FragmentActivity)?.also {
ViewModelProvider(it).get(ContentViewModel::class.java).snackShort(messageId)
}
}
} | app/src/main/java/jp/toastkid/yobidashi/settings/background/ViewHolder.kt | 621620317 |
package com.egenvall.travelplanner.base.presentation
interface BaseView | app/src/main/java/com/egenvall/travelplanner/base/presentation/BaseView.kt | 1691298195 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.tiles
@RequiresOptIn(
message = "Horologist Tiles is experimental. The API may be changed in the future."
)
@Retention(AnnotationRetention.BINARY)
public annotation class ExperimentalHorologistTilesApi
| tiles/src/main/java/com/google/android/horologist/tiles/ExperimentalHorologistTilesApi.kt | 3521635275 |
import com.google.gson.Gson
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServer
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.BodyHandler
import kotlin.reflect.KClass
/**
* Created by mike on 14/11/15.
*/
val GSON = Gson()
fun Vertx.restApi(port: Int, body: Router.() -> Unit) {
createHttpServer().restApi(this, body).listen(port) {
if (it.succeeded()) println("Server listening at $port")
else println(it.cause())
}
}
fun HttpServer.restApi(vertx: Vertx, body: Router.() -> Unit): HttpServer {
val router = Router.router(vertx)
router.route().handler(BodyHandler.create()) // Required for RoutingContext.bodyAsString
router.body()
requestHandler { router.accept(it) }
return this
}
fun Router.get(path: String, rctx:RoutingContext.() -> Unit) = get(path).handler { it.rctx() }
fun Router.post(path: String, rctx:RoutingContext.() -> Unit) = post(path).handler { it.rctx() }
fun Router.put(path: String, rctx:RoutingContext.() -> Unit) = put(path).handler { it.rctx() }
fun Router.delete(path: String, rctx:RoutingContext.() -> Unit) = delete(path).handler { it.rctx() }
fun RoutingContext.param(name: String): String =
request().getParam(name)
fun RoutingContext.bodyAs<T>(clazz: KClass<out Any>): T =
GSON.fromJson(bodyAsString, clazz.java) as T
fun RoutingContext.send<T : Any?>(promise: Promise<T>) {
promise
.then {
val res = if (it == null) "" else GSON.toJson(it)
response().end(res)
}
.fail { response().setStatusCode(500).end(it.toString()) }
}
| step05/src/rest_utils.kt | 91445316 |
package com.moez.QKSMS.common.util.extensions
fun now(): Long {
return System.currentTimeMillis()
}
| common/src/main/java/com/moez/QKSMS/common/util/extensions/GlobalExtensions.kt | 4078562771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.