content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package kebab.report /** * Created by yy_yank on 2016/10/06. */ class PageSourceReporter : Reporter { override fun writeReport(reportState: ReportState) { // throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addListener(listener: ReportingListener) { // throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates. } }
src/main/kotlin/report/PageSourceReporter.kt
2318127050
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.utils.DayTester /** * Test for Day08 * @author Jelle Stege */ class Day08Test : DayTester(Day08())
aoc-2016/src/test/kotlin/nl/jstege/adventofcode/aoc2016/days/Day08Test.kt
976375219
package org.hexworks.zircon import org.hexworks.cobalt.events.api.EventBus import org.hexworks.cobalt.events.api.Subscription import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.application.RenderData import org.hexworks.zircon.api.grid.TileGrid import org.hexworks.zircon.internal.application.InternalApplication import org.hexworks.zircon.internal.event.ZirconScope class ApplicationStub : InternalApplication { override var config: AppConfig = AppConfig.defaultConfiguration() override var eventBus: EventBus = EventBus.create() override var eventScope: ZirconScope = ZirconScope() override lateinit var tileGrid: TileGrid var started = false private set var paused = false private set var resumed = false private set var stopped = false private set override fun start() { started = true } override fun pause() { paused = true } override fun resume() { resumed = true } override fun stop() { stopped = true } override fun asInternal() = this override fun beforeRender(listener: (RenderData) -> Unit): Subscription { error("not implemented") } override fun afterRender(listener: (RenderData) -> Unit): Subscription { error("not implemented") } }
zircon.core/src/commonTest/kotlin/org/hexworks/zircon/ApplicationStub.kt
3997274712
package com.edwardharker.aircraftrecognition.filter.picker import com.edwardharker.aircraftrecognition.filter.FakeSelectedFilterOptions import com.edwardharker.aircraftrecognition.model.Aircraft import com.edwardharker.aircraftrecognition.model.Filter import com.edwardharker.aircraftrecognition.repository.FakeAircraftRepository import com.edwardharker.aircraftrecognition.repository.FakeFilterRepository import org.junit.Test import rx.observers.TestSubscriber class RepositoryFilterPickerUseCaseTest { @Test fun emitsFiltersWhenNoFiltersSelected() { val filters = listOf(Filter()) val fakeSelectedFilterOptions = FakeSelectedFilterOptions() val useCase = RepositoryFilterPickerUseCase( filterRepository = FakeFilterRepository().thatEmits(filters), selectedFilterOptions = fakeSelectedFilterOptions, aircraftRepository = FakeAircraftRepository().thatEmits(listOf(Aircraft())), filterOptionsRemover = { filter, _ -> filter } ) val testSubscriber = TestSubscriber.create<List<Filter>>() useCase.filters().subscribe(testSubscriber) fakeSelectedFilterOptions.subject.onNext(emptyMap()) testSubscriber.assertValues(filters) } }
recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/filter/picker/RepositoryFilterPickerUseCaseTest.kt
2406464414
package org.wordpress.android.editor.gutenberg import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.Fragment import com.google.android.material.dialog.MaterialAlertDialogBuilder class GutenbergDialogFragment : AppCompatDialogFragment() { private lateinit var mTag: String private lateinit var mMessage: CharSequence private var mPositiveButtonLabel: CharSequence? = null private var mTitle: CharSequence? = null private var mNegativeButtonLabel: CharSequence? = null private var mId: Int = 0 private var dismissedByPositiveButton = false private var dismissedByNegativeButton = false interface GutenbergDialogPositiveClickInterface { fun onGutenbergDialogPositiveClicked(instanceTag: String, id: Int) } interface GutenbergDialogNegativeClickInterface { fun onGutenbergDialogNegativeClicked(instanceTag: String) } interface GutenbergDialogOnDismissByOutsideTouchInterface { fun onDismissByOutsideTouch(instanceTag: String) } fun initialize( tag: String, title: CharSequence?, message: CharSequence, positiveButtonLabel: CharSequence, negativeButtonLabel: CharSequence? = null, id: Int ) { mTag = tag mTitle = title mMessage = message mPositiveButtonLabel = positiveButtonLabel mNegativeButtonLabel = negativeButtonLabel mId = id } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.isCancelable = true val theme = 0 setStyle(STYLE_NORMAL, theme) if (savedInstanceState != null) { mTag = requireNotNull(savedInstanceState.getString(STATE_KEY_TAG)) mTitle = savedInstanceState.getCharSequence(STATE_KEY_TITLE) mMessage = requireNotNull(savedInstanceState.getCharSequence(STATE_KEY_MESSAGE)) mPositiveButtonLabel = savedInstanceState.getCharSequence(STATE_KEY_POSITIVE_BUTTON_LABEL) mNegativeButtonLabel = savedInstanceState.getCharSequence(STATE_KEY_NEGATIVE_BUTTON_LABEL) mId = savedInstanceState.getInt(STATE_KEY_ID) } } override fun onSaveInstanceState(outState: Bundle) { outState.putString(STATE_KEY_TAG, mTag) outState.putCharSequence(STATE_KEY_TITLE, mTitle) outState.putCharSequence(STATE_KEY_MESSAGE, mMessage) outState.putCharSequence(STATE_KEY_POSITIVE_BUTTON_LABEL, mPositiveButtonLabel) outState.putCharSequence(STATE_KEY_NEGATIVE_BUTTON_LABEL, mNegativeButtonLabel) outState.putInt(STATE_KEY_ID, mId) super.onSaveInstanceState(outState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = MaterialAlertDialogBuilder(requireActivity()) builder.setMessage(mMessage) mTitle?.let { builder.setTitle(mTitle) } mPositiveButtonLabel?.let { builder.setPositiveButton(mPositiveButtonLabel) { _, _ -> dismissedByPositiveButton = true (parentFragment as? GutenbergDialogPositiveClickInterface)?.let { it.onGutenbergDialogPositiveClicked(mTag, mId) } }.setCancelable(true) } mNegativeButtonLabel?.let { builder.setNegativeButton(mNegativeButtonLabel) { _, _ -> dismissedByNegativeButton = true (parentFragment as? GutenbergDialogNegativeClickInterface)?.let { it.onGutenbergDialogNegativeClicked(mTag) } } } return builder.create() } @Suppress("TooGenericExceptionThrown") override fun onAttach(context: Context) { super.onAttach(context) val parentFragment: Fragment? = parentFragment if (parentFragment !is GutenbergDialogPositiveClickInterface) { throw RuntimeException("Parent fragment must implement GutenbergDialogPositiveClickInterface") } if (mNegativeButtonLabel != null && parentFragment !is GutenbergDialogNegativeClickInterface) { throw RuntimeException("Parent fragment must implement GutenbergDialogNegativeClickInterface") } } override fun onDismiss(dialog: DialogInterface) { // Only handle the event if it wasn't triggered by a button if (!dismissedByPositiveButton && !dismissedByNegativeButton) { (parentFragment as? GutenbergDialogOnDismissByOutsideTouchInterface)?.let { it.onDismissByOutsideTouch(mTag) } } super.onDismiss(dialog) } companion object { private const val STATE_KEY_TAG = "state_key_tag" private const val STATE_KEY_TITLE = "state_key_title" private const val STATE_KEY_MESSAGE = "state_key_message" private const val STATE_KEY_POSITIVE_BUTTON_LABEL = "state_key_positive_button_label" private const val STATE_KEY_NEGATIVE_BUTTON_LABEL = "state_key_negative_button_label" private const val STATE_KEY_ID = "state_key_id" } }
libs/editor/src/main/java/org/wordpress/android/editor/gutenberg/GutenbergDialogFragment.kt
3831939855
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.highlighting import com.intellij.JavaTestUtil import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase /** * @author Pavel.Dolgov */ class AtomicReferenceImplicitUsageTest : LightJavaCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = JAVA_8 override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/atomicReferenceImplicitUsage/" override fun setUp() { super.setUp() myFixture.enableInspections(UnusedDeclarationInspection()) } fun testReferenceGet() = doTest() fun testIntegerGet() = doTest() fun testLongGet() = doTest() fun testReferenceCAS() = doTest() fun testIntegerCAS() = doTest() fun testLongCAS() = doTest() fun testReferenceGetAndSet() = doTest() fun testIntegerGetAndSet() = doTest() fun testLongGetAndSet() = doTest() fun testReferenceSet() = doTest() fun testIntegerSet() = doTest() fun testLongSet() = doTest() fun testIntegerIncrement() = doTest() fun testLongIncrement() = doTest() fun testNonVolatile() = doTest() private fun doTest() { myFixture.configureByFile(getTestName(false) + ".java") myFixture.checkHighlighting() } }
java/java-tests/testSrc/com/intellij/java/codeInsight/highlighting/AtomicReferenceImplicitUsageTest.kt
2840330019
package vendor import react.RBuilder import react.RHandler fun RBuilder.tab(id: TabId, contents: RHandler<TabProps>) = child(Tab::class) { attrs.id = id contents() } fun RBuilder.tabList(contents: RHandler<TabListProps>) = child(TabList::class, contents) fun RBuilder.tabPanel(tabId: TabId, contents: RHandler<TabPanelProps>) = child(TabPanel::class) { attrs.tabId = tabId contents() } fun RBuilder.tabPanelWrapper(contents: RHandler<TabPanelWrapperProps>) = child(TabPanelWrapper::class, contents)
webui/src/main/kotlin/vendor/react-aria-tabpanel-dsl.kt
507721583
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema /** * Represents types defined by the Thrift IDL, such as the numeric types, * strings, binaries, and void. */ class BuiltinType internal constructor( name: String, override val annotations: Map<String, String> = emptyMap() ) : ThriftType(name) { /** * True if this represents a numeric type, otherwise false. */ val isNumeric: Boolean get() = (this == I8 || this == I16 || this == I32 || this == I64 || this == DOUBLE) override val isBuiltin: Boolean = true override fun <T> accept(visitor: ThriftType.Visitor<T>): T { return when (this) { VOID -> visitor.visitVoid(this) BOOL -> visitor.visitBool(this) BYTE, I8 -> visitor.visitByte(this) I16 -> visitor.visitI16(this) I32 -> visitor.visitI32(this) I64 -> visitor.visitI64(this) DOUBLE -> visitor.visitDouble(this) STRING -> visitor.visitString(this) BINARY -> visitor.visitBinary(this) else -> throw AssertionError("Unexpected ThriftType: $name") } } override fun withAnnotations(annotations: Map<String, String>): ThriftType { return BuiltinType(name, mergeAnnotations(this.annotations, annotations)) } /** @inheritdoc */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (javaClass != other.javaClass) return false val that = other as BuiltinType if (this.name == that.name) { return true } // 'byte' and 'i8' are synonyms val synonyms = arrayOf(BYTE.name, I8.name) return this.name in synonyms && that.name in synonyms } /** @inheritdoc */ override fun hashCode(): Int { var name = name if (name == I8.name) { name = BYTE.name } return name.hashCode() } companion object { /** * The boolean type. */ val BOOL: ThriftType = BuiltinType("bool") /** * The (signed) byte type. */ val BYTE: ThriftType = BuiltinType("byte") /** * The (signed) byte type; identical to [BYTE], but with a regularized * name. */ val I8: ThriftType = BuiltinType("i8") /** * A 16-bit signed integer type (e.g. [Short]). */ val I16: ThriftType = BuiltinType("i16") /** * A 32-bit signed integer type (e.g. [Int]). */ val I32: ThriftType = BuiltinType("i32") /** * A 64-bit signed integer type (e.g. [Long]). */ val I64: ThriftType = BuiltinType("i64") /** * A double-precision floating-point type (e.g. [Double]). */ val DOUBLE: ThriftType = BuiltinType("double") /** * A type representing a series of bytes of unspecified encoding, * but we'll use UTF-8. */ val STRING: ThriftType = BuiltinType("string") /** * A type representing a series of bytes. */ val BINARY: ThriftType = BuiltinType("binary") /** * No type; used exclusively to indicate that a service method has no * return value. */ val VOID: ThriftType = BuiltinType("void") private val BUILTINS = listOf(BOOL, BYTE, I8, I16, I32, I64, DOUBLE, STRING, BINARY, VOID) .map { it.name to it } .toMap() /** * Returns the builtin type corresponding to the given [name], or null * if no such type exists. */ fun get(name: String): ThriftType? { return BUILTINS[name] } } }
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/BuiltinType.kt
2068588916
package pl.elpassion.cloudtimer.signin import android.support.test.runner.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import pl.elpassion.cloudtimer.ComponentsTestsUtils.isComponentDisplayed import pl.elpassion.cloudtimer.ComponentsTestsUtils.pressButton import pl.elpassion.cloudtimer.R import pl.elpassion.cloudtimer.dao.TimerDaoProvider import pl.elpassion.cloudtimer.domain.Timer import pl.elpassion.cloudtimer.login.authtoken.AuthTokenSharedPreferences import pl.elpassion.cloudtimer.rule import pl.elpassion.cloudtimer.timerslist.ListOfTimersActivity @RunWith(AndroidJUnit4::class) class SigninActivityStartTest { @Rule @JvmField val rule = rule<ListOfTimersActivity>() { val alarmDao = TimerDaoProvider.getInstance() alarmDao.deleteAll() alarmDao.save(Timer("placeholder", 1001000L)) AuthTokenSharedPreferences.sharedPreferences.edit().clear().commit() } @Test fun startLoginActivity() { pressButton(R.id.timer_share_button) isComponentDisplayed(R.id.send_activation_email) } }
app/src/androidTest/java/pl/elpassion/cloudtimer/signin/SigninActivityStartTest.kt
225746722
package com.meiji.daily.di.component import com.meiji.daily.MainActivity import com.meiji.daily.di.scope.ActivityScoped import com.meiji.daily.module.base.BaseActivity import dagger.Component /** * Created by Meiji on 2017/12/28. */ @ActivityScoped @Component(dependencies = arrayOf(AppComponent::class)) interface CommonActivityComponent { fun inject(baseActivity: BaseActivity) fun inject(mainActivity: MainActivity) }
app/src/main/java/com/meiji/daily/di/component/CommonActivityComponent.kt
1612205136
package com.netflix.spinnaker.orca /** * Default implementation just uses the task definition as is and will not to do any changes to the * task definition itself. */ class NoOpTaskImplementationResolver : TaskImplementationResolver
orca-core/src/main/java/com/netflix/spinnaker/orca/NoOpTaskImplementationResolver.kt
3408899203
package com.austinv11.d4j.bot import com.austinv11.d4j.bot.extensions.json import com.austinv11.d4j.bot.extensions.obj import java.io.File val CONFIG: Config by lazy { val configFile = File("./config.json") if (configFile.exists()) return@lazy configFile.readText().obj<Config>() else { val returnVal = Config() returnVal.save() return@lazy returnVal } } data class Config(var prefix: String = "~", var success_message: String = ":ok_hand:", var error_message: String = ":poop:", var ignored: Array<String> = emptyArray()) { fun save() { File("./config.json").writeText(this.json) } }
src/main/kotlin/com/austinv11/d4j/bot/Config.kt
1756786656
package com.austinv11.d4j.bot.extensions import com.google.gson.GsonBuilder val GSON = GsonBuilder().setPrettyPrinting().serializeNulls().create()!! val Any.json : String get() = GSON.toJson(this) inline fun <reified T> String.obj(): T = GSON.fromJson(this, T::class.java)
src/main/kotlin/com/austinv11/d4j/bot/extensions/GsonExtensions.kt
1038363024
// PROBLEM: none var a = 5 fun foo() = <caret>try { a = 6 } catch (e: Exception) { a = 8 }
plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/tryToAssignment/usedAsExpression.kt
4161071874
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.intellij.openapi.module.Module import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion internal data class PackagesToUpgrade( val upgradesByModule: Map<Module, Set<PackageUpgradeInfo>> ) { val allUpdates by lazy { upgradesByModule.values.flatten() } fun getUpdatesForModule(moduleModel: ModuleModel) = upgradesByModule[moduleModel.projectModule.nativeModule]?.toList() ?: emptyList() data class PackageUpgradeInfo( val packageModel: PackageModel.Installed, val usageInfo: DependencyUsageInfo, val targetVersion: NormalizedPackageVersion<PackageVersion.Named>, val computeUpgradeOperationsForSingleModule: List<PackageSearchOperation<*>> ) companion object { val EMPTY = PackagesToUpgrade(emptyMap()) } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackagesToUpgrade.kt
2629711654
val foo: <selection><caret>Int</selection>? = 1
plugins/kotlin/idea/tests/testData/wordSelection/DefiningVariable/1.kt
1111589770
package org.thoughtcrime.securesms.service.webrtc import org.signal.ringrtc.CallManager import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.recipients.RecipientId import java.util.UUID data class GroupCallRingCheckInfo( val recipientId: RecipientId, val groupId: GroupId.V2, val ringId: Long, val ringerUuid: UUID, val ringUpdate: CallManager.RingUpdate )
app/src/main/java/org/thoughtcrime/securesms/service/webrtc/GroupCallRingCheckInfo.kt
416529491
package com.devbrackets.android.playlistcoredemo.ui.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.ListView import androidx.appcompat.app.AppCompatActivity import com.devbrackets.android.playlistcore.annotation.SupportedMediaType import com.devbrackets.android.playlistcore.manager.BasePlaylistManager import com.devbrackets.android.playlistcoredemo.R import com.devbrackets.android.playlistcoredemo.data.Samples import com.devbrackets.android.playlistcoredemo.ui.activity.AudioPlayerActivity import com.devbrackets.android.playlistcoredemo.ui.activity.MediaSelectionActivity import com.devbrackets.android.playlistcoredemo.ui.activity.VideoPlayerActivity import com.devbrackets.android.playlistcoredemo.ui.adapter.SampleListAdapter /** * A simple activity that allows the user to select a chapter form "The Count of Monte Cristo" * or a sample video to play. */ class MediaSelectionActivity : AppCompatActivity(), OnItemClickListener { private var isAudio = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.list_selection_activity) isAudio = intent.getLongExtra(EXTRA_MEDIA_TYPE, BasePlaylistManager.AUDIO.toLong()) == BasePlaylistManager.AUDIO.toLong() if (supportActionBar != null) { supportActionBar!!.title = resources.getString(if (isAudio) R.string.title_audio_selection_activity else R.string.title_video_selection_activity) } val exampleList = findViewById<ListView>(R.id.selection_activity_list) exampleList.adapter = SampleListAdapter(this, if (isAudio) Samples.audio else Samples.video) exampleList.onItemClickListener = this } override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { if (isAudio) { startAudioPlayerActivity(position) } else { startVideoPlayerActivity(position) } } private fun startAudioPlayerActivity(selectedIndex: Int) { val intent = Intent(this, AudioPlayerActivity::class.java) intent.putExtra(AudioPlayerActivity.Companion.EXTRA_INDEX, selectedIndex) startActivity(intent) } private fun startVideoPlayerActivity(selectedIndex: Int) { val intent = Intent(this, VideoPlayerActivity::class.java) intent.putExtra(VideoPlayerActivity.Companion.EXTRA_INDEX, selectedIndex) startActivity(intent) } companion object { const val EXTRA_MEDIA_TYPE = "EXTRA_MEDIA_TYPE" fun show(activity: Activity, @SupportedMediaType mediaType: Long) { val intent = Intent(activity, MediaSelectionActivity::class.java) intent.putExtra(EXTRA_MEDIA_TYPE, mediaType) activity.startActivity(intent) } } }
demo/src/main/java/com/devbrackets/android/playlistcoredemo/ui/activity/MediaSelectionActivity.kt
1404111248
package moe.kyubey.site.entities data class Log( val event: String, // Message val messageId: Long, val content: String, val attachments: List<String>, val embeds: List<Map<String, Any>>, val timestamp: Long, // Author val authorId: Long, val authorName: String, val authorDiscrim: String, val authorAvatar: String, val authorNick: String, // Guild val guildId: Long, val guildName: String, // Channel val channelId: Long, val channelName: String )
src/main/kotlin/moe/kyubey/site/entities/Log.kt
2046276354
@file:Suppress("unused") package me.ycdev.android.lib.common.utils import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.PowerManager import androidx.annotation.IntDef import timber.log.Timber @Suppress("MemberVisibilityCanBePrivate") object IntentUtils { private const val TAG = "IntentUtils" const val INTENT_TYPE_ACTIVITY = 1 const val INTENT_TYPE_BROADCAST = 2 const val INTENT_TYPE_SERVICE = 3 @IntDef(INTENT_TYPE_ACTIVITY, INTENT_TYPE_BROADCAST, INTENT_TYPE_SERVICE) @Retention(AnnotationRetention.SOURCE) annotation class IntentType const val EXTRA_FOREGROUND_SERVICE = "extra.foreground_service" fun canStartActivity(cxt: Context, intent: Intent): Boolean { // Use PackageManager.MATCH_DEFAULT_ONLY to behavior same as Context#startAcitivty() val resolveInfo = cxt.packageManager.resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY ) return resolveInfo != null } fun startActivity(context: Context, intent: Intent): Boolean { return if (canStartActivity(context, intent)) { context.startActivity(intent) true } else { Timber.tag(TAG).w("cannot start Activity: $intent") false } } fun needForegroundService( context: Context, ai: ApplicationInfo, listenSensor: Boolean ): Boolean { // no background limitation before Android O if (VERSION.SDK_INT < VERSION_CODES.O) { return false } // Need foreground service on Android P to listen sensors if (listenSensor && VERSION.SDK_INT >= VERSION_CODES.P) { return true } // The background limitation only works when the targetSdk is 26 or higher if (ai.targetSdkVersion < VERSION_CODES.O) { return false } // no background limitation if the app is in the battery optimization whitelist. val powerMgr = context.getSystemService(Context.POWER_SERVICE) as PowerManager if (powerMgr.isIgnoringBatteryOptimizations(ai.packageName)) { return false } // yes, we need foreground service return true } fun needForegroundService(context: Context, listenSensor: Boolean): Boolean { return needForegroundService(context, context.applicationInfo, listenSensor) } @SuppressLint("NewApi") fun startService(context: Context, intent: Intent): Boolean { val resolveInfo = context.packageManager.resolveService(intent, 0) ?: return false intent.setClassName( resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name ) // Here, we should set "listenSensor" to false. // The target service still can set "listenSensor" to true for its checking. if (needForegroundService(context, resolveInfo.serviceInfo.applicationInfo, false)) { intent.putExtra(EXTRA_FOREGROUND_SERVICE, true) context.startForegroundService(intent) } else { intent.putExtra(EXTRA_FOREGROUND_SERVICE, false) context.startService(intent) } return true } fun startForegroundService(context: Context, intent: Intent): Boolean { val resolveInfo = context.packageManager.resolveService(intent, 0) ?: return false intent.setClassName( resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name ) if (VERSION.SDK_INT < VERSION_CODES.O) { intent.putExtra(EXTRA_FOREGROUND_SERVICE, false) context.startService(intent) } else { // here, we add an extra so that the target service can know // it needs to call #startForeground() intent.putExtra(EXTRA_FOREGROUND_SERVICE, true) context.startForegroundService(intent) } return true } }
baseLib/src/main/java/me/ycdev/android/lib/common/utils/IntentUtils.kt
1731933919
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.launcher import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testGuiFramework.impl.GuiTestStarter import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder.Companion.isWin import com.intellij.testGuiFramework.launcher.classpath.PathUtils import com.intellij.testGuiFramework.launcher.ide.Ide import com.intellij.testGuiFramework.launcher.ide.IdeType import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.junit.Assert.fail import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.net.URL import java.nio.file.Paths import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.jar.JarInputStream import java.util.stream.Collectors import kotlin.concurrent.thread /** * @author Sergey Karashevich */ object GuiTestLocalLauncher { private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher") var process: Process? = null val TEST_GUI_FRAMEWORK_MODULE_NAME = "testGuiFramework" val project: JpsProject by lazy { val home = PathManager.getHomePath() val model = JpsElementFactory.getInstance().createModel() val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) val jpsProject = model.project JpsProjectLoader.loadProject(jpsProject, pathVariables, home) jpsProject.changeOutputIfNeeded() jpsProject } val modulesList: List<JpsModule> by lazy { project.modules } val testGuiFrameworkModule: JpsModule by lazy { modulesList.module(TEST_GUI_FRAMEWORK_MODULE_NAME) ?: throw Exception("Unable to find module '$TEST_GUI_FRAMEWORK_MODULE_NAME'") } fun killProcessIfPossible() { try { if (process?.isAlive ?: false) process!!.destroyForcibly() } catch (e: KotlinNullPointerException) { LOG.error("Seems that process has already destroyed, right after condition") } } fun runIdeLocally(ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) { //todo: check that we are going to run test locally val args = createArgs(ide = ide, port = port) return startIde(ide = ide, args = args) } fun runIdeByPath(path: String, ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) { //todo: check that we are going to run test locally val args = createArgsByPath(path, port) return startIde(ide = ide, args = args) } fun firstStartIdeLocally(ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0)) { val args = createArgsForFirstStart(ide) return startIdeAndWait(ide = ide, args = args) } fun firstStartIdeByPath(path: String, ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0)) { val args = createArgsForFirstStartByPath(ide, path) return startIdeAndWait(ide = ide, args = args) } private fun startIde(ide: Ide, needToWait: Boolean = false, timeOut: Long = 0, timeOutUnit: TimeUnit = TimeUnit.SECONDS, args: List<String>): Unit { LOG.info("Running $ide locally \n with args: $args") val startLatch = CountDownLatch(1) thread(start = true, name = "IdeaTestThread") { val ideaStartTest = ProcessBuilder().inheritIO().command(args) process = ideaStartTest.start() startLatch.countDown() } if (needToWait) { startLatch.await() if (timeOut != 0L) process!!.waitFor(timeOut, timeOutUnit) else process!!.waitFor() if (process!!.exitValue() != 1) { println("${ide.ideType} process completed successfully") LOG.info("${ide.ideType} process completed successfully") } else { System.err.println("${ide.ideType} process execution error:") val collectedError = BufferedReader(InputStreamReader(process!!.errorStream)).lines().collect(Collectors.joining("\n")) System.err.println(collectedError) LOG.error("${ide.ideType} process execution error:") LOG.error(collectedError) fail("Starting ${ide.ideType} failed.") } } } private fun startIdeAndWait(ide: Ide, args: List<String>): Unit = startIde(ide = ide, needToWait = true, args = args) private fun createArgs(ide: Ide, mainClass: String = "com.intellij.idea.Main", port: Int = 0): List<String> = createArgsBase(ide, mainClass, GuiTestStarter.COMMAND_NAME, port) private fun createArgsForFirstStart(ide: Ide, port: Int = 0): List<String> = createArgsBase(ide, "com.intellij.testGuiFramework.impl.FirstStarterKt", null, port) private fun createArgsBase(ide: Ide, mainClass: String, commandName: String?, port: Int): List<String> { var resultingArgs = listOf<String>() .plus(getCurrentJavaExec()) .plus(getDefaultVmOptions(ide)) .plus("-classpath") .plus(getOsSpecificClasspath(ide.ideType.mainModule)) .plus(mainClass) if (commandName != null) resultingArgs = resultingArgs.plus(commandName) if (port != 0) resultingArgs = resultingArgs.plus("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } private fun createArgsForFirstStartByPath(ide: Ide, path: String): List<String> { val classpath = PathUtils(path).makeClassPathBuilder().build(emptyList()) val resultingArgs = listOf<String>() .plus(getCurrentJavaExec()) .plus(getDefaultVmOptions(ide)) .plus("-classpath") .plus(classpath) .plus(com.intellij.testGuiFramework.impl.FirstStarter::class.qualifiedName!! + "Kt") return resultingArgs } private fun createArgsByPath(path: String, port: Int = 0): List<String> { var resultingArgs = listOf<String>() .plus("open") .plus(path) //path to exec .plus("--args") .plus(GuiTestStarter.COMMAND_NAME) if (port != 0) resultingArgs = resultingArgs.plus("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } /** * Default VM options to start IntelliJ IDEA (or IDEA-based IDE). To customize options use com.intellij.testGuiFramework.launcher.GuiTestOptions */ private fun getDefaultVmOptions(ide: Ide) : List<String> { return listOf<String>() .plus("-Xmx${GuiTestOptions.getXmxSize()}m") .plus("-XX:ReservedCodeCacheSize=150m") .plus("-XX:+UseConcMarkSweepGC") .plus("-XX:SoftRefLRUPolicyMSPerMB=50") .plus("-XX:MaxJavaStackTraceDepth=10000") .plus("-ea") .plus("-Xbootclasspath/p:${GuiTestOptions.getBootClasspath()}") .plus("-Dsun.awt.disablegrab=true") .plus("-Dsun.io.useCanonCaches=false") .plus("-Djava.net.preferIPv4Stack=true") .plus("-Dapple.laf.useScreenMenuBar=${GuiTestOptions.useAppleScreenMenuBar().toString()}") .plus("-Didea.is.internal=${GuiTestOptions.isInternal().toString()}") .plus("-Didea.config.path=${GuiTestOptions.getConfigPath()}") .plus("-Didea.system.path=${GuiTestOptions.getSystemPath()}") .plus("-Dfile.encoding=${GuiTestOptions.getEncoding()}") .plus("-Didea.platform.prefix=${ide.ideType.platformPrefix}") .plus("-Xdebug") .plus("-Xrunjdwp:transport=dt_socket,server=y,suspend=${GuiTestOptions.suspendDebug()},address=${GuiTestOptions.getDebugPort()}") } private fun getCurrentJavaExec(): String { return PathUtils.getJreBinPath() } private fun getOsSpecificClasspath(moduleName: String): String = ClassPathBuilder.buildOsSpecific( getFullClasspath(moduleName).map { it.path }) /** * return union of classpaths for current test (get from classloader) and classpaths of main and testGuiFramework modules* */ private fun getFullClasspath(moduleName: String): List<File> { val classpath = getExtendedClasspath(moduleName) classpath.addAll(getTestClasspath()) return classpath.toList() } private fun getTestClasspath(): List<File> { val classLoader = this.javaClass.classLoader val urlClassLoaderClass = classLoader.javaClass val getUrlsMethod = urlClassLoaderClass.methods.filter { it.name.toLowerCase() == "geturls" }.firstOrNull()!! @Suppress("UNCHECKED_CAST") val urlsListOrArray = getUrlsMethod.invoke(classLoader) var urls = (urlsListOrArray as? List<*> ?: (urlsListOrArray as Array<*>).toList()).filterIsInstance(URL::class.java) if (isWin()) { val classPathUrl = urls.find { it.toString().contains(Regex("classpath[\\d]*.jar")) } if (classPathUrl != null) { val jarStream = JarInputStream(File(classPathUrl.path).inputStream()) val mf = jarStream.manifest urls = mf.mainAttributes.getValue("Class-Path").split(" ").map { URL(it) } } } return urls.map { Paths.get(it.toURI()).toFile() } } /** * return union of classpaths for @moduleName and testGuiFramework modules */ private fun getExtendedClasspath(moduleName: String): MutableSet<File> { // here we trying to analyze output path for project from classloader path and from modules classpath. // If they didn't match than change it to output path from classpath val resultSet = LinkedHashSet<File>() val module = modulesList.module(moduleName) ?: throw Exception("Unable to find module with name: $moduleName") resultSet.addAll(module.getClasspath()) resultSet.addAll(testGuiFrameworkModule.getClasspath()) return resultSet } private fun List<JpsModule>.module(moduleName: String): JpsModule? = this.filter { it.name == moduleName }.firstOrNull() private fun JpsModule.getClasspath(): MutableCollection<File> = JpsJavaExtensionService.dependencies(this).productionOnly().runtimeOnly().recursively().classes().roots private fun getOutputRootFromClassloader(): File { val pathFromClassloader = PathManager.getJarPathForClass(GuiTestLocalLauncher::class.java) val productionDir = File(pathFromClassloader).parentFile assert(productionDir.isDirectory) val outputDir = productionDir.parentFile assert(outputDir.isDirectory) return outputDir } /** * @return true if classloader's output path is the same to module's output path (and also same to project) */ private fun needToChangeProjectOutput(project: JpsProject): Boolean = JpsJavaExtensionService.getInstance().getProjectExtension(project)?.outputUrl == getOutputRootFromClassloader().path private fun JpsProject.changeOutputIfNeeded() { if (!needToChangeProjectOutput(this)) { val projectExtension = JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(this) projectExtension.outputUrl = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(getOutputRootFromClassloader().path)) } } } fun main(args: Array<String>) { GuiTestLocalLauncher.firstStartIdeLocally(Ide(ideType = IdeType.WEBSTORM, version = 0, build = 0)) }
platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GuiTestLocalLauncher.kt
2321216053
package net.computingtutor.robert.computingtutor import android.util.Log class BaseConverter(val inputVal: String, val plusve: Boolean, val fractional: Boolean, val inputBase: String){ var binaryResult: String = "" var hexResult: String = "" var decimalResult: String = "" val inputLength: Int = inputVal.length init { if (inputBase == "Base 2"){ binaryResult = inputVal //toHex() binToDecimal() } else if (inputBase == "Base 16") { //toBin() hexResult = inputVal //toDecimal() } else if (inputBase == "Base 10") { //toBin() //toHex() //toDecimal() } } private fun binToDecimal() { var tempDecimal: Double = 0.0 if (plusve and !fractional){ var count: Int = 0 var power: Int = inputLength - 1 while (count < inputLength){ if (inputVal.get(count) == '1'){ tempDecimal += Math.pow(2.0, power.toDouble()) } count += 1 power -= 1 } } else if (plusve and fractional) { } else if (!plusve and !fractional) { } else if (!plusve and fractional) { } decimalResult = tempDecimal.toInt().toString() } fun binToHex() { } fun hexToBin() { } fun hexToDec() { } fun decimalToHex() { } fun decimalToBin() { var tempBin: String = "" if (plusve and !fractional) { } } }
app/src/main/java/net/computingtutor/robert/computingtutor/BaseConverter.kt
1017352764
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.utils.io.js import org.khronos.webgl.* internal fun Decoder(encoding: String, fatal: Boolean = true): Decoder = try { TextDecoder(encoding, textDecoderOptions(fatal)).toKtor() } catch (cause: Throwable) { TextDecoderFallback(encoding, fatal) } internal interface Decoder { fun decode(): String fun decode(buffer: ArrayBufferView): String fun decode(buffer: ArrayBufferView, options: dynamic): String } @Suppress("NOTHING_TO_INLINE") internal inline fun Decoder.decodeStream(buffer: ArrayBufferView, stream: Boolean): String { decodeWrap { return decode(buffer, decodeOptions(stream)) } } internal fun decodeOptions(stream: Boolean): dynamic = Any().apply { with(this.asDynamic()) { this.stream = stream } }
ktor-io/js/src/io/ktor/utils/io/js/Decoder.kt
2865408610
package io.casey.musikcube.remote.ui.settings.activity import android.app.Dialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.uacf.taskrunner.Task import com.uacf.taskrunner.Tasks import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.playback.PlayerWrapper import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy import io.casey.musikcube.remote.ui.navigation.Transition import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.settings.model.Connection import io.casey.musikcube.remote.ui.settings.model.ConnectionsDb import io.casey.musikcube.remote.ui.shared.activity.BaseActivity import io.casey.musikcube.remote.ui.shared.extension.* import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin import java.util.* import javax.inject.Inject import io.casey.musikcube.remote.ui.settings.constants.Prefs.Default as Defaults import io.casey.musikcube.remote.ui.settings.constants.Prefs.Key as Keys class SettingsActivity : BaseActivity() { @Inject lateinit var connectionsDb: ConnectionsDb @Inject lateinit var streamProxy: StreamProxy private lateinit var addressText: EditText private lateinit var portText: EditText private lateinit var httpPortText: EditText private lateinit var passwordText: EditText private lateinit var albumArtCheckbox: CheckBox private lateinit var softwareVolume: CheckBox private lateinit var sslCheckbox: CheckBox private lateinit var certCheckbox: CheckBox private lateinit var transferCheckbox: CheckBox private lateinit var bitrateSpinner: Spinner private lateinit var formatSpinner: Spinner private lateinit var cacheSpinner: Spinner private lateinit var titleEllipsisSpinner: Spinner private lateinit var playback: PlaybackMixin private lateinit var data: MetadataProxyMixin override fun onCreate(savedInstanceState: Bundle?) { data = mixin(MetadataProxyMixin()) playback = mixin(PlaybackMixin()) component.inject(this) super.onCreate(savedInstanceState) prefs = this.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) setContentView(R.layout.settings_activity) setTitle(R.string.settings_title) cacheViews() bindListeners() rebindUi() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.settings_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } R.id.action_save -> { save() return true } } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == CONNECTIONS_REQUEST_CODE && resultCode == RESULT_OK) { if (data != null) { val connection = data.getParcelableExtra<Connection>( ConnectionsActivity.EXTRA_SELECTED_CONNECTION) if (connection != null) { addressText.setText(connection.hostname) passwordText.setText(connection.password) portText.setText(connection.wssPort.toString()) httpPortText.setText(connection.httpPort.toString()) sslCheckbox.setCheckWithoutEvent(connection.ssl, sslCheckChanged) certCheckbox.setCheckWithoutEvent(connection.noValidate, certValidationChanged) } } } super.onActivityResult(requestCode, resultCode, data) } override val transitionType: Transition get() = Transition.Vertical private fun rebindSpinner(spinner: Spinner, arrayResourceId: Int, key: String, defaultIndex: Int) { val items = ArrayAdapter.createFromResource(this, arrayResourceId, android.R.layout.simple_spinner_item) items.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = items spinner.setSelection(prefs.getInt(key, defaultIndex)) } private fun rebindUi() { /* connection info */ addressText.setTextAndMoveCursorToEnd(prefs.getString(Keys.ADDRESS) ?: Defaults.ADDRESS) portText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.MAIN_PORT, Defaults.MAIN_PORT))) httpPortText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.AUDIO_PORT, Defaults.AUDIO_PORT))) passwordText.setTextAndMoveCursorToEnd(prefs.getString(Keys.PASSWORD) ?: Defaults.PASSWORD) /* bitrate */ rebindSpinner( bitrateSpinner, R.array.transcode_bitrate_array, Keys.TRANSCODER_BITRATE_INDEX, Defaults.TRANSCODER_BITRATE_INDEX) /* format */ rebindSpinner( formatSpinner, R.array.transcode_format_array, Keys.TRANSCODER_FORMAT_INDEX, Defaults.TRANSCODER_FORMAT_INDEX) /* disk cache */ rebindSpinner( cacheSpinner, R.array.disk_cache_array, Keys.DISK_CACHE_SIZE_INDEX, Defaults.DISK_CACHE_SIZE_INDEX) /* title ellipsis mode */ rebindSpinner( titleEllipsisSpinner, R.array.title_ellipsis_mode_array, Keys.TITLE_ELLIPSIS_MODE_INDEX, Defaults.TITLE_ELLIPSIS_SIZE_INDEX) /* advanced */ transferCheckbox.isChecked = prefs.getBoolean( Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, Defaults.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT) albumArtCheckbox.isChecked = prefs.getBoolean( Keys.LASTFM_ENABLED, Defaults.LASTFM_ENABLED) softwareVolume.isChecked = prefs.getBoolean( Keys.SOFTWARE_VOLUME, Defaults.SOFTWARE_VOLUME) sslCheckbox.setCheckWithoutEvent( this.prefs.getBoolean(Keys.SSL_ENABLED,Defaults.SSL_ENABLED), sslCheckChanged) certCheckbox.setCheckWithoutEvent( this.prefs.getBoolean( Keys.CERT_VALIDATION_DISABLED, Defaults.CERT_VALIDATION_DISABLED), certValidationChanged) enableUpNavigation() } private fun onDisableSslFromDialog() { sslCheckbox.setCheckWithoutEvent(false, sslCheckChanged) } private fun onDisableCertValidationFromDialog() { certCheckbox.setCheckWithoutEvent(false, certValidationChanged) } private val sslCheckChanged = { _: CompoundButton, value:Boolean -> if (value) { if (!dialogVisible(SslAlertDialog.TAG)) { showDialog(SslAlertDialog.newInstance(), SslAlertDialog.TAG) } } } private val certValidationChanged = { _: CompoundButton, value: Boolean -> if (value) { if (!dialogVisible(DisableCertValidationAlertDialog.TAG)) { showDialog( DisableCertValidationAlertDialog.newInstance(), DisableCertValidationAlertDialog.TAG) } } } private fun cacheViews() { this.addressText = findViewById(R.id.address) this.portText = findViewById(R.id.port) this.httpPortText = findViewById(R.id.http_port) this.passwordText = findViewById(R.id.password) this.albumArtCheckbox = findViewById(R.id.album_art_checkbox) this.softwareVolume = findViewById(R.id.software_volume) this.bitrateSpinner = findViewById(R.id.transcoder_bitrate_spinner) this.formatSpinner = findViewById(R.id.transcoder_format_spinner) this.cacheSpinner = findViewById(R.id.streaming_disk_cache_spinner) this.titleEllipsisSpinner = findViewById(R.id.title_ellipsis_mode_spinner) this.sslCheckbox = findViewById(R.id.ssl_checkbox) this.certCheckbox = findViewById(R.id.cert_validation) this.transferCheckbox = findViewById(R.id.transfer_on_disconnect_checkbox) } private fun bindListeners() { findViewById<View>(R.id.button_save_as).setOnClickListener{ showSaveAsDialog() } findViewById<View>(R.id.button_load).setOnClickListener{ startActivityForResult( ConnectionsActivity.getStartIntent(this), CONNECTIONS_REQUEST_CODE) } findViewById<View>(R.id.button_diagnostics).setOnClickListener { startActivity(Intent(this, DiagnosticsActivity::class.java)) } } private fun showSaveAsDialog() { if (!dialogVisible(SaveAsDialog.TAG)) { showDialog(SaveAsDialog.newInstance(), SaveAsDialog.TAG) } } private fun showInvalidConnectionDialog(messageId: Int = R.string.settings_invalid_connection_message) { if (!dialogVisible(InvalidConnectionDialog.TAG)) { showDialog(InvalidConnectionDialog.newInstance(messageId), InvalidConnectionDialog.TAG) } } private fun saveAs(name: String) { try { val connection = Connection() connection.name = name connection.hostname = addressText.text.toString() connection.wssPort = portText.text.toString().toInt() connection.httpPort = httpPortText.text.toString().toInt() connection.password = passwordText.text.toString() connection.ssl = sslCheckbox.isChecked connection.noValidate = certCheckbox.isChecked if (connection.valid) { runner.run(SaveAsTask.nameFor(connection), SaveAsTask(connectionsDb, connection)) } else { showInvalidConnectionDialog() } } catch (ex: NumberFormatException) { showInvalidConnectionDialog() } } private fun save() { val addr = addressText.text.toString() val port = portText.text.toString() val httpPort = httpPortText.text.toString() val password = passwordText.text.toString() try { prefs.edit() .putString(Keys.ADDRESS, addr) .putInt(Keys.MAIN_PORT, if (port.isNotEmpty()) port.toInt() else 0) .putInt(Keys.AUDIO_PORT, if (httpPort.isNotEmpty()) httpPort.toInt() else 0) .putString(Keys.PASSWORD, password) .putBoolean(Keys.LASTFM_ENABLED, albumArtCheckbox.isChecked) .putBoolean(Keys.SOFTWARE_VOLUME, softwareVolume.isChecked) .putBoolean(Keys.SSL_ENABLED, sslCheckbox.isChecked) .putBoolean(Keys.CERT_VALIDATION_DISABLED, certCheckbox.isChecked) .putBoolean(Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, transferCheckbox.isChecked) .putInt(Keys.TRANSCODER_BITRATE_INDEX, bitrateSpinner.selectedItemPosition) .putInt(Keys.TRANSCODER_FORMAT_INDEX, formatSpinner.selectedItemPosition) .putInt(Keys.DISK_CACHE_SIZE_INDEX, cacheSpinner.selectedItemPosition) .putInt(Keys.TITLE_ELLIPSIS_MODE_INDEX, titleEllipsisSpinner.selectedItemPosition) .apply() if (!softwareVolume.isChecked) { PlayerWrapper.setVolume(1.0f) } streamProxy.reload() data.wss.disconnect() finish() } catch (ex: NumberFormatException) { showInvalidConnectionDialog(R.string.settings_invalid_connection_no_name_message) } } override fun onTaskCompleted(taskName: String, taskId: Long, task: Task<*, *>, result: Any) { if (SaveAsTask.match(taskName)) { if ((result as SaveAsTask.Result) == SaveAsTask.Result.Exists) { val connection = (task as SaveAsTask).connection if (!dialogVisible(ConfirmOverwriteDialog.TAG)) { showDialog( ConfirmOverwriteDialog.newInstance(connection), ConfirmOverwriteDialog.TAG) } } else { showSnackbar( findViewById<View>(android.R.id.content), R.string.snackbar_saved_connection_preset) } } } class SslAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_ssl_dialog_title) .setMessage(R.string.settings_ssl_dialog_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableSslFromDialog() } .setNeutralButton(R.string.button_learn_more) { _, _ -> try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LEARN_MORE_URL)) startActivity(intent) } catch (ex: Exception) { } } .create() dlg.setCancelable(false) return dlg } companion object { private const val LEARN_MORE_URL = "https://github.com/clangen/musikcube/wiki/ssl-server-setup" const val TAG = "ssl_alert_dialog_tag" fun newInstance(): SslAlertDialog { return SslAlertDialog() } } } class DisableCertValidationAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_disable_cert_validation_title) .setMessage(R.string.settings_disable_cert_validation_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableCertValidationFromDialog() } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "disable_cert_verify_dialog" fun newInstance(): DisableCertValidationAlertDialog { return DisableCertValidationAlertDialog() } } } class InvalidConnectionDialog: DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_invalid_connection_title) .setMessage(arguments!!.getInt(EXTRA_MESSAGE_ID)) .setNegativeButton(R.string.button_ok, null) .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "invalid_connection_dialog" private const val EXTRA_MESSAGE_ID = "extra_message_id" fun newInstance(messageId: Int = R.string.settings_invalid_connection_message): InvalidConnectionDialog { val args = Bundle() args.putInt(EXTRA_MESSAGE_ID, messageId) val result = InvalidConnectionDialog() result.arguments = args return result } } } class ConfirmOverwriteDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_confirm_overwrite_title) .setMessage(R.string.settings_confirm_overwrite_message) .setNegativeButton(R.string.button_no, null) .setPositiveButton(R.string.button_yes) { _, _ -> when (val connection = arguments?.getParcelable<Connection>(EXTRA_CONNECTION)) { null -> throw IllegalArgumentException("invalid connection") else -> { val db = (activity as SettingsActivity).connectionsDb val saveAs = SaveAsTask(db, connection, true) (activity as SettingsActivity).runner.run(SaveAsTask.nameFor(connection), saveAs) } } } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "confirm_overwrite_dialog" private const val EXTRA_CONNECTION = "extra_connection" fun newInstance(connection: Connection): ConfirmOverwriteDialog { val args = Bundle() args.putParcelable(EXTRA_CONNECTION, connection) val result = ConfirmOverwriteDialog() result.arguments = args return result } } } class SaveAsDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog_edit, null) val edit = view.findViewById<EditText>(R.id.edit) edit.requestFocus() val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_save_as_title) .setNegativeButton(R.string.button_cancel) { _, _ -> hideKeyboard() } .setOnCancelListener { hideKeyboard() } .setPositiveButton(R.string.button_save) { _, _ -> (activity as SettingsActivity).saveAs(edit.text.toString()) } .create() dlg.setView(view) dlg.setCancelable(false) return dlg } override fun onResume() { super.onResume() showKeyboard() } override fun onPause() { super.onPause() hideKeyboard() } companion object { const val TAG = "save_as_dialog" fun newInstance(): SaveAsDialog { return SaveAsDialog() } } } companion object { const val CONNECTIONS_REQUEST_CODE = 1000 fun getStartIntent(context: Context): Intent { return Intent(context, SettingsActivity::class.java) } } } private class SaveAsTask(val db: ConnectionsDb, val connection: Connection, val overwrite: Boolean = false) : Tasks.Blocking<SaveAsTask.Result, Exception>() { enum class Result { Exists, Added } override fun exec(context: Context?): Result { val dao = db.connectionsDao() if (!overwrite) { val existing: Connection? = dao.query(connection.name) if (existing != null) { return Result.Exists } } dao.insert(connection) return Result.Added } companion object { const val NAME = "SaveAsTask" fun nameFor(connection: Connection): String { return "$NAME.${connection.name}" } fun match(name: String?): Boolean { return name != null && name.startsWith("$NAME.") } } }
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/settings/activity/SettingsActivity.kt
436318594
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.isMixin import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.util.equivalentTo import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.shortName import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiClass import com.intellij.psi.PsiElementVisitor class MixinSuperClassInspection : MixinInspection() { override fun getStaticDescription() = "Reports invalid @Mixin super classes." override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitClass(psiClass: PsiClass) { if (!psiClass.isMixin) { return } val superClass = psiClass.superClass ?: return if (superClass.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT) { return } val targetClasses = psiClass.mixinTargets.ifEmpty { return } val superTargets = superClass.mixinTargets if (superTargets.isEmpty()) { // Super class must be a regular class in the hierarchy of the target class(es) for (targetClass in targetClasses) { if (targetClass equivalentTo superClass) { reportSuperClass(psiClass, "Cannot extend target class") } else if (!targetClass.isInheritor(superClass, true)) { reportSuperClass(psiClass, "Cannot find '${superClass.shortName}' in the hierarchy of target class '${targetClass.shortName}'") } } } else { // At least one of the target classes of the super mixin must be in the hierarchy of the target class(es) for (targetClass in targetClasses) { if (!superTargets.any { superTarget -> targetClass.isInheritor(superTarget, true) }) { reportSuperClass(psiClass, "Cannot find '${targetClass.shortName}' in the hierarchy of the super mixin") } } } } private fun reportSuperClass(psiClass: PsiClass, description: String) { holder.registerProblem(psiClass.extendsList?.referenceElements?.firstOrNull() ?: psiClass, description) } } }
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/MixinSuperClassInspection.kt
4164760799
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val EXT_texture_filter_minmax = "EXTTextureFilterMinmax".nativeClassGLES("EXT_texture_filter_minmax", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. In unextended OpenGL 4.3, minification and magnification filters such as LINEAR allow texture lookups to returned a filtered texel value produced by computing an weighted average of a collection of texels in the neighborhood of the texture coordinate provided. This extension provides a new texture and sampler parameter (TEXTURE_REDUCTION_MODE_EXT) which allows applications to produce a filtered texel value by computing a component-wise minimum (MIN) or maximum (MAX) of the texels that would normally be averaged. The reduction mode is orthogonal to the minification and magnification filter parameters. The filter parameters are used to identify the set of texels used to produce a final filtered value; the reduction mode identifies how these texels are combined. """ IntConstant( """ Accepted by the {@code pname} parameter to SamplerParameter{i f}{v}, SamplerParameterI{u}iv, GetSamplerParameter{i f}v, GetSamplerParameterI{u}iv, TexParameter{i f}{v}, TexParameterI{u}iv, GetTexParameter{i f}v, GetTexParameterI{u}iv, TextureParameter{i f}{v}EXT, TextureParameterI{u}ivEXT, GetTextureParameter{i f}vEXT, GetTextureParameterI{u}ivEXT, MultiTexParameter{i f}{v}EXT, MultiTexParameterI{u}ivEXT, GetMultiTexParameter{i f}vEXT, and GetMultiTexParameterI{u}ivEXT. """, "TEXTURE_REDUCTION_MODE_EXT"..0x9366 ) IntConstant( """ Accepted by the {@code param} or {@code params} parameter to SamplerParameter{i f}{v}, SamplerParameterI{u}iv, TexParameter{i f}{v}, TexParameterI{u}iv, TextureParameter{i f}{v}EXT, TextureParameterI{u}ivEXT, MultiTexParameter{i f}{v}EXT, or MultiTexParameterI{u}ivEXT when {@code pname} is TEXTURE_REDUCTION_MODE_EXT. """, "WEIGHTED_AVERAGE_EXT"..0x9367 ) }
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_texture_filter_minmax.kt
1878998256
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val NV_texture_barrier = "NVTextureBarrier".nativeClassGL("NV_texture_barrier", postfix = NV) { documentation = """ Native bindings to the $registryLink extension. This extension relaxes the restrictions on rendering to a currently bound texture and provides a mechanism to avoid read-after-write hazards. """ void( "TextureBarrierNV", "Guarantees that writes have completed and caches have been invalidated before subsequent Draws are executed." ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/NV_texture_barrier.kt
3257036424
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl.templates import org.lwjgl.generator.* import opencl.* val arm_protected_memory_allocation = "ARMProtectedMemoryAllocation".nativeClassCL("arm_protected_memory_allocation", ARM) { documentation = """ Native bindings to the $extensionLink extension. This extensions enables the creation of buffers and images backed by protected memory, i.e. memory protected using TrustZone Media Protection. Requires ${CL12.link}. """ IntConstant( """ New flag added to {@code cl_mem_flags}. Specifies that the memory object being created will be backed by protected memory. When this flag is present, the only host flag allowed is #MEM_HOST_NO_ACCESS. If host flags are omitted, {@code CL_MEM_HOST_NO_ACCESS} is assumed. """, "MEM_PROTECTED_ALLOC_ARM".."1 << 36" ) }
modules/lwjgl/opencl/src/templates/kotlin/opencl/templates/arm_protected_memory_allocation.kt
1473568870
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.ownership import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.common.internal.DataStatePropagator import org.hisp.dhis.android.core.maintenance.D2Error @Reusable internal class ProgramOwnerPostCall @Inject constructor( private val ownershipService: OwnershipService, private val apiCallExecutor: APICallExecutor, private val programOwnerStore: ObjectWithoutUidStore<ProgramOwner>, private val dataStatePropagator: DataStatePropagator ) { fun uploadProgramOwner(programOwner: ProgramOwner): Boolean { return try { val response = apiCallExecutor.executeObjectCall( ownershipService.transfer( programOwner.trackedEntityInstance(), programOwner.program(), programOwner.ownerOrgUnit() ) ) @Suppress("MagicNumber") val isSuccessful = response.httpStatusCode() == 200 if (isSuccessful) { val syncedProgramOwner = programOwner.toBuilder().syncState(State.SYNCED).build() programOwnerStore.updateOrInsertWhere(syncedProgramOwner) dataStatePropagator.refreshTrackedEntityInstanceAggregatedSyncState( programOwner.trackedEntityInstance() ) } isSuccessful } catch (e: D2Error) { // TODO Create a record in TEI false } } }
core/src/main/java/org/hisp/dhis/android/core/trackedentity/ownership/ProgramOwnerPostCall.kt
466905120
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <git@axavier.org> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.inject import dagger.Module import dagger.Provides import org.isoron.uhabits.core.models.Habit @Module class HabitModule(private val habit: Habit) { @Provides fun getHabit() = habit }
uhabits-android/src/main/java/org/isoron/uhabits/inject/HabitModule.kt
1377375820
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <git@axavier.org> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.core.models import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder import java.util.Arrays class WeekdayList { private val weekdays: BooleanArray constructor(packedList: Int) { weekdays = BooleanArray(7) var current = 1 for (i in 0..6) { if (packedList and current != 0) weekdays[i] = true current = current shl 1 } } constructor(weekdays: BooleanArray?) { this.weekdays = Arrays.copyOf(weekdays, 7) } val isEmpty: Boolean get() { for (d in weekdays) if (d) return false return true } fun toArray(): BooleanArray { return weekdays.copyOf(7) } fun toInteger(): Int { var packedList = 0 var current = 1 for (i in 0..6) { if (weekdays[i]) packedList = packedList or current current = current shl 1 } return packedList } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as WeekdayList return EqualsBuilder().append(weekdays, that.weekdays).isEquals } override fun hashCode(): Int { return HashCodeBuilder(17, 37).append(weekdays).toHashCode() } override fun toString() = "{weekdays: [${weekdays.joinToString(separator = ",")}]}" companion object { val EVERY_DAY = WeekdayList(127) } }
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/WeekdayList.kt
3619912733
package org.wikipedia.feed.image import android.content.Context import android.view.LayoutInflater import android.view.View import org.wikipedia.databinding.ViewCardFeaturedImageBinding import org.wikipedia.feed.view.DefaultFeedCardView import org.wikipedia.feed.view.FeedAdapter import org.wikipedia.richtext.RichTextUtil import org.wikipedia.views.ImageZoomHelper import org.wikipedia.views.ViewUtil class FeaturedImageCardView(context: Context) : DefaultFeedCardView<FeaturedImageCard>(context) { interface Callback { fun onShareImage(card: FeaturedImageCard) fun onDownloadImage(image: FeaturedImage) fun onFeaturedImageSelected(card: FeaturedImageCard) } private val binding = ViewCardFeaturedImageBinding.inflate(LayoutInflater.from(context), this, true) override var card: FeaturedImageCard? = null set(value) { field = value value?.let { image(it.baseImage()) description(it.description().orEmpty()) header(it) setClickListeners() } } override var callback: FeedAdapter.Callback? = null set(value) { field = value binding.viewFeaturedImageCardHeader.setCallback(value) } private fun image(image: FeaturedImage) { binding.viewFeaturedImageCardContentContainer.post { if (!isAttachedToWindow) { return@post } loadImage(image) } } private fun loadImage(image: FeaturedImage) { ImageZoomHelper.setViewZoomable(binding.viewFeaturedImageCardImage) ViewUtil.loadImage(binding.viewFeaturedImageCardImage, image.thumbnailUrl) binding.viewFeaturedImageCardImagePlaceholder.layoutParams = LayoutParams( binding.viewFeaturedImageCardContentContainer.width, ViewUtil.adjustImagePlaceholderHeight( binding.viewFeaturedImageCardContentContainer.width.toFloat(), image.thumbnail.width.toFloat(), image.thumbnail.height.toFloat() ) ) } private fun description(text: String) { binding.viewFeaturedImageCardImageDescription.text = RichTextUtil.stripHtml(text) } private fun setClickListeners() { binding.viewFeaturedImageCardContentContainer.setOnClickListener(CardClickListener()) binding.viewFeaturedImageCardDownloadButton.setOnClickListener(CardDownloadListener()) binding.viewFeaturedImageCardShareButton.setOnClickListener(CardShareListener()) } private fun header(card: FeaturedImageCard) { binding.viewFeaturedImageCardHeader.setTitle(card.title()) .setLangCode(null) .setCard(card) .setCallback(callback) } private inner class CardClickListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onFeaturedImageSelected(it) } } } private inner class CardDownloadListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onDownloadImage(it.baseImage()) } } } private inner class CardShareListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onShareImage(it) } } } }
app/src/main/java/org/wikipedia/feed/image/FeaturedImageCardView.kt
3557439777
@file:JvmName("RelayPi") package com.homemods.relay.pi import com.homemods.relay.Relay import com.homemods.relay.pi.bluetooth.PiBluetoothServer import com.homemods.relay.pi.pin.PiPinFactory /** * @author sergeys */ fun main(args: Array<String>) { Relay(PiPinFactory(), PiBluetoothServer()).run() }
pi/src/com/homemods/relay/pi/RelayPi.kt
1768267912
package klay.jvm import klay.core.buffers.Buffer import klay.core.buffers.ByteBuffer import klay.core.buffers.FloatBuffer import klay.core.buffers.IntBuffer import org.lwjgl.BufferUtils import org.lwjgl.opengl.* import org.lwjgl.system.MemoryUtil import java.io.UnsupportedEncodingException import java.nio.ByteOrder /** * An implementation of the [GL20] interface based on LWJGL3 and OpenGL ~3.0. */ class JvmGL20 : klay.core.GL20(JvmBuffers(), java.lang.Boolean.getBoolean("klay.glerrors")) { override fun glActiveTexture(texture: Int) { GL13.glActiveTexture(texture) } override fun glAttachShader(program: Int, shader: Int) { GL20.glAttachShader(program, shader) } override fun glBindAttribLocation(program: Int, index: Int, name: String) { GL20.glBindAttribLocation(program, index, name) } override fun glBindBuffer(target: Int, buffer: Int) { GL15.glBindBuffer(target, buffer) } override fun glBindFramebuffer(target: Int, framebuffer: Int) { EXTFramebufferObject.glBindFramebufferEXT(target, framebuffer) } override fun glBindRenderbuffer(target: Int, renderbuffer: Int) { EXTFramebufferObject.glBindRenderbufferEXT(target, renderbuffer) } override fun glBindTexture(target: Int, texture: Int) { GL11.glBindTexture(target, texture) } override fun glBlendColor(red: Float, green: Float, blue: Float, alpha: Float) { GL14.glBlendColor(red, green, blue, alpha) } override fun glBlendEquation(mode: Int) { GL14.glBlendEquation(mode) } override fun glBlendEquationSeparate(modeRGB: Int, modeAlpha: Int) { GL20.glBlendEquationSeparate(modeRGB, modeAlpha) } override fun glBlendFunc(sfactor: Int, dfactor: Int) { GL11.glBlendFunc(sfactor, dfactor) } override fun glBlendFuncSeparate(srcRGB: Int, dstRGB: Int, srcAlpha: Int, dstAlpha: Int) { GL14.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha) } override fun glBufferData(target: Int, size: Int, data: Buffer, usage: Int) { // Limit the buffer to the given size, restoring it afterwards val oldLimit = data.limit() if (data is JvmByteBuffer) { data.limit(data.position() + size) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmIntBuffer) { data.limit(data.position() + size / 4) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmFloatBuffer) { data.limit(data.position() + size / 4) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmDoubleBuffer) { data.limit(data.position() + size / 8) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmShortBuffer) { data.limit(data.position() + size / 2) GL15.glBufferData(target, data.nioBuffer, usage) } data.limit(oldLimit) } override fun glBufferSubData(target: Int, offset: Int, size: Int, data: Buffer) { // Limit the buffer to the given size, restoring it afterwards val oldLimit = data.limit() if (data is JvmByteBuffer) { data.limit(data.position() + size) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmIntBuffer) { data.limit(data.position() + size / 4) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmFloatBuffer) { data.limit(data.position() + size / 4) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmDoubleBuffer) { data.limit(data.position() + size / 8) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmShortBuffer) { data.limit(data.position() + size / 2) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } data.limit(oldLimit) } override fun glCheckFramebufferStatus(target: Int): Int { return EXTFramebufferObject.glCheckFramebufferStatusEXT(target) } override fun glClear(mask: Int) { GL11.glClear(mask) } override fun glClearColor(red: Float, green: Float, blue: Float, alpha: Float) { GL11.glClearColor(red, green, blue, alpha) } override fun glClearDepthf(depth: Float) { GL11.glClearDepth(depth.toDouble()) } override fun glClearStencil(s: Int) { GL11.glClearStencil(s) } override fun glColorMask(red: Boolean, green: Boolean, blue: Boolean, alpha: Boolean) { GL11.glColorMask(red, green, blue, alpha) } override fun glCompileShader(shader: Int) { GL20.glCompileShader(shader) } override fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Buffer) { throw UnsupportedOperationException("not implemented") } override fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Buffer) { throw UnsupportedOperationException("not implemented") } override fun glCopyTexImage2D(target: Int, level: Int, internalformat: Int, x: Int, y: Int, width: Int, height: Int, border: Int) { GL11.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border) } override fun glCopyTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, x: Int, y: Int, width: Int, height: Int) { GL11.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) } override fun glCreateProgram(): Int { return GL20.glCreateProgram() } override fun glCreateShader(type: Int): Int { return GL20.glCreateShader(type) } override fun glCullFace(mode: Int) { GL11.glCullFace(mode) } override fun glDeleteBuffers(n: Int, buffers: IntBuffer) { GL15.glDeleteBuffers((buffers as JvmIntBuffer).nioBuffer) } override fun glDeleteFramebuffers(n: Int, framebuffers: IntBuffer) { EXTFramebufferObject.glDeleteFramebuffersEXT((framebuffers as JvmIntBuffer).nioBuffer) } override fun glDeleteProgram(program: Int) { GL20.glDeleteProgram(program) } override fun glDeleteRenderbuffers(n: Int, renderbuffers: IntBuffer) { EXTFramebufferObject.glDeleteRenderbuffersEXT((renderbuffers as JvmIntBuffer).nioBuffer) } override fun glDeleteShader(shader: Int) { GL20.glDeleteShader(shader) } override fun glDeleteTextures(n: Int, textures: IntBuffer) { GL11.glDeleteTextures((textures as JvmIntBuffer).nioBuffer) } override fun glDepthFunc(func: Int) { GL11.glDepthFunc(func) } override fun glDepthMask(flag: Boolean) { GL11.glDepthMask(flag) } override fun glDepthRangef(zNear: Float, zFar: Float) { GL11.glDepthRange(zNear.toDouble(), zFar.toDouble()) } override fun glDetachShader(program: Int, shader: Int) { GL20.glDetachShader(program, shader) } override fun glDisable(cap: Int) { GL11.glDisable(cap) } override fun glDisableVertexAttribArray(index: Int) { GL20.glDisableVertexAttribArray(index) } override fun glDrawArrays(mode: Int, first: Int, count: Int) { GL11.glDrawArrays(mode, first, count) } override fun glDrawElements(mode: Int, count: Int, type: Int, indices: Buffer) { if (indices is JvmShortBuffer && type == GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, indices.nioBuffer) else if (indices is JvmByteBuffer && type == GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, indices.nioBuffer.asShortBuffer()) // FIXME // yay... else if (indices is JvmByteBuffer && type == GL_UNSIGNED_BYTE) GL11.glDrawElements(mode, indices.nioBuffer) else throw RuntimeException( "Can't use " + indices.javaClass.name + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL") } override fun glEnable(cap: Int) { GL11.glEnable(cap) } override fun glEnableVertexAttribArray(index: Int) { GL20.glEnableVertexAttribArray(index) } override fun glFinish() { GL11.glFinish() } override fun glFlush() { GL11.glFlush() } override fun glFramebufferRenderbuffer(target: Int, attachment: Int, renderbuffertarget: Int, renderbuffer: Int) { EXTFramebufferObject.glFramebufferRenderbufferEXT( target, attachment, renderbuffertarget, renderbuffer) } override fun glFramebufferTexture2D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int) { EXTFramebufferObject.glFramebufferTexture2DEXT(target, attachment, textarget, texture, level) } override fun glFrontFace(mode: Int) { GL11.glFrontFace(mode) } override fun glGenBuffers(n: Int, buffers: IntBuffer) { GL15.glGenBuffers((buffers as JvmIntBuffer).nioBuffer) } override fun glGenFramebuffers(n: Int, framebuffers: IntBuffer) { EXTFramebufferObject.glGenFramebuffersEXT((framebuffers as JvmIntBuffer).nioBuffer) } override fun glGenRenderbuffers(n: Int, renderbuffers: IntBuffer) { EXTFramebufferObject.glGenRenderbuffersEXT((renderbuffers as JvmIntBuffer).nioBuffer) } override fun glGenTextures(n: Int, textures: IntBuffer) { GL11.glGenTextures((textures as JvmIntBuffer).nioBuffer) } override fun glGenerateMipmap(target: Int) { EXTFramebufferObject.glGenerateMipmapEXT(target) } override fun glGetAttribLocation(program: Int, name: String): Int { return GL20.glGetAttribLocation(program, name) } override fun glGetBufferParameteriv(target: Int, pname: Int, params: IntBuffer) { GL15.glGetBufferParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetError(): Int { return GL11.glGetError() } override fun glGetFloatv(pname: Int, params: FloatBuffer) { GL11.glGetFloatv(pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetFramebufferAttachmentParameteriv(target: Int, attachment: Int, pname: Int, params: IntBuffer) { EXTFramebufferObject.glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetIntegerv(pname: Int, params: IntBuffer) { GL11.glGetIntegerv(pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetProgramInfoLog(program: Int): String { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetProgramInfoLog(program, intBuffer, buffer) val numBytes = intBuffer.get(0) val bytes = ByteArray(numBytes) buffer.get(bytes) return String(bytes) } override fun glGetProgramiv(program: Int, pname: Int, params: IntBuffer) { GL20.glGetProgramiv(program, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetRenderbufferParameteriv(target: Int, pname: Int, params: IntBuffer) { EXTFramebufferObject.glGetRenderbufferParameterivEXT(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetShaderInfoLog(shader: Int): String { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetShaderInfoLog(shader, intBuffer, buffer) val numBytes = intBuffer.get(0) val bytes = ByteArray(numBytes) buffer.get(bytes) return String(bytes) } override fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntBuffer, precision: IntBuffer) { glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision) } override fun glGetShaderiv(shader: Int, pname: Int, params: IntBuffer) { GL20.glGetShaderiv(shader, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetString(name: Int): String { return GL11.glGetString(name) } override fun glGetTexParameterfv(target: Int, pname: Int, params: FloatBuffer) { GL11.glGetTexParameterfv(target, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetTexParameteriv(target: Int, pname: Int, params: IntBuffer) { GL11.glGetTexParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetUniformLocation(program: Int, name: String): Int { return GL20.glGetUniformLocation(program, name) } override fun glGetUniformfv(program: Int, location: Int, params: FloatBuffer) { GL20.glGetUniformfv(program, location, (params as JvmFloatBuffer).nioBuffer) } override fun glGetUniformiv(program: Int, location: Int, params: IntBuffer) { GL20.glGetUniformiv(program, location, (params as JvmIntBuffer).nioBuffer) } override fun glGetVertexAttribfv(index: Int, pname: Int, params: FloatBuffer) { GL20.glGetVertexAttribfv(index, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetVertexAttribiv(index: Int, pname: Int, params: IntBuffer) { GL20.glGetVertexAttribiv(index, pname, (params as JvmIntBuffer).nioBuffer) } override fun glHint(target: Int, mode: Int) { GL11.glHint(target, mode) } override fun glIsBuffer(buffer: Int): Boolean { return GL15.glIsBuffer(buffer) } override fun glIsEnabled(cap: Int): Boolean { return GL11.glIsEnabled(cap) } override fun glIsFramebuffer(framebuffer: Int): Boolean { return EXTFramebufferObject.glIsFramebufferEXT(framebuffer) } override fun glIsProgram(program: Int): Boolean { return GL20.glIsProgram(program) } override fun glIsRenderbuffer(renderbuffer: Int): Boolean { return EXTFramebufferObject.glIsRenderbufferEXT(renderbuffer) } override fun glIsShader(shader: Int): Boolean { return GL20.glIsShader(shader) } override fun glIsTexture(texture: Int): Boolean { return GL11.glIsTexture(texture) } override fun glLineWidth(width: Float) { GL11.glLineWidth(width) } override fun glLinkProgram(program: Int) { GL20.glLinkProgram(program) } override fun glPixelStorei(pname: Int, param: Int) { GL11.glPixelStorei(pname, param) } override fun glPolygonOffset(factor: Float, units: Float) { GL11.glPolygonOffset(factor, units) } override fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer) { if (pixels is JvmByteBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL") } override fun glReleaseShaderCompiler() { // nothing to do here } override fun glRenderbufferStorage(target: Int, internalformat: Int, width: Int, height: Int) { EXTFramebufferObject.glRenderbufferStorageEXT(target, internalformat, width, height) } override fun glSampleCoverage(value: Float, invert: Boolean) { GL13.glSampleCoverage(value, invert) } override fun glScissor(x: Int, y: Int, width: Int, height: Int) { GL11.glScissor(x, y, width, height) } override fun glShaderBinary(n: Int, shaders: IntBuffer, binaryformat: Int, binary: Buffer, length: Int) { throw UnsupportedOperationException("unsupported, won't implement") } override fun glShaderSource(shader: Int, string: String) { GL20.glShaderSource(shader, string) } override fun glStencilFunc(func: Int, ref: Int, mask: Int) { GL11.glStencilFunc(func, ref, mask) } override fun glStencilFuncSeparate(face: Int, func: Int, ref: Int, mask: Int) { GL20.glStencilFuncSeparate(face, func, ref, mask) } override fun glStencilMask(mask: Int) { GL11.glStencilMask(mask) } override fun glStencilMaskSeparate(face: Int, mask: Int) { GL20.glStencilMaskSeparate(face, mask) } override fun glStencilOp(fail: Int, zfail: Int, zpass: Int) { GL11.glStencilOp(fail, zfail, zpass) } override fun glStencilOpSeparate(face: Int, fail: Int, zfail: Int, zpass: Int) { GL20.glStencilOpSeparate(face, fail, zfail, zpass) } override fun glTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Buffer?) { if (pixels == null) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, null as java.nio.ByteBuffer?) else if (pixels is JvmByteBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmDoubleBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL") } override fun glTexParameterf(target: Int, pname: Int, param: Float) { GL11.glTexParameterf(target, pname, param) } override fun glTexParameterfv(target: Int, pname: Int, params: FloatBuffer) { GL11.glTexParameterfv(target, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glTexParameteri(target: Int, pname: Int, param: Int) { GL11.glTexParameteri(target, pname, param) } override fun glTexParameteriv(target: Int, pname: Int, params: IntBuffer) { GL11.glTexParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer) { if (pixels is JvmByteBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmDoubleBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL") } override fun glUniform1f(location: Int, x: Float) { GL20.glUniform1f(location, x) } override fun glUniform1fv(location: Int, count: Int, buffer: FloatBuffer) { val oldLimit = buffer.limit() buffer.limit(buffer.position() + count) GL20.glUniform1fv(location, (buffer as JvmFloatBuffer).nioBuffer) buffer.limit(oldLimit) } override fun glUniform1i(location: Int, x: Int) { GL20.glUniform1i(location, x) } override fun glUniform1iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + count) GL20.glUniform1iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform2f(location: Int, x: Float, y: Float) { GL20.glUniform2f(location, x, y) } override fun glUniform2fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * count) GL20.glUniform2fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform2i(location: Int, x: Int, y: Int) { GL20.glUniform2i(location, x, y) } override fun glUniform2iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * count) GL20.glUniform2iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform3f(location: Int, x: Float, y: Float, z: Float) { GL20.glUniform3f(location, x, y, z) } override fun glUniform3fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * count) GL20.glUniform3fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform3i(location: Int, x: Int, y: Int, z: Int) { GL20.glUniform3i(location, x, y, z) } override fun glUniform3iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * count) GL20.glUniform3iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform4f(location: Int, x: Float, y: Float, z: Float, w: Float) { GL20.glUniform4f(location, x, y, z, w) } override fun glUniform4fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * count) GL20.glUniform4fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform4i(location: Int, x: Int, y: Int, z: Int, w: Int) { GL20.glUniform4i(location, x, y, z, w) } override fun glUniform4iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * count) GL20.glUniform4iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix2fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * 2 * count) GL20.glUniformMatrix2fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix3fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * 3 * count) GL20.glUniformMatrix3fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix4fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * 4 * count) GL20.glUniformMatrix4fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUseProgram(program: Int) { GL20.glUseProgram(program) } override fun glValidateProgram(program: Int) { GL20.glValidateProgram(program) } override fun glVertexAttrib1f(index: Int, x: Float) { GL20.glVertexAttrib1f(index, x) } override fun glVertexAttrib1fv(index: Int, values: FloatBuffer) { GL20.glVertexAttrib1f(index, (values as JvmFloatBuffer).nioBuffer.get()) } override fun glVertexAttrib2f(index: Int, x: Float, y: Float) { GL20.glVertexAttrib2f(index, x, y) } override fun glVertexAttrib2fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib2f(index, nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttrib3f(index: Int, x: Float, y: Float, z: Float) { GL20.glVertexAttrib3f(index, x, y, z) } override fun glVertexAttrib3fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib3f(index, nioBuffer.get(), nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttrib4f(index: Int, x: Float, y: Float, z: Float, w: Float) { GL20.glVertexAttrib4f(index, x, y, z, w) } override fun glVertexAttrib4fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib4f(index, nioBuffer.get(), nioBuffer.get(), nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Buffer) { if (ptr is JvmFloatBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmByteBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmShortBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmIntBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else { throw RuntimeException("NYI for " + ptr.javaClass) } } override fun glViewport(x: Int, y: Int, width: Int, height: Int) { GL11.glViewport(x, y, width, height) } override fun glDrawElements(mode: Int, count: Int, type: Int, indices: Int) { GL11.glDrawElements(mode, count, type, indices.toLong()) } override fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Int) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.toLong()) } override val platformGLExtensions: String get() = throw UnsupportedOperationException("NYI - not in LWJGL.") override val swapInterval: Int get() = throw UnsupportedOperationException("NYI - not in LWJGL.") override fun glClearDepth(depth: Double) { GL11.glClearDepth(depth) } override fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Int) { GL13.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data.toLong()) } override fun glCompressedTexImage3D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: ByteBuffer) { GL13.glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, MemoryUtil.memAddress((data as JvmByteBuffer).nioBuffer)) } override fun glCompressedTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: Int) { GL13.glCompressedTexImage3D( target, level, internalFormat, width, height, depth, border, imageSize, data.toLong()) } override fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Int) { GL13.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data.toLong()) } override fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: ByteBuffer) { // imageSize is calculated in glCompressedTexSubImage3D. GL13.glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, (data as JvmByteBuffer).nioBuffer) } override fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: Int) { val dataBuffer = BufferUtils.createByteBuffer(4) dataBuffer.putInt(data) dataBuffer.rewind() // imageSize is calculated in glCompressedTexSubImage3D. GL13.glCompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, dataBuffer) } override fun glCopyTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, x: Int, y: Int, width: Int, height: Int) { GL12.glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height) } override fun glDepthRange(zNear: Double, zFar: Double) { GL11.glDepthRange(zNear, zFar) } override fun glFramebufferTexture3D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int, zoffset: Int) { EXTFramebufferObject.glFramebufferTexture3DEXT( target, attachment, textarget, texture, level, zoffset) } override fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int) { // http://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetActiveAttrib.xml // Returns length, size, type, name bufs.resizeIntBuffer(2) // Return name, length val nameString = GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(bufsize), (bufs.intBuffer as JvmIntBuffer).nioBuffer) try { val nameBytes = nameString.toByteArray(charset("UTF-8")) val nameLength = nameBytes.size - nameOffset bufs.setByteBuffer(nameBytes, nameOffset, nameLength) bufs.byteBuffer.get(name, nameOffset, nameLength) length[lengthOffset] = nameLength } catch (e: UnsupportedEncodingException) { e.printStackTrace() } // Return size, type bufs.intBuffer.get(size, 0, 1) bufs.intBuffer.get(type, 0, 1) } override fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer) { val typeTmp = BufferUtils.createIntBuffer(2) GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(256), typeTmp) type.put(typeTmp.get(0)) type.rewind() } override fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int) { bufs.resizeIntBuffer(2) // Return name, length val nameString = GL20.glGetActiveUniform(program, index, BufferUtils.createIntBuffer(256), (bufs.intBuffer as JvmIntBuffer).nioBuffer) try { val nameBytes = nameString.toByteArray(charset("UTF-8")) val nameLength = nameBytes.size - nameOffset bufs.setByteBuffer(nameBytes, nameOffset, nameLength) bufs.byteBuffer.get(name, nameOffset, nameLength) length[lengthOffset] = nameLength } catch (e: UnsupportedEncodingException) { e.printStackTrace() } // Return size, type bufs.intBuffer.get(size, 0, 1) bufs.intBuffer.get(type, 0, 1) } override fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer) { val typeTmp = BufferUtils.createIntBuffer(2) GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(256), typeTmp) type.put(typeTmp.get(0)) type.rewind() } override fun glGetAttachedShaders(program: Int, maxcount: Int, count: IntBuffer, shaders: IntBuffer) { GL20.glGetAttachedShaders(program, (count as JvmIntBuffer).nioBuffer, (shaders as JvmIntBuffer).nioBuffer) } override fun glGetBoolean(pname: Int): Boolean { return GL11.glGetBoolean(pname) } override fun glGetBooleanv(pname: Int, params: ByteBuffer) { GL11.glGetBooleanv(pname, (params as JvmByteBuffer).nioBuffer) } override fun glGetBoundBuffer(target: Int): Int { throw UnsupportedOperationException("glGetBoundBuffer not supported in GLES 2.0 or LWJGL.") } override fun glGetFloat(pname: Int): Float { return GL11.glGetFloat(pname) } override fun glGetInteger(pname: Int): Int { return GL11.glGetInteger(pname) } override fun glGetProgramBinary(program: Int, bufSize: Int, length: IntBuffer, binaryFormat: IntBuffer, binary: ByteBuffer) { GL41.glGetProgramBinary(program, (length as JvmIntBuffer).nioBuffer, (binaryFormat as JvmIntBuffer).nioBuffer, (binary as JvmByteBuffer).nioBuffer) } override fun glGetProgramInfoLog(program: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer) { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetProgramInfoLog(program, intBuffer, buffer) } override fun glGetShaderInfoLog(shader: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer) { GL20.glGetShaderInfoLog(shader, (length as JvmIntBuffer).nioBuffer, (infolog as JvmByteBuffer).nioBuffer) } override fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntArray, rangeOffset: Int, precision: IntArray, precisionOffset: Int) { throw UnsupportedOperationException("NYI") } override fun glGetShaderSource(shader: Int, bufsize: Int, length: IntArray, lengthOffset: Int, source: ByteArray, sourceOffset: Int) { throw UnsupportedOperationException("NYI") } override fun glGetShaderSource(shader: Int, bufsize: Int, length: IntBuffer, source: ByteBuffer) { throw UnsupportedOperationException("NYI") } override fun glIsVBOArrayEnabled(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun glIsVBOElementEnabled(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun glMapBuffer(target: Int, access: Int): ByteBuffer { return JvmByteBuffer(GL15.glMapBuffer(target, access, null)) } override fun glProgramBinary(program: Int, binaryFormat: Int, binary: ByteBuffer, length: Int) { // Length is calculated in glProgramBinary. GL41.glProgramBinary(program, binaryFormat, (binary as JvmByteBuffer).nioBuffer) } override fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixelsBufferOffset: Int) { GL11.glReadPixels(x, y, width, height, format, type, pixelsBufferOffset.toLong()) } override fun glShaderBinary(n: Int, shaders: IntArray, offset: Int, binaryformat: Int, binary: Buffer, length: Int) { throw UnsupportedOperationException("NYI") } override fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntArray, lengthOffset: Int) { for (str in strings) GL20.glShaderSource(shader, str) } override fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntBuffer) { for (str in strings) GL20.glShaderSource(shader, str) } override fun glTexImage2D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Int) { GL11.glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels.toLong()) } override fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Buffer) { if (pixels !is JvmByteBuffer) throw UnsupportedOperationException("Buffer must be a ByteBuffer.") GL12.glTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels.nioBuffer) } override fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Int) { GL12.glTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels.toLong()) } override fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Int) { GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.toLong()) } override fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: ByteBuffer) { GL12.glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, (pixels as JvmByteBuffer).nioBuffer) } override fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: Int) { val byteBuffer = BufferUtils.createByteBuffer(1) byteBuffer.putInt(pixels) byteBuffer.rewind() GL12.glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, byteBuffer) } override fun glUnmapBuffer(target: Int): Boolean { return GL15.glUnmapBuffer(target) } override fun hasGLSL(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun isExtensionAvailable(extension: String): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun isFunctionAvailable(function: String): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } }
klay-jvm/src/main/kotlin/klay/jvm/JvmGL20.kt
3680522459
object ReferenceTo { fun foo() { } private class MainConstructor(foo: Int) fun main() { ReferenceTo.foo() MainConstructor(1) // TODO getValue, setValue, contains, invoke } }
server/src/test/resources/references/ReferenceTo.kt
2875262745
package org.moire.ultrasonic.api.subsonic import org.junit.Test /** * Integration test for [SubsonicAPIClient] for createPlaylist call. */ class SubsonicApiCreatePlaylistTest : SubsonicAPIClientTest() { @Test fun `Should handle error response`() { checkErrorCallParsed(mockWebServerRule) { client.api.createPlaylist().execute() } } @Test fun `Should hanlde ok response`() { mockWebServerRule.enqueueResponse("ping_ok.json") val response = client.api.createPlaylist().execute() assertResponseSuccessful(response) } @Test fun `Should pass id param in request`() { val id = "56" mockWebServerRule.assertRequestParam( responseResourceName = "ping_ok.json", expectedParam = "playlistId=$id" ) { client.api.createPlaylist(id = id).execute() } } @Test fun `Should pass name param in request`() { val name = "some-name" mockWebServerRule.assertRequestParam( responseResourceName = "ping_ok.json", expectedParam = "name=$name" ) { client.api.createPlaylist(name = name).execute() } } @Test fun `Should pass song id param in request`() { val songId = listOf("4410", "852") mockWebServerRule.assertRequestParam( responseResourceName = "ping_ok.json", expectedParam = "songId=${songId[0]}&songId=${songId[1]}" ) { client.api.createPlaylist(songIds = songId).execute() } } }
core/subsonic-api/src/integrationTest/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicApiCreatePlaylistTest.kt
1343438925
// ERROR: Type mismatch: inferred type is Unit but Int was expected // ERROR: 'when' expression must be exhaustive, add necessary 'else' branch object NonDefault { @JvmStatic fun main(args: Array<String>) { val value = 3 val valueString = "" val a: Int = when (value) { } println(valueString) } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/newJavaFeatures/switchExpression/emptySwitch.kt
1713114691
package com.jetbrains.python.sdk import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import java.io.File val Module.rootManager: ModuleRootManager get() = ModuleRootManager.getInstance(this) val Module.baseDir: VirtualFile? get() { val roots = rootManager.contentRoots val moduleFile = moduleFile ?: return roots.firstOrNull() return roots.firstOrNull { VfsUtil.isAncestor(it, moduleFile, true) } ?: roots.firstOrNull() } val Module.basePath: String? get() = baseDir?.path
python/python-sdk/src/com/jetbrains/python/sdk/BasePySdkExt.kt
80388505
// 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 org.jetbrains.intellij.build.images import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtilRt import com.intellij.ui.svg.SvgTranscoder import com.intellij.ui.svg.createSvgDocument import com.intellij.util.io.DigestUtil import java.awt.Dimension import java.awt.image.BufferedImage import java.io.File import java.io.IOException import java.math.BigInteger import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import javax.imageio.ImageIO internal val File.children: List<File> get() = if (isDirectory) listFiles()?.toList() ?: emptyList() else emptyList() internal fun isImage(file: Path, iconsOnly: Boolean): Boolean { return if (iconsOnly) isIcon(file) else isImage(file) } // allow other project path setups to generate Android Icons var androidIcons: Path = Paths.get(PathManager.getCommunityHomePath(), "android/artwork/resources") internal fun isIcon(file: Path): Boolean { if (!isImage(file)) { return false } val size = imageSize(file) ?: return false if (file.startsWith(androidIcons)) { return true } return size.height == size.width || size.height <= 100 && size.width <= 100 } internal fun isImage(file: Path) = ImageExtension.fromName(file.fileName.toString()) != null internal fun isImage(file: File) = ImageExtension.fromName(file.name) != null internal fun imageSize(file: Path, failOnMalformedImage: Boolean = false): Dimension? { val image = try { loadImage(file, failOnMalformedImage) } catch (e: Exception) { if (failOnMalformedImage) throw e null } if (image == null) { if (failOnMalformedImage) error("Can't load $file") println("WARNING: can't load $file") return null } val width = image.width val height = image.height return Dimension(width, height) } private fun loadImage(file: Path, failOnMalformedImage: Boolean): BufferedImage? { if (file.toString().endsWith(".svg")) { // don't mask any exception for svg file Files.newInputStream(file).use { try { return SvgTranscoder.createImage(1f, createSvgDocument(null, it), null) } catch (e: Exception) { throw IOException("Cannot decode $file", e) } } } try { return Files.newInputStream(file).buffered().use { ImageIO.read(it) } } catch (e: Exception) { if (failOnMalformedImage) throw e return null } } internal fun md5(file: Path): String { val hash = DigestUtil.md5().digest(Files.readAllBytes(file)) return BigInteger(hash).abs().toString(16) } internal enum class ImageType(private val suffix: String) { BASIC(""), RETINA("@2x"), DARCULA("_dark"), RETINA_DARCULA("@2x_dark"); companion object { fun getBasicName(suffix: String, prefix: String): String { return "$prefix/${stripSuffix(FileUtilRt.getNameWithoutExtension(suffix))}" } fun fromFile(file: Path): ImageType { return fromName(FileUtilRt.getNameWithoutExtension(file.fileName.toString())) } private fun fromName(name: String): ImageType { return when { name.endsWith(RETINA_DARCULA.suffix) -> RETINA_DARCULA name.endsWith(RETINA.suffix) -> RETINA name.endsWith(DARCULA.suffix) -> DARCULA else -> BASIC } } fun stripSuffix(name: String): String { return name.removeSuffix(fromName(name).suffix) } } } internal enum class ImageExtension(private val suffix: String) { PNG(".png"), SVG(".svg"), GIF(".gif"); companion object { fun fromFile(file: Path) = fromName(file.fileName.toString()) fun fromName(name: String): ImageExtension? { if (name.endsWith(PNG.suffix)) return PNG if (name.endsWith(SVG.suffix)) return SVG if (name.endsWith(GIF.suffix)) return GIF return null } } }
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/util.kt
2566736130
class SomeClass { internal fun doSomeFor() { var a: Int var b: Int for (i in 0..9) { b = i a = b } } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/for/assignmentAsExpressionInBody.kt
1838302
package com.intellij.settingsSync import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.actions.RevealFileAction import com.intellij.ide.actions.ShowLogAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.settingsSync.auth.SettingsSyncAuthService import com.intellij.ui.JBAccountInfoService import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.RowLayout import com.intellij.ui.dsl.builder.panel import com.intellij.util.io.Compressor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.cloudconfig.FileVersionInfo import org.jetbrains.annotations.Nls import java.awt.BorderLayout import java.io.File import java.text.SimpleDateFormat import java.util.* import javax.swing.Action import javax.swing.JButton import javax.swing.JComponent import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED internal class SettingsSyncTroubleshootingAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isSettingsSyncEnabledByKey() } override fun actionPerformed(e: AnActionEvent) { val remoteCommunicator = SettingsSyncMain.getInstance().getRemoteCommunicator() if (remoteCommunicator !is CloudConfigServerCommunicator) { Messages.showErrorDialog(e.project, SettingsSyncBundle.message("troubleshooting.dialog.error.wrong.configuration", remoteCommunicator::class), SettingsSyncBundle.message("troubleshooting.dialog.title")) return } try { val version = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val fileVersion = remoteCommunicator.getLatestVersion() if (fileVersion == null) { null } else { val zip = downloadToZip(fileVersion, remoteCommunicator) Version(fileVersion, SettingsSnapshotZipSerializer.extractFromZip(zip!!.toPath())) } }, SettingsSyncBundle.message("troubleshooting.loading.info.progress.dialog.title"), false, e.project) TroubleshootingDialog(e.project, remoteCommunicator, version).show() } catch (ex: Exception) { LOG.error(ex) if (Messages.OK == Messages.showOkCancelDialog(e.project, SettingsSyncBundle.message("troubleshooting.dialog.error.check.log.file.for.errors"), SettingsSyncBundle.message("troubleshooting.dialog.error.loading.info.failed"), ShowLogAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { ShowLogAction.showLog() } } } private data class Version(val fileVersion: FileVersionInfo, val snapshot: SettingsSnapshot?) private class TroubleshootingDialog(val project: Project?, val remoteCommunicator: CloudConfigServerCommunicator, val latestVersion: Version?) : DialogWrapper(project, true) { val userData = SettingsSyncAuthService.getInstance().getUserData() init { title = SettingsSyncBundle.message("troubleshooting.dialog.title") init() } override fun createActions(): Array<Action> { setCancelButtonText(CommonBundle.getCloseButtonText()) cancelAction.putValue(DEFAULT_ACTION, true) return arrayOf(cancelAction) } override fun createCenterPanel(): JComponent { return panel { statusRow() serverUrlRow() loginNameRow(userData) emailRow(userData) appInfoRow() if (latestVersion == null) { row { label(SettingsSyncBundle.message("troubleshooting.dialog.no.file.on.server", SETTINGS_SYNC_SNAPSHOT_ZIP)) } } else { row { label(SettingsSyncBundle.message("troubleshooting.dialog.latest.version.label", SETTINGS_SYNC_SNAPSHOT_ZIP)).bold() } versionRow(latestVersion) row { button(SettingsSyncBundle.message("troubleshooting.dialog.show.history.button")) { showHistoryDialog(project, remoteCommunicator, userData?.loginName!!) } button(SettingsSyncBundle.message("troubleshooting.dialog.delete.button")) { deleteFile(project, remoteCommunicator) } } } } } private fun Panel.statusRow() = row { label(SettingsSyncBundle.message("troubleshooting.dialog.local.status.label")) label(if (SettingsSyncSettings.getInstance().syncEnabled) IdeBundle.message("plugins.configurable.enabled") else IdeBundle.message("plugins.configurable.disabled")) }.layout(RowLayout.PARENT_GRID) private fun Panel.serverUrlRow() = row { label(SettingsSyncBundle.message("troubleshooting.dialog.server.url.label")) copyableLabel(CloudConfigServerCommunicator.url) }.layout(RowLayout.PARENT_GRID) private fun Panel.loginNameRow(userData: JBAccountInfoService.JBAData?) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.login.label")) copyableLabel(userData?.loginName) }.layout(RowLayout.PARENT_GRID) private fun Panel.emailRow(userData: JBAccountInfoService.JBAData?) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.email.label")) copyableLabel(userData?.email) }.layout(RowLayout.PARENT_GRID) private fun Panel.appInfoRow() { val appInfo = getLocalApplicationInfo() row { label(SettingsSyncBundle.message("troubleshooting.dialog.applicationId.label")) copyableLabel(appInfo.applicationId) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.username.label")) copyableLabel(appInfo.userName) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.hostname.label")) copyableLabel(appInfo.hostName) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.configFolder.label")) copyableLabel(appInfo.configFolder) }.layout(RowLayout.PARENT_GRID) } private fun String.shorten() = StringUtil.shortenTextWithEllipsis(this, 12, 0, true) private fun Panel.versionRow(version: Version) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.version.date.label")) copyableLabel(formatDate(version.fileVersion.modifiedDate)) label(SettingsSyncBundle.message("troubleshooting.dialog.version.id.label")) copyableLabel(version.fileVersion.versionId.shorten()) val snapshot = version.snapshot if (snapshot != null) { label(SettingsSyncBundle.message("troubleshooting.dialog.machineInfo.label")) val appInfo = snapshot.metaInfo.appInfo val text = if (appInfo != null) { val appId = appInfo.applicationId val thisOrThat = if (appId == SettingsSyncLocalSettings.getInstance().applicationId) "[this] " else "[other]" "$thisOrThat ${appId.toString().shorten()} - ${appInfo.userName} - ${appInfo.hostName} - ${appInfo.configFolder}" } else { "Unknown" } copyableLabel(text) } actionButton(object : DumbAwareAction(AllIcons.Actions.Download) { override fun actionPerformed(e: AnActionEvent) { downloadVersion(version.fileVersion, e.project) } }) } private fun downloadVersion(version: FileVersionInfo, project: Project?) { val zipFile = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable<File?, Exception> { downloadToZip(version, remoteCommunicator) }, SettingsSyncBundle.message("troubleshooting.dialog.downloading.settings.from.server.progress.title"), false, project) if (zipFile != null) { showFileDownloadedMessage(zipFile, SettingsSyncBundle.message("troubleshooting.dialog.successfully.downloaded.message")) } else { if (Messages.OK == Messages.showOkCancelDialog(contentPane, SettingsSyncBundle.message("troubleshooting.dialog.error.check.log.file.for.errors"), SettingsSyncBundle.message("troubleshooting.dialog.error.download.zip.file.failed"), ShowLogAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { ShowLogAction.showLog() } } } private fun showFileDownloadedMessage(zipFile: File, @Nls message: String) { if (Messages.OK == Messages.showOkCancelDialog(contentPane, message, "", RevealFileAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { RevealFileAction.openFile(zipFile) } } private fun showHistoryDialog(project: Project?, remoteCommunicator: CloudConfigServerCommunicator, loginName: String) { val history = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { remoteCommunicator.fetchHistory().mapIndexed { index, fileVersion -> val snapshot = if (index < 10) { val zip = downloadToZip(fileVersion, remoteCommunicator) SettingsSnapshotZipSerializer.extractFromZip(zip!!.toPath()) } else null Version(fileVersion, snapshot) } }, SettingsSyncBundle.message("troubleshooting.fetching.history.progress.title"), false, project) val dialogBuilder = DialogBuilder(contentPane).title(SettingsSyncBundle.message("troubleshooting.settings.history.dialog.title")) val historyPanel = panel { for (version in history) { versionRow(version).layout(RowLayout.PARENT_GRID) } }.withBorder(JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP)) val button = JButton(SettingsSyncBundle.message("troubleshooting.dialog.download.full.history.button")) button.addActionListener { downloadFullHistory(project, remoteCommunicator, history, loginName) } val scrollPanel = JBScrollPane(historyPanel, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED) val mainPanel = JBUI.Panels.simplePanel() mainPanel.add(scrollPanel, BorderLayout.CENTER) mainPanel.add(button, BorderLayout.SOUTH) dialogBuilder.centerPanel(mainPanel) dialogBuilder.addCloseButton() dialogBuilder.show() } private fun downloadFullHistory(project: Project?, remoteCommunicator: CloudConfigServerCommunicator, history: List<Version>, loginName: String) { val compoundZip = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val fileName = "settings-server-history-${FileUtil.sanitizeFileName(loginName)}-${formatDate(Date())}.zip" val zipFile = FileUtil.createTempFile(fileName, null) val indicator = ProgressManager.getInstance().progressIndicator indicator.isIndeterminate = false Compressor.Zip(zipFile).use { zip -> for ((step, version) in history.withIndex()) { indicator.checkCanceled() indicator.fraction = (step.toDouble() / history.size) val fileVersion = version.fileVersion val stream = remoteCommunicator.downloadSnapshot(fileVersion) if (stream != null) { zip.addFile(getSnapshotFileName(fileVersion), stream) } else { LOG.warn("Couldn't download snapshot for version made on ${fileVersion.modifiedDate}") } } } zipFile }, SettingsSyncBundle.message("troubleshooting.fetching.history.progress.title"), true, project) showFileDownloadedMessage(compoundZip, SettingsSyncBundle.message("troubleshooting.dialog.download.full.history.success.message")) } private fun deleteFile(project: Project?, remoteCommunicator: CloudConfigServerCommunicator) { val choice = Messages.showOkCancelDialog(contentPane, SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.message"), SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.title"), IdeBundle.message("button.delete"), CommonBundle.getCancelButtonText(), null) if (choice == Messages.OK) { try { ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { SettingsSyncSettings.getInstance().syncEnabled = false remoteCommunicator.delete() }, SettingsSyncBundle.message("troubleshooting.delete.file.from.server.progress.title"), false, project) } catch (e: Exception) { LOG.warn("Couldn't delete $SETTINGS_SYNC_SNAPSHOT_ZIP from server", e) Messages.showErrorDialog(contentPane, e.message, SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.title")) } } } private fun Row.copyableLabel(@NlsSafe text: Any?) = cell(JBLabel(text.toString()).apply { setCopyable(true) }) } companion object { val LOG = logger<SettingsSyncTroubleshootingAction>() } } private fun downloadToZip(version: FileVersionInfo, remoteCommunicator: CloudConfigServerCommunicator): File? { val stream = remoteCommunicator.downloadSnapshot(version) ?: return null try { val tempFile = FileUtil.createTempFile(getSnapshotFileName(version), null) FileUtil.writeToFile(tempFile, stream.readAllBytes()) return tempFile } catch (e: Throwable) { SettingsSyncTroubleshootingAction.LOG.error(e) return null } } private fun getSnapshotFileName(version: FileVersionInfo) = "settings-sync-snapshot-${formatDate(version.modifiedDate)}.zip" private fun formatDate(date: Date) = SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.US).format(date)
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncTroubleshootingAction.kt
750946630
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val KHR_binding_modification = "KHRBindingModification".nativeClassXR("KHR_binding_modification", type = "instance", postfix = "KHR") { documentation = """ The $templateName extension. """ IntConstant( "The extension specification version.", "KHR_binding_modification_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "KHR_BINDING_MODIFICATION_EXTENSION_NAME".."XR_KHR_binding_modification" ) EnumConstant( "Extends {@code XrStructureType}.", "TYPE_BINDING_MODIFICATIONS_KHR".."1000120000" ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/KHR_binding_modification.kt
1190063382
package org.secfirst.umbrella.data.database.content import android.content.Context import android.content.Intent import android.net.Uri import org.apache.commons.text.WordUtils import org.secfirst.advancedsearch.models.SearchResult import org.secfirst.umbrella.data.database.checklist.Content import org.secfirst.umbrella.data.database.form.Form import org.secfirst.umbrella.data.database.lesson.Module import org.secfirst.umbrella.data.database.reader.FeedSource import org.secfirst.umbrella.data.database.reader.RSS class ContentData(val modules: MutableList<Module> = arrayListOf(), val forms: MutableList<Form> = arrayListOf()) fun Content.toSearchResult(): SearchResult { val segments = this.checklist?.id.orEmpty().split("/") return SearchResult("${WordUtils.capitalizeFully(segments[1])} - ${WordUtils.capitalizeFully(segments[2])}", "" ) { c: Context -> val withoutLanguage = this.checklist?.id?.split("/")?.drop(1)?.joinToString("/") c.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("umbrella://$withoutLanguage"))) } } fun createFeedSources(): List<FeedSource> { val feedSources = mutableListOf<FeedSource>() val feedSource1 = FeedSource("ReliefWeb / United Nations (UN)", false, 0) val feedSource3 = FeedSource("Foreign and Commonwealth Office", false, 2) val feedSource4 = FeedSource("Centres for Disease Control", false, 3) val feedSource5 = FeedSource("Global Disaster Alert Coordination System", false, 4) val feedSource6 = FeedSource("US State Department Country Warnings", false, 5) feedSources.add(feedSource1) feedSources.add(feedSource3) feedSources.add(feedSource4) feedSources.add(feedSource5) feedSources.add(feedSource6) return feedSources } fun createDefaultRSS(): List<RSS> { val rssList = mutableListOf<RSS>() val rss1 = RSS("https://threatpost.com/feed/") val rss2 = RSS("https://krebsonsecurity.com/feed/") val rss3 = RSS("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk") val rss4 = RSS("http://rss.cnn.com/rss/edition.rss") val rss5 = RSS("https://www.aljazeera.com/xml/rss/all.xml") val rss6 = RSS("https://www.theguardian.com/world/rss") rssList.add(rss1) rssList.add(rss2) rssList.add(rss3) rssList.add(rss4) rssList.add(rss5) rssList.add(rss6) return rssList }
app/src/main/java/org/secfirst/umbrella/data/database/content/entity.kt
877162375
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import core.windows.* import vulkan.* val KHR_external_fence_win32 = "KHRExternalFenceWin32".nativeClassVK("KHR_external_fence_win32", type = "device", postfix = "KHR") { javaImport("org.lwjgl.system.windows.*") documentation = """ An application using external memory may wish to synchronize access to that memory using fences. This extension enables an application to export fence payload to and import fence payload from Windows handles. <h5>VK_KHR_external_fence_win32</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_KHR_external_fence_win32}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>115</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRExternalFence VK_KHR_external_fence} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Jesse Hall <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_external_fence_win32]%20@critsec%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_external_fence_win32%20extension%3E%3E">critsec</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2017-05-08</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Jesse Hall, Google</li> <li>James Jones, NVIDIA</li> <li>Jeff Juliano, NVIDIA</li> <li>Cass Everitt, Oculus</li> <li>Contributors to {@link KHRExternalSemaphoreWin32 VK_KHR_external_semaphore_win32}</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "KHR_EXTERNAL_FENCE_WIN32_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME".."VK_KHR_external_fence_win32" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR".."1000114000", "STRUCTURE_TYPE_EXPORT_FENCE_WIN32_HANDLE_INFO_KHR".."1000114001", "STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR".."1000114002" ) VkResult( "ImportFenceWin32HandleKHR", """ Import a fence from a Windows HANDLE. <h5>C Specification</h5> To import a fence payload from a Windows handle, call: <pre><code> ￿VkResult vkImportFenceWin32HandleKHR( ￿ VkDevice device, ￿ const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo);</code></pre> <h5>Description</h5> Importing a fence payload from Windows handles does not transfer ownership of the handle to the Vulkan implementation. For handle types defined as NT handles, the application <b>must</b> release ownership using the {@code CloseHandle} system call when the handle is no longer needed. Applications <b>can</b> import the same fence payload into multiple instances of Vulkan, into the same instance from which it was exported, and multiple times into a given Vulkan instance. <h5>Valid Usage</h5> <ul> <li>{@code fence} <b>must</b> not be associated with any queue command that has not yet completed execution on that queue</li> </ul> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pImportFenceWin32HandleInfo} <b>must</b> be a valid pointer to a valid ##VkImportFenceWin32HandleInfoKHR structure</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_OUT_OF_HOST_MEMORY</li> <li>#ERROR_INVALID_EXTERNAL_HANDLE</li> </ul></dd> </dl> <h5>See Also</h5> ##VkImportFenceWin32HandleInfoKHR """, VkDevice("device", "the logical device that created the fence."), VkImportFenceWin32HandleInfoKHR.const.p("pImportFenceWin32HandleInfo", "a pointer to a ##VkImportFenceWin32HandleInfoKHR structure specifying the fence and import parameters.") ) VkResult( "GetFenceWin32HandleKHR", """ Get a Windows HANDLE for a fence. <h5>C Specification</h5> To export a Windows handle representing the state of a fence, call: <pre><code> ￿VkResult vkGetFenceWin32HandleKHR( ￿ VkDevice device, ￿ const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo, ￿ HANDLE* pHandle);</code></pre> <h5>Description</h5> For handle types defined as NT handles, the handles returned by {@code vkGetFenceWin32HandleKHR} are owned by the application. To avoid leaking resources, the application <b>must</b> release ownership of them using the {@code CloseHandle} system call when they are no longer needed. Exporting a Windows handle from a fence <b>may</b> have side effects depending on the transference of the specified handle type, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#synchronization-fences-importing">Importing Fence Payloads</a>. <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li> <li>{@code pGetWin32HandleInfo} <b>must</b> be a valid pointer to a valid ##VkFenceGetWin32HandleInfoKHR structure</li> <li>{@code pHandle} <b>must</b> be a valid pointer to a {@code HANDLE} value</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_TOO_MANY_OBJECTS</li> <li>#ERROR_OUT_OF_HOST_MEMORY</li> </ul></dd> </dl> <h5>See Also</h5> ##VkFenceGetWin32HandleInfoKHR """, VkDevice("device", "the logical device that created the fence being exported."), VkFenceGetWin32HandleInfoKHR.const.p("pGetWin32HandleInfo", "a pointer to a ##VkFenceGetWin32HandleInfoKHR structure containing parameters of the export operation."), Check(1)..HANDLE.p("pHandle", "will return the Windows handle representing the fence state.") ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_external_fence_win32.kt
1693643107
package org.amshove.kluent.tests.basic import org.amshove.kluent.assertMessageContain import org.amshove.kluent.internal.assertFails import org.amshove.kluent.shouldBeFalse import kotlin.test.Test class ShouldBeFalseShould { @Test fun passWhenPassingFalse() { false.shouldBeFalse() } @Test fun failWhenPassingTrue() { assertFails { true.shouldBeFalse() } } @Test fun provideADescriptiveMessage() { assertMessageContain("Expected value to be false, but was true") { true.shouldBeFalse() } } }
common/src/test/kotlin/org/amshove/kluent/tests/basic/ShouldBeFalseShould.kt
2042961310
package k interface A<T> { fun foo(t: T) } class B : A<String> { override fun foo(t: String) {} }
java/ql/test/kotlin/library-tests/methods-mixed-java-and-kotlin/W.kt
3967761301
package com.programming.kotlin.chapter12.hello.impl import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.lightbend.lagom.serialization.Jsonable interface HelloEvent : Jsonable @JsonDeserialize data class GreetingMessageChanged @JsonCreator constructor(val message: String) : HelloEvent
Chapter12/hello-impl/src/main/kotlin/com.programming.kotlin.chapter12.hello.impl/HelloEvent.kt
2626947236
package com.mgaetan89.showsrage.model import com.mgaetan89.showsrage.network.SickRageApi import io.realm.RealmList import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class Show_GetSeasonsListIntTest(val show: Show, val seasonsListInt: List<Int>) { @Test fun getSeasonsListInt() { assertThat(this.show.getSeasonsListInt()).isEqualTo(this.seasonsListInt) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any>> { val gson = SickRageApi.gson return listOf( arrayOf(gson.fromJson("{}", Show::class.java), emptyList<String>()), arrayOf(buildJsonForSeasonList(emptyArray()), emptyList<String>()), arrayOf(buildJsonForSeasonList(arrayOf("10")), listOf(10)), arrayOf(buildJsonForSeasonList(arrayOf("10", "hello")), listOf(10)), arrayOf(buildJsonForSeasonList(arrayOf("10", "hello", "")), listOf(10)), arrayOf(buildJsonForSeasonList(arrayOf("10", "hello", "4294967295")), listOf(10)), arrayOf(buildJsonForSeasonList(arrayOf("10", "hello", "4294967295", "42")), listOf(10, 42)) ) } private fun buildJsonForSeasonList(seasonList: Array<String>): Show { return Show().apply { this.seasonList = RealmList<String>().apply { this.addAll(seasonList) } } } } }
app/src/test/kotlin/com/mgaetan89/showsrage/model/Show_GetSeasonsListIntTest.kt
1911022878
package maximmakarov.anylist.list import com.arellomobile.mvp.MvpView import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy import com.arellomobile.mvp.viewstate.strategy.StateStrategyType import maximmakarov.anylist.item.Item /** * @author Maxim Makarov * @since 05.05.2017 */ @StateStrategyType(value = AddToEndSingleStrategy::class) interface IListView : MvpView { fun onItemsLoaded(items: MutableList<Item>) }
app/src/main/java/maximmakarov/anylist/list/IListView.kt
4157787282
package top.zbeboy.isy.service.internship import org.jooq.Record import org.jooq.Result import top.zbeboy.isy.domain.tables.pojos.GraduationPracticeUnify import top.zbeboy.isy.web.util.DataTablesUtils import top.zbeboy.isy.web.vo.internship.apply.GraduationPracticeUnifyVo import java.util.* /** * Created by zbeboy 2017-12-27 . **/ interface GraduationPracticeUnifyService { /** * 通过id查询 * * @param id 主键 * @return 毕业实习(学校统一组织校外实习) */ fun findById(id: String): GraduationPracticeUnify /** * 通过实习发布id与学生id查询 * * @param internshipReleaseId 实习发布id * @param studentId 学生id * @return 数据 */ fun findByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int): Optional<Record> /** * 保存 * * @param graduationPracticeUnify 毕业实习(学校统一组织校外实习) */ fun save(graduationPracticeUnify: GraduationPracticeUnify) /** * 开启事务保存 * * @param graduationPracticeUnifyVo 毕业实习(学校统一组织校外实习) */ fun saveWithTransaction(graduationPracticeUnifyVo: GraduationPracticeUnifyVo) /** * 更新 * * @param graduationPracticeUnify 毕业实习(学校统一组织校外实习) */ fun update(graduationPracticeUnify: GraduationPracticeUnify) /** * 通过实习发布id与学生id查询 * * @param internshipReleaseId 实习发布id * @param studentId 学生id */ fun deleteByInternshipReleaseIdAndStudentId(internshipReleaseId: String, studentId: Int) /** * 分页查询 * * @param dataTablesUtils datatables工具类 * @return 分页数据 */ fun findAllByPage(dataTablesUtils: DataTablesUtils<GraduationPracticeUnify>, graduationPracticeUnify: GraduationPracticeUnify): Result<Record> /** * 系总数 * * @return 总数 */ fun countAll(graduationPracticeUnify: GraduationPracticeUnify): Int /** * 根据条件查询总数 * * @return 条件查询总数 */ fun countByCondition(dataTablesUtils: DataTablesUtils<GraduationPracticeUnify>, graduationPracticeUnify: GraduationPracticeUnify): Int /** * 查询 * * @param dataTablesUtils datatables工具类 * @param graduationPracticeUnify 毕业实习(学校统一组织校外实习) * @return 导出数据 */ fun exportData(dataTablesUtils: DataTablesUtils<GraduationPracticeUnify>, graduationPracticeUnify: GraduationPracticeUnify): Result<Record> }
src/main/java/top/zbeboy/isy/service/internship/GraduationPracticeUnifyService.kt
2865728964
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.vsphere.api import com.vmware.vim25.InvalidState import com.vmware.vim25.RuntimeFault import com.vmware.vim25.TaskDescription import com.vmware.vim25.TaskFilterSpec import com.vmware.vim25.TaskInfo import com.vmware.vim25.mo.ManagedObject import com.vmware.vim25.mo.Task import com.vmware.vim25.mo.TaskHistoryCollector import java.rmi.RemoteException interface TaskManagerApi { val description: TaskDescription val maxCollector: Int val recentTasks: List<Task> @Throws(InvalidState::class, RuntimeFault::class, RemoteException::class) fun createCollectorForTasks(filter: TaskFilterSpec): TaskHistoryCollector /** * SDK2.5 signature for back compatibility */ @Throws(RuntimeFault::class, RemoteException::class) fun createTask(obj: ManagedObject, taskTypeId: String, initiatedBy: String, cancelable: Boolean): TaskInfo /** * SDK4.0 signature */ @Throws(RuntimeFault::class, RemoteException::class) fun createTask(obj: ManagedObject, taskTypeId: String, initiatedBy: String, cancelable: Boolean, parentTaskKey: String): TaskInfo }
src/main/kotlin/org/jclouds/vsphere/api/TaskManagerApi.kt
276114252
package top.zbeboy.isy.service.internship import org.jooq.Record import org.jooq.Result import top.zbeboy.isy.web.bean.internship.statistics.InternshipStatisticsBean import top.zbeboy.isy.web.util.DataTablesUtils /** * Created by zbeboy 2017-12-28 . **/ interface InternshipStatisticsService { /** * 分页查询 已提交数据 * * @param dataTablesUtils datatables工具类 * @return 分页数据 */ fun submittedFindAllByPage(dataTablesUtils: DataTablesUtils<InternshipStatisticsBean>, internshipStatisticsBean: InternshipStatisticsBean): Result<Record> /** * 已提交数据 总数 * * @return 总数 */ fun submittedCountAll(internshipStatisticsBean: InternshipStatisticsBean): Int /** * 根据条件查询总数 已提交数据 * * @return 条件查询总数 */ fun submittedCountByCondition(dataTablesUtils: DataTablesUtils<InternshipStatisticsBean>, internshipStatisticsBean: InternshipStatisticsBean): Int /** * 分页查询 未提交数据 * * @param dataTablesUtils datatables工具类 * @return 分页数据 */ fun unsubmittedFindAllByPage(dataTablesUtils: DataTablesUtils<InternshipStatisticsBean>, internshipStatisticsBean: InternshipStatisticsBean): Result<Record> /** * 未提交数据 总数 * * @return 总数 */ fun unsubmittedCountAll(internshipStatisticsBean: InternshipStatisticsBean): Int /** * 根据条件查询总数 未提交数据 * * @return 条件查询总数 */ fun unsubmittedCountByCondition(dataTablesUtils: DataTablesUtils<InternshipStatisticsBean>, internshipStatisticsBean: InternshipStatisticsBean): Int }
src/main/java/top/zbeboy/isy/service/internship/InternshipStatisticsService.kt
1686051357
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic import com.intellij.openapi.application.PermanentInstallationID import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import java.text.SimpleDateFormat import java.util.* import java.util.prefs.Preferences object DeviceIdManager { private val LOG = Logger.getInstance(DeviceIdManager::class.java) private const val DEVICE_ID_SHARED_FILE = "PermanentDeviceId" private const val DEVICE_ID_PREFERENCE_KEY = "device_id" fun getOrGenerateId(): String { val appInfo = ApplicationInfoImpl.getShadowInstance() val prefs = getPreferences(appInfo) var deviceId = prefs.get(DEVICE_ID_PREFERENCE_KEY, null) if (StringUtil.isEmptyOrSpaces(deviceId)) { deviceId = generateId(Calendar.getInstance(), getOSChar()) prefs.put(DEVICE_ID_PREFERENCE_KEY, deviceId) LOG.info("Generating new Device ID") } if (appInfo.isVendorJetBrains && SystemInfo.isWindows) { deviceId = PermanentInstallationID.syncWithSharedFile(DEVICE_ID_SHARED_FILE, deviceId, prefs, DEVICE_ID_PREFERENCE_KEY) } return deviceId } private fun getPreferences(appInfo: ApplicationInfoEx): Preferences { val companyName = appInfo.shortCompanyName val name = if (StringUtil.isEmptyOrSpaces(companyName)) "jetbrains" else companyName.toLowerCase(Locale.US) return Preferences.userRoot().node(name) } /** * Device id is generating by concatenating following values: * Current date, written in format ddMMyy, where year coerced between 2000 and 2099 * Character, representing user's OS (see [getOSChar]) * [toString] call on representation of [UUID.randomUUID] */ fun generateId(calendar: Calendar, OSChar: Char): String { calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR).coerceIn(2000, 2099)) return SimpleDateFormat("ddMMyy").format(calendar.time) + OSChar + UUID.randomUUID().toString() } private fun getOSChar() = if (SystemInfo.isWindows) '1' else if (SystemInfo.isMac) '2' else if (SystemInfo.isLinux) '3' else '0' }
platform/platform-impl/src/com/intellij/internal/statistic/DeviceIdManager.kt
3991303360
package com.outbrain.ob1k.crud.model import com.fasterxml.jackson.annotation.JsonIgnore import com.google.gson.JsonObject data class EntityField(@JsonIgnore var dbName: String, var name: String, var label: String, var type: EFieldType, var required: Boolean = true, var readOnly: Boolean = false, @JsonIgnore var autoGenerate: Boolean = false, var reference: String? = null, var target: String? = null, var display: EntityFieldDisplay? = null, var hidden: Boolean = false, var options: EntityFieldOptions? = null, var choices: List<String>? = null, var rangeStyles: MutableList<RangeStyle>? = null, var fields: MutableList<EntityField>? = null) { var className: String? = null fun withRangeStyle(values: List<String>, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, values = values)) fun withRangeStyle(value: String, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, value = value)) fun withRangeStyle(start: Number?, end: Number?, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, range = listOf(start, end))) private fun withRangeStyle(rangeStyle: RangeStyle): EntityField { if (rangeStyles == null) { rangeStyles = mutableListOf() } rangeStyles?.let { it += rangeStyle } return this } fun nonNullOptions(): EntityFieldOptions { if (options == null) { options = EntityFieldOptions() } return options!! } fun setChoices(cls: Class<*>) { choices = cls.enumChoices() } internal fun toMysqlMatchValue(value: String): String { return when (type) { EFieldType.BOOLEAN -> if (value == "true") "=1" else "=0" EFieldType.STRING, EFieldType.URL, EFieldType.TEXT, EFieldType.SELECT_BY_STRING, EFieldType.IMAGE -> " LIKE \"%$value%\"" EFieldType.NUMBER, EFieldType.REFERENCE -> { val cleaned = value.removePrefix("[").removeSuffix("]").replace("\"", "") val split = cleaned.split(",") return if (split.size == 1) "=$cleaned" else " IN ($cleaned)" } EFieldType.DATE -> "=\"$value\"" EFieldType.SELECT_BY_IDX -> "=${choices!!.indexOf(value)}" else -> "=$value" } } internal fun toMysqlValue(value: String): String { return when (type) { EFieldType.BOOLEAN -> if (value == "true") "1" else "0" EFieldType.STRING, EFieldType.DATE, EFieldType.URL, EFieldType.TEXT, EFieldType.SELECT_BY_STRING, EFieldType.IMAGE -> "\"$value\"" EFieldType.SELECT_BY_IDX -> "${choices!!.indexOf(value)}" else -> value } } internal fun fillJsonObject(obj: JsonObject, property: String, value: String?) { when (type) { EFieldType.BOOLEAN -> obj.addProperty(property, value == "1") EFieldType.NUMBER, EFieldType.REFERENCE -> { value?.let { try { obj.addProperty(property, it.toInt()) } catch (e: NumberFormatException) { try { obj.addProperty(property, it.toDouble()) } catch (e: NumberFormatException) { throw RuntimeException(e.message, e) } } } } EFieldType.REFERENCEMANY -> throw UnsupportedOperationException() EFieldType.SELECT_BY_IDX -> value?.let { obj.addProperty(property, choices!![it.toInt()]) } else -> obj.addProperty(property, value) } } private fun Class<*>.enumChoices() = enumConstants?.map { it.toString() } }
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/model/EntityField.kt
1804237574
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.rebase import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import git4idea.branch.GitRebaseParams class GitInteractiveRebaseAction : GitCommitEditingAction() { override fun update(e: AnActionEvent) { super.update(e) prohibitRebaseDuringRebase(e, "rebase") } override fun actionPerformedAfterChecks(e: AnActionEvent) { val commit = getSelectedCommit(e) val project = e.project!! val repository = getRepository(e) object : Task.Backgroundable(project, "Rebasing") { override fun run(indicator: ProgressIndicator) { val params = GitRebaseParams.editCommits(commit.parents.first().asString(), null, false) GitRebaseUtils.rebase(project, listOf(repository), params, indicator); } }.queue() } override fun getFailureTitle(): String = "Couldn't Start Rebase" }
plugins/git4idea/src/git4idea/rebase/GitInteractiveRebaseAction.kt
1781312171
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.commands import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.util.containers.ContainerUtil.newConcurrentMap import java.util.concurrent.Semaphore import java.util.function.Supplier private val LOG = logger<GitRestrictingAuthenticationGate>() class GitRestrictingAuthenticationGate : GitAuthenticationGate { private val semaphore = Semaphore(1) @Volatile private var cancelled = false private val inputData = newConcurrentMap<String, String>() override fun <T> waitAndCompute(operation: Supplier<T>): T { try { LOG.debug("Entered waitAndCompute") semaphore.acquire() LOG.debug("Acquired permission") if (cancelled) { LOG.debug("Authentication Gate has already been cancelled") throw ProcessCanceledException() } return operation.get() } catch (e: InterruptedException) { LOG.warn(e) throw ProcessCanceledException(e) } finally { semaphore.release() } } override fun cancel() { cancelled = true } override fun getSavedInput(key: String): String? { return inputData[key] } override fun saveInput(key: String, value: String) { inputData[key] = value } } class GitPassthroughAuthenticationGate : GitAuthenticationGate { override fun <T> waitAndCompute(operation: Supplier<T>): T { return operation.get() } override fun cancel() { } override fun getSavedInput(key: String): String? { return null } override fun saveInput(key: String, value: String) { } companion object { @JvmStatic val instance = GitPassthroughAuthenticationGate() } }
plugins/git4idea/src/git4idea/commands/GitAuthenticationGates.kt
491263509
/* * 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 com.intellij.diff.tools.fragmented import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.comparison.iterables.DiffIterable import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.fragments.LineFragment import com.intellij.diff.fragments.LineFragmentImpl import com.intellij.diff.util.LineRange import com.intellij.diff.util.Range import com.intellij.diff.util.Side import com.intellij.openapi.editor.impl.DocumentImpl import junit.framework.TestCase import java.util.* class UnifiedFragmentBuilderTest : DiffTestCase() { fun testSimple() { Test("", "", ".", " ") .run() Test("A_B_C", "A_B_C", "A_B_C", " _ _ ") .run() // empty document has one line, so it's "modified" case (and not "deleted") Test("A", "", "A_.", "L_R") .run() Test("", "A", "._A", "L_R") .run() Test("A_", "", "A_.", "L_ ") .run() Test("A_", "B", "A_._B", "L_L_R") .run() Test("B_", "B", "B_.", " _L") .run() Test("_B", "B", "._B", "L_ ") .run() Test("A_A", "B", "A_A_B", "L_L_R") .run() Test("A_B_C_D", "A_D", "A_B_C_D", " _L_L_ ") .run() Test("X_B_C", "A_B_C", "X_A_B_C", "L_R_ _ ") .run() Test("A_B_C", "A_B_Y", "A_B_C_Y", " _ _L_R") .run() Test("A_B_C_D_E_F", "A_X_C_D_Y_F", "A_B_X_C_D_E_Y_F", " _L_R_ _ _L_R_ ") .run() Test("A_B_C_D_E_F", "A_B_X_C_D_F", "A_B_X_C_D_E_F", " _ _R_ _ _L_ ") .run() Test("A_B_C_D_E_F", "A_B_X_Y_E_F", "A_B_C_D_X_Y_E_F", " _ _L_L_R_R_ _ ") .run() Test("", "", ".", " ") .changes() .run() Test("A", "B", "A_B", "L_R") .changes(mod(0, 0, 1, 1)) .runLeft() Test("A", "B", "A", " ") .changes() .runLeft() Test("A", "B", "B", " ") .changes() .runRight() } fun testNonFair() { Test("A_B", "", "A_B", " _ ") .changes() .runLeft() Test("A_B", "", ".", " ") .changes() .runRight() Test("A_B", "A_._B", "A_B", " _ ") .changes() .runLeft() Test("A_B", "A_._B", "A_._B", " _ _ ") .changes() .runRight() Test("_._A_._", "X", "._._A_X_._.", " _ _L_R_ _ ") .changes(mod(2, 0, 1, 1)) .runLeft() Test("_._A_._", "X", "A_X", "L_R") .changes(mod(2, 0, 1, 1)) .runRight() Test("A_B_C_D", "X_BC_Y", "A_X_BC_D_Y", "L_R_ _L_R") .changes(mod(0, 0, 1, 1), mod(3, 2, 1, 1)) .runRight() Test("A_B_C_D", "A_BC_Y", "A_BC_D_Y", " _ _L_R") .changes(mod(3, 2, 1, 1)) .runRight() Test("AB_C_DE", "A_B_D_E", "AB_C_DE", " _L_ ") .changes(del(1, 2, 1)) .runLeft() Test("AB_C_DE", "A_B_D_E", "A_B_C_D_E", " _ _L_ _ ") .changes(del(1, 2, 1)) .runRight() Test("AB_DE", "A_B_C_D_E", "AB_C_DE", " _R_ ") .changes(ins(1, 2, 1)) .runLeft() Test("AB_DE", "A_B_C_D_E", "A_B_C_D_E", " _ _R_ _ ") .changes(ins(1, 2, 1)) .runRight() } private inner class Test(val input1: String, val input2: String, val result: String, val lineMapping: String) { private var customFragments: List<LineFragment>? = null fun runLeft() { doRun(Side.LEFT) } fun runRight() { doRun(Side.RIGHT) } fun run() { doRun(Side.LEFT, Side.RIGHT) } private fun doRun(vararg sides: Side) { sides.forEach { side -> assert(result.length == lineMapping.length) val text1 = processText(input1) val text2 = processText(input2) val fragments = if (customFragments != null) customFragments!! else MANAGER.compareLines(text1, text2, ComparisonPolicy.DEFAULT, INDICATOR) val builder = UnifiedFragmentBuilder(fragments, DocumentImpl(text1), DocumentImpl(text2), side) builder.exec() val lineCount1 = input1.count { it == '_' } + 1 val lineCount2 = input2.count { it == '_' } + 1 val resultLineCount = result.count { it == '_' } + 1 val lineIterable = DiffIterableUtil.create(fragments.map { Range(it.startLine1, it.endLine1, it.startLine2, it.endLine2) }, lineCount1, lineCount2) val expectedText = processText(result) val actualText = processActualText(builder) val expectedMapping = processExpectedLineMapping(lineMapping) val actualMapping = processActualLineMapping(builder.blocks, resultLineCount) val expectedChangedLines = processExpectedChangedLines(lineMapping) val actualChangedLines = processActualChangedLines(builder.changedLines) val expectedMappedLines1 = processExpectedMappedLines(lineIterable, Side.LEFT) val expectedMappedLines2 = processExpectedMappedLines(lineIterable, Side.RIGHT) val actualMappedLines1 = processActualMappedLines(builder.convertor1, resultLineCount) val actualMappedLines2 = processActualMappedLines(builder.convertor2, resultLineCount) assertEquals(expectedText, actualText) assertEquals(expectedMapping, actualMapping) assertEquals(expectedChangedLines, actualChangedLines) if (customFragments == null) { assertEquals(expectedMappedLines1, actualMappedLines1) assertEquals(expectedMappedLines2, actualMappedLines2) } } } fun changes(vararg ranges: Range): Test { customFragments = ranges.map { LineFragmentImpl(it.start1, it.end1, it.start2, it.end2, -1, -1, -1, -1) } return this } private fun processText(text: String): String { return text.filterNot { it == '.' }.replace('_', '\n') } private fun processActualText(builder: UnifiedFragmentBuilder): String { return builder.text.toString().removeSuffix("\n") } private fun processExpectedLineMapping(lineMapping: String): LineMapping { val leftSet = BitSet() val rightSet = BitSet() val unchangedSet = BitSet() lineMapping.split('_').forEachIndexed { index, line -> if (!line.isEmpty()) { val left = line.all { it == 'L' } val right = line.all { it == 'R' } val unchanged = line.all { it == ' ' } if (left) leftSet.set(index) else if (right) rightSet.set(index) else if (unchanged) unchangedSet.set(index) else TestCase.fail() } } return LineMapping(leftSet, rightSet, unchangedSet) } private fun processActualLineMapping(blocks: List<ChangedBlock>, lineCount: Int): LineMapping { val leftSet = BitSet() val rightSet = BitSet() val unchangedSet = BitSet() blocks.forEach { leftSet.set(it.range1.start, it.range1.end) rightSet.set(it.range2.start, it.range2.end) } unchangedSet.set(0, lineCount) unchangedSet.andNot(leftSet) unchangedSet.andNot(rightSet) return LineMapping(leftSet, rightSet, unchangedSet) } private fun processExpectedChangedLines(lineMapping: String): BitSet { val expectedMapping = processExpectedLineMapping(lineMapping) val result = BitSet() result.or(expectedMapping.left) result.or(expectedMapping.right) return result } private fun processActualChangedLines(changedRanges: List<LineRange>): BitSet { val result = BitSet() changedRanges.forEach { result.set(it.start, it.end) } return result } private fun processExpectedMappedLines(iterable: DiffIterable, side: Side): BitSet { val result = BitSet() DiffIterableUtil.iterateAll(iterable).forEach { pair -> val range = pair.first val start = side.select(range.start1, range.start2) val end = side.select(range.end1, range.end2) result.set(start, end) } return result } private fun processActualMappedLines(convertor: LineNumberConvertor, lineCount: Int): BitSet { val result = BitSet() for (i in -5..lineCount + 5) { val line = convertor.convert(i) if (line != -1) { if (result[line]) TestCase.fail() result.set(line) } } return result } } private fun mod(line1: Int, line2: Int, count1: Int, count2: Int): Range { assert(count1 != 0) assert(count2 != 0) return Range(line1, line1 + count1, line2, line2 + count2) } private fun del(line1: Int, line2: Int, count1: Int): Range { assert(count1 != 0) return Range(line1, line1 + count1, line2, line2) } private fun ins(line1: Int, line2: Int, count2: Int): Range { assert(count2 != 0) return Range(line1, line1, line2, line2 + count2) } private data class LineMapping(val left: BitSet, val right: BitSet, val unchanged: BitSet) }
platform/diff-impl/tests/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilderTest.kt
1043002168
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.data import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.readAction import com.intellij.openapi.components.Service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiManager import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider import com.jetbrains.packagesearch.intellij.plugin.util.BackgroundLoadingBarController import com.jetbrains.packagesearch.intellij.plugin.util.PowerSaveModeState import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo import com.jetbrains.packagesearch.intellij.plugin.util.batchAtIntervals import com.jetbrains.packagesearch.intellij.plugin.util.catchAndLog import com.jetbrains.packagesearch.intellij.plugin.util.combineLatest import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.mapLatestTimedWithLoading import com.jetbrains.packagesearch.intellij.plugin.util.modifiedBy import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow import com.jetbrains.packagesearch.intellij.plugin.util.moduleTransformers import com.jetbrains.packagesearch.intellij.plugin.util.nativeModulesFlow import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap import com.jetbrains.packagesearch.intellij.plugin.util.parallelUpdatedKeys import com.jetbrains.packagesearch.intellij.plugin.util.powerSaveModeFlow import com.jetbrains.packagesearch.intellij.plugin.util.replayOnSignals import com.jetbrains.packagesearch.intellij.plugin.util.send import com.jetbrains.packagesearch.intellij.plugin.util.showBackgroundLoadingBar import com.jetbrains.packagesearch.intellij.plugin.util.throttle import com.jetbrains.packagesearch.intellij.plugin.util.timer import com.jetbrains.packagesearch.intellij.plugin.util.toolWindowManagerFlow import com.jetbrains.packagesearch.intellij.plugin.util.trustedProjectFlow import com.jetbrains.packagesearch.intellij.plugin.util.trySend import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combineTransform import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.take import kotlinx.serialization.json.Json import org.jetbrains.idea.packagesearch.api.PackageSearchApiClient import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.seconds @Service(Service.Level.PROJECT) internal class PackageSearchProjectService(private val project: Project) { private val retryFromErrorChannel = Channel<Unit>() val dataProvider = ProjectDataProvider( PackageSearchApiClient(), project.packageSearchProjectCachesService.installedDependencyCache ) private val projectModulesLoadingFlow = MutableStateFlow(false) private val knownRepositoriesLoadingFlow = MutableStateFlow(false) private val moduleModelsLoadingFlow = MutableStateFlow(false) private val allInstalledKnownRepositoriesLoadingFlow = MutableStateFlow(false) private val installedPackagesStep1LoadingFlow = MutableStateFlow(false) private val installedPackagesStep2LoadingFlow = MutableStateFlow(false) private val installedPackagesDifferenceLoadingFlow = MutableStateFlow(false) private val packageUpgradesLoadingFlow = MutableStateFlow(false) private val availableUpgradesLoadingFlow = MutableStateFlow(false) private val computationInterruptedChannel = Channel<Unit>() private val computationStartedChannel = Channel<Unit>() private val computationAllowedState = channelFlow { computationInterruptedChannel.consumeAsFlow() .onEach { send(false) } .launchIn(this) computationStartedChannel.consumeAsFlow() .onEach { send(true) } .launchIn(this) }.stateIn(project.lifecycleScope, SharingStarted.Eagerly, true) val isComputationAllowed get() = computationAllowedState.value private val canShowLoadingBar = MutableStateFlow(false) private val operationExecutedChannel = Channel<List<ProjectModule>>() private val json = Json { prettyPrint = true } private val cacheDirectory = project.packageSearchProjectCachesService.projectCacheDirectory.resolve("installedDependencies") val isLoadingFlow = combineTransform( projectModulesLoadingFlow, knownRepositoriesLoadingFlow, moduleModelsLoadingFlow, allInstalledKnownRepositoriesLoadingFlow, installedPackagesStep1LoadingFlow, installedPackagesStep2LoadingFlow, installedPackagesDifferenceLoadingFlow, packageUpgradesLoadingFlow ) { booleans -> emit(booleans.any { it }) } .stateIn(project.lifecycleScope, SharingStarted.Eagerly, false) private val projectModulesSharedFlow = combine( project.trustedProjectFlow, ApplicationManager.getApplication().powerSaveModeFlow.map { it == PowerSaveModeState.ENABLED }, computationAllowedState ) { isProjectTrusted, powerSaveModeEnabled, computationEnabled -> isProjectTrusted && !powerSaveModeEnabled && computationEnabled } .flatMapLatest { isPkgsEnabled -> if (isPkgsEnabled) project.nativeModulesFlow else flowOf(emptyList()) } .replayOnSignals( retryFromErrorChannel.receiveAsFlow().throttle(10.seconds), project.moduleChangesSignalFlow, ) .mapLatestTimedWithLoading("projectModulesSharedFlow", projectModulesLoadingFlow) { modules -> project.moduleTransformers .map { async { it.transformModules(project, modules) } } .awaitAll() .flatten() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesSharedFlow", message = "Error while elaborating latest project modules" ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val projectModulesStateFlow = projectModulesSharedFlow.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val isAvailable get() = projectModulesStateFlow.value.isNotEmpty() || !isComputationAllowed private val knownRepositoriesFlow = timer(1.hours) .mapLatestTimedWithLoading("knownRepositoriesFlow", knownRepositoriesLoadingFlow) { dataProvider.fetchKnownRepositories() } .catchAndLog( context = "${this::class.qualifiedName}#knownRepositoriesFlow", message = "Error while refreshing known repositories" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) private val buildFileChangesFlow = combine( projectModulesSharedFlow, project.filesChangedEventFlow.map { it.mapNotNull { it.file } } ) { modules, changedBuildFiles -> modules.filter { it.buildFile in changedBuildFiles } } .shareIn(project.lifecycleScope, SharingStarted.Eagerly) private val projectModulesChangesFlow = merge( buildFileChangesFlow.filter { it.isNotEmpty() }, operationExecutedChannel.consumeAsFlow() ) .batchAtIntervals(1.seconds) .map { it.flatMap { it }.distinct() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesChangesFlow", message = "Error while checking Modules changes" ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val moduleModelsStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading( loggingContext = "moduleModelsStateFlow", loadingFlow = moduleModelsLoadingFlow ) { projectModules -> projectModules.parallelMap { it to ModuleModel(it) }.toMap() } .modifiedBy(projectModulesChangesFlow) { repositories, changedModules -> repositories.parallelUpdatedKeys(changedModules) { ModuleModel(it) } } .map { it.values.toList() } .catchAndLog( context = "${this::class.qualifiedName}#moduleModelsStateFlow", message = "Error while evaluating modules models" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val allInstalledKnownRepositoriesStateFlow = combine(moduleModelsStateFlow, knownRepositoriesFlow) { moduleModels, repos -> moduleModels to repos } .mapLatestTimedWithLoading( loggingContext = "allInstalledKnownRepositoriesFlow", loadingFlow = allInstalledKnownRepositoriesLoadingFlow ) { (moduleModels, repos) -> allKnownRepositoryModels(moduleModels, repos) } .catchAndLog( context = "${this::class.qualifiedName}#allInstalledKnownRepositoriesFlow", message = "Error while evaluating installed repositories" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, KnownRepositories.All.EMPTY) val dependenciesByModuleStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading("installedPackagesStep1LoadingFlow", installedPackagesStep1LoadingFlow) { fetchProjectDependencies(it, cacheDirectory, json) } .modifiedBy(projectModulesChangesFlow) { installed, changedModules -> val (result, time) = installedPackagesDifferenceLoadingFlow.whileLoading { installed.parallelUpdatedKeys(changedModules) { it.installedDependencies(cacheDirectory, json) } } logTrace("installedPackagesStep1LoadingFlow") { "Took ${time} to process diffs for ${changedModules.size} module" + if (changedModules.size > 1) "s" else "" } result } .catchAndLog( context = "${this::class.qualifiedName}#dependenciesByModuleStateFlow", message = "Error while evaluating installed dependencies" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyMap()) val installedPackagesStateFlow = dependenciesByModuleStateFlow .mapLatestTimedWithLoading("installedPackagesStep2LoadingFlow", installedPackagesStep2LoadingFlow) { installedPackages( it, project, dataProvider, TraceInfo(TraceInfo.TraceSource.INIT) ) } .catchAndLog( context = "${this::class.qualifiedName}#installedPackagesStateFlow", message = "Error while evaluating installed packages" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val packageUpgradesStateFlow = combineLatest( installedPackagesStateFlow, moduleModelsStateFlow, knownRepositoriesFlow ) { (installedPackages, moduleModels, repos) -> availableUpgradesLoadingFlow.emit(true) val result = PackageUpgradeCandidates( computePackageUpgrades( installedPackages = installedPackages, onlyStable = false, normalizer = packageVersionNormalizer, repos = allKnownRepositoryModels(moduleModels, repos), nativeModulesMap = moduleModels.associateBy { it.projectModule } ) ) availableUpgradesLoadingFlow.emit(false) result } .catchAndLog( context = "${this::class.qualifiedName}#packageUpgradesStateFlow", message = "Error while evaluating packages upgrade candidates" ) .stateIn(project.lifecycleScope, SharingStarted.Lazily, PackageUpgradeCandidates.EMPTY) init { // allows rerunning PKGS inspections on already opened files // when the data is finally available or changes for PackageUpdateInspection // or when a build file changes packageUpgradesStateFlow.throttle(5.seconds) .map { projectModulesStateFlow.value.mapNotNull { it.buildFile?.path }.toSet() } .filter { it.isNotEmpty() } .flatMapLatest { knownBuildFiles -> FileEditorManager.getInstance(project).openFiles .filter { it.path in knownBuildFiles }.asFlow() } .mapNotNull { readAction { PsiManager.getInstance(project).findFile(it) } } .onEach { readAction { DaemonCodeAnalyzer.getInstance(project).restart(it) } } .catchAndLog("${this::class.qualifiedName}#inspectionsRestart") .launchIn(project.lifecycleScope) var controller: BackgroundLoadingBarController? = null project.toolWindowManagerFlow .filter { it.id == PackageSearchToolWindowFactory.ToolWindowId } .take(1) .onEach { canShowLoadingBar.emit(true) } .launchIn(project.lifecycleScope) if (PluginEnvironment.isNonModalLoadingEnabled) { canShowLoadingBar.filter { it } .flatMapLatest { isLoadingFlow } .throttle(1.seconds) .onEach { controller?.clear() } .filter { it } .onEach { controller = showBackgroundLoadingBar( project = project, title = PackageSearchBundle.message("toolwindow.stripe.Dependencies"), upperMessage = PackageSearchBundle.message("packagesearch.ui.loading"), cancellable = true ).also { it.addOnComputationInterruptedCallback { computationInterruptedChannel.trySend() } } }.launchIn(project.lifecycleScope) } } fun notifyOperationExecuted(successes: List<ProjectModule>) { operationExecutedChannel.trySend(successes) } suspend fun restart() { computationStartedChannel.send() retryFromErrorChannel.send() } fun resumeComputation() { computationStartedChannel.trySend() } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackageSearchProjectService.kt
3674506632
package com.virtlink.terms /** * Default implementation of a term factory. */ open class DefaultTermFactory : TermFactory() { /** The registered term builders. */ private val termBuilders: HashMap<ITermConstructor, (ITermConstructor, List<ITerm>) -> ITerm> = hashMapOf() override fun createString(value: String): StringTerm = getTerm(StringTerm(value)) override fun createInt(value: Int): IntTerm = getTerm(IntTerm(value)) override fun <T: ITerm> createList(elements: List<T>): ListTerm<T> = getTerm(ListTerm(elements)) override fun <T : ITerm> createOption(value: T?): OptionTerm<T> = getTerm(if (value != null) SomeTerm(value) else NoneTerm()) override fun createTerm(constructor: ITermConstructor, children: List<ITerm>): ITerm { if (children.size != constructor.arity) { throw IllegalArgumentException("Expected ${constructor.arity} child terms, got ${children.size}.") } val builder = getBuilder(constructor) ?: { c, cl -> c.create(cl) } return getTerm(builder(constructor, children)) } override fun registerBuilder(constructor: ITermConstructor, builder: (ITermConstructor, List<ITerm>) -> ITerm) { this.termBuilders.put(constructor, builder) } override fun unregisterBuilder(constructor: ITermConstructor) { this.termBuilders.remove(constructor) } /** * Gets the term builder with the specified term constructor. * * @param constructor The term constructor. * @return The term builder; or null when not found. */ protected fun getBuilder(constructor: ITermConstructor): ((ITermConstructor, List<ITerm>) -> ITerm)? { return this.termBuilders[constructor] } /** * Gets the actual term given a term. * * @param term The input term. * @return The resulting term. */ protected open fun <T: ITerm> getTerm(term: T): T { // Default implementation. return term } }
paplj/src/main/kotlin/com/virtlink/terms/DefaultTermFactory.kt
2730557001
// 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 git4idea.conflicts import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.impl.BackgroundableActionLock import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import git4idea.GitNotificationIdsHolder import git4idea.i18n.GitBundle import git4idea.merge.GitMergeUtil import git4idea.repo.GitConflict import git4idea.repo.GitRepositoryManager import org.jetbrains.annotations.Nls object GitConflictsUtil { internal fun getConflictOperationLock(project: Project, conflict: GitConflict): BackgroundableActionLock { return BackgroundableActionLock.getLock(project, conflict.filePath) } internal fun acceptConflictSide(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, takeTheirs: Boolean) { acceptConflictSide(project, handler, selectedConflicts, takeTheirs) { root -> isReversedRoot(project, root) } } internal fun acceptConflictSide(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, takeTheirs: Boolean, isReversed: (root: VirtualFile) -> Boolean) { val conflicts = selectedConflicts.filterNot { getConflictOperationLock(project, it).isLocked }.toList() if (conflicts.isEmpty()) return val locks = conflicts.map { getConflictOperationLock(project, it) } locks.forEach { it.lock() } object : Task.Backgroundable(project, GitBundle.message("conflicts.accept.progress", conflicts.size), true) { override fun run(indicator: ProgressIndicator) { val reversedRoots = conflicts.mapTo(mutableSetOf()) { it.root }.filter(isReversed) handler.acceptOneVersion(conflicts, reversedRoots, takeTheirs) } override fun onFinished() { locks.forEach { it.unlock() } } }.queue() } private fun hasActiveMergeWindow(conflict: GitConflict) : Boolean { val file = LocalFileSystem.getInstance().findFileByPath(conflict.filePath.path) ?: return false return MergeConflictResolveUtil.hasActiveMergeWindow(file) } internal fun canShowMergeWindow(project: Project, handler: GitMergeHandler, conflict: GitConflict): Boolean { return handler.canResolveConflict(conflict) && (!getConflictOperationLock(project, conflict).isLocked || hasActiveMergeWindow(conflict)) } internal fun showMergeWindow(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>) { showMergeWindow(project, handler, selectedConflicts, { root -> isReversedRoot(project, root) }) } internal fun showMergeWindow(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, isReversed: (root: VirtualFile) -> Boolean) { val conflicts = selectedConflicts.filter { canShowMergeWindow(project, handler, it) }.toList() if (conflicts.isEmpty()) return for (conflict in conflicts) { val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(conflict.filePath.path) if (file == null) { VcsNotifier.getInstance(project).notifyError(GitNotificationIdsHolder.CANNOT_RESOLVE_CONFLICT, GitBundle.message("conflicts.merge.window.error.title"), GitBundle.message("conflicts.merge.window.error.message", conflict.filePath)) continue } val lock = getConflictOperationLock(project, conflict) MergeConflictResolveUtil.showMergeWindow(project, file, lock) { handler.resolveConflict(conflict, file, isReversed(conflict.root)) } } } @Nls internal fun getConflictType(conflict: GitConflict): String { val oursStatus = conflict.getStatus(GitConflict.ConflictSide.OURS, true) val theirsStatus = conflict.getStatus(GitConflict.ConflictSide.THEIRS, true) return when { oursStatus == GitConflict.Status.DELETED && theirsStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.both.deleted") oursStatus == GitConflict.Status.ADDED && theirsStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.both.added") oursStatus == GitConflict.Status.MODIFIED && theirsStatus == GitConflict.Status.MODIFIED -> GitBundle.message("conflicts.type.both.modified") oursStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.deleted.by.you") theirsStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.deleted.by.them") oursStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.added.by.you") theirsStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.added.by.them") else -> throw IllegalStateException("ours: $oursStatus; theirs: $theirsStatus") } } internal fun isReversedRoot(project: Project, root: VirtualFile): Boolean { val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root) ?: return false return GitMergeUtil.isReverseRoot(repository) } }
plugins/git4idea/src/git4idea/conflicts/GitConflictsUtil.kt
4021774371
// 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.openapi.externalSystem.autoimport import com.intellij.ide.file.BatchFileChangeListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros.CACHE_FILE import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.* import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS import com.intellij.openapi.externalSystem.autoimport.update.PriorityEatUpdate import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.CompoundParallelOperationTrace import com.intellij.openapi.observable.properties.AtomicBooleanProperty import com.intellij.openapi.observable.properties.BooleanProperty import com.intellij.openapi.progress.impl.CoreProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.util.LocalTimeCounter.currentTime import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.TestOnly import java.util.concurrent.ConcurrentHashMap import kotlin.streams.asStream @State(name = "ExternalSystemProjectTracker", storages = [Storage(CACHE_FILE)]) class AutoImportProjectTracker(private val project: Project) : ExternalSystemProjectTracker, PersistentStateComponent<AutoImportProjectTracker.State> { private val settings get() = AutoImportProjectTrackerSettings.getInstance(project) private val projectStates = ConcurrentHashMap<State.Id, State.Project>() private val projectDataMap = ConcurrentHashMap<ExternalSystemProjectId, ProjectData>() private val isDisabled = AtomicBooleanProperty(isDisabledAutoReload.get()) private val asyncChangesProcessingProperty = AtomicBooleanProperty( !ApplicationManager.getApplication().isHeadlessEnvironment || CoreProgressManager.shouldKeepTasksAsynchronousInHeadlessMode() ) private val projectChangeOperation = AnonymousParallelOperationTrace(debugName = "Project change operation") private val projectReloadOperation = CompoundParallelOperationTrace<String>(debugName = "Project reload operation") private val dispatcher = MergingUpdateQueue("AutoImportProjectTracker.dispatcher", 300, false, null, project) private val backgroundExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("AutoImportProjectTracker.backgroundExecutor", 1) var isAsyncChangesProcessing by asyncChangesProcessingProperty private fun createProjectChangesListener() = object : ProjectBatchFileChangeListener(project) { override fun batchChangeStarted(activityName: String?) = projectChangeOperation.startTask() override fun batchChangeCompleted() = projectChangeOperation.finishTask() } private fun createProjectReloadListener(projectData: ProjectData) = object : ExternalSystemProjectListener { val id = "ProjectTracker: ${projectData.projectAware.projectId.debugName}" override fun onProjectReloadStart() { projectReloadOperation.startTask(id) projectData.status.markSynchronized(currentTime()) projectData.isActivated = true } override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) { if (status != SUCCESS) projectData.status.markBroken(currentTime()) projectReloadOperation.finishTask(id) } } override fun scheduleProjectRefresh() { LOG.debug("Schedule project reload", Throwable()) schedule(priority = 0, dispatchIterations = 1) { reloadProject(smart = false) } } override fun scheduleChangeProcessing() { LOG.debug("Schedule change processing") schedule(priority = 1, dispatchIterations = 1) { processChanges() } } /** * ``` * dispatcher.mergingTimeSpan = 300 ms * dispatchIterations = 9 * We already dispatched processChanges * So delay is equal to (1 + 9) * 300 ms = 3000 ms = 3 s * ``` */ private fun scheduleDelayedSmartProjectReload() { LOG.debug("Schedule delayed project reload") schedule(priority = 2, dispatchIterations = 9) { reloadProject(smart = true) } } private fun schedule(priority: Int, dispatchIterations: Int, action: () -> Unit) { dispatcher.queue(PriorityEatUpdate(priority) { if (dispatchIterations - 1 > 0) { schedule(priority, dispatchIterations - 1, action) } else { action() } }) } private fun processChanges() { when (settings.autoReloadType) { AutoReloadType.ALL -> when (getModificationType()) { INTERNAL -> scheduleDelayedSmartProjectReload() EXTERNAL -> scheduleDelayedSmartProjectReload() UNKNOWN -> updateProjectNotification() } AutoReloadType.SELECTIVE -> when (getModificationType()) { INTERNAL -> updateProjectNotification() EXTERNAL -> scheduleDelayedSmartProjectReload() UNKNOWN -> updateProjectNotification() } AutoReloadType.NONE -> updateProjectNotification() } } private fun reloadProject(smart: Boolean) { LOG.debug("Incremental project reload") val projectsToReload = projectDataMap.values .filter { (!smart || it.isActivated) && !it.isUpToDate() } if (isDisabledAutoReload() || projectsToReload.isEmpty()) { LOG.debug("Skipped all projects reload") updateProjectNotification() return } for (projectData in projectsToReload) { LOG.debug("${projectData.projectAware.projectId.debugName}: Project reload") val hasUndefinedModifications = !projectData.status.isUpToDate() val settingsContext = projectData.settingsTracker.getSettingsContext() val context = ProjectReloadContext(!smart, hasUndefinedModifications, settingsContext) projectData.projectAware.reloadProject(context) } } private fun updateProjectNotification() { LOG.debug("Notification status update") val isDisabledAutoReload = isDisabledAutoReload() val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) for ((projectId, data) in projectDataMap) { when (isDisabledAutoReload || data.isUpToDate()) { true -> notificationAware.notificationExpire(projectId) else -> notificationAware.notificationNotify(data.projectAware) } } } private fun isDisabledAutoReload(): Boolean { return isDisabled.get() || Registry.`is`("external.system.auto.import.disabled") || !projectChangeOperation.isOperationCompleted() || !projectReloadOperation.isOperationCompleted() } private fun getModificationType(): ExternalSystemModificationType { return projectDataMap.values .asSequence() .map { it.getModificationType() } .asStream() .reduce(ProjectStatus::merge) .orElse(UNKNOWN) } override fun register(projectAware: ExternalSystemProjectAware) { val projectId = projectAware.projectId val projectIdName = projectId.debugName val activationProperty = AtomicBooleanProperty(false) val projectStatus = ProjectStatus(debugName = projectIdName) val parentDisposable = Disposer.newDisposable(projectIdName) val settingsTracker = ProjectSettingsTracker(project, this, backgroundExecutor, projectAware, parentDisposable) val projectData = ProjectData(projectStatus, activationProperty, projectAware, settingsTracker, parentDisposable) val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) projectDataMap[projectId] = projectData val id = "ProjectSettingsTracker: $projectIdName" settingsTracker.beforeApplyChanges { projectReloadOperation.startTask(id) } settingsTracker.afterApplyChanges { projectReloadOperation.finishTask(id) } activationProperty.afterSet({ LOG.debug("$projectIdName is activated") }, parentDisposable) activationProperty.afterSet({ scheduleChangeProcessing() }, parentDisposable) Disposer.register(project, parentDisposable) projectAware.subscribe(createProjectReloadListener(projectData), parentDisposable) Disposer.register(parentDisposable, Disposable { notificationAware.notificationExpire(projectId) }) loadState(projectId, projectData) } override fun activate(id: ExternalSystemProjectId) { val projectData = projectDataMap(id) { get(it) } ?: return projectData.isActivated = true } override fun remove(id: ExternalSystemProjectId) { val projectData = projectDataMap.remove(id) ?: return Disposer.dispose(projectData.parentDisposable) } override fun markDirty(id: ExternalSystemProjectId) { val projectData = projectDataMap(id) { get(it) } ?: return projectData.status.markDirty(currentTime()) } override fun markDirtyAllProjects() { val modificationTimeStamp = currentTime() projectDataMap.forEach { it.value.status.markDirty(modificationTimeStamp) } } private fun projectDataMap( id: ExternalSystemProjectId, action: MutableMap<ExternalSystemProjectId, ProjectData>.(ExternalSystemProjectId) -> ProjectData? ): ProjectData? { val projectData = projectDataMap.action(id) if (projectData == null) { LOG.warn(String.format("Project isn't registered by id=%s", id), Throwable()) } return projectData } override fun getState(): State { val projectSettingsTrackerStates = projectDataMap.asSequence() .map { (id, data) -> id.getState() to data.getState() } .toMap() return State(projectSettingsTrackerStates) } override fun loadState(state: State) { projectStates.putAll(state.projectSettingsTrackerStates) projectDataMap.forEach { (id, data) -> loadState(id, data) } } private fun loadState(projectId: ExternalSystemProjectId, projectData: ProjectData) { val projectState = projectStates.remove(projectId.getState()) val settingsTrackerState = projectState?.settingsTracker if (settingsTrackerState == null || projectState.isDirty) { projectData.status.markDirty(currentTime(), EXTERNAL) scheduleChangeProcessing() return } projectData.settingsTracker.loadState(settingsTrackerState) projectData.settingsTracker.refreshChanges() } override fun initializeComponent() { LOG.debug("Project tracker initialization") ApplicationManager.getApplication().messageBus.connect(project).subscribe(BatchFileChangeListener.TOPIC, createProjectChangesListener()) dispatcher.setRestartTimerOnAdd(true) dispatcher.isPassThrough = !isAsyncChangesProcessing dispatcher.activate() } @TestOnly fun getActivatedProjects() = projectDataMap.values .filter { it.isActivated } .map { it.projectAware.projectId } .toSet() /** * Enables auto-import in tests * Note: project tracker automatically enabled out of tests */ @TestOnly fun enableAutoImportInTests() { isDisabled.set(false) } @TestOnly fun setDispatcherMergingSpan(delay: Int) { dispatcher.setMergingTimeSpan(delay) } init { val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) projectReloadOperation.beforeOperation { LOG.debug("Project reload started") } projectReloadOperation.beforeOperation { notificationAware.notificationExpire() } projectReloadOperation.afterOperation { scheduleChangeProcessing() } projectReloadOperation.afterOperation { LOG.debug("Project reload finished") } projectChangeOperation.beforeOperation { LOG.debug("Project change started") } projectChangeOperation.beforeOperation { notificationAware.notificationExpire() } projectChangeOperation.afterOperation { scheduleChangeProcessing() } projectChangeOperation.afterOperation { LOG.debug("Project change finished") } settings.autoReloadTypeProperty.afterChange { scheduleChangeProcessing() } asyncChangesProcessingProperty.afterChange { dispatcher.isPassThrough = !it } } private fun ProjectData.getState() = State.Project(status.isDirty(), settingsTracker.getState()) private fun ProjectSystemId.getState() = id private fun ExternalSystemProjectId.getState() = State.Id(systemId.getState(), externalProjectPath) private data class ProjectData( val status: ProjectStatus, val activationProperty: BooleanProperty, val projectAware: ExternalSystemProjectAware, val settingsTracker: ProjectSettingsTracker, val parentDisposable: Disposable ) { var isActivated by activationProperty fun isUpToDate() = status.isUpToDate() && settingsTracker.isUpToDate() fun getModificationType(): ExternalSystemModificationType { return ProjectStatus.merge(status.getModificationType(), settingsTracker.getModificationType()) } } data class State(var projectSettingsTrackerStates: Map<Id, Project> = emptyMap()) { data class Id(var systemId: String? = null, var externalProjectPath: String? = null) data class Project( var isDirty: Boolean = false, var settingsTracker: ProjectSettingsTracker.State? = null ) } private data class ProjectReloadContext( override val isExplicitReload: Boolean, override val hasUndefinedModifications: Boolean, override val settingsFilesContext: ExternalSystemSettingsFilesReloadContext ) : ExternalSystemProjectReloadContext companion object { val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport") @TestOnly @JvmStatic fun getInstance(project: Project): AutoImportProjectTracker { return ExternalSystemProjectTracker.getInstance(project) as AutoImportProjectTracker } private val isDisabledAutoReload = AtomicBooleanProperty( ApplicationManager.getApplication().isUnitTestMode ) @TestOnly fun enableAutoReloadInTests(parentDisposable: Disposable) { Disposer.register(parentDisposable) { isDisabledAutoReload.reset() } isDisabledAutoReload.set(false) } } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/AutoImportProjectTracker.kt
251553231
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XChildEntityImpl(val dataSource: XChildEntityData) : XChildEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val CHILDCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(XChildEntity::class.java, XChildChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, CHILDCHILD_CONNECTION_ID, ) } override val childProperty: String get() = dataSource.childProperty override val dataClass: DataClassX? get() = dataSource.dataClass override val parentEntity: XParentEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override val childChild: List<XChildChildEntity> get() = snapshot.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: XChildEntityData?) : ModifiableWorkspaceEntityBase<XChildEntity>(), XChildEntity.Builder { constructor() : this(XChildEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XChildEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isChildPropertyInitialized()) { error("Field XChildEntity#childProperty should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field XChildEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field XChildEntity#parentEntity should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDCHILD_CONNECTION_ID, this) == null) { error("Field XChildEntity#childChild should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] == null) { error("Field XChildEntity#childChild should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as XChildEntity this.entitySource = dataSource.entitySource this.childProperty = dataSource.childProperty this.dataClass = dataSource.dataClass if (parents != null) { this.parentEntity = parents.filterIsInstance<XParentEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var childProperty: String get() = getEntityData().childProperty set(value) { checkModificationAllowed() getEntityData().childProperty = value changedProperty.add("childProperty") } override var dataClass: DataClassX? get() = getEntityData().dataClass set(value) { checkModificationAllowed() getEntityData().dataClass = value changedProperty.add("dataClass") } override var parentEntity: XParentEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } // List of non-abstract referenced types var _childChild: List<XChildChildEntity>? = emptyList() override var childChild: List<XChildChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDCHILD_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] = value } changedProperty.add("childChild") } override fun getEntityData(): XChildEntityData = result ?: super.getEntityData() as XChildEntityData override fun getEntityClass(): Class<XChildEntity> = XChildEntity::class.java } } class XChildEntityData : WorkspaceEntityData<XChildEntity>() { lateinit var childProperty: String var dataClass: DataClassX? = null fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<XChildEntity> { val modifiable = XChildEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): XChildEntity { return getCached(snapshot) { val entity = XChildEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XChildEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return XChildEntity(childProperty, entitySource) { this.dataClass = this@XChildEntityData.dataClass this.parentEntity = parents.filterIsInstance<XParentEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(XParentEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.entitySource != other.entitySource) return false if (this.childProperty != other.childProperty) return false if (this.dataClass != other.dataClass) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.childProperty != other.childProperty) return false if (this.dataClass != other.dataClass) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childProperty.hashCode() result = 31 * result + dataClass.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childProperty.hashCode() result = 31 * result + dataClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(DataClassX::class.java) this.dataClass?.let { collector.addDataToInspect(it) } collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XChildEntityImpl.kt
1015157545
package quickbeer.android.domain.reviewlist.network import quickbeer.android.domain.review.Review import quickbeer.android.domain.review.network.ReviewJson import quickbeer.android.domain.review.network.ReviewJsonMapper import quickbeer.android.util.JsonMapper class ReviewListJsonMapper<in K> : JsonMapper<K, List<Review>, List<ReviewJson>> { override fun map(key: K, source: List<ReviewJson>): List<Review> { return source.map { ReviewJsonMapper.map(it.id, it) } } }
app/src/main/java/quickbeer/android/domain/reviewlist/network/ReviewListJsonMapper.kt
1318604963
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Entity.getModel::class) class Model : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.type == method<Entity.getModel>().returnType } class verticesX : OrderMapper.InConstructor.Field(Model::class, 0) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class verticesY : OrderMapper.InConstructor.Field(Model::class, 1) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class verticesZ : OrderMapper.InConstructor.Field(Model::class, 2) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices1 : OrderMapper.InConstructor.Field(Model::class, 3) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices2 : OrderMapper.InConstructor.Field(Model::class, 4) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices3 : OrderMapper.InConstructor.Field(Model::class, 5) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } @MethodParameters("yaw", "cameraPitchSine", "cameraPitchCosine", "cameraYawSine", "cameraYawCosine", "x", "y", "z", "tag") @DependsOn(Entity.draw::class) class draw : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.mark == method<Entity.draw>().mark } } @MethodParameters("pitch") @DependsOn(Projectile.getModel::class) class rotateZ : OrderMapper.InMethod.Method(Projectile.getModel::class, 0) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() } } class draw0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.startsWith(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE) } } class verticesCount : OrderMapper.InConstructor.Field(Model::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } override val constructorPredicate = predicateOf<Method2> { it.arguments.isEmpty() } } class indicesCount : OrderMapper.InConstructor.Field(Model::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } override val constructorPredicate = predicateOf<Method2> { it.arguments.isEmpty() } } // either xz or xyz @DependsOn(Model.draw::class) class xzRadius : OrderMapper.InMethod.Field(Model.draw::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE } } @MethodParameters("x", "y", "z") @DependsOn(Npc.getModel::class) class offset : OrderMapper.InMethod.Method(Npc.getModel::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Model>() } } // yaw @MethodParameters() @DependsOn(Player.getModel::class) class rotateY90Ccw : OrderMapper.InMethod.Method(Player.getModel::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Model>() && it.methodType.argumentTypes.size in 0..1 } } @MethodParameters() @DependsOn(rotateZ::class) class resetBounds : UniqueMapper.InMethod.Method(rotateZ::class) { override val predicate = predicateOf<Instruction2> { it.isMethod } } // new = old * scale / 128 @MethodParameters("x", "y", "z") class resize : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 3..4 } .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.count { it.opcode == SIPUSH && it.intOperand == 128 } == 3 } } @MethodParameters() @DependsOn(draw::class) class calculateBoundsCylinder : OrderMapper.InMethod.Method(draw::class, 0) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @MethodParameters("yaw") @DependsOn(draw::class) class calculateBoundingBox : OrderMapper.InMethod.Method(draw::class, 1) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @DependsOn(draw::class) class boundsType : OrderMapper.InMethod.Field(draw::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class bottomY : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class radius : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, -2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class diameter : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class xMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class yMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class zMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class xMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class yMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 4) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class zMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 5) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(Model::class, Player.getModel::class) class isSingleTile : UniqueMapper.InMethod.Field(Player.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isField && it.fieldOwner == type<Model>() && it.fieldType == BOOLEAN_TYPE } } @DependsOn(Model::class) class copy0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<Model>() } .and { it.arguments.startsWith(BOOLEAN_TYPE, type<Model>(), ByteArray::class.type) } } @MethodParameters("type", "labels", "tx", "ty", "tz") class transform : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 5..6 } .and { it.arguments.startsWith(INT_TYPE, IntArray::class.type, INT_TYPE, INT_TYPE, INT_TYPE) } } @DependsOn(transform::class) class vertexLabels : OrderMapper.InMethod.Field(transform::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE.withDimensions(2) } } @DependsOn(transform::class) class faceLabelsAlpha : OrderMapper.InMethod.Field(transform::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE.withDimensions(2) } } @MethodParameters("frames", "frame") @DependsOn(AnimFrameset::class) class animate : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 2..3 } .and { it.arguments.startsWith(type<AnimFrameset>(), INT_TYPE) } } @DependsOn(AnimFrameset::class) class animate2 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 5..6 } .and { it.arguments.startsWith(type<AnimFrameset>(), INT_TYPE, type<AnimFrameset>(), INT_TYPE, IntArray::class.type) } } @MethodParameters("b") @DependsOn(SpotType.getModel::class) class toSharedSpotAnimationModel : UniqueMapper.InMethod.Method(SpotType.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() && it.methodType.returnType == type<Model>() } } @MethodParameters("b") @DependsOn(NPCType.getModel::class) class toSharedSequenceModel : UniqueMapper.InMethod.Method(NPCType.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() && it.methodType.returnType == type<Model>() } } @DependsOn(transform::class) class faceAlphas : UniqueMapper.InMethod.Field(transform::class) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == ByteArray::class.type } } @MethodParameters() class rotateY180 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.count { it.opcode == INEG } == 2 } .and { it.instructions.count { it.opcode == IASTORE } == 2 } } @MethodParameters() @DependsOn(rotateY90Ccw::class) class rotateY270Ccw : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.count { it.opcode == INEG } == 1 } .and { it != method<rotateY90Ccw>() } } @DependsOn(UnlitModel.light::class) class faceColors1 : OrderMapper.InMethod.Field(UnlitModel.light::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceColors2 : OrderMapper.InMethod.Field(UnlitModel.light::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceColors3 : OrderMapper.InMethod.Field(UnlitModel.light::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceTextures : OrderMapper.InMethod.Field(UnlitModel.light::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == ShortArray::class.type } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Model.kt
293317579
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data class GHMannequin(id: String, override val login: String, override val url: String, override val avatarUrl: String, val name: String?) : GHNode(id), GHActor { override fun getPresentableName(): String = name ?: login }
plugins/github/src/org/jetbrains/plugins/github/api/data/GHMannequin.kt
689979956
// 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.codeInsight.hints.declarative.impl import com.intellij.codeInsight.hints.InlayHintsUtils import com.intellij.codeInsight.hints.declarative.impl.util.TinyTree import com.intellij.codeInsight.hints.presentation.InlayTextMetricsStorage import com.intellij.codeInsight.hints.presentation.withTranslated import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.GraphicsUtil import org.jetbrains.annotations.TestOnly import java.awt.Graphics2D import java.awt.Point import java.awt.geom.Rectangle2D /** * @see PresentationTreeBuilderImpl */ class InlayPresentationList(private var state: TinyTree<Any?>, @TestOnly var hasBackground: Boolean, @TestOnly var isDisabled: Boolean) { companion object { private const val NOT_COMPUTED = -1 private const val LEFT_MARGIN = 7 private const val RIGHT_MARGIN = 7 private const val BOTTOM_MARGIN = 1 private const val TOP_MARGIN = 1 private const val ARC_WIDTH = 8 private const val ARC_HEIGHT = 8 private const val BACKGROUND_ALPHA : Float = 0.55f } private var entries: Array<InlayPresentationEntry> = PresentationEntryBuilder(state).buildPresentationEntries() private var _partialWidthSums: IntArray? = null private var computedWidth: Int = NOT_COMPUTED private fun computePartialSums(fontMetricsStorage: InlayTextMetricsStorage): IntArray { var width = 0 return IntArray(entries.size) { val entry = entries[it] val oldWidth = width width += entry.computeWidth(fontMetricsStorage) oldWidth } } private fun getPartialWidthSums(storage: InlayTextMetricsStorage): IntArray { val sums = _partialWidthSums if (sums != null) { return sums } val computed = computePartialSums(storage) _partialWidthSums = computed return computed } fun handleClick(e: EditorMouseEvent, pointInsideInlay: Point, fontMetricsStorage: InlayTextMetricsStorage) { val entry = findEntryByPoint(fontMetricsStorage, pointInsideInlay) ?: return entry.handleClick(e.editor, this) } private fun findEntryByPoint(fontMetricsStorage: InlayTextMetricsStorage, pointInsideInlay: Point): InlayPresentationEntry? { val x = pointInsideInlay.x val partialWidthSums = getPartialWidthSums(fontMetricsStorage) for ((index, entry) in entries.withIndex()) { val leftBound = partialWidthSums[index] + LEFT_MARGIN val rightBound = partialWidthSums.getOrElse(index + 1) { Int.MAX_VALUE - LEFT_MARGIN } + LEFT_MARGIN if (x in leftBound..rightBound) { return entry } } return null } @RequiresEdt fun updateState(state: TinyTree<Any?>, disabled: Boolean, hasBackground: Boolean) { updateStateTree(state, this.state, 0, 0) this.state = state this.entries = PresentationEntryBuilder(state).buildPresentationEntries() this.computedWidth = NOT_COMPUTED this._partialWidthSums = null this.isDisabled = disabled this.hasBackground = hasBackground } private fun updateStateTree(treeToUpdate: TinyTree<Any?>, treeToUpdateFrom: TinyTree<Any?>, treeToUpdateIndex: Byte, treeToUpdateFromIndex: Byte) { // we want to preserve the structure val treeToUpdateTag = treeToUpdate.getBytePayload(treeToUpdateIndex) val treeToUpdateFromTag = treeToUpdateFrom.getBytePayload(treeToUpdateFromIndex) if (treeToUpdateFromTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG || treeToUpdateFromTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG) { if (treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_EXPANDED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_COLLAPSED_TAG) { treeToUpdate.setBytePayload(nodePayload = treeToUpdateFromTag, index = treeToUpdateIndex) } } treeToUpdateFrom.syncProcessChildren(treeToUpdateFromIndex, treeToUpdateIndex, treeToUpdate) { treeToUpdateFromChildIndex, treeToUpdateChildIndex -> updateStateTree(treeToUpdate, treeToUpdateFrom, treeToUpdateChildIndex, treeToUpdateFromChildIndex) true } } fun toggleTreeState(parentIndexToSwitch: Byte) { when (val payload = state.getBytePayload(parentIndexToSwitch)) { InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG, InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_COLLAPSED_TAG -> { state.setBytePayload(InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG, parentIndexToSwitch) } InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG, InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_EXPANDED_TAG -> { state.setBytePayload(InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG, parentIndexToSwitch) } else -> { error("Unexpected payload: $payload") } } updateState(state, isDisabled, hasBackground) } fun getWidthInPixels(textMetricsStorage: InlayTextMetricsStorage) : Int { if (computedWidth == NOT_COMPUTED) { val width = entries.sumOf { it.computeWidth(textMetricsStorage) } + LEFT_MARGIN + RIGHT_MARGIN computedWidth = width return width } return computedWidth } fun paint(inlay: Inlay<*>, g: Graphics2D, targetRegion: Rectangle2D, textAttributes: TextAttributes) { val editor = inlay.editor as EditorImpl val storage = InlayHintsUtils.getTextMetricStorage(editor) val height = if (entries.isEmpty()) 0 else entries.maxOf { it.computeHeight(storage) } var xOffset = 0 val gap = (targetRegion.height.toInt() - height) / 2 val attrKey = if (hasBackground) DefaultLanguageHighlighterColors.INLAY_DEFAULT else DefaultLanguageHighlighterColors.INLAY_TEXT_WITHOUT_BACKGROUND val attrs = editor.colorsScheme.getAttributes(attrKey) g.withTranslated(targetRegion.x, targetRegion.y) { if (hasBackground) { val rectHeight = height + TOP_MARGIN + BOTTOM_MARGIN val rectWidth = getWidthInPixels(storage) val config = GraphicsUtil.setupAAPainting(g) GraphicsUtil.paintWithAlpha(g, BACKGROUND_ALPHA) g.color = attrs.backgroundColor ?: textAttributes.backgroundColor g.fillRoundRect(0, gap, rectWidth, rectHeight, ARC_WIDTH, ARC_HEIGHT) config.restore() } } g.withTranslated(LEFT_MARGIN + targetRegion.x, targetRegion.y) { for (entry in entries) { val hovered = entry.isHovered val finalAttrs = if (hovered) { val refAttrs = inlay.editor.colorsScheme.getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR) val inlayAttrsWithRefForeground = attrs.clone() inlayAttrsWithRefForeground.foregroundColor = refAttrs.foregroundColor inlayAttrsWithRefForeground } else { attrs } g.withTranslated(xOffset, 0) { entry.render(g, storage, finalAttrs, isDisabled, gap) } xOffset += entry.computeWidth(storage) } } } @TestOnly fun getEntries(): Array<InlayPresentationEntry> { return entries } fun getMouseArea(pointInsideInlay: Point, fontMetricsStorage: InlayTextMetricsStorage): InlayMouseArea? { val entry = findEntryByPoint(fontMetricsStorage, pointInsideInlay) ?: return null return entry.clickArea } }
platform/lang-impl/src/com/intellij/codeInsight/hints/declarative/impl/InlayPresentationList.kt
2878799104
// 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.codeInsight.hints.declarative.impl import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.hints.declarative.DeclarativeInlayHintsSettings import com.intellij.codeInsight.hints.declarative.InlayHintsProviderFactory import com.intellij.codeInsight.hints.declarative.impl.util.TinyTree import com.intellij.codeInsight.hints.presentation.InlayTextMetricsStorage import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.ui.JBPopupMenu import com.intellij.psi.PsiDocumentManager import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.Nls import org.jetbrains.annotations.TestOnly import java.awt.Graphics2D import java.awt.Point import java.awt.geom.Rectangle2D class DeclarativeInlayRenderer( @TestOnly val presentationList: InlayPresentationList, private val fontMetricsStorage: InlayTextMetricsStorage, val providerId: String, ) : EditorCustomElementRenderer { private var inlay: Inlay<DeclarativeInlayRenderer>? = null override fun calcWidthInPixels(inlay: Inlay<*>): Int { return presentationList.getWidthInPixels(fontMetricsStorage) } @RequiresEdt fun updateState(newState: TinyTree<Any?>, disabled: Boolean, hasBackground: Boolean) { presentationList.updateState(newState, disabled, hasBackground) } override fun paint(inlay: Inlay<*>, g: Graphics2D, targetRegion: Rectangle2D, textAttributes: TextAttributes) { presentationList.paint(inlay, g, targetRegion, textAttributes) } fun handleLeftClick(e: EditorMouseEvent, pointInsideInlay: Point) { presentationList.handleClick(e, pointInsideInlay, fontMetricsStorage) } fun handleRightClick(e: EditorMouseEvent) { val project = e.editor.project ?: return val document = e.editor.document val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return val providerInfo = InlayHintsProviderFactory.getProviderInfo(psiFile.language, providerId) ?: return val providerName = providerInfo.providerName JBPopupMenu.showByEvent(e.mouseEvent, "InlayMenu", DefaultActionGroup(DisableDeclarativeInlayAction(providerName, providerId))) } fun setInlay(inlay: Inlay<DeclarativeInlayRenderer>) { this.inlay = inlay } fun getMouseArea(pointInsideInlay: Point): InlayMouseArea? { return presentationList.getMouseArea(pointInsideInlay, fontMetricsStorage) } // this should not be shown anywhere, but it is required to show custom menu in com.intellij.openapi.editor.impl.EditorImpl.DefaultPopupHandler.getActionGroup override fun getContextMenuGroupId(inlay: Inlay<*>): String { return "DummyActionGroup" } } private class DisableDeclarativeInlayAction(private val providerName: @Nls String, private val providerId: String) : AnAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.text = CodeInsightBundle.message("inlay.hints.declarative.disable.action.text", providerName) } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val settings = DeclarativeInlayHintsSettings.getInstance(project) settings.setProviderEnabled(providerId, false) } }
platform/lang-impl/src/com/intellij/codeInsight/hints/declarative/impl/DeclarativeInlayRenderer.kt
3229833345
package com.intellij.remoteDev.tests.impl import com.intellij.codeWithMe.ClientId import com.intellij.codeWithMe.ClientId.Companion.isLocal import com.intellij.diagnostic.DebugLogManager import com.intellij.diagnostic.ThreadDumper import com.intellij.ide.IdeEventQueue import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.observable.util.whenDisposed import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.util.SystemInfo import com.intellij.remoteDev.tests.* import com.intellij.util.application import com.intellij.remoteDev.tests.modelGenerated.* import com.intellij.util.alsoIfNull import com.jetbrains.rd.framework.* import com.jetbrains.rd.framework.impl.RdTask import com.jetbrains.rd.util.lifetime.LifetimeDefinition import com.jetbrains.rd.util.measureTimeMillis import com.jetbrains.rd.util.reactive.viewNotNull import org.jetbrains.annotations.ApiStatus import java.io.File import java.net.InetAddress import java.time.LocalTime import java.time.format.DateTimeFormatter import kotlin.reflect.full.createInstance class DistributedTestHost(private val agentProject: Project) : DistributedTestHostBase() { override val projectOrNull: Project get() = agentProject override val project: Project get() = agentProject } class DistributedTestHostGateway : DistributedTestHostBase() { override val projectOrNull: Project? get() = null override val project: Project get() = error("Project shouldn't be referenced for gateway") } @ApiStatus.Internal abstract class DistributedTestHostBase() { companion object { private val logger = Logger.getInstance(DistributedTestHostBase::class.java) } protected abstract val projectOrNull: Project? protected abstract val project: Project init { val hostAddress = when (SystemInfo.isLinux) { true -> System.getenv(AgentConstants.dockerHostIpEnvVar)?.let { logger.info("${AgentConstants.dockerHostIpEnvVar} env var is set=$it, will try to get address from it.") // this won't work when we do custom network setups as the default gateway will be overridden // val hostEntries = File("/etc/hosts").readText().lines() // val dockerInterfaceEntry = hostEntries.last { it.isNotBlank() } // val ipAddress = dockerInterfaceEntry.split("\\s".toRegex()).first() InetAddress.getByName(it) } ?: InetAddress.getLoopbackAddress() false -> InetAddress.getLoopbackAddress() } logger.info("Host address=${hostAddress}") val port = System.getenv(AgentConstants.protocolPortEnvVar)?.toIntOrNull() if (port != null) { logger.info("Queue creating protocol on port $port") application.invokeLater { createProtocol(hostAddress, port) } } } private fun createProtocol(hostAddress: InetAddress, port: Int) { logger.info("Creating protocol...") val lifetime = LifetimeDefinition() projectOrNull?.whenDisposed { lifetime.terminate() } .alsoIfNull { application.whenDisposed { lifetime.terminate() } } val wire = SocketWire.Client(lifetime, DistributedTestIdeScheduler, port, AgentConstants.protocolName, hostAddress) val protocol = Protocol(AgentConstants.protocolName, Serializers(), Identities(IdKind.Client), DistributedTestIdeScheduler, wire, lifetime) val model = protocol.distributedTestModel logger.info("Advise for session...") model.session.viewNotNull(lifetime) { lt, session -> try { val context = AgentContext(session.agentId, application, projectOrNull, protocol) logger.info("New test session: ${session.testClassName}.${session.testMethodName}") logger.info("Setting up loggers") AgentTestLoggerFactory.bindSession(lt, session) // Create test class val testClass = Class.forName(session.testClassName) val testClassObject = testClass.kotlin.createInstance() as DistributedTestPlayer // Tell test we are running it inside an agent val agentInfo = AgentInfo(session.agentId, session.testMethodName) val queue = testClassObject.initAgent(agentInfo) // Play test method val testMethod = testClass.getMethod(session.testMethodName) testClassObject.performInit(testMethod) testMethod.invoke(testClassObject) // Advice for processing events session.runNextAction.set { _, _ -> var actionTitle: String? = null try { assert(ClientId.current.isLocal) { "ClientId '${ClientId.current}' should be local when test method starts" } val action = queue.remove() actionTitle = action.title showNotification(actionTitle) // Flush all events to process pending protocol events and other things // before actual test method execution IdeEventQueue.getInstance().flushQueue() // Execute test method lateinit var result: RdTask<Boolean> logger.info("'$actionTitle': starting action") val elapsedAction = measureTimeMillis { result = action.action.invoke(context) } logger.info("'$actionTitle': completed action in ${elapsedAction}ms") projectOrNull?.let { // Sync state across all IDE agents to maintain proper order in protocol events logger.info("Sync protocol events after execution...") val elapsedSync = measureTimeMillis { DistributedTestBridge.getInstance(it).syncProtocolEvents() IdeEventQueue.getInstance().flushQueue() } logger.info("Protocol state sync completed in ${elapsedSync}ms") } // Assert state assertStateAfterTestMethod() return@set result } catch (ex: Throwable) { logger.warn("Test action ${actionTitle?.let { "'$it' " }.orEmpty()}hasn't finished successfully", ex) return@set RdTask.faulted(ex) } } session.shutdown.advise(lifetime) { projectOrNull?.let { logger.info("Close project...") try { ProjectManagerEx.getInstanceEx().forceCloseProject(it) } catch (e: Exception) { logger.error("Error on project closing", e) } } logger.info("Shutdown application...") application.exit(true, true, false) } session.dumpThreads.adviseOn(lifetime, DistributedTestInplaceScheduler) { logger.info("Dump threads...") val threadDump = ThreadDumper.dumpThreadsToString() val threadDumpStamp = LocalTime.now().format(DateTimeFormatter.ofPattern("HH_mm_ss_SSS")) val threadDumpFileName = "${AgentConstants.threadDumpFilePrefix}_$threadDumpStamp.log" val threadDumpFile = File(PathManager.getLogPath()).resolve(threadDumpFileName) threadDumpFile.writeText(threadDump) } // Initialize loggers DebugLogManager.getInstance().applyCategories( session.traceCategories.map { DebugLogManager.Category(it, DebugLogManager.DebugLogLevel.TRACE) } ) logger.info("Test session ready!") session.ready.value = true } catch (ex: Throwable) { logger.error("Test session initialization hasn't finished successfully", ex) session.ready.value = false } } } private fun assertStateAfterTestMethod() { assert(Logger.getFactory() is AgentTestLoggerFactory) { "Logger Factory was overridden during test method execution. " + "Inspect logs to find stack trace of the overrider. " + "Overriding logger factory leads to breaking distributes test log processing." } } @Suppress("HardCodedStringLiteral", "DialogTitleCapitalization") private fun showNotification(text: String?): Notification? { if (application.isHeadlessEnvironment || text.isNullOrBlank()) return null val notification = Notification("TestFramework", "Test Framework", text, NotificationType.INFORMATION) Notifications.Bus.notify(notification) return notification } private fun Throwable.toModel(): RdTestSessionException { fun getRdTestStackTraceElement(trace: Array<StackTraceElement>?): List<RdTestSessionStackTraceElement> = trace?.map { it -> RdTestSessionStackTraceElement(it.className, it.methodName, it.fileName.orEmpty(), it.lineNumber) } ?: emptyList() val rdTestSessionExceptionCause = this.cause?.let { cause -> RdTestSessionExceptionCause( cause.javaClass.typeName, cause.message, getRdTestStackTraceElement(cause.stackTrace) ) } return RdTestSessionException( this.javaClass.typeName, this.message, getRdTestStackTraceElement(this.stackTrace), rdTestSessionExceptionCause ) } }
platform/remoteDev-util/src/com/intellij/remoteDev/tests/impl/DistributedTestHostBase.kt
3230372654
package org.stepik.android.view.catalog.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.doOnLayout import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.error_no_connection_with_button_small.* import org.stepic.droid.R import org.stepik.android.view.catalog.model.CatalogItem import ru.nobird.app.core.model.safeCast import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class OfflineAdapterDelegate( private val onRetry: () -> Unit ) : AdapterDelegate<CatalogItem, DelegateViewHolder<CatalogItem>>() { override fun isForViewType(position: Int, data: CatalogItem): Boolean = data is CatalogItem.Offline override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogItem> { val view = createView(parent, R.layout.error_no_connection_with_button_small) view.updateLayoutParams<ViewGroup.MarginLayoutParams> { width = ViewGroup.LayoutParams.MATCH_PARENT } return OfflineViewHolder(view, onRetry = onRetry) } private class OfflineViewHolder( override val containerView: View, private val onRetry: () -> Unit ) : DelegateViewHolder<CatalogItem>(containerView), LayoutContainer { init { tryAgain.setOnClickListener { onRetry() } containerView.isVisible = true } override fun onBind(data: CatalogItem) { data as CatalogItem.Offline itemView.doOnLayout { val parent = it.parent.safeCast<View>() ?: return@doOnLayout val remainingHeight = parent.height - containerView.bottom - containerView.top if (remainingHeight > 0) { itemView.updateLayoutParams { height = containerView.height + remainingHeight } } } } } }
app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/OfflineAdapterDelegate.kt
3991513625
package com.nononsenseapps.feeder.ui import androidx.lifecycle.viewModelScope import com.nononsenseapps.feeder.archmodel.Repository import com.nononsenseapps.feeder.base.DIAwareViewModel import kotlinx.coroutines.launch import org.kodein.di.DI import org.kodein.di.instance class NavigationDeepLinkViewModel(di: DI) : DIAwareViewModel(di) { private val repository: Repository by instance() fun setCurrentFeedAndTag(feedId: Long, tag: String) { repository.setCurrentFeedAndTag(feedId, tag) // Should open feed in portrait repository.setIsArticleOpen(false) } fun setCurrentArticle(itemId: Long) { viewModelScope.launch { repository.markAsReadAndNotified(itemId) } repository.setCurrentArticle(itemId) // Should open article in portrait repository.setIsArticleOpen(true) } }
app/src/main/java/com/nononsenseapps/feeder/ui/NavigationDeepLinkViewModel.kt
3654874022
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS import com.intellij.openapi.externalSystem.autoimport.MockProjectAware.RefreshCollisionPassType.* import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task import com.intellij.openapi.util.Disposer import com.intellij.util.ConcurrencyUtil.once import com.intellij.util.EventDispatcher import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference class MockProjectAware(override val projectId: ExternalSystemProjectId) : ExternalSystemProjectAware { val subscribeCounter = AtomicInteger(0) val unsubscribeCounter = AtomicInteger(0) val settingsAccessCounter = AtomicInteger(0) val refreshCounter = AtomicInteger(0) val refreshCollisionPassType = AtomicReference(DUPLICATE) val refreshStatus = AtomicReference(SUCCESS) private val eventDispatcher = EventDispatcher.create(Listener::class.java) private val refresh = AnonymousParallelOperationTrace(debugName = "$projectId MockProjectAware.refreshProject") private val _settingsFiles = LinkedHashSet<String>() override val settingsFiles: Set<String> get() = _settingsFiles.toSet().also { settingsAccessCounter.incrementAndGet() } fun resetAssertionCounters() { settingsAccessCounter.set(0) refreshCounter.set(0) subscribeCounter.set(0) unsubscribeCounter.set(0) } fun registerSettingsFile(path: String) { _settingsFiles.add(path) } override fun subscribe(listener: ExternalSystemProjectRefreshListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener.asListener(), parentDisposable) subscribeCounter.incrementAndGet() Disposer.register(parentDisposable, Disposable { unsubscribeCounter.incrementAndGet() }) } override fun reloadProject(context: ExternalSystemProjectReloadContext) { when (refreshCollisionPassType.get()!!) { DUPLICATE -> { doRefreshProject(context) } CANCEL -> { val task = once { doRefreshProject(context) } refresh.afterOperation { task.run() } if (refresh.isOperationCompleted()) task.run() } IGNORE -> { if (refresh.isOperationCompleted()) { doRefreshProject(context) } } } } private fun doRefreshProject(context: ExternalSystemProjectReloadContext) { val refreshStatus = refreshStatus.get() eventDispatcher.multicaster.beforeProjectRefresh() refresh.task { refreshCounter.incrementAndGet() eventDispatcher.multicaster.insideProjectRefresh(context) } eventDispatcher.multicaster.afterProjectRefresh(refreshStatus) } fun onceDuringRefresh(action: (ExternalSystemProjectReloadContext) -> Unit) { val disposable = Disposer.newDisposable() duringRefresh(disposable) { Disposer.dispose(disposable) action(it) } } fun duringRefresh(parentDisposable: Disposable, action: (ExternalSystemProjectReloadContext) -> Unit) { eventDispatcher.addListener(object : Listener { override fun insideProjectRefresh(context: ExternalSystemProjectReloadContext) = action(context) }, parentDisposable) } private fun ExternalSystemProjectRefreshListener.asListener(): Listener { return object : Listener, ExternalSystemProjectRefreshListener { override fun beforeProjectRefresh() { this@asListener.beforeProjectRefresh() } override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) { this@asListener.afterProjectRefresh(status) } } } interface Listener : ExternalSystemProjectRefreshListener, EventListener { @JvmDefault fun insideProjectRefresh(context: ExternalSystemProjectReloadContext) { } } enum class RefreshCollisionPassType { DUPLICATE, CANCEL, IGNORE } }
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/MockProjectAware.kt
2438780613
/* * 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.example.wear.tiles.golden import android.content.Context import androidx.wear.tiles.ColorBuilders import androidx.wear.tiles.DeviceParametersBuilders.DeviceParameters import androidx.wear.tiles.DimensionBuilders.ExpandedDimensionProp import androidx.wear.tiles.ModifiersBuilders.Clickable import androidx.wear.tiles.material.Button import androidx.wear.tiles.material.ChipColors import androidx.wear.tiles.material.CompactChip import androidx.wear.tiles.material.Text import androidx.wear.tiles.material.TitleChip import androidx.wear.tiles.material.Typography import androidx.wear.tiles.material.layouts.MultiButtonLayout import androidx.wear.tiles.material.layouts.PrimaryLayout object Workout { const val BUTTON_1_ICON_ID = "workout 1" const val BUTTON_2_ICON_ID = "workout 2" const val BUTTON_3_ICON_ID = "workout 3" fun buttonsLayout( context: Context, deviceParameters: DeviceParameters, weekSummary: String, button1Clickable: Clickable, button2Clickable: Clickable, button3Clickable: Clickable, chipClickable: Clickable ) = PrimaryLayout.Builder(deviceParameters) .setPrimaryLabelTextContent( Text.Builder(context, weekSummary) .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.Blue)) .build() ) .setContent( MultiButtonLayout.Builder() .addButtonContent( Button.Builder(context, button1Clickable).setIconContent(BUTTON_1_ICON_ID) .build() ) .addButtonContent( Button.Builder(context, button2Clickable).setIconContent(BUTTON_2_ICON_ID) .build() ) .addButtonContent( Button.Builder(context, button3Clickable).setIconContent(BUTTON_3_ICON_ID) .build() ) .build() ) .setPrimaryChipContent( CompactChip.Builder(context, "More", chipClickable, deviceParameters) .setChipColors( ChipColors( /*backgroundColor=*/ ColorBuilders.argb(GoldenTilesColors.BlueGray), /*contentColor=*/ ColorBuilders.argb(GoldenTilesColors.White) ) ) .build() ) .build() fun largeChipLayout( context: Context, deviceParameters: DeviceParameters, clickable: Clickable, lastWorkoutSummary: String ) = PrimaryLayout.Builder(deviceParameters) .setPrimaryLabelTextContent( Text.Builder(context, "Power Yoga") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.Yellow)) .build() ) .setContent( TitleChip.Builder(context, "Start", clickable, deviceParameters) // TitleChip/Chip's default width == device width minus some padding // Since PrimaryLayout's content slot already has margin, this leads to clipping // unless we override the width to use the available space .setWidth(ExpandedDimensionProp.Builder().build()) .setChipColors( ChipColors( /*backgroundColor=*/ ColorBuilders.argb(GoldenTilesColors.Yellow), /*contentColor=*/ ColorBuilders.argb(GoldenTilesColors.Black) ) ) .build() ) .setSecondaryLabelTextContent( Text.Builder(context, lastWorkoutSummary) .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.White)) .build() ) .build() }
WearTilesKotlin/app/src/debug/java/com/example/wear/tiles/golden/Workout.kt
84400339
package net.serverpeon.discord.event.message import net.serverpeon.discord.event.Event import net.serverpeon.discord.model.Channel import net.serverpeon.discord.model.PostedMessage import net.serverpeon.discord.model.User /** * Fired when a new [message] is posted to [channel]. * * If the message contains embeddable links then a [MessageEmbedEvent] will follow this event. */ interface MessageCreateEvent : Event { val message: PostedMessage val author: User get() = message.author val channel: Channel.Text get() = message.channel }
api/src/main/kotlin/net/serverpeon/discord/event/message/MessageCreateEvent.kt
1066560515
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework import com.intellij.util.lang.CompoundRuntimeException inline fun MutableList<Throwable>.catchAndStoreExceptions(executor: () -> Unit) { try { executor() } catch (e: CompoundRuntimeException) { addAll(e.exceptions) } catch (e: Throwable) { add(e) } }
platform/testFramework/src/com/intellij/testFramework/runAll.kt
4180686517
package io.petros.posts.kotlin.datastore import android.arch.lifecycle.LiveData import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.KodeinAware import com.github.salomonbrys.kodein.instance import io.petros.posts.kotlin.datastore.db.PostDao import io.petros.posts.kotlin.datastore.db.UserDao import io.petros.posts.kotlin.model.Post import io.petros.posts.kotlin.model.User import io.petros.posts.kotlin.util.rx.RxSchedulers import io.reactivex.Single import timber.log.Timber class Datastore(override val kodein: Kodein) : KodeinAware { private val rxSchedulers: RxSchedulers = instance() private val userDao: UserDao = instance() private val postDao: PostDao = instance() fun getUser(id: String): Single<User> { Timber.v("Getting user... [Id: $id]") return userDao.get(id) } fun saveUsers(users: List<User>): Boolean { if (!users.isEmpty()) { Single.fromCallable { Timber.v("Saving users... [$users]") userDao.save(users) }.observeOn(rxSchedulers.androidMainThreadScheduler) .subscribeOn(rxSchedulers.ioScheduler) .subscribe() return true } else return false } fun getPosts(): LiveData<List<Post>> { Timber.v("Getting posts...") return postDao.getAll() } fun savePosts(posts: List<Post>): Boolean { if (!posts.isEmpty()) { Single.fromCallable { Timber.v("Saving posts... [$posts]") postDao.save(posts) }.observeOn(rxSchedulers.androidMainThreadScheduler) .subscribeOn(rxSchedulers.ioScheduler) .subscribe() return true } else return false } }
app/src/main/java/io/petros/posts/kotlin/datastore/Datastore.kt
818444490
package io.github.notsyncing.cowherd.api import io.github.notsyncing.cowherd.CowherdPart import io.github.notsyncing.cowherd.commons.CowherdConfiguration import io.github.notsyncing.cowherd.models.RouteInfo import io.github.notsyncing.cowherd.service.ServiceManager import io.vertx.core.json.JsonObject class CowherdApiPart : CowherdPart { private val defConfig = JsonObject() init { defConfig.put("urlPrefix", "service") } override fun init() { var config = CowherdConfiguration.getRawConfiguration().getJsonObject("api") if (config == null) { config = defConfig } val apiRoute = RouteInfo() //apiRoute.path = "^/${config.getString("urlPrefix")}/gateway/(?<path>.*?)$" apiRoute.path = "/${config.getString("urlPrefix")}/gateway/**:path" apiRoute.domain = config.getString("domain") apiRoute.isFastRoute = true ServiceManager.addServiceClass(CowherdApiGatewayService::class.java, apiRoute) } override fun destroy() { CowherdApiHub.reset() } }
cowherd-api/src/main/kotlin/io/github/notsyncing/cowherd/api/CowherdApiPart.kt
494523510
package org.mrlem.happycows.ui.caches import com.badlogic.gdx.utils.Disposable import kotlin.collections.HashMap /** * @author Sébastien Guillemin <seb@mrlem.org> */ abstract class AbstractCache<K, R : Disposable?> protected constructor() : Disposable { private var resources: MutableMap<K, R> = HashMap() operator fun get(name: K): R? { synchronized(resources) { return resources[name] ?: newResource(name) } } override fun dispose() { var resourcesToDispose: Map<K, R> synchronized(resources) { resourcesToDispose = resources resources = HashMap() } resourcesToDispose.values.forEach { it?.dispose() } } /** * Deallocate a specific resource, if present. * * @param key identifying the resource */ fun dispose(key: K) { resources.remove(key) ?.apply { dispose() } } protected abstract fun newResource(key: K): R }
core/src/org/mrlem/happycows/ui/caches/AbstractCache.kt
1959522787
package jetbrains.buildServer.dotnet enum class ToolType { VisualStudio, MSBuild, VSTest }
plugin-dotnet-common/src/main/kotlin/jetbrains/buildServer/dotnet/ToolType.kt
2890612934
// 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.uast.expressions import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.util.PartiallyKnownString import com.intellij.psi.util.StringEntry import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* class UStringConcatenationsFacade @ApiStatus.Experimental constructor(uContext: UExpression) { val uastOperands: Sequence<UExpression> = run { when { uContext is UPolyadicExpression -> uContext.operands.asSequence() uContext is ULiteralExpression && uContext.uastParent !is UPolyadicExpression -> { val host = uContext.sourceInjectionHost if (host == null || !host.isValidHost) emptySequence() else sequenceOf(uContext) } else -> emptySequence() } } val psiLanguageInjectionHosts: Sequence<PsiLanguageInjectionHost> = uastOperands.mapNotNull { (it as? ULiteralExpression)?.psiLanguageInjectionHost }.distinct() /** * external (non string-literal) expressions in string interpolations and/or concatenations */ val placeholders: List<Pair<TextRange, String>> get() = segments.mapNotNull { segment -> when (segment) { is Segment.Placeholder -> segment.range to (segment.value ?: "missingValue") else -> null } } private sealed class Segment { abstract val value: String? abstract val range: TextRange abstract val uExpression: UExpression class StringLiteral(override val value: String, override val range: TextRange, override val uExpression: ULiteralExpression) : Segment() class Placeholder(override val value: String?, override val range: TextRange, override val uExpression: UExpression) : Segment() } private val segments: List<Segment> by lazy(LazyThreadSafetyMode.NONE) { val bounds = uContext.sourcePsi?.textRange ?: return@lazy emptyList<Segment>() val operandsList = uastOperands.toList() ArrayList<Segment>(operandsList.size).apply { for (i in operandsList.indices) { val operand = operandsList[i] val sourcePsi = operand.sourcePsi ?: continue val selfRange = sourcePsi.textRange if (operand is ULiteralExpression) add(Segment.StringLiteral(operand.evaluateString() ?: "", selfRange, operand)) else { val prev = operandsList.getOrNull(i - 1) val next = operandsList.getOrNull(i + 1) val start = when (prev) { null -> bounds.startOffset is ULiteralExpression -> prev.sourcePsi?.textRange?.endOffset ?: selfRange.startOffset else -> selfRange.startOffset } val end = when (next) { null -> bounds.endOffset is ULiteralExpression -> next.sourcePsi?.textRange?.startOffset ?: selfRange.endOffset else -> selfRange.endOffset } val range = TextRange.create(start, end) val evaluate = operand.evaluateString() add(Segment.Placeholder(evaluate, range, operand)) } } } } @ApiStatus.Experimental fun asPartiallyKnownString() : PartiallyKnownString = PartiallyKnownString(segments.map { segment -> segment.value?.let { value -> StringEntry.Known(value, segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) } ?: StringEntry.Unknown(segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) }) private fun getSegmentInnerTextRange(segment: Segment): TextRange { val sourcePsi = segment.uExpression.sourcePsi ?: throw IllegalStateException("no sourcePsi for $segment") val sourcePsiTextRange = sourcePsi.textRange val range = segment.range if (range.startOffset > sourcePsiTextRange.startOffset) return range.shiftLeft(sourcePsiTextRange.startOffset) return ElementManipulators.getValueTextRange(sourcePsi) } companion object { @JvmStatic fun create(context: PsiElement): UStringConcatenationsFacade? { if (context !is PsiLanguageInjectionHost && context.firstChild !is PsiLanguageInjectionHost) { return null } val uElement = context.toUElement(UExpression::class.java) ?: return null return UStringConcatenationsFacade(uElement) } } }
uast/uast-common/src/org/jetbrains/uast/expressions/UStringConcatenationsFacade.kt
2490196751
package org.purescript.lexer import junit.framework.TestCase class PSLexerTest : TestCase() { fun testItHandlesFileEndingInEmptyLine() { val lexer = PSLexer() lexer.start(""" module Main where """.trimIndent()) while (lexer.tokenEnd < lexer.bufferEnd) { lexer.advance() } } }
src/test/kotlin/org/purescript/lexer/PSLexerTest.kt
658741479
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.legacy import android.util.Log import androidx.room.TypeConverter import org.json.JSONArray import org.json.JSONException import java.util.ArrayList /** * Converts a list of commands into and from a persisted value */ object UserCommandTypeConverter { private const val TAG = "UserCmdTypeConverter" @TypeConverter fun fromString(commandsString: String): MutableList<String> { val commands = ArrayList<String>() if (commandsString.isEmpty()) { return commands } try { val commandArray = JSONArray(commandsString) (0 until commandArray.length()).mapTo(commands) { index -> commandArray.getString(index) } } catch (e: JSONException) { Log.e(TAG, "Error parsing commands from $commandsString", e) } return commands } @TypeConverter fun commandsListToString(commands: MutableList<String>?): String = JSONArray().apply { commands?.forEach { command -> put(command) } }.toString() }
legacy-standalone/src/main/java/com/google/android/apps/muzei/legacy/UserCommandTypeConverter.kt
2870976787
operator fun Long.component1() = this + 1 operator fun Long.component2() = this + 2 fun doTest(): String { var s = "" for ((a, b) in 0.toLong().rangeTo(2.toLong())) { s += "$a:$b;" } return s } fun box(): String { val s = doTest() return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s" }
backend.native/tests/external/codegen/box/multiDecl/forRange/explicitRangeTo/long/MultiDeclForComponentExtensions.kt
1898596896
package com.vimeo.networking2.functions class AnnotatedFunctionContainer { @Deprecated("Use something else") fun doSomething() { println("Hello World") } }
model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/functions/AnnotatedFunctionContainer.kt
1003407740
package tech.salroid.filmy.data.local.model import com.google.gson.annotations.SerializedName data class SimilarMoviesResponse( @SerializedName("page") var page: Int? = null, @SerializedName("results") var similars: ArrayList<SimilarMovie> = arrayListOf(), @SerializedName("total_pages") var totalPages: Int? = null, @SerializedName("total_results") var totalResults: Int? = null )
app/src/main/java/tech/salroid/filmy/data/local/model/SimilarMoviesResponse.kt
1747977009
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.navigation import training.learn.lesson.general.navigation.SearchEverywhereLesson class PythonSearchEverywhereLesson : SearchEverywhereLesson() { override val existedFile = "src/declaration_and_usages_demo.py" override val resultFileName: String = "quadratic_equations_solver.py" }
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/navigation/PythonSearchEverywhereLesson.kt
2640552901
package io.fotoapparat.characteristic import io.fotoapparat.hardware.orientation.Orientation /** * A set of information about the camera. */ internal data class Characteristics( val cameraId: Int, val lensPosition: LensPosition, val cameraOrientation: Orientation, val isMirrored: Boolean )
fotoapparat/src/main/java/io/fotoapparat/characteristic/Characteristics.kt
1340042421
// "Remove redundant initializer" "true" // WITH_STDLIB // ERROR: A 'return' expression required in a function with a block body ('{...}') // ERROR: Unresolved reference: abc // ERROR: Unresolved reference: abc class KTest { private fun test(urlMapping: String?): String { if (urlMapping == null) return "" var urlPattern = urlMapping<caret>.substring(123) urlPattern = abc urlPattern = abc(urlPattern, 1)
plugins/kotlin/idea/tests/testData/quickfix/removeRedundantInitializer/brokenFile.kt
613218368
// WITH_STDLIB fun test(list: List<String>) { list.forEach { item -> println(item) /* comment */ }<caret> }
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToSingleLine/multiLineBody2.kt
932476772
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.util.Processor import com.intellij.util.Url import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.values.FunctionValue const val VM_SCHEME: String = "vm" const val WEBPACK_INTERNAL_SCHEME: String = "webpack-internal" interface ScriptManager { fun getSource(script: Script): Promise<String> fun hasSource(script: Script): Boolean fun containsScript(script: Script): Boolean fun forEachScript(scriptProcessor: (Script) -> Boolean) fun forEachScript(scriptProcessor: Processor<Script>): Unit = forEachScript { scriptProcessor.process(it)} fun getScript(function: FunctionValue): Promise<Script> fun getScript(frame: CallFrame): Script? fun findScriptByUrl(rawUrl: String): Script? fun findScriptByUrl(url: Url): Script? fun findScriptById(id: String): Script? = null }
platform/script-debugger/backend/src/debugger/ScriptManager.kt
1210966302
// PROBLEM: 'also' has empty body // FIX: none // WITH_STDLIB fun test(i: Int) { i.<caret>also { // comment } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/controlFlowWithEmptyBody/also/blockHasComment.kt
3462304796
// WITH_STDLIB // SUGGESTED_RETURN_TYPES: kotlin.Boolean?, kotlin.Boolean // PARAM_DESCRIPTOR: value-parameter it: kotlin.collections.Map.Entry<kotlin.Boolean!, kotlin.Boolean!> defined in test.<anonymous> // PARAM_TYPES: kotlin.collections.Map.Entry<kotlin.Boolean!, kotlin.Boolean!> fun test() { J.getMap().filter { <selection>it.key</selection> } }
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/callWithPlatformTypeReceiver.kt
3494554074
class Generic1<T> class Generic2<T1, T2> fun foo(): G<caret> // EXIST: { lookupString: "Generic1", itemText: "Generic1", tailText: "<T> (<root>)", icon: "org/jetbrains/kotlin/idea/icons/classKotlin.svg"} // EXIST: { lookupString: "Generic2", itemText: "Generic2", tailText: "<T1, T2> (<root>)", icon: "org/jetbrains/kotlin/idea/icons/classKotlin.svg"}
plugins/kotlin/completion/tests/testData/basic/common/GenericKotlinClass.kt
1111653604
class A { final fun <caret>foo() { } }
plugins/kotlin/idea/tests/testData/intentions/moveToCompanion/dropFinal.kt
3018904374
// 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.intellij.plugins.markdown.lang.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.common.AbstractBlock import com.intellij.psi.formatter.common.SettingsAwareBlock import com.intellij.psi.tree.TokenSet import org.intellij.plugins.markdown.injection.MarkdownCodeFenceUtils import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings import org.intellij.plugins.markdown.lang.psi.MarkdownAstUtils.children import org.intellij.plugins.markdown.lang.psi.MarkdownAstUtils.parents import org.intellij.plugins.markdown.util.MarkdownPsiUtil /** * Formatting block used by markdown plugin * * It defines alignment equal for all block on the same line, and new for inner lists */ internal open class MarkdownFormattingBlock( node: ASTNode, private val settings: CodeStyleSettings, protected val spacing: SpacingBuilder, alignment: Alignment? = null, wrap: Wrap? = null ) : AbstractBlock(node, wrap, alignment), SettingsAwareBlock { companion object { private val NON_ALIGNABLE_LIST_ELEMENTS = TokenSet.orSet(MarkdownTokenTypeSets.LIST_MARKERS, MarkdownTokenTypeSets.LISTS) } override fun getSettings(): CodeStyleSettings = settings protected fun obtainCustomSettings(): MarkdownCustomCodeStyleSettings { return settings.getCustomSettings(MarkdownCustomCodeStyleSettings::class.java) } override fun isLeaf(): Boolean = subBlocks.isEmpty() override fun getSpacing(child1: Block?, child2: Block): Spacing? = spacing.getSpacing(this, child1, child2) override fun getIndent(): Indent? { if (node.elementType in MarkdownTokenTypeSets.LISTS && node.parents(withSelf = false).any { it.elementType == MarkdownElementTypes.LIST_ITEM }) { return Indent.getNormalIndent() } return Indent.getNoneIndent() } /** * Get indent for new formatting block, that will be created when user will start typing after enter * In general `getChildAttributes` defines where to move caret after enter. * Other changes (for example, adding of `>` for blockquote) are handled by MarkdownEnterHandler */ override fun getChildAttributes(newChildIndex: Int): ChildAttributes { return MarkdownEditingAligner.calculateChildAttributes(subBlocks.getOrNull(newChildIndex - 1)) } override fun getSubBlocks(): List<Block?> { //Non top-level codefences cannot be formatted correctly even with correct inject, so -- just ignore it if (MarkdownCodeFenceUtils.isCodeFence(node) && !MarkdownPsiUtil.isTopLevel(node)) return EMPTY return super.getSubBlocks() } override fun buildChildren(): List<Block> { val newAlignment = Alignment.createAlignment() return when (node.elementType) { //Code fence alignment is not supported for now because of manipulator problems // and the fact that when end of code fence is in blockquote -- parser // would treat blockquote as a part of code fence end token MarkdownElementTypes.CODE_FENCE -> emptyList() MarkdownElementTypes.LIST_ITEM -> { MarkdownBlocks.create(node.children(), settings, spacing) { if (it.elementType in NON_ALIGNABLE_LIST_ELEMENTS) alignment else newAlignment }.toList() } MarkdownElementTypes.PARAGRAPH, MarkdownElementTypes.CODE_BLOCK, MarkdownElementTypes.BLOCK_QUOTE -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment ?: newAlignment }.toList() } else -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment }.toList() } } } }
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/blocks/MarkdownFormattingBlock.kt
3458474398
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.settingsRepository import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import org.jetbrains.settingsRepository.SyncType internal object IcsActionsLogger { fun logSettingsSync(project: Project?, type: SyncType) { val data = FeatureUsageData().addData("sync_type", StringUtil.toLowerCase(type.name)) FUCounterUsageLogger.getInstance().logEvent(project, "settings.repository", "sync.settings", data) } }
plugins/settings-repository/src/IcsActionsLogger.kt
2087802566
package org.jetbrains.uast.kotlin fun foo() { val lam1 = { a: Int -> val b = 1 a + b } val lam2 = { a: Int -> val c = 1 if (a > 0) a + c else a - c } val lam3 = lbd@{ a: Int -> val d = 1 return@lbd a + d } val lam4 = fun(a: Int): String { if (a < 5) return "5" if (a > 0) return "1" else return "2" } val lam5 = fun(a: Int) = "a" + a bar { if (it > 5) return val b = 1 it + b } val x: () -> Unit = { val (a, b) = listOf(1, 2) } val y: () -> Unit = { listOf(1) } } private inline fun bar(lmbd: (Int) -> Int) { lmbd(1) }
plugins/kotlin/uast/uast-kotlin/tests/testData/LambdaReturn.kt
1310273428
// AFTER-WARNING: Parameter 'a' is never used fun <T> doSomething(a: T) {} fun test(n: Int): String { var res: String if (n == 1) { <caret>res = if (3 > 2) { doSomething("***") "one" } else { doSomething("***") "???" } } else if (n == 2) { doSomething("***") res = "two" } else { doSomething("***") res = "too many" } return res }
plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/assignmentToIf/innerIfTransformed.kt
634861088
package flank.scripts.ops.assemble.android import flank.common.androidTestProjectsPath import flank.common.flankFixturesTmpPath import flank.scripts.utils.createGradleCommand import flank.scripts.utils.runCommand import java.nio.file.Files import java.nio.file.Paths fun AndroidBuildConfiguration.buildDuplicatedNamesApks() { if (artifacts.canExecute("buildDuplicatedNamesApks").not()) return val modules = (0..3).map { "dir$it" } createGradleCommand( workingDir = androidTestProjectsPath, options = listOf("-p", androidTestProjectsPath) + modules.map { "$it:testModule:assembleAndroidTest" }.toList() ).runCommand() if (copy) copyDuplicatedNamesApks() } private fun copyDuplicatedNamesApks() { val modules = (0..3).map { "dir$it" } val outputDir = Paths.get(flankFixturesTmpPath, "apk", "duplicated_names") if (!outputDir.toFile().exists()) Files.createDirectories(outputDir) modules.map { Paths.get(androidTestProjectsPath, it, "testModule", "build", "outputs", "apk").toFile() } .flatMap { it.findApks().toList() } .forEachIndexed { index, file -> file.copyApkToDirectory(Paths.get(outputDir.toString(), modules[index], file.name)) } }
flank-scripts/src/main/kotlin/flank/scripts/ops/assemble/android/BuildDuplicatedNamesApks.kt
4097685495
package com.kickstarter.libs.utils import com.kickstarter.libs.RefTag import com.kickstarter.libs.utils.EventContextValues.VideoContextName.LENGTH import com.kickstarter.libs.utils.EventContextValues.VideoContextName.POSITION import com.kickstarter.libs.utils.RewardUtils.isItemized import com.kickstarter.libs.utils.RewardUtils.isReward import com.kickstarter.libs.utils.RewardUtils.isShippable import com.kickstarter.libs.utils.RewardUtils.isTimeLimitedEnd import com.kickstarter.libs.utils.extensions.addOnsCost import com.kickstarter.libs.utils.extensions.bonus import com.kickstarter.libs.utils.extensions.intValueOrZero import com.kickstarter.libs.utils.extensions.isNonZero import com.kickstarter.libs.utils.extensions.isTrue import com.kickstarter.libs.utils.extensions.refTag import com.kickstarter.libs.utils.extensions.rewardCost import com.kickstarter.libs.utils.extensions.round import com.kickstarter.libs.utils.extensions.shippingAmount import com.kickstarter.libs.utils.extensions.timeInDaysOfDuration import com.kickstarter.libs.utils.extensions.timeInSecondsUntilDeadline import com.kickstarter.libs.utils.extensions.totalAmount import com.kickstarter.libs.utils.extensions.totalCountUnique import com.kickstarter.libs.utils.extensions.totalQuantity import com.kickstarter.libs.utils.extensions.userIsCreator import com.kickstarter.models.Activity import com.kickstarter.models.Category import com.kickstarter.models.Location import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.Update import com.kickstarter.models.User import com.kickstarter.models.extensions.getCreatedAndDraftProjectsCount import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.PledgeData import java.util.Locale import kotlin.math.ceil import kotlin.math.roundToInt object AnalyticEventsUtils { @JvmOverloads fun checkoutProperties(checkoutData: CheckoutData, pledgeData: PledgeData, prefix: String = "checkout_"): Map<String, Any> { val project = pledgeData.projectData().project() val properties = HashMap<String, Any>().apply { put("amount", checkoutData.amount().round()) checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) put("shipping_amount_usd", checkoutData.shippingAmount(project.staticUsdRate()).round()) put("bonus_amount", checkoutData.bonus()) put("bonus_amount_usd", checkoutData.bonus(project.staticUsdRate()).round()) put("add_ons_count_total", pledgeData.totalQuantity()) put("add_ons_count_unique", pledgeData.totalCountUnique()) put("add_ons_minimum_usd", pledgeData.addOnsCost(project.staticUsdRate()).round()) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun checkoutProperties(checkoutData: CheckoutData, project: Project, addOns: List<Reward>?, prefix: String = "checkout_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("amount", checkoutData.amount().round()) checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) put("shipping_amount_usd", checkoutData.shippingAmount(project.staticUsdRate()).round()) put("bonus_amount", checkoutData.bonus()) put("bonus_amount_usd", checkoutData.bonus(project.staticUsdRate()).round()) put("add_ons_count_total", totalQuantity(addOns)) put("add_ons_count_unique", totalCountUnique(addOns)) put("add_ons_minimum_usd", addOnsCost(project.staticUsdRate(), addOns).round()) } return MapUtils.prefixKeys(properties, prefix) } fun checkoutDataProperties(checkoutData: CheckoutData, pledgeData: PledgeData, loggedInUser: User?): Map<String, Any> { val props = pledgeDataProperties(pledgeData, loggedInUser) props.putAll(checkoutProperties(checkoutData, pledgeData)) return props } @JvmOverloads fun discoveryParamsProperties(params: DiscoveryParams, discoverSort: DiscoveryParams.Sort? = params.sort(), prefix: String = "discover_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("everything", params.isAllProjects.isTrue()) put("pwl", params.staffPicks().isTrue()) put("recommended", params.recommended()?.isTrue() ?: false) params.refTag()?.tag()?.let { put("ref_tag", it) } params.term()?.let { put("search_term", it) } put("social", params.social().isNonZero()) put( "sort", discoverSort?.let { when (it) { DiscoveryParams.Sort.POPULAR -> "popular" DiscoveryParams.Sort.ENDING_SOON -> "ending_soon" else -> it.toString() } } ?: "" ) params.tagId()?.let { put("tag", it) } put("watched", params.starred().isNonZero()) val paramsCategory = params.category() paramsCategory?.let { category -> if (category.isRoot) { putAll(categoryProperties(category)) } else { category.root()?.let { putAll(categoryProperties(it)) } putAll(subcategoryProperties(category)) } } } return MapUtils.prefixKeys(properties, prefix) } fun subcategoryProperties(category: Category): Map<String, Any> { return categoryProperties(category, "subcategory_") } @JvmOverloads fun categoryProperties(category: Category, prefix: String = "category_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("id", category.id().toString()) put("name", category.analyticsName().toString()) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun locationProperties(location: Location, prefix: String = "location_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("id", location.id().toString()) put("name", location.name()) put("displayable_name", location.displayableName()) location.city()?.let { put("city", it) } location.state()?.let { put("state", it) } put("country", location.country()) location.projectsCount()?.let { put("projects_count", it) } } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun userProperties(user: User, prefix: String = "user_"): Map<String, Any> { val properties = HashMap<String, Any>() properties["backed_projects_count"] = user.backedProjectsCount() ?: 0 properties["launched_projects_count"] = user.createdProjectsCount() ?: 0 properties["created_projects_count"] = user.getCreatedAndDraftProjectsCount() properties["facebook_connected"] = user.facebookConnected() ?: false properties["watched_projects_count"] = user.starredProjectsCount() ?: 0 properties["uid"] = user.id().toString() properties["is_admin"] = user.isAdmin() ?: false return MapUtils.prefixKeys(properties, prefix) } fun pledgeDataProperties(pledgeData: PledgeData, loggedInUser: User?): MutableMap<String, Any> { val projectData = pledgeData.projectData() val props = projectProperties(projectData.project(), loggedInUser) props.putAll(pledgeProperties(pledgeData)) props.putAll(refTagProperties(projectData.refTagFromIntent(), projectData.refTagFromCookie())) props["context_pledge_flow"] = pledgeData.pledgeFlowContext().trackingString return props } @JvmOverloads fun videoProperties(videoLength: Long, videoPosition: Long, prefix: String = "video_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put(LENGTH.contextName, videoLength) put(POSITION.contextName, videoPosition) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun pledgeProperties(pledgeData: PledgeData, prefix: String = "checkout_"): Map<String, Any> { val reward = pledgeData.reward() val project = pledgeData.projectData().project() val properties = HashMap<String, Any>().apply { reward.estimatedDeliveryOn()?.let { deliveryDate -> put("estimated_delivery_on", deliveryDate) } put("has_items", isItemized(reward)) put("id", reward.id().toString()) put("is_limited_time", isTimeLimitedEnd(reward)) put("is_limited_quantity", reward.limit() != null) put("minimum", reward.minimum()) put("shipping_enabled", isShippable(reward)) put("minimum_usd", pledgeData.rewardCost(project.staticUsdRate()).round()) reward.shippingPreference()?.let { put("shipping_preference", it) } reward.title()?.let { put("title", it) } } val props = MapUtils.prefixKeys(properties, "reward_") props.apply { put("add_ons_count_total", pledgeData.totalQuantity()) put("add_ons_count_unique", pledgeData.totalCountUnique()) put("add_ons_minimum_usd", addOnsCost(project.staticUsdRate(), pledgeData.addOns()?.let { it as? List<Reward> } ?: emptyList()).round()) } return MapUtils.prefixKeys(props, prefix) } @JvmOverloads fun projectProperties(project: Project, loggedInUser: User?, prefix: String = "project_"): MutableMap<String, Any> { val properties = HashMap<String, Any>().apply { put("backers_count", project.backersCount()) project.category()?.let { category -> if (category.isRoot) { put("category", category.analyticsName()) } else { category.parent()?.let { parent -> put("category", parent.analyticsName()) } ?: category.parentName()?.let { if (!this.containsKey("category")) this["category"] = it } put("subcategory", category.analyticsName()) } } project.commentsCount()?.let { put("comments_count", it) } project.prelaunchActivated()?.let { put("project_prelaunch_activated", it) } put("country", project.country()) put("creator_uid", project.creator().id().toString()) put("currency", project.currency()) put("current_pledge_amount", project.pledged()) put("current_amount_pledged_usd", (project.pledged() * project.usdExchangeRate()).round()) project.deadline()?.let { deadline -> put("deadline", deadline) } put("duration", project.timeInDaysOfDuration().toFloat().roundToInt()) put("goal", project.goal()) put("goal_usd", (project.goal() * project.usdExchangeRate()).round()) put("has_video", project.video() != null) put("hours_remaining", ceil((project.timeInSecondsUntilDeadline() / 60.0f / 60.0f).toDouble()).toInt()) put("is_repeat_creator", project.creator().createdProjectsCount().intValueOrZero() >= 2) project.launchedAt()?.let { launchedAt -> put("launched_at", launchedAt) } project.location()?.let { location -> put("location", location.name()) } put("name", project.name()) put("percent_raised", (project.percentageFunded()).toInt()) put("pid", project.id().toString()) put("prelaunch_activated", project.prelaunchActivated().isTrue()) project.rewards()?.let { a -> val rewards = a.filter { isReward(it) } put("rewards_count", rewards.size) } put("state", project.state()) put("static_usd_rate", project.staticUsdRate()) project.updatesCount()?.let { put("updates_count", it) } put("user_is_project_creator", project.userIsCreator(loggedInUser)) put("user_is_backer", project.isBacking()) put("user_has_watched", project.isStarred()) val hasAddOns = project.rewards()?.find { it.hasAddons() } put("has_add_ons", hasAddOns?.hasAddons() ?: false) put("tags", project.tags()?.let { it.joinToString(", ") } ?: "") put("url", project.urls().web().project()) project.photo()?.full()?.let { put("image_url", it) } } return MapUtils.prefixKeys(properties, prefix) } fun refTagProperties(intentRefTag: RefTag?, cookieRefTag: RefTag?) = HashMap<String, Any>().apply { intentRefTag?.tag()?.let { put("session_ref_tag", it) } cookieRefTag?.tag()?.let { put("session_referrer_credit", it) } } @JvmOverloads fun activityProperties(activity: Activity, loggedInUser: User?, prefix: String = "activity_"): Map<String, Any> { val props = HashMap<String, Any>().apply { activity.category()?.let { put("category", it) } } val properties = MapUtils.prefixKeys(props, prefix) activity.project()?.let { project -> properties.putAll(projectProperties(project, loggedInUser)) activity.update()?.let { update -> properties.putAll(updateProperties(project, update, loggedInUser)) } } return properties } @JvmOverloads fun updateProperties(project: Project, update: Update, loggedInUser: User?, prefix: String = "update_"): Map<String, Any> { val props = HashMap<String, Any>().apply { update.commentsCount()?.let { put("comments_count", it) } update.hasLiked()?.let { put("has_liked", it) } put("id", update.id()) update.likesCount()?.let { put("likes_count", it) } put("title", update.title()) put("sequence", update.sequence()) update.visible()?.let { put("visible", it) } update.publishedAt()?.let { put("published_at", it) } } val properties = MapUtils.prefixKeys(props, prefix) properties.putAll(projectProperties(project, loggedInUser)) return properties } }
app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt
583172119
package com.habitrpg.android.habitica.ui.menu import android.graphics.drawable.Drawable import android.os.Bundle data class HabiticaDrawerItem(var transitionId: Int, val identifier: String, val text: String, val isHeader: Boolean = false) { constructor(transitionId: Int, identifier: String) : this(transitionId, identifier, "") var bundle: Bundle? = null var itemViewType: Int? = null var subtitle: String? = null var subtitleTextColor: Int? = null var pillText: String? = null var pillBackground: Drawable? = null var showBubble: Boolean = false var isVisible: Boolean = true var isEnabled: Boolean = true }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/menu/HabiticaDrawerItem.kt
3525849417