content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.twitter.meil_mitu.twitter4hk.converter
import com.squareup.okhttp.Response
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
interface IOauth2TokenConverter<TOauth2Token> : IJsonConverter {
@Throws(Twitter4HKException::class)
fun toOauth2Token(res: Response): TOauth2Token
@Throws(Twitter4HKException::class)
fun toOauth2Token(res: Response, tokenType: String): TOauth2Token
} | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/IOauth2TokenConverter.kt | 3179912037 |
package com.twitter.meil_mitu.twitter4hk.api.account
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.AbsPost
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.converter.ISettingConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class PostSettings<TSetting>(
oauth: AbsOauth,
protected val json: ISettingConverter<TSetting>) : AbsPost<TSetting>(oauth) {
var trendLocationWoeid: Int? by intParam("trend_location_woeid")
var sleepTimeEnabled: Boolean? by booleanParam("sleep_time_enabled")
var startSleepTime: Int? by intParam("start_sleep_time")
var endSleepTime: Int? by intParam("end_sleep_time")
var timeZone: String? by stringParam("time_zone")
var lang: String? by stringParam("lang")
override val url = "https://api.twitter.com/1.1/account/settings.json"
override val allowOauthType = OauthType.oauth1
override val isAuthorization = true
@Throws(Twitter4HKException::class)
override fun call(): TSetting {
return json.toSetting(oauth.post(this))
}
}
| library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/account/PostSettings.kt | 1746684019 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.runAnything
import com.intellij.execution.Executor
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.ide.actions.runAnything.RunAnythingAction
import com.intellij.ide.actions.runAnything.RunAnythingContext
import com.intellij.ide.actions.runAnything.activity.RunAnythingProviderBase
import com.intellij.ide.actions.runAnything.getPath
import com.intellij.ide.actions.runAnything.items.RunAnythingItem
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil.trimStart
import com.intellij.util.execution.ParametersListUtil
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.runconfig.getAppropriateCargoProject
import org.rust.cargo.runconfig.hasCargoProject
import org.rust.cargo.util.RsCommandCompletionProvider
import org.rust.stdext.toPath
import java.nio.file.Path
abstract class RsRunAnythingProvider : RunAnythingProviderBase<String>() {
abstract override fun getMainListItem(dataContext: DataContext, value: String): RunAnythingItem
protected abstract fun run(
executor: Executor,
command: String,
params: List<String>,
workingDirectory: Path,
cargoProject: CargoProject
)
abstract fun getCompletionProvider(project: Project, dataContext: DataContext) : RsCommandCompletionProvider
override fun findMatchingValue(dataContext: DataContext, pattern: String): String? =
if (pattern.startsWith(helpCommand)) getCommand(pattern) else null
override fun getValues(dataContext: DataContext, pattern: String): Collection<String> {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return emptyList()
if (!project.hasCargoProject) return emptyList()
val completionProvider = getCompletionProvider(project, dataContext)
return when {
pattern.startsWith(helpCommand) -> {
val context = trimStart(pattern, helpCommand).substringBeforeLast(' ')
val prefix = pattern.substringBeforeLast(' ')
completionProvider.complete(context).map { "$prefix ${it.lookupString}" }
}
pattern.isNotBlank() && helpCommand.startsWith(pattern) ->
completionProvider.complete("").map { "$helpCommand ${it.lookupString}" }
else -> emptyList()
}
}
override fun execute(dataContext: DataContext, value: String) {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return
if (!project.hasCargoProject) return
val cargoProject = getAppropriateCargoProject(dataContext) ?: return
val params = ParametersListUtil.parse(trimStart(value, helpCommand))
val executionContext = dataContext.getData(EXECUTING_CONTEXT) ?: RunAnythingContext.ProjectContext(project)
val path = executionContext.getPath()?.toPath() ?: return
val executor = dataContext.getData(RunAnythingAction.EXECUTOR_KEY) ?: DefaultRunExecutor.getRunExecutorInstance()
run(executor, params.firstOrNull() ?: "--help", params.drop(1), path, cargoProject)
}
abstract override fun getHelpCommand(): String
}
| src/main/kotlin/org/rust/ide/actions/runAnything/RsRunAnythingProvider.kt | 1976192559 |
package com.gh0u1l5.wechatmagician.backend.plugins
import com.gh0u1l5.wechatmagician.Global.SETTINGS_SNS_KEYWORD_BLACKLIST
import com.gh0u1l5.wechatmagician.Global.SETTINGS_SNS_KEYWORD_BLACKLIST_CONTENT
import com.gh0u1l5.wechatmagician.backend.WechatHook
import com.gh0u1l5.wechatmagician.backend.storage.list.SnsBlacklist
import com.gh0u1l5.wechatmagician.spellbook.interfaces.IXmlParserHook
object SnsBlock : IXmlParserHook {
private const val ROOT_TAG = "TimelineObject"
private const val CONTENT_TAG = ".TimelineObject.contentDesc"
private const val ID_TAG = ".TimelineObject.id"
private const val PRIVATE_TAG = ".TimelineObject.private"
private val pref = WechatHook.settings
private fun isPluginEnabled() = pref.getBoolean(SETTINGS_SNS_KEYWORD_BLACKLIST, false)
override fun onXmlParsed(xml: String, root: String, result: MutableMap<String, String>) {
if (!isPluginEnabled()) {
return
}
if (root == ROOT_TAG && result[PRIVATE_TAG] != "1") {
val content = result[CONTENT_TAG] ?: return
val keywords = pref.getStringList(SETTINGS_SNS_KEYWORD_BLACKLIST_CONTENT, emptyList())
keywords.forEach { keyword ->
if (content.contains(keyword)) {
SnsBlacklist += result[ID_TAG]
result[PRIVATE_TAG] = "1"
return
}
}
}
}
}
| app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/SnsBlock.kt | 3789646858 |
package de.blankedv.lanbahnpanel.railroad
import android.util.Log
import de.blankedv.lanbahnpanel.elements.ActivePanelElement
import de.blankedv.lanbahnpanel.model.*
class Commands {
companion object {
fun readChannel(addr: Int, peClass: Class<*> = Object::class.java) {
if (addr == INVALID_INT) return
var cmd = "READ $addr"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
fun readMultipleChannels(aArray: ArrayList<Int>) {
var cmd = "";
val aArr = aArray.sorted()
for (a in aArr) {
if (a != INVALID_INT) {
cmd += ";READ $a"
}
}
if (cmd.isEmpty()) return
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
fun setChannel(addr: Int, data: Int, peClass: Class<*> = Object::class.java) {
if ((addr == INVALID_INT) or (data == INVALID_INT)) return
var cmd = "SET $addr $data"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setChannel failed, queue full")
}
}
fun setPower(state: Int) {
var cmd = "SETPOWER "
when (state) {
POWER_ON -> cmd += "1"
POWER_OFF -> cmd += "0"
POWER_UNKNOWN -> cmd += "1" // switch on in this case
}
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setPower failed, queue full")
}
}
fun readPower() {
var cmd = "READPOWER "
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readPower failed, queue full")
}
}
fun setLocoData(addr : Int, data : Int) {
if ((addr == INVALID_INT) or (data == INVALID_INT)) return
var cmd = "SETLOCO $addr $data"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setLocoData failed, queue full")
}
}
fun readLocoData(addr : Int) {
if (addr == INVALID_INT) return
var cmd = "READLOCO $addr"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
/** needed for sx loco control TODO works only for SX */
fun requestAllLocoData() {
for (l in locolist) {
readLocoData(l.adr) // TODO works only for SX
}
}
}
} | app/src/main/java/de/blankedv/lanbahnpanel/railroad/Commands.kt | 960853806 |
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.anko.appcompat.v7
import org.jetbrains.anko.*
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.support.v7.app.AlertDialog
import android.view.KeyEvent
import android.view.View
import org.jetbrains.anko.internals.AnkoInternals
import org.jetbrains.anko.internals.AnkoInternals.NO_GETTER
import kotlin.DeprecationLevel.ERROR
val Appcompat: AlertBuilderFactory<AlertDialog> = ::AppcompatAlertBuilder
internal class AppcompatAlertBuilder(override val ctx: Context) : AlertBuilder<AlertDialog> {
private val builder = AlertDialog.Builder(ctx)
override var title: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setTitle(value) }
override var titleResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setTitle(value) }
override var message: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setMessage(value) }
override var messageResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setMessage(value) }
override var icon: Drawable
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setIcon(value) }
override var iconResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setIcon(value) }
override var customTitle: View
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setCustomTitle(value) }
override var customView: View
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setView(value) }
override fun onCancelled(handler: (DialogInterface) -> Unit) {
builder.setOnCancelListener(handler)
}
override fun onKeyPressed(handler: (dialog: DialogInterface, keyCode: Int, e: KeyEvent) -> Boolean) {
builder.setOnKeyListener(handler)
}
override fun positiveButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setPositiveButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun positiveButton(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setPositiveButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun negativeButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNegativeButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun negativeButton(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNegativeButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun neutralPressed(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNeutralButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun neutralPressed(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNeutralButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun items(items: List<CharSequence>, onItemSelected: (dialog: DialogInterface, index: Int) -> Unit) {
builder.setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
onItemSelected(dialog, which)
}
}
override fun <T> items(items: List<T>, onItemSelected: (dialog: DialogInterface, item: T, index: Int) -> Unit) {
builder.setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
onItemSelected(dialog, items[which], which)
}
}
override fun build(): AlertDialog = builder.create()
override fun show(): AlertDialog = builder.show()
} | anko/library/static/appcompatV7/src/SupportAlertBuilder.kt | 1146161473 |
/*
Copyright 2017-2020 Charles Korn.
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 batect.journeytests
import batect.journeytests.testutils.ApplicationRunner
import batect.journeytests.testutils.itCleansUpAllContainersItCreates
import batect.journeytests.testutils.itCleansUpAllNetworksItCreates
import batect.testutils.createForGroup
import batect.testutils.on
import batect.testutils.runBeforeGroup
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object SimpleTaskWithEnvironmentFromHostTest : Spek({
describe("a simple task with a task-level environment variable") {
val runner by createForGroup { ApplicationRunner("simple-task-with-environment-from-host") }
on("running that task") {
val result by runBeforeGroup { runner.runApplication(listOf("the-task"), mapOf("MESSAGE" to "This is some output from the environment variable")) }
it("prints the output from that task") {
assertThat(result.output, containsSubstring("This is some output from the environment variable\r\nThis is the default message\r\n"))
}
it("returns the exit code from that task") {
assertThat(result.exitCode, equalTo(123))
}
itCleansUpAllContainersItCreates { result }
itCleansUpAllNetworksItCreates { result }
}
}
})
| app/src/journeyTest/kotlin/batect/journeytests/SimpleTaskWithEnvironmentFromHostTest.kt | 216312402 |
package com.habitrpg.android.habitica.ui.fragments.social.challenges
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentRefreshRecyclerviewBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.adapter.social.ChallengesListViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.EmptyItem
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.utils.Action1
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.kotlin.Flowables
import javax.inject.Inject
import javax.inject.Named
class ChallengeListFragment : BaseFragment<FragmentRefreshRecyclerviewBinding>(), androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener {
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var userRepository: UserRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
override var binding: FragmentRefreshRecyclerviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRefreshRecyclerviewBinding {
return FragmentRefreshRecyclerviewBinding.inflate(inflater, container, false)
}
private var challengeAdapter: ChallengesListViewAdapter? = null
private var viewUserChallengesOnly: Boolean = false
private var nextPageToLoad = 0
private var loadedAllData = false
private var challenges: List<Challenge>? = null
private var filterGroups: MutableList<Group>? = null
private var filterOptions: ChallengeFilterOptions? = null
fun setViewUserChallengesOnly(only: Boolean) {
this.viewUserChallengesOnly = only
}
override fun onDestroy() {
challengeRepository.close()
super.onDestroy()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
challengeAdapter = ChallengesListViewAdapter(viewUserChallengesOnly, userId)
challengeAdapter?.getOpenDetailFragmentFlowable()?.subscribe({ openDetailFragment(it) }, RxErrorHandler.handleEmptyError())
?.let { compositeSubscription.add(it) }
binding?.refreshLayout?.setOnRefreshListener(this)
if (viewUserChallengesOnly) {
binding?.recyclerView?.emptyItem = EmptyItem(
getString(R.string.empty_challenge_list),
getString(R.string.empty_discover_description)
)
}
binding?.recyclerView?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.activity)
binding?.recyclerView?.adapter = challengeAdapter
if (!viewUserChallengesOnly) {
binding?.recyclerView?.setBackgroundResource(R.color.content_background)
}
compositeSubscription.add(
Flowables.combineLatest(socialRepository.getGroup(Group.TAVERN_ID), socialRepository.getUserGroups("guild")).subscribe(
{
this.filterGroups = mutableListOf()
filterGroups?.add(it.first)
filterGroups?.addAll(it.second)
},
RxErrorHandler.handleEmptyError()
)
)
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
challengeAdapter?.updateUnfilteredData(challenges)
loadLocalChallenges()
binding?.recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!recyclerView.canScrollVertically(1)) {
retrieveChallengesPage()
}
}
})
}
private fun openDetailFragment(challengeID: String) {
MainNavigationController.navigate(ChallengesOverviewFragmentDirections.openChallengeDetail(challengeID))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onRefresh() {
nextPageToLoad = 0
loadedAllData = false
retrieveChallengesPage(true)
}
private fun setRefreshing(state: Boolean) {
binding?.refreshLayout?.isRefreshing = state
}
private fun loadLocalChallenges() {
val observable: Flowable<out List<Challenge>> = if (viewUserChallengesOnly) {
challengeRepository.getUserChallenges()
} else {
challengeRepository.getChallenges()
}
compositeSubscription.add(
observable.subscribe(
{ challenges ->
if (challenges.size == 0) {
retrieveChallengesPage()
}
this.challenges = challenges
challengeAdapter?.updateUnfilteredData(challenges)
},
RxErrorHandler.handleEmptyError()
)
)
}
internal fun retrieveChallengesPage(forced: Boolean = false) {
if ((!forced && binding?.refreshLayout?.isRefreshing == true) || loadedAllData || !this::challengeRepository.isInitialized) {
return
}
setRefreshing(true)
compositeSubscription.add(
challengeRepository.retrieveChallenges(nextPageToLoad, viewUserChallengesOnly).doOnComplete {
setRefreshing(false)
}.subscribe(
{
if (it.size < 10) {
loadedAllData = true
}
nextPageToLoad += 1
},
RxErrorHandler.handleEmptyError()
)
)
}
internal fun showFilterDialog() {
activity?.let {
ChallengeFilterDialogHolder.showDialog(
it,
filterGroups ?: emptyList(),
filterOptions,
object : Action1<ChallengeFilterOptions> {
override fun call(t: ChallengeFilterOptions) {
changeFilter(t)
}
}
)
}
}
private fun changeFilter(challengeFilterOptions: ChallengeFilterOptions) {
filterOptions = challengeFilterOptions
challengeAdapter?.filter(challengeFilterOptions)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/challenges/ChallengeListFragment.kt | 1889117688 |
package app.cash.paparazzi.agent
import net.bytebuddy.agent.ByteBuddyAgent
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
class InterceptorRegistrarTest {
@Before
fun setup() {
InterceptorRegistrar.addMethodInterceptors(
Utils::class.java,
setOf(
"log1" to Interceptor1::class.java,
"log2" to Interceptor2::class.java
)
)
ByteBuddyAgent.install()
InterceptorRegistrar.registerMethodInterceptors()
}
@Test
fun test() {
Utils.log1()
Utils.log2()
assertThat(logs).containsExactly("intercept1", "intercept2")
}
@After
fun teardown() {
InterceptorRegistrar.clearMethodInterceptors()
}
object Utils {
fun log1() {
logs += "original1"
}
fun log2() {
logs += "original2"
}
}
object Interceptor1 {
@Suppress("unused")
@JvmStatic
fun intercept() {
logs += "intercept1"
}
}
object Interceptor2 {
@Suppress("unused")
@JvmStatic
fun intercept() {
logs += "intercept2"
}
}
companion object {
private val logs = mutableListOf<String>()
}
}
| external/paparazzi/paparazzi-agent/src/test/java/app/cash/paparazzi/agent/InterceptorRegistrarTest.kt | 3340393969 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.platform.client.impl
import androidx.health.platform.client.error.ErrorStatus
import androidx.health.platform.client.impl.error.toException
import androidx.health.platform.client.response.InsertDataResponse
import androidx.health.platform.client.service.IInsertDataCallback
import com.google.common.util.concurrent.SettableFuture
/** Wrapper to convert [IInsertDataCallback] to listenable futures. */
internal class InsertDataCallback(private val resultFuture: SettableFuture<List<String>>) :
IInsertDataCallback.Stub() {
override fun onSuccess(response: InsertDataResponse) {
resultFuture.set(response.dataPointUids)
}
override fun onError(error: ErrorStatus) {
resultFuture.setException(error.toException())
}
}
| health/connect/connect-client/src/main/java/androidx/health/platform/client/impl/InsertDataCallback.kt | 505553003 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.services.client.data
import androidx.annotation.RestrictTo
import androidx.health.services.client.proto.DataProto
/** Exercise type used to configure sensors and algorithms. */
public class ExerciseType @RestrictTo(RestrictTo.Scope.LIBRARY) public constructor(
/** Returns a unique identifier of for the [ExerciseType], as an `int`. */
public val id: Int,
/** Returns a human readable name to represent this [ExerciseType]. */
public val name: String
) {
override fun toString(): String {
return name
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExerciseType) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public fun toProto(): DataProto.ExerciseType =
DataProto.ExerciseType.forNumber(id) ?: DataProto.ExerciseType.EXERCISE_TYPE_UNKNOWN
public companion object {
// Next ID: 93
/** The current exercise type of the user is unknown or not set. */
@JvmField public val UNKNOWN: ExerciseType = ExerciseType(0, "UNKNOWN")
@JvmField public val ALPINE_SKIING: ExerciseType = ExerciseType(92, "ALPINE_SKIING")
@JvmField public val BACKPACKING: ExerciseType = ExerciseType(84, "BACKPACKING")
@JvmField public val BACK_EXTENSION: ExerciseType = ExerciseType(1, "BACK_EXTENSION")
@JvmField public val BADMINTON: ExerciseType = ExerciseType(2, "BADMINTON")
@JvmField
public val BARBELL_SHOULDER_PRESS: ExerciseType = ExerciseType(3, "BARBELL_SHOULDER_PRESS")
@JvmField public val BASEBALL: ExerciseType = ExerciseType(4, "BASEBALL")
@JvmField public val BASKETBALL: ExerciseType = ExerciseType(5, "BASKETBALL")
@JvmField public val BENCH_PRESS: ExerciseType = ExerciseType(6, "BENCH_PRESS")
@JvmField internal val BENCH_SIT_UP: ExerciseType = ExerciseType(7, "BENCH_SIT_UP")
@JvmField public val BIKING: ExerciseType = ExerciseType(8, "BIKING")
@JvmField public val BIKING_STATIONARY: ExerciseType = ExerciseType(9, "BIKING_STATIONARY")
@JvmField public val BOOT_CAMP: ExerciseType = ExerciseType(10, "BOOT_CAMP")
@JvmField public val BOXING: ExerciseType = ExerciseType(11, "BOXING")
@JvmField public val BURPEE: ExerciseType = ExerciseType(12, "BURPEE")
/** Calisthenics (E.g., push ups, sit ups, pull-ups, jumping jacks). */
@JvmField public val CALISTHENICS: ExerciseType = ExerciseType(13, "CALISTHENICS")
@JvmField public val CRICKET: ExerciseType = ExerciseType(14, "CRICKET")
@JvmField
public val CROSS_COUNTRY_SKIING: ExerciseType = ExerciseType(91, "CROSS_COUNTRY_SKIING")
@JvmField public val CRUNCH: ExerciseType = ExerciseType(15, "CRUNCH")
@JvmField public val DANCING: ExerciseType = ExerciseType(16, "DANCING")
@JvmField public val DEADLIFT: ExerciseType = ExerciseType(17, "DEADLIFT")
@JvmField
internal val DUMBBELL_CURL_RIGHT_ARM: ExerciseType =
ExerciseType(18, "DUMBBELL_CURL_RIGHT_ARM")
@JvmField
internal val DUMBBELL_CURL_LEFT_ARM: ExerciseType =
ExerciseType(19, "DUMBBELL_CURL_LEFT_ARM")
@JvmField
internal val DUMBBELL_FRONT_RAISE: ExerciseType = ExerciseType(20, "DUMBBELL_FRONT_RAISE")
@JvmField
internal val DUMBBELL_LATERAL_RAISE: ExerciseType =
ExerciseType(21, "DUMBBELL_LATERAL_RAISE")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM: ExerciseType =
ExerciseType(22, "DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM: ExerciseType =
ExerciseType(23, "DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_TWO_ARM: ExerciseType =
ExerciseType(24, "DUMBBELL_TRICEPS_EXTENSION_TWO_ARM")
@JvmField public val ELLIPTICAL: ExerciseType = ExerciseType(25, "ELLIPTICAL")
@JvmField public val EXERCISE_CLASS: ExerciseType = ExerciseType(26, "EXERCISE_CLASS")
@JvmField public val FENCING: ExerciseType = ExerciseType(27, "FENCING")
@JvmField public val FRISBEE_DISC: ExerciseType = ExerciseType(28, "FRISBEE_DISC")
@JvmField public val FOOTBALL_AMERICAN: ExerciseType = ExerciseType(29, "FOOTBALL_AMERICAN")
@JvmField
public val FOOTBALL_AUSTRALIAN: ExerciseType = ExerciseType(30, "FOOTBALL_AUSTRALIAN")
@JvmField public val FORWARD_TWIST: ExerciseType = ExerciseType(31, "FORWARD_TWIST")
@JvmField public val GOLF: ExerciseType = ExerciseType(32, "GOLF")
@JvmField public val GUIDED_BREATHING: ExerciseType = ExerciseType(33, "GUIDED_BREATHING")
@JvmField public val HORSE_RIDING: ExerciseType = ExerciseType(88, "HORSE_RIDING")
@JvmField public val GYMNASTICS: ExerciseType = ExerciseType(34, "GYMNASTICS")
@JvmField public val HANDBALL: ExerciseType = ExerciseType(35, "HANDBALL")
@JvmField
public val HIGH_INTENSITY_INTERVAL_TRAINING: ExerciseType =
ExerciseType(36, "HIGH_INTENSITY_INTERVAL_TRAINING")
@JvmField public val HIKING: ExerciseType = ExerciseType(37, "HIKING")
@JvmField public val ICE_HOCKEY: ExerciseType = ExerciseType(38, "ICE_HOCKEY")
@JvmField public val ICE_SKATING: ExerciseType = ExerciseType(39, "ICE_SKATING")
@JvmField public val INLINE_SKATING: ExerciseType = ExerciseType(87, "INLINE_SKATING")
@JvmField public val JUMP_ROPE: ExerciseType = ExerciseType(40, "JUMP_ROPE")
@JvmField public val JUMPING_JACK: ExerciseType = ExerciseType(41, "JUMPING_JACK")
@JvmField public val LAT_PULL_DOWN: ExerciseType = ExerciseType(42, "LAT_PULL_DOWN")
@JvmField public val LUNGE: ExerciseType = ExerciseType(43, "LUNGE")
@JvmField public val MARTIAL_ARTS: ExerciseType = ExerciseType(44, "MARTIAL_ARTS")
@JvmField public val MEDITATION: ExerciseType = ExerciseType(45, "MEDITATION")
@JvmField public val MOUNTAIN_BIKING: ExerciseType = ExerciseType(85, "MOUNTAIN_BIKING")
@JvmField public val ORIENTEERING: ExerciseType = ExerciseType(86, "ORIENTEERING")
@JvmField public val PADDLING: ExerciseType = ExerciseType(46, "PADDLING")
@JvmField public val PARA_GLIDING: ExerciseType = ExerciseType(47, "PARA_GLIDING")
@JvmField public val PILATES: ExerciseType = ExerciseType(48, "PILATES")
@JvmField public val PLANK: ExerciseType = ExerciseType(49, "PLANK")
@JvmField public val RACQUETBALL: ExerciseType = ExerciseType(50, "RACQUETBALL")
@JvmField public val ROCK_CLIMBING: ExerciseType = ExerciseType(51, "ROCK_CLIMBING")
@JvmField public val ROLLER_HOCKEY: ExerciseType = ExerciseType(52, "ROLLER_HOCKEY")
@JvmField public val ROLLER_SKATING: ExerciseType = ExerciseType(89, "ROLLER_SKATING")
@JvmField public val ROWING: ExerciseType = ExerciseType(53, "ROWING")
@JvmField public val ROWING_MACHINE: ExerciseType = ExerciseType(54, "ROWING_MACHINE")
@JvmField public val RUNNING: ExerciseType = ExerciseType(55, "RUNNING")
@JvmField public val RUNNING_TREADMILL: ExerciseType = ExerciseType(56, "RUNNING_TREADMILL")
@JvmField public val RUGBY: ExerciseType = ExerciseType(57, "RUGBY")
@JvmField public val SAILING: ExerciseType = ExerciseType(58, "SAILING")
@JvmField public val SCUBA_DIVING: ExerciseType = ExerciseType(59, "SCUBA_DIVING")
@JvmField public val SKATING: ExerciseType = ExerciseType(60, "SKATING")
@JvmField public val SKIING: ExerciseType = ExerciseType(61, "SKIING")
@JvmField public val SNOWBOARDING: ExerciseType = ExerciseType(62, "SNOWBOARDING")
@JvmField public val SNOWSHOEING: ExerciseType = ExerciseType(63, "SNOWSHOEING")
@JvmField public val SOCCER: ExerciseType = ExerciseType(64, "SOCCER")
@JvmField public val SOFTBALL: ExerciseType = ExerciseType(65, "SOFTBALL")
@JvmField public val SQUASH: ExerciseType = ExerciseType(66, "SQUASH")
@JvmField public val SQUAT: ExerciseType = ExerciseType(67, "SQUAT")
@JvmField public val STAIR_CLIMBING: ExerciseType = ExerciseType(68, "STAIR_CLIMBING")
@JvmField
public val STAIR_CLIMBING_MACHINE: ExerciseType = ExerciseType(69, "STAIR_CLIMBING_MACHINE")
@JvmField public val STRENGTH_TRAINING: ExerciseType = ExerciseType(70, "STRENGTH_TRAINING")
@JvmField public val STRETCHING: ExerciseType = ExerciseType(71, "STRETCHING")
@JvmField public val SURFING: ExerciseType = ExerciseType(72, "SURFING")
@JvmField
public val SWIMMING_OPEN_WATER: ExerciseType = ExerciseType(73, "SWIMMING_OPEN_WATER")
@JvmField public val SWIMMING_POOL: ExerciseType = ExerciseType(74, "SWIMMING_POOL")
@JvmField public val TABLE_TENNIS: ExerciseType = ExerciseType(75, "TABLE_TENNIS")
@JvmField public val TENNIS: ExerciseType = ExerciseType(76, "TENNIS")
@JvmField public val UPPER_TWIST: ExerciseType = ExerciseType(77, "UPPER_TWIST")
@JvmField public val VOLLEYBALL: ExerciseType = ExerciseType(78, "VOLLEYBALL")
@JvmField public val WALKING: ExerciseType = ExerciseType(79, "WALKING")
@JvmField public val WATER_POLO: ExerciseType = ExerciseType(80, "WATER_POLO")
@JvmField public val WEIGHTLIFTING: ExerciseType = ExerciseType(81, "WEIGHTLIFTING")
@JvmField public val WORKOUT: ExerciseType = ExerciseType(82, "WORKOUT")
@JvmField public val YACHTING: ExerciseType = ExerciseType(90, "YACHTING")
@JvmField public val YOGA: ExerciseType = ExerciseType(83, "YOGA")
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
public val VALUES: List<ExerciseType> =
listOf(
UNKNOWN,
ALPINE_SKIING,
BACKPACKING,
BACK_EXTENSION,
BADMINTON,
BARBELL_SHOULDER_PRESS,
BASEBALL,
BASKETBALL,
BENCH_PRESS,
BENCH_SIT_UP,
BIKING,
BIKING_STATIONARY,
BOOT_CAMP,
BOXING,
BURPEE,
CALISTHENICS,
CRICKET,
CROSS_COUNTRY_SKIING,
CRUNCH,
DANCING,
DEADLIFT,
DUMBBELL_CURL_RIGHT_ARM,
DUMBBELL_CURL_LEFT_ARM,
DUMBBELL_FRONT_RAISE,
DUMBBELL_LATERAL_RAISE,
DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM,
DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM,
DUMBBELL_TRICEPS_EXTENSION_TWO_ARM,
ELLIPTICAL,
EXERCISE_CLASS,
FENCING,
FRISBEE_DISC,
FOOTBALL_AMERICAN,
FOOTBALL_AUSTRALIAN,
FORWARD_TWIST,
GOLF,
GUIDED_BREATHING,
HORSE_RIDING,
GYMNASTICS,
HANDBALL,
HIGH_INTENSITY_INTERVAL_TRAINING,
HIKING,
ICE_HOCKEY,
ICE_SKATING,
INLINE_SKATING,
JUMP_ROPE,
JUMPING_JACK,
LAT_PULL_DOWN,
LUNGE,
MARTIAL_ARTS,
MEDITATION,
MOUNTAIN_BIKING,
ORIENTEERING,
PADDLING,
PARA_GLIDING,
PILATES,
PLANK,
RACQUETBALL,
ROCK_CLIMBING,
ROLLER_HOCKEY,
ROLLER_SKATING,
ROWING,
ROWING_MACHINE,
RUNNING,
RUNNING_TREADMILL,
RUGBY,
SAILING,
SCUBA_DIVING,
SKATING,
SKIING,
SNOWBOARDING,
SNOWSHOEING,
SOCCER,
SOFTBALL,
SQUASH,
SQUAT,
STAIR_CLIMBING,
STAIR_CLIMBING_MACHINE,
STRENGTH_TRAINING,
STRETCHING,
SURFING,
SWIMMING_OPEN_WATER,
SWIMMING_POOL,
TABLE_TENNIS,
TENNIS,
UPPER_TWIST,
VOLLEYBALL,
WALKING,
WATER_POLO,
WEIGHTLIFTING,
WORKOUT,
YACHTING,
YOGA,
)
private val IDS = VALUES.map { it.id to it }.toMap()
/**
* Returns the [ExerciseType] based on its unique `id`.
*
* If the `id` doesn't map to an particular [ExerciseType], then [ExerciseType.UNKNOWN] is
* returned by default.
*/
@JvmStatic
public fun fromId(id: Int): ExerciseType {
val exerciseType = IDS[id]
return exerciseType ?: UNKNOWN
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public fun fromProto(proto: DataProto.ExerciseType): ExerciseType = fromId(proto.number)
}
}
| health/health-services-client/src/main/java/androidx/health/services/client/data/ExerciseType.kt | 2734121978 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.animation.core.AnimationConstants.DefaultDurationMillis
import androidx.compose.animation.core.internal.JvmDefaultWithCompatibility
/**
* [FloatAnimationSpec] interface is similar to [VectorizedAnimationSpec], except it deals
* exclusively with floats.
*
* Like [VectorizedAnimationSpec], [FloatAnimationSpec] is entirely stateless as well. It requires
* start/end values and start velocity to be passed in for the query of velocity and value of the
* animation. The [FloatAnimationSpec] itself stores only the animation configuration (such as the
* delay, duration and easing curve for [FloatTweenSpec], or spring constants for
* [FloatSpringSpec].
*
* A [FloatAnimationSpec] can be converted to an [VectorizedAnimationSpec] using [vectorize].
*
* @see [VectorizedAnimationSpec]
*/
@JvmDefaultWithCompatibility
interface FloatAnimationSpec : AnimationSpec<Float> {
/**
* Calculates the value of the animation at given the playtime, with the provided start/end
* values, and start velocity.
*
* @param playTimeNanos time since the start of the animation
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float
/**
* Calculates the velocity of the animation at given the playtime, with the provided start/end
* values, and start velocity.
*
* @param playTimeNanos time since the start of the animation
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float
/**
* Calculates the end velocity of the animation with the provided start/end values, and start
* velocity. For duration-based animations, end velocity will be the velocity of the
* animation at the duration time. This is also the default assumption. However, for
* spring animations, the transient trailing velocity will be snapped to zero.
*
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getEndVelocity(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float =
getVelocityFromNanos(
getDurationNanos(initialValue, targetValue, initialVelocity),
initialValue,
targetValue,
initialVelocity
)
/**
* Calculates the duration of an animation. For duration-based animations, this will return the
* pre-defined duration. For physics-based animations, the duration will be estimated based on
* the physics configuration (such as spring stiffness, damping ratio, visibility threshold)
* as well as the [initialValue], [targetValue] values, and [initialVelocity].
*
* __Note__: this may be a computation that is expensive - especially with spring based
* animations
*
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
@Suppress("MethodNameUnits")
fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long
/**
* Create an [VectorizedAnimationSpec] that animates [AnimationVector] from a [FloatAnimationSpec]. Every
* dimension of the [AnimationVector] will be animated using the given [FloatAnimationSpec].
*/
override fun <V : AnimationVector> vectorize(converter: TwoWayConverter<Float, V>) =
VectorizedFloatAnimationSpec<V>(this)
}
/**
* [FloatSpringSpec] animation uses a spring animation to animate a [Float] value. Its
* configuration can be tuned via adjusting the spring parameters, namely damping ratio and
* stiffness.
*
* @param dampingRatio damping ratio of the spring. Defaults to [Spring.DampingRatioNoBouncy]
* @param stiffness Stiffness of the spring. Defaults to [Spring.StiffnessMedium]
* @param visibilityThreshold The value threshold such that the animation is no longer
* significant. e.g. 1px for translation animations. Defaults to
* [Spring.DefaultDisplacementThreshold]
*/
class FloatSpringSpec(
val dampingRatio: Float = Spring.DampingRatioNoBouncy,
val stiffness: Float = Spring.StiffnessMedium,
private val visibilityThreshold: Float = Spring.DefaultDisplacementThreshold
) : FloatAnimationSpec {
private val spring = SpringSimulation(1f).also {
it.dampingRatio = dampingRatio
it.stiffness = stiffness
}
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the spring impl
val playTimeMillis = playTimeNanos / MillisToNanos
spring.finalPosition = targetValue
val value = spring.updateValues(initialValue, initialVelocity, playTimeMillis).value
return value
}
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the spring impl
val playTimeMillis = playTimeNanos / MillisToNanos
spring.finalPosition = targetValue
val velocity = spring.updateValues(initialValue, initialVelocity, playTimeMillis).velocity
return velocity
}
override fun getEndVelocity(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float = 0f
@Suppress("MethodNameUnits")
override fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long =
estimateAnimationDurationMillis(
stiffness = spring.stiffness,
dampingRatio = spring.dampingRatio,
initialDisplacement = (initialValue - targetValue) / visibilityThreshold,
initialVelocity = initialVelocity / visibilityThreshold,
delta = 1f
) * MillisToNanos
}
/**
* [FloatTweenSpec] animates a Float value from any start value to any end value using a provided
* [easing] function. The animation will finish within the [duration] time. Unless a [delay] is
* specified, the animation will start right away.
*
* @param duration the amount of time (in milliseconds) the animation will take to finish.
* Defaults to [DefaultDuration]
* @param delay the amount of time the animation will wait before it starts running. Defaults to 0.
* @param easing the easing function that will be used to interoplate between the start and end
* value of the animation. Defaults to [FastOutSlowInEasing].
*/
class FloatTweenSpec(
val duration: Int = DefaultDurationMillis,
val delay: Int = 0,
private val easing: Easing = FastOutSlowInEasing
) : FloatAnimationSpec {
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the impl
val playTimeMillis = playTimeNanos / MillisToNanos
val clampedPlayTime = clampPlayTime(playTimeMillis)
val rawFraction = if (duration == 0) 1f else clampedPlayTime / duration.toFloat()
val fraction = easing.transform(rawFraction.coerceIn(0f, 1f))
return lerp(initialValue, targetValue, fraction)
}
private fun clampPlayTime(playTime: Long): Long {
return (playTime - delay).coerceIn(0, duration.toLong())
}
@Suppress("MethodNameUnits")
override fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long {
return (delay + duration) * MillisToNanos
}
// Calculate velocity by difference between the current value and the value 1 ms ago. This is a
// preliminary way of calculating velocity used by easing curve based animations, and keyframe
// animations. Physics-based animations give a much more accurate velocity.
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the impl
val playTimeMillis = playTimeNanos / MillisToNanos
val clampedPlayTime = clampPlayTime(playTimeMillis)
if (clampedPlayTime < 0) {
return 0f
} else if (clampedPlayTime == 0L) {
return initialVelocity
}
val startNum = getValueFromNanos(
(clampedPlayTime - 1) * MillisToNanos,
initialValue,
targetValue,
initialVelocity
)
val endNum = getValueFromNanos(
clampedPlayTime * MillisToNanos,
initialValue,
targetValue,
initialVelocity
)
return (endNum - startNum) * 1000f
}
}
| compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/FloatAnimationSpec.kt | 3334725650 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Removes the KT class from the public API */
@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
package androidx.wear.watchface.complications
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.graphics.RectF
import android.util.TypedValue
import androidx.annotation.RestrictTo
import androidx.wear.watchface.complications.data.ComplicationType
import java.io.DataOutputStream
const val NAMESPACE_APP = "http://schemas.android.com/apk/res-auto"
const val NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"
/**
* ComplicationSlotBounds are defined by fractional screen space coordinates in unit-square [0..1].
* These bounds will be subsequently clamped to the unit square and converted to screen space
* coordinates. NB 0 and 1 are included in the unit square.
*
* One bound is expected per [ComplicationType] to allow [androidx.wear.watchface.ComplicationSlot]s
* to change shape depending on the type.
*
* Taps on the watch are tested first against each ComplicationSlot's [perComplicationTypeBounds]
* for the relevant [ComplicationType]. Its assumed that [perComplicationTypeBounds] don't overlap.
* If no intersection was found then taps are checked against [perComplicationTypeBounds] expanded
* by [perComplicationTypeMargins]. Expanded bounds can overlap so the ComplicationSlot with the
* lowest id that intersects the coordinates, if any, is selected.
*
* @param perComplicationTypeBounds Per [ComplicationType] fractional unit-square screen space
* complication bounds.
* @param perComplicationTypeMargins Per [ComplicationType] fractional unit-square screen space
* complication margins for tap detection (doesn't affect rendering).
*/
public class ComplicationSlotBounds(
public val perComplicationTypeBounds: Map<ComplicationType, RectF>,
public val perComplicationTypeMargins: Map<ComplicationType, RectF>
) {
@Deprecated(
"Use a constructor that specifies perComplicationTypeMargins",
ReplaceWith(
"ComplicationSlotBounds(Map<ComplicationType, RectF>, Map<ComplicationType, RectF>)"
)
)
constructor(perComplicationTypeBounds: Map<ComplicationType, RectF>) : this(
perComplicationTypeBounds,
perComplicationTypeBounds.mapValues { RectF() }
)
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun write(dos: DataOutputStream) {
perComplicationTypeBounds.keys.toSortedSet().forEach { type ->
dos.writeInt(type.toWireComplicationType())
perComplicationTypeBounds[type]!!.write(dos)
perComplicationTypeMargins[type]!!.write(dos)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ComplicationSlotBounds
if (perComplicationTypeBounds != other.perComplicationTypeBounds) return false
return perComplicationTypeMargins == other.perComplicationTypeMargins
}
override fun hashCode(): Int {
var result = perComplicationTypeBounds.toSortedMap().hashCode()
result = 31 * result + perComplicationTypeMargins.toSortedMap().hashCode()
return result
}
override fun toString(): String {
return "ComplicationSlotBounds(perComplicationTypeBounds=$perComplicationTypeBounds, " +
"perComplicationTypeMargins=$perComplicationTypeMargins)"
}
/**
* Constructs a ComplicationSlotBounds where all complication types have the same screen space
* unit-square [bounds] and [margins].
*/
@JvmOverloads
public constructor(
bounds: RectF,
margins: RectF = RectF()
) : this(
ComplicationType.values().associateWith { bounds },
ComplicationType.values().associateWith { margins }
)
init {
require(perComplicationTypeBounds.size == ComplicationType.values().size) {
"perComplicationTypeBounds must contain entries for each ComplicationType"
}
require(perComplicationTypeMargins.size == ComplicationType.values().size) {
"perComplicationTypeMargins must contain entries for each ComplicationType"
}
for (type in ComplicationType.values()) {
require(perComplicationTypeBounds.containsKey(type)) {
"Missing bounds for $type"
}
require(perComplicationTypeMargins.containsKey(type)) {
"Missing margins for $type"
}
}
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
internal const val NODE_NAME = "ComplicationSlotBounds"
/**
* Constructs a [ComplicationSlotBounds] from a potentially incomplete
* Map<ComplicationType, RectF>, backfilling with empty [RectF]s. This method is necessary
* because there can be a skew between the version of the library between the watch face and
* the system which would otherwise be problematic if new complication types have been
* introduced.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun createFromPartialMap(
partialPerComplicationTypeBounds: Map<ComplicationType, RectF>,
partialPerComplicationTypeMargins: Map<ComplicationType, RectF>
): ComplicationSlotBounds {
val boundsMap = HashMap(partialPerComplicationTypeBounds)
val marginsMap = HashMap(partialPerComplicationTypeMargins)
for (type in ComplicationType.values()) {
boundsMap.putIfAbsent(type, RectF())
marginsMap.putIfAbsent(type, RectF())
}
return ComplicationSlotBounds(boundsMap, marginsMap)
}
/**
* The [parser] should be inside a node with any number of ComplicationSlotBounds child
* nodes. No other child nodes are expected.
*/
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotBounds? {
val perComplicationTypeBounds by lazy { HashMap<ComplicationType, RectF>() }
val perComplicationTypeMargins by lazy { HashMap<ComplicationType, RectF>() }
parser.iterate {
when (parser.name) {
NODE_NAME -> {
val rect = if (parser.hasValue("left"))
RectF(
parser.requireAndGet("left", resources, complicationScaleX),
parser.requireAndGet("top", resources, complicationScaleY),
parser.requireAndGet("right", resources, complicationScaleX),
parser.requireAndGet("bottom", resources, complicationScaleY)
)
else if (parser.hasValue("center_x")) {
val halfWidth =
parser.requireAndGet("size_x", resources, complicationScaleX) / 2.0f
val halfHeight =
parser.requireAndGet("size_y", resources, complicationScaleY) / 2.0f
val centerX =
parser.requireAndGet("center_x", resources, complicationScaleX)
val centerY =
parser.requireAndGet("center_y", resources, complicationScaleY)
RectF(
centerX - halfWidth,
centerY - halfHeight,
centerX + halfWidth,
centerY + halfHeight
)
} else {
throw IllegalArgumentException("$NODE_NAME must " +
"either define top, bottom, left, right" +
"or center_x, center_y, size_x, size_y should be specified")
}
val margin = RectF(
parser.get("marginLeft", resources, complicationScaleX) ?: 0f,
parser.get("marginTop", resources, complicationScaleY) ?: 0f,
parser.get("marginRight", resources, complicationScaleX) ?: 0f,
parser.get("marginBottom", resources, complicationScaleY) ?: 0f
)
if (null != parser.getAttributeValue(
NAMESPACE_APP,
"complicationType"
)
) {
val complicationType = ComplicationType.fromWireType(
parser.getAttributeIntValue(
NAMESPACE_APP,
"complicationType",
0
)
)
require(
!perComplicationTypeBounds.contains(complicationType)
) {
"Duplicate $complicationType"
}
perComplicationTypeBounds[complicationType] = rect
perComplicationTypeMargins[complicationType] = margin
} else {
for (complicationType in ComplicationType.values()) {
require(
!perComplicationTypeBounds.contains(
complicationType
)
) {
"Duplicate $complicationType"
}
perComplicationTypeBounds[complicationType] = rect
perComplicationTypeMargins[complicationType] = margin
}
}
}
else -> throw IllegalNodeException(parser)
}
}
return if (perComplicationTypeBounds.isEmpty()) {
null
} else {
createFromPartialMap(perComplicationTypeBounds, perComplicationTypeMargins)
}
}
}
}
internal fun XmlResourceParser.requireAndGet(
id: String,
resources: Resources,
scale: Float
): Float {
val value = get(id, resources, scale)
require(value != null) {
"${ComplicationSlotBounds.NODE_NAME} must define '$id'"
}
return value
}
internal fun XmlResourceParser.get(
id: String,
resources: Resources,
scale: Float
): Float? {
val stringValue = getAttributeValue(NAMESPACE_APP, id) ?: return null
val resId = getAttributeResourceValue(NAMESPACE_APP, id, 0)
if (resId != 0) {
return resources.getDimension(resId) / resources.displayMetrics.widthPixels
}
// There is "dp" -> "dip" conversion while resources compilation.
val dpStr = "dip"
if (stringValue.endsWith(dpStr)) {
val dps = stringValue.substring(0, stringValue.length - dpStr.length).toFloat()
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dps,
resources.displayMetrics
) / resources.displayMetrics.widthPixels
} else {
require(scale > 0) { "scale should be positive" }
return stringValue.toFloat() / scale
}
}
fun XmlResourceParser.hasValue(id: String): Boolean {
return null != getAttributeValue(NAMESPACE_APP, id)
}
internal fun RectF.write(dos: DataOutputStream) {
dos.writeFloat(left)
dos.writeFloat(right)
dos.writeFloat(top)
dos.writeFloat(bottom)
} | wear/watchface/watchface-complications/src/main/java/androidx/wear/watchface/complications/ComplicationSlotBounds.kt | 3109341685 |
/*
* SimpleItemPresenter.kt
*
* Copyright (C) 2017 Retrograde Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.retrograde.lib.ui
import android.content.Context
import android.content.res.Resources
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.leanback.widget.ImageCardView
import androidx.leanback.widget.Presenter
import com.codebutler.retrograde.lib.R
sealed class TextOrResource {
class Text(val value: String) : TextOrResource()
class Resource(@StringRes val value: Int) : TextOrResource()
fun getText(resources: Resources): String = when (this) {
is Text -> value
is Resource -> resources.getString(value)
}
}
open class SimpleItem private constructor (val title: TextOrResource, @DrawableRes val image: Int?) {
constructor(text: String, @DrawableRes image: Int? = 0) : this(TextOrResource.Text(text), image)
constructor(@StringRes resId: Int, @DrawableRes image: Int = 0) : this (TextOrResource.Resource(resId), image)
}
class SimpleItemPresenter(context: Context) : Presenter() {
private val themedContext = ContextThemeWrapper(context, R.style.SimpleImageCardTheme)
private var imageWidth: Int = -1
private var imageHeight: Int = -1
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder {
val cardView = ImageCardView(themedContext)
val res = cardView.resources
imageWidth = res.getDimensionPixelSize(R.dimen.card_width)
imageHeight = res.getDimensionPixelSize(R.dimen.card_height)
cardView.setMainImageScaleType(ImageView.ScaleType.CENTER)
cardView.isFocusable = true
cardView.isFocusableInTouchMode = true
cardView.setMainImageDimensions(imageWidth, imageHeight)
return Presenter.ViewHolder(cardView)
}
override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
when (item) {
is SimpleItem -> {
val resources = viewHolder.view.resources
val cardView = viewHolder.view as ImageCardView
cardView.titleText = item.title.getText(resources)
if (item.image != null && item.image != 0) {
cardView.mainImage = resources.getDrawable(item.image)
} else {
cardView.mainImage = null
}
}
}
}
override fun onUnbindViewHolder(viewHolder: ViewHolder?) { }
}
| retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/ui/SimpleItemPresenter.kt | 3957935673 |
/**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.graph
import com.gs.obevo.api.appdata.CodeDependencyType
import com.gs.obevo.api.platform.ChangeType
import org.eclipse.collections.api.tuple.Pair
import org.eclipse.collections.impl.tuple.Tuples
import org.jgrapht.Graph
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.slf4j.LoggerFactory
/**
* Created a graph out of the input changes, so that the graph can be shared by other components
*/
class GraphEnricherImpl(private val convertDbObjectName: Function1<String, String>) : GraphEnricher {
override fun <T : SortableDependencyGroup> createDependencyGraph(inputs: Iterable<T>, rollback: Boolean): Graph<T, DefaultEdge> {
val changeIndexes = listOf(
ObjectIndex(),
SchemaObjectIndex(),
ObjectChangeIndex<T>(),
SchemaChangeObjectIndex<T>()
)
changeIndexes.forEach { changeIndex -> inputs.forEach(changeIndex::add) }
val graph = DefaultDirectedGraph<T, DependencyEdge>(DependencyEdge::class.java)
// First - add the core objects to the graph
inputs.forEach { graph.addVertex(it) }
// Now add the declared dependencies to the graph
for (changeGroup in inputs) {
for (change in changeGroup.components) {
if (change.codeDependencies != null) {
for (dependency in change.codeDependencies) {
var dependencyVertex: T? = null
for (changeIndex in changeIndexes) {
dependencyVertex = changeIndex.retrieve(change.changeKey.objectKey.schema, dependency.target)
if (dependencyVertex != null) {
if (LOG.isTraceEnabled) {
LOG.trace("Discovered dependency from {} to {} using index {}",
dependencyVertex,
change.changeKey,
changeIndex)
}
break
}
}
if (dependencyVertex == null) {
LOG.trace("Dependency not found; likely due to not enriching the full graph in source. Should be OK to ignore: {} - {}", dependency, change)
} else {
graph.addEdge(dependencyVertex, changeGroup, DependencyEdge(dependency.codeDependencyType))
}
}
}
}
}
// Add in changes within incremental files to ensure proper order
val groupToComponentPairs = inputs.flatMap { group -> group.components.map { Pair(group, it) } }
val incrementalChangeByObjectMap = groupToComponentPairs.groupBy { pair ->
val tSortMetadata = pair.second
var changeType = tSortMetadata.changeKey.objectKey.changeType.name
if (changeType == ChangeType.TRIGGER_INCREMENTAL_OLD_STR || changeType == ChangeType.FOREIGN_KEY_STR) {
changeType = ChangeType.TABLE_STR
}
changeType + ":" + tSortMetadata.changeKey.objectKey.schema + ":" + convertDbObjectName(tSortMetadata.changeKey.objectKey.objectName)
}
incrementalChangeByObjectMap.values
.map { it.sortedBy { pair -> pair.second.orderWithinObject } }
.forEach { pair ->
pair.map { it.first }.zipWithNext().forEach { (each, nextChange) ->
// if rollback, then go from the next change to the previous
val fromVertex = if (rollback) nextChange else each
val toVertex = if (rollback) each else nextChange
graph.addEdge(fromVertex, toVertex, DependencyEdge(CodeDependencyType.IMPLICIT))
}
}
// validate
GraphUtil.validateNoCycles(graph,
{ vertex, target, edge ->
vertex.components
.map { sortableDependency ->
val name = if (target && edge.edgeType == CodeDependencyType.DISCOVERED)
sortableDependency.changeKey.objectKey.objectName
else sortableDependency.changeKey.objectKey.objectName + "." + sortableDependency.changeKey.changeName
"[$name]"
}
.joinToString(", ")
},
{ dependencyEdge -> dependencyEdge.edgeType.name }
)
return graph as Graph<T, DefaultEdge>
}
override fun <T> createSimpleDependencyGraph(inputs: Iterable<T>, edgesFunction: Function1<T, Iterable<T>>): Graph<T, DefaultEdge> {
val graph = DefaultDirectedGraph<T, DefaultEdge>(DefaultEdge::class.java)
inputs.forEach { graph.addVertex(it) }
inputs.forEach { input ->
val targetVertices = edgesFunction.invoke(input)
for (targetVertex in targetVertices) {
if (graph.containsVertex(targetVertex)) {
graph.addEdge(targetVertex, input)
} else {
LOG.info("Problem?")
}
}
}
return graph
}
private interface ChangeIndex<T> {
fun add(change: T)
fun retrieve(schema: String, dependency: String): T?
}
/**
* Looks for the given dependency/object
*/
private inner class ObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val schemaToObjectMap = mutableMapOf<Pair<String, String>, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
val existingChange = retrieve(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))
// TODO getFirst is not ideal here
if (existingChange == null || existingChange.components.first.orderWithinObject < change.orderWithinObject) {
// only keep the latest (why latest vs earliest?)
schemaToObjectMap[Tuples.pair(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))] = changeGroup
}
}
}
override fun retrieve(schema: String, dependency: String): T? {
return schemaToObjectMap[Tuples.pair(schema, convertDbObjectName(dependency))]
}
}
private inner class SchemaObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val objectMap = mutableMapOf<String, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
val existingChange = retrieve(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))
// TODO getFirst is not ideal here
if (existingChange == null || existingChange.components.first.orderWithinObject < change.orderWithinObject) {
// only keep the latest (why latest vs earliest?)
objectMap[convertDbObjectName(change.changeKey.objectKey.schema + "." + change.changeKey.objectKey.objectName)] = changeGroup
}
}
}
override fun retrieve(schema: String, dependency: String): T? {
return objectMap[convertDbObjectName(dependency)]
}
}
private inner class ObjectChangeIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val schemaToObjectMap = mutableMapOf<Pair<String, String>, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
schemaToObjectMap[Tuples.pair(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName + "." + change.changeKey.changeName))] = changeGroup
}
}
override fun retrieve(schema: String, dependency: String): T? {
return schemaToObjectMap[Tuples.pair(schema, convertDbObjectName(dependency))]
}
}
private inner class SchemaChangeObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val objectMap = mutableMapOf<String, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
objectMap[convertDbObjectName(change.changeKey.objectKey.schema + "." + change.changeKey.objectKey.objectName + "." + change.changeKey.changeName)] = changeGroup
}
}
override fun retrieve(schema: String, dependency: String): T? {
return objectMap[convertDbObjectName(dependency)]
}
}
/**
* Custom edge type to allow for better error logging for cycles, namely to show the dependency edge type.
*/
private class DependencyEdge internal constructor(internal val edgeType: CodeDependencyType) : DefaultEdge()
companion object {
private val LOG = LoggerFactory.getLogger(GraphEnricherImpl::class.java)
}
}
| obevo-core/src/main/java/com/gs/obevo/impl/graph/GraphEnricherImpl.kt | 1665754219 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_compressed_texture_pixel_storage = "ARBCompressedTexturePixelStorage".nativeClassGL("ARB_compressed_texture_pixel_storage") {
documentation =
"""
Native bindings to the $registryLink extension.
This extension expands the functionality of the GL11#PixelStorei() modes to allow GL11#UNPACK_ROW_LENGTH, GL11#UNPACK_SKIP_ROWS,
GL11#UNPACK_SKIP_PIXELS, GL12#UNPACK_IMAGE_HEIGHT and GL12#UNPACK_SKIP_IMAGES to affect the operation of CompressedTexImage*D and
CompressedTexSubImage*D. Similarly, it also allows GL11#PACK_ROW_LENGTH, GL11#PACK_SKIP_ROWS, GL11#PACK_SKIP_PIXELS, GL12#PACK_IMAGE_HEIGHT and
GL12#PACK_SKIP_IMAGES to affect the operation of GetCompressedTexImage*D. This allows data to be transferred to or from a specified sub-rectangle of a
larger compressed image.
This extension is designed primarily to support compressed image formats with fixed-size blocks. To use this new mechanism, an application should
program new parameters UNPACK_COMPRESSED_BLOCK_{WIDTH,HEIGHT,DEPTH,SIZE} to indicate the number of texels in each dimension of the fixed-size block as
well as the number of bytes consumed by each block. These parameters, in addition to the existing PixelStore parameters, are used to identify a
collection of bytes in client memory or a buffer object's data store to use as compressed texture data. This operation is unlikely to have the desired
results if the client programs a block size inconsistent with the underlying compressed image format, or if the compressed image format has
variable-sized blocks.
Requires ${GL21.core}. ${GL42.promoted}
"""
IntConstant(
"Accepted by the {@code pname} parameter of PixelStore[fi], GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev.",
"UNPACK_COMPRESSED_BLOCK_WIDTH"..0x9127,
"UNPACK_COMPRESSED_BLOCK_HEIGHT"..0x9128,
"UNPACK_COMPRESSED_BLOCK_DEPTH"..0x9129,
"UNPACK_COMPRESSED_BLOCK_SIZE"..0x912A,
"PACK_COMPRESSED_BLOCK_WIDTH"..0x912B,
"PACK_COMPRESSED_BLOCK_HEIGHT"..0x912C,
"PACK_COMPRESSED_BLOCK_DEPTH"..0x912D,
"PACK_COMPRESSED_BLOCK_SIZE"..0x912E
)
} | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_compressed_texture_pixel_storage.kt | 3389030942 |
/*
* Copyright (C) 2017 Glass Software Ltd
*
* 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 uk.co.glass_software.android.shared_preferences.demo.model
import uk.co.glass_software.android.shared_preferences.persistence.base.KeyValueStore
import uk.co.glass_software.android.shared_preferences.persistence.preferences.StoreEntry
class PersonEntry(store: KeyValueStore)
: StoreEntry<Person>(store, KEY, Person::class.java) {
companion object {
const val KEY = "person"
}
}
| app/src/main/java/uk/co/glass_software/android/shared_preferences/demo/model/PersonEntry.kt | 3327645930 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.tracer
/** A call tree, represented recursively. Also see [CallTreeUtil]. */
interface CallTree {
val tracepoint: Tracepoint
val callCount: Long
val wallTime: Long
val maxWallTime: Long
val children: Map<Tracepoint, CallTree>
fun forEachNodeInSubtree(action: (CallTree) -> Unit) {
action(this)
for (child in children.values) {
child.forEachNodeInSubtree(action)
}
}
fun allNodesInSubtree(): Sequence<CallTree> {
val nodes = mutableListOf<CallTree>()
forEachNodeInSubtree { nodes.add(it) }
return nodes.asSequence()
}
fun copy(): CallTree {
val copy = MutableCallTree(Tracepoint.ROOT)
copy.accumulate(this)
return copy
}
}
/** A mutable call tree implementation. */
class MutableCallTree(
override val tracepoint: Tracepoint
): CallTree {
override var callCount: Long = 0L
override var wallTime: Long = 0L
override var maxWallTime: Long = 0L
override val children: MutableMap<Tracepoint, MutableCallTree> = LinkedHashMap()
/** Accumulates the data from another call tree into this one. */
fun accumulate(other: CallTree) {
require(other.tracepoint == tracepoint) {
"Doesn't make sense to sum call tree nodes representing different tracepoints"
}
callCount += other.callCount
wallTime += other.wallTime
maxWallTime = maxOf(maxWallTime, other.maxWallTime)
for ((childTracepoint, otherChild) in other.children) {
val child = children.getOrPut(childTracepoint) { MutableCallTree(childTracepoint) }
child.accumulate(otherChild)
}
}
}
| src/main/java/com/google/idea/perf/tracer/CallTree.kt | 1102708960 |
package streetwalrus.usbmountr
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.preference.Preference
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.io.File
class FilePickerPreference : Preference, ActivityResultDispatcher.ActivityResultHandler {
val TAG = "FilePickerPreference"
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes)
private var mActivityResultId = -1
init {
val appContext = context.applicationContext as UsbMountrApplication
mActivityResultId = appContext.mActivityResultDispatcher.registerHandler(this)
}
override fun onCreateView(parent: ViewGroup?): View {
updateSummary()
return super.onCreateView(parent)
}
override fun onPrepareForRemoval() {
super.onPrepareForRemoval()
val appContext = context.applicationContext as UsbMountrApplication
appContext.mActivityResultDispatcher.removeHandler(mActivityResultId)
}
override fun onClick() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
val activity = context as Activity
activity.startActivityForResult(intent, mActivityResultId)
}
override fun onActivityResult(resultCode: Int, resultData: Intent?) {
if (resultCode == Activity.RESULT_OK && resultData != null) {
try {
val path = PathResolver.getPath(context, resultData.data)
Log.d(TAG, "Picked file $path")
persistString(path)
updateSummary()
} catch (e: SecurityException) {
// I'm extremely lazy and don't want to figure permissions out right now
Toast.makeText(context.applicationContext,
context.getString(R.string.file_picker_denied),
Toast.LENGTH_LONG
).show()
}
}
}
private fun updateSummary() {
val value = getPersistedString("")
if (value.equals("")) {
summary = context.getString(R.string.file_picker_nofile)
} else {
summary = File(value).name
}
}
} | app/src/main/java/streetwalrus/usbmountr/FilePickerPreference.kt | 1927256662 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.logger
enum class LogType {
DEBUG, INFO, WARNING, ERROR
}
| powermanager-base/src/main/java/com/pyamsoft/powermanager/base/logger/LogType.kt | 3968187073 |
package me.proxer.app.info.industry
import me.proxer.app.base.BaseContentViewModel
import me.proxer.library.api.Endpoint
import me.proxer.library.entity.info.Industry
/**
* @author Ruben Gees
*/
class IndustryInfoViewModel(private val industryId: String) : BaseContentViewModel<Industry>() {
override val endpoint: Endpoint<Industry>
get() = api.info.industry(industryId)
}
| src/main/kotlin/me/proxer/app/info/industry/IndustryInfoViewModel.kt | 2234497461 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.folding
import com.intellij.application.options.editor.CodeFoldingOptionsProvider
import com.intellij.openapi.options.BeanConfigurable
class MixinFoldingOptionsProvider :
BeanConfigurable<MixinFoldingSettings.State>(MixinFoldingSettings.instance.state), CodeFoldingOptionsProvider {
init {
title = "Mixin"
val settings = MixinFoldingSettings.instance
checkBox(
"Target descriptors",
{ settings.state.foldTargetDescriptors },
{ b -> settings.state.foldTargetDescriptors = b }
)
checkBox("Object casts", { settings.state.foldObjectCasts }, { b -> settings.state.foldObjectCasts = b })
checkBox(
"Invoker casts",
{ settings.state.foldInvokerCasts },
{ b -> settings.state.foldInvokerCasts = b }
)
checkBox(
"Invoker method calls",
{ settings.state.foldInvokerMethodCalls },
{ b -> settings.state.foldInvokerMethodCalls = b }
)
checkBox(
"Accessor casts",
{ settings.state.foldAccessorCasts },
{ b -> settings.state.foldAccessorCasts = b }
)
checkBox(
"Accessor method calls",
{ settings.state.foldAccessorMethodCalls },
{ b -> settings.state.foldAccessorMethodCalls = b }
)
}
}
| src/main/kotlin/platform/mixin/folding/MixinFoldingOptionsProvider.kt | 3408235158 |
package com.veyndan.paper.reddit.post.media.mutator
import com.veyndan.paper.reddit.post.media.model.Image
import com.veyndan.paper.reddit.post.model.Post
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
class ImgflipMutatorFactory : MutatorFactory {
companion object {
private val REGEX = Regex("""^https?://(?:www\.)?imgflip\.com/i/(.*)#.*$""")
}
override fun mutate(post: Post): Maybe<Post> {
val matchResult = REGEX.matchEntire(post.linkUrl)
return Single.just(post)
.filter { matchResult != null }
.map {
val directImageUrl: String = "https://i.imgflip.com/${matchResult!!.groupValues[1]}.jpg"
val image: Image = Image(directImageUrl)
it.copy(it.medias.concatWith(Observable.just(image)))
}
}
}
| app/src/main/java/com/veyndan/paper/reddit/post/media/mutator/ImgflipMutatorFactory.kt | 3401474879 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.openapi.util.Computable
import com.intellij.psi.stubs.StubElement
import com.tang.intellij.lua.ext.recursionGuard
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
/**
* func body owner stub
* Created by TangZX on 2017/2/4.
*/
interface LuaFuncBodyOwnerStub<T : LuaFuncBodyOwner> : StubElement<T> {
val returnDocTy:ITy?
val params: Array<LuaParamInfo>
val tyParams: Array<TyParameter>
val overloads: Array<IFunSignature>
val varargTy: ITy?
private fun walkStub(stub: StubElement<*>, context: SearchContext): ITy? {
val psi = stub.psi
return recursionGuard(stub, Computable {
val ty = when (psi) {
is LuaReturnStat -> {
psi.exprList?.guessTypeAt(context)
}
is LuaDoStat,
is LuaWhileStat,
is LuaIfStat,
is LuaForAStat,
is LuaForBStat,
is LuaRepeatStat -> {
var ret: ITy? = null
for (childrenStub in stub.childrenStubs) {
ret = walkStub(childrenStub, context)
if (ret != null)
break
}
ret
}
else -> null
}
ty
})
}
fun guessReturnTy(context: SearchContext): ITy {
val docTy = returnDocTy
if (docTy != null){
if (docTy is TyTuple && context.index != -1) {
return docTy.list.getOrElse(context.index) { Ty.UNKNOWN }
}
return docTy
}
childrenStubs
.mapNotNull { walkStub(it, context) }
.forEach { return it }
return Ty.VOID
}
} | src/main/java/com/tang/intellij/lua/stubs/LuaFuncBodyOwnerStub.kt | 3434180248 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin
import com.google.common.base.MoreObjects
import com.mycollab.common.GenericLinkUtils
import com.mycollab.common.SessionIdGenerator
import com.mycollab.common.i18n.ErrorI18nEnum
import com.mycollab.configuration.ApplicationConfiguration
import com.mycollab.configuration.IDeploymentMode
import com.mycollab.core.utils.StringUtils
import com.mycollab.db.arguments.GroupIdProvider
import com.mycollab.module.billing.SubDomainNotExistException
import com.mycollab.module.user.domain.SimpleBillingAccount
import com.mycollab.module.user.service.BillingAccountService
import com.mycollab.spring.AppContextUtil
import com.mycollab.vaadin.ui.ThemeManager
import com.mycollab.vaadin.ui.UIUtils
import com.vaadin.server.Page
import com.vaadin.server.VaadinRequest
import com.vaadin.server.VaadinServletRequest
import com.vaadin.ui.UI
import org.slf4j.LoggerFactory
import java.util.*
/**
* @author MyCollab Ltd.
* @since 4.3.2
*/
abstract class AppUI : UI() {
/**
* Context of current logged in user
*/
protected var currentContext: UserUIContext? = null
private var initialSubDomain = "1"
var currentFragmentUrl: String? = null
private var _billingAccount: SimpleBillingAccount? = null
private val attributes = mutableMapOf<String, Any?>()
protected fun postSetupApp(request: VaadinRequest) {
initialSubDomain = UIUtils.getSubDomain(request)
val billingService = AppContextUtil.getSpringBean(BillingAccountService::class.java)
LOG.info("Load account info of sub-domain $initialSubDomain from ${(request as VaadinServletRequest).serverName}")
_billingAccount = billingService.getAccountByDomain(initialSubDomain)
if (_billingAccount == null) {
throw SubDomainNotExistException(UserUIContext.getMessage(ErrorI18nEnum.SUB_DOMAIN_IS_NOT_EXISTED, initialSubDomain))
} else {
LOG.info("Billing account info ")
val accountId = _billingAccount!!.id
ThemeManager.loadDesktopTheme(accountId!!)
}
}
fun setAttribute(key: String, value: Any?) {
attributes[key] = value
}
fun getAttribute(key: String): Any? = attributes[key]
val account: SimpleBillingAccount
get() = _billingAccount!!
val loggedInUser: String?
get() = currentContext?.session?.username
override fun close() {
LOG.debug("Application is closed. Clean all resources")
currentContext?.clearSessionVariables()
currentContext = null
super.close()
}
companion object {
private const val serialVersionUID = 1L
private val LOG = LoggerFactory.getLogger(AppUI::class.java)
init {
GroupIdProvider.registerAccountIdProvider(object : GroupIdProvider() {
override val groupId: Int
get() = AppUI.accountId
override val groupRequestedUser: String
get() = UserUIContext.getUsername()
})
SessionIdGenerator.registerSessionIdGenerator(object : SessionIdGenerator() {
override val sessionIdApp: String
get() = UI.getCurrent().toString()
})
}
/**
* @return
*/
@JvmStatic
val siteUrl: String
get() {
val deploymentMode = AppContextUtil.getSpringBean(IDeploymentMode::class.java)
return deploymentMode.getSiteUrl(instance._billingAccount!!.subdomain)
}
@JvmStatic
fun getBillingAccount(): SimpleBillingAccount? = instance._billingAccount
@JvmStatic
val instance: AppUI
get() = UI.getCurrent() as AppUI
@JvmStatic
val subDomain: String
get() = instance._billingAccount!!.subdomain
/**
* Get account id of current user
*
* @return account id of current user. Return 0 if can not get
*/
@JvmStatic
val accountId: Int
get() = try {
instance._billingAccount!!.id
} catch (e: Exception) {
0
}
@JvmStatic
val siteName: String
get() {
val appConfig = AppContextUtil.getSpringBean(ApplicationConfiguration::class.java)
return try {
MoreObjects.firstNonNull(instance._billingAccount!!.sitename, appConfig.siteName)
} catch (e: Exception) {
appConfig.siteName
}
}
@JvmStatic
val defaultCurrency: Currency
get() = instance._billingAccount!!.currencyInstance!!
@JvmStatic
val longDateFormat: String
get() = instance._billingAccount!!.longDateFormatInstance
@JvmStatic
fun showEmailPublicly(): Boolean? = instance._billingAccount!!.displayemailpublicly
@JvmStatic
val shortDateFormat: String
get() = instance._billingAccount!!.shortDateFormatInstance
@JvmStatic
val dateFormat: String
get() = instance._billingAccount!!.dateFormatInstance
@JvmStatic
val dateTimeFormat: String
get() = instance._billingAccount!!.dateTimeFormatInstance
@JvmStatic
val defaultLocale: Locale
get() = instance._billingAccount!!.localeInstance!!
/**
* @param fragment
* @param windowTitle
*/
@JvmStatic
fun addFragment(fragment: String, windowTitle: String) {
if (fragment.startsWith(GenericLinkUtils.URL_PREFIX_PARAM)) {
val newFragment = fragment.substring(1)
Page.getCurrent().setUriFragment(newFragment, false)
} else {
Page.getCurrent().setUriFragment(fragment, false)
}
Page.getCurrent().setTitle("${StringUtils.trim(windowTitle, 150)} [$siteName]")
}
}
}
| mycollab-web/src/main/java/com/mycollab/vaadin/AppUI.kt | 1216517616 |
package org.ccci.gto.android.common.jsonapi.annotation
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class JsonApiId
| gto-support-jsonapi/src/main/java/org/ccci/gto/android/common/jsonapi/annotation/JsonApiId.kt | 3496690521 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.schedule.email.service
import com.hp.gagawa.java.elements.A
import com.hp.gagawa.java.elements.Span
import com.mycollab.common.MonitorTypeConstants
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.StringUtils
import com.mycollab.html.FormatUtils
import com.mycollab.html.LinkUtils
import com.mycollab.module.mail.MailUtils
import com.mycollab.module.project.ProjectLinkGenerator
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.Milestone
import com.mycollab.module.project.domain.ProjectRelayEmailNotification
import com.mycollab.module.project.domain.SimpleMilestone
import com.mycollab.module.project.i18n.MilestoneI18nEnum
import com.mycollab.module.project.i18n.OptionI18nEnum
import com.mycollab.module.project.service.MilestoneService
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.module.user.service.UserService
import com.mycollab.schedule.email.ItemFieldMapper
import com.mycollab.schedule.email.MailContext
import com.mycollab.schedule.email.format.DateFieldFormat
import com.mycollab.schedule.email.format.FieldFormat
import com.mycollab.schedule.email.format.I18nFieldFormat
import com.mycollab.schedule.email.project.ProjectMilestoneRelayEmailNotificationAction
import com.mycollab.spring.AppContextUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class ProjectMilestoneRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleMilestone>(), ProjectMilestoneRelayEmailNotificationAction {
@Autowired private lateinit var milestoneService: MilestoneService
private val mapper = MilestoneFieldNameMapper()
override fun getItemName(): String = StringUtils.trim(bean!!.name, 100)
override fun getProjectName(): String = bean!!.projectName!!
override fun getCreateSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCreateSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
override fun getUpdateSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getUpdateSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
override fun getCommentSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCommentSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write()
private fun userLink(context: MailContext<SimpleMilestone>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write()
private fun milestoneLink() = A(ProjectLinkGenerator.generateMilestonePreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write()
override fun getItemFieldMapper(): ItemFieldMapper = mapper
override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleMilestone? =
milestoneService.findById(notification.typeid.toInt(), notification.saccountid)
override fun getType(): String = ProjectTypeConstants.MILESTONE
override fun getTypeId(): String = "${bean!!.id}"
class MilestoneFieldNameMapper : ItemFieldMapper() {
init {
put(Milestone.Field.name, GenericI18Enum.FORM_NAME, true)
put(Milestone.Field.status, I18nFieldFormat(Milestone.Field.status.name, GenericI18Enum.FORM_STATUS,
OptionI18nEnum.MilestoneStatus::class.java))
put(Milestone.Field.assignuser, AssigneeFieldFormat(Milestone.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE))
put(Milestone.Field.startdate, DateFieldFormat(Milestone.Field.startdate.name, GenericI18Enum.FORM_START_DATE))
put(Milestone.Field.enddate, DateFieldFormat(Milestone.Field.enddate.name, GenericI18Enum.FORM_END_DATE))
put(Milestone.Field.description, GenericI18Enum.FORM_DESCRIPTION, true)
}
}
class AssigneeFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val milestone = context.wrappedBean as SimpleMilestone
return if (milestone.assignuser != null) {
val userAvatarLink = MailUtils.getAvatarLink(milestone.ownerAvatarId, 16)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(milestone.saccountid),
milestone.assignuser)
val link = FormatUtils.newA(userLink, milestone.ownerFullName)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
if (StringUtils.isBlank(value)) {
return Span().write()
}
val userService = AppContextUtil.getSpringBean(UserService::class.java)
val user = userService.findUserByUserNameInAccount(value, context.saccountid)
return if (user != null) {
val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid),
user.username)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val link = FormatUtils.newA(userLink, user.displayName!!)
FormatUtils.newLink(img, link).write()
} else value
}
}
override fun buildExtraTemplateVariables(context: MailContext<SimpleMilestone>) {
val emailNotification = context.emailNotification
val summary = bean!!.name
val summaryLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(siteUrl, bean!!.projectid, bean!!.id)
val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else ""
val userAvatar = LinkUtils.newAvatar(avatarId)
val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}"
val actionEnum = when (emailNotification.action) {
MonitorTypeConstants.CREATE_ACTION -> MilestoneI18nEnum.MAIL_CREATE_ITEM_HEADING
MonitorTypeConstants.UPDATE_ACTION -> MilestoneI18nEnum.MAIL_UPDATE_ITEM_HEADING
MonitorTypeConstants.ADD_COMMENT_ACTION -> MilestoneI18nEnum.MAIL_COMMENT_ITEM_HEADING
else -> throw MyCollabException("Not support action ${emailNotification.action}")
}
contentGenerator.putVariable("projectName", bean!!.projectName!!)
contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid))
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("name", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
}
} | mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ProjectMilestoneRelayEmailNotificationActionImpl.kt | 3160268894 |
package bjzhou.coolapk.app.net
/**
* author: zhoubinjia
* date: 2017/2/22
*/
class DownloadStatus {
var percent = 0
var status = STATUS_NOT_STARTED
companion object {
val STATUS_NOT_STARTED = 0
}
} | app/src/main/kotlin/bjzhou/coolapk/app/net/DownloadStatus.kt | 3664250453 |
package org.ccci.gto.android.common.androidx.collection
import android.os.Parcel
import android.os.Parcelable
import androidx.collection.LongSparseArray
import kotlinx.parcelize.Parceler
import kotlinx.parcelize.Parcelize
@Parcelize
class LongSparseParcelableArray<T : Parcelable?> : LongSparseArray<T>(), Parcelable {
internal companion object : Parceler<LongSparseParcelableArray<Parcelable?>> {
override fun LongSparseParcelableArray<Parcelable?>.write(parcel: Parcel, flags: Int) {
val size = size()
val keys = LongArray(size)
val values = arrayOfNulls<Parcelable>(size)
for (i in 0 until size) {
keys[i] = keyAt(i)
values[i] = valueAt(i)
}
parcel.writeInt(size)
parcel.writeLongArray(keys)
parcel.writeParcelableArray(values, 0)
}
override fun create(parcel: Parcel): LongSparseParcelableArray<Parcelable?> {
val size = parcel.readInt()
val keys = LongArray(size).also { parcel.readLongArray(it) }
val values = parcel.readParcelableArray(LongSparseParcelableArray::class.java.classLoader)
return LongSparseParcelableArray<Parcelable?>()
.apply { for (i in 0 until size) put(keys[i], values?.get(i)) }
}
}
}
| gto-support-androidx-collection/src/main/kotlin/org/ccci/gto/android/common/androidx/collection/LongSparseParcelableArray.kt | 2415408667 |
package de.gesellix.docker.compose.types
import com.squareup.moshi.Json
import de.gesellix.docker.compose.adapters.DriverOptsType
import de.gesellix.docker.compose.adapters.ExternalType
import de.gesellix.docker.compose.adapters.LabelsType
data class StackVolume(
var name: String? = "",
var driver: String? = null,
@Json(name = "driver_opts")
@DriverOptsType
var driverOpts: DriverOpts = DriverOpts(),
// StackVolume.external.name is deprecated and replaced by StackVolume.name
@ExternalType
var external: External = External(),
@LabelsType
var labels: Labels = Labels()
)
| src/main/kotlin/de/gesellix/docker/compose/types/StackVolume.kt | 4035206330 |
/*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpm.optree.function
import com.intellij.util.xmlb.annotations.Attribute
import uk.co.reecedunn.intellij.plugin.core.serviceContainer.KotlinLazyInstance
class XpmFunctionDecoratorBean : KotlinLazyInstance<XpmFunctionDecorator>() {
@Attribute("implementationClass")
override var implementationClass: String = ""
@Attribute("fieldName")
override var fieldName: String = ""
}
| src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/optree/function/XpmFunctionDecoratorBean.kt | 558839328 |
package de.westnordost.streetcomplete.quests.wheelchair_access
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddWheelChairAccessToilets(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters =
" nodes, ways with amenity=toilets and access !~ private|customers and !wheelchair"
override val commitMessage = "Add wheelchair access to toilets"
override val icon = R.drawable.ic_quest_toilets_wheelchair
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_wheelchairAccess_toilets_name_title
else
R.string.quest_wheelchairAccess_toilets_title
override fun createForm() = AddWheelchairAccessToiletsForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("wheelchair", answer)
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/wheelchair_access/AddWheelChairAccessToilets.kt | 700962581 |
package de.westnordost.streetcomplete.quests.opening_hours
import de.westnordost.streetcomplete.data.osm.changes.StringMapEntryAdd
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.quests.opening_hours.model.*
import de.westnordost.streetcomplete.quests.verifyAnswer
import org.junit.Test
import org.mockito.Mockito.mock
class AddOpeningHoursTest {
private val questType = AddOpeningHours(mock(OverpassMapDataDao::class.java))
@Test fun `apply description answer`() {
questType.verifyAnswer(
DescribeOpeningHours("my cool \"opening\" hours"),
StringMapEntryAdd("opening_hours", "\"my cool opening hours\"")
)
}
@Test fun `apply no opening hours sign answer`() {
questType.verifyAnswer(
NoOpeningHoursSign,
StringMapEntryAdd("opening_hours:signed", "no")
)
}
@Test fun `apply always open answer`() {
questType.verifyAnswer(
AlwaysOpen,
StringMapEntryAdd("opening_hours", "24/7")
)
}
@Test fun `apply opening hours answer`() {
questType.verifyAnswer(
RegularOpeningHours(listOf(OpeningMonths(
CircularSection(0,11),
listOf(
listOf(
OpeningWeekdays(
Weekdays(booleanArrayOf(true)),
mutableListOf(TimeRange(0, 12*60))
)
),
listOf(
OpeningWeekdays(
Weekdays(booleanArrayOf(false, true)),
mutableListOf(TimeRange(12*60, 24*60))
)
)
)
))),
StringMapEntryAdd("opening_hours", "Mo 00:00-12:00; Tu 12:00-24:00")
)
}
}
| app/src/test/java/de/westnordost/streetcomplete/quests/opening_hours/AddOpeningHoursTest.kt | 2408246809 |
package org.stepik.android.data.last_step.source
import io.reactivex.Completable
import io.reactivex.Maybe
import org.stepik.android.domain.last_step.model.LastStep
interface LastStepCacheDataSource {
fun getLastStep(id: String): Maybe<LastStep>
fun saveLastStep(lastStep: LastStep): Completable
} | app/src/main/java/org/stepik/android/data/last_step/source/LastStepCacheDataSource.kt | 1361853354 |
class A(val a: Int)
open class B {
lateinit var a: A
}
class C: B() {
fun foo() { a = A(42) }
}
fun main(args: Array<String>) {
val c = C()
c.foo()
println(c.a.a)
}
| backend.native/tests/codegen/lateinit/inBaseClass.kt | 662093092 |
package org.stepik.android.view.injection.view_assignment
import dagger.Module
import dagger.Provides
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.subjects.BehaviorSubject
import org.stepic.droid.di.AppSingleton
import org.stepic.droid.di.qualifiers.BackgroundScheduler
@Module
abstract class ViewAssignmentBusModule {
@Module
companion object {
/**
* Provides publisher that should be notified if view report was failed to post
*/
@Provides
@JvmStatic
@AppSingleton
@ViewAssignmentBus
internal fun provideViewAssignmentPublisher(): BehaviorSubject<Unit> =
BehaviorSubject.createDefault(Unit)
@Provides
@JvmStatic
@AppSingleton
@ViewAssignmentBus
internal fun provideViewAssignmentObservable(
@ViewAssignmentBus
vewAssignmentPublisher: BehaviorSubject<Unit>,
@BackgroundScheduler
scheduler: Scheduler
): Observable<Unit> =
vewAssignmentPublisher.observeOn(scheduler)
}
} | app/src/main/java/org/stepik/android/view/injection/view_assignment/ViewAssignmentBusModule.kt | 4125524671 |
package org.walleth.nfc
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_nfc_enter_credentials.*
import org.ligi.kaxt.setVisibility
import org.ligi.kaxtui.alert
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.data.EXTRA_KEY_NFC_CREDENTIALS
class NFCEnterCredentialsActivity : BaseSubActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nfc_enter_credentials)
radio_new_card.setOnCheckedChangeListener { _, _ ->
refresh()
}
fab.setOnClickListener {
when {
input_pin.text?.length != 6 -> alert("The PIN must have 6 digits")
input_puk.text?.length != 12 && isNewCard() -> alert("The PUK must have 12 digits")
input_pairingpwd.text.isNullOrBlank() -> alert("The pairing password cannot be blank")
else -> {
val nfcCredentials = NFCCredentials(
isNewCard = radio_new_card.isChecked,
pin = input_pin.text.toString(),
puk = input_puk.text.toString(),
pairingPassword = input_pairingpwd.text.toString()
)
val resultIntent = Intent().putExtra(EXTRA_KEY_NFC_CREDENTIALS, nfcCredentials)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
}
refresh()
}
private fun refresh() {
puk_input_layout.setVisibility(isNewCard())
}
private fun isNewCard() = radio_new_card.isChecked
}
| app/src/main/java/org/walleth/nfc/NFCEnterCredentialsActivity.kt | 466370022 |
package me.liuqingwen.android.projectbasicmaterialdesign
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.layout_activity_main.*
import kotlinx.android.synthetic.main.recycler_list_item.view.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jetbrains.anko.toast
class MainActivity : AppCompatActivity()
{
private val dataUrl = "http://liuqingwen.me/data/get-images-json.php?type=json&delay=0"
private val httpClient by lazy { OkHttpClient.Builder().build() }
private val dataObservable by lazy {
Observable.create(ObservableOnSubscribe<Response> {
val request = Request.Builder().get().url(this.dataUrl).build()
try
{
val response = this.httpClient.newCall(request).execute()
it.onNext(response)
it.onComplete()
}
catch(e: Exception)
{
//it.onError(e)
this.onLoadError()
}
})
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.init()
this.loadData()
}
private fun onLoadError()
{
Snackbar.make(this.floatingActionButton, "Error Loading.", Snackbar.LENGTH_INDEFINITE).setAction("Reload") { this.loadData() }.show()
}
private fun loadData()
{
this.dataObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
if (it.isSuccessful)
{
val content = it.body()?.string()
val type = object : TypeToken<List<MyItem>>() {}.type
try
{
val items = Gson().fromJson<List<MyItem>>(content, type)
this.displayItems(items)
}
catch(e: Exception)
{
this.onLoadError()
}
}else
{
this.onLoadError()
}
}
}
private fun displayItems(items: List<MyItem>?)
{
if (items == null)
{
this.onLoadError()
return
}
Snackbar.make(this.floatingActionButton, "Is Done!", Snackbar.LENGTH_LONG).setAction("OK") { }.show()
val adapter = MyAdapter(this, items)
this.recyclerView.adapter = adapter
val layoutManager = GridLayoutManager(this, 2)
this.recyclerView.layoutManager = layoutManager
}
private fun init()
{
this.setSupportActionBar(this.toolbar)
this.supportActionBar?.setDisplayHomeAsUpEnabled(true)
this.supportActionBar?.setHomeAsUpIndicator(R.drawable.menu)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
this.menuInflater.inflate(R.menu.menu_toolbar, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean
{
when(item?.itemId)
{
android.R.id.home -> { this.layoutDrawer.openDrawer(Gravity.START) }
R.id.menuVideoCall -> {}
R.id.menuUpload -> {}
R.id.menuGlobe -> {}
R.id.menuPlus -> {}
else -> this.toast("Not implemented yet!")
}
return super.onOptionsItemSelected(item)
}
}
data class MyItem(val url:String, val title:String)
class MyViewHolder(itemView:View):RecyclerView.ViewHolder(itemView)
{
val labelTitle:TextView = itemView.labelTitle
val imageTitle:ImageView = itemView.imageTitle
}
class MyAdapter(val context:Context, val dataList:List<MyItem>):RecyclerView.Adapter<MyViewHolder>()
{
private val inflater by lazy { LayoutInflater.from(this.context) }
override fun onBindViewHolder(holder: MyViewHolder?, position: Int)
{
val item = this.dataList[position]
holder?.labelTitle?.text = item.title
Glide.with(this.context).load(item.url).into(holder?.imageTitle)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder
{
val view = this.inflater.inflate(R.layout.recycler_list_item, parent, false)
val viewHolder = MyViewHolder(view)
return viewHolder
}
override fun getItemCount(): Int
{
return this.dataList.size
}
}
| ProjectBasicMaterialDesign/app/src/main/java/me/liuqingwen/android/projectbasicmaterialdesign/MainActivity.kt | 3703194806 |
package org.dictat.wikistat.wikidata
import java.util.HashMap
import org.apache.http.client.HttpClient
import org.apache.http.impl.client.AutoRetryHttpClient
import org.apache.http.impl.client.DecompressingHttpClient
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet
import java.net.URLEncoder
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.ObjectMapper
import java.util.Collections
import org.apache.http.protocol.HTTP
import org.dictat.wikistat.utils.VersionUtils
class WikiData() {
class PageMissingException() : Exception() {
}
fun langLinks(wikipage: String, lang: String): Map<String, String> {
//TODO: this method is messy, cleanup needed
val ret = HashMap<String, String>();
val defaultHttpClient = DefaultHttpClient()
defaultHttpClient.getParams()!!.setParameter(HTTP.USER_AGENT,"wikistat robot "+ VersionUtils.getVersion() + " http://dictat.org/");
val client: HttpClient = AutoRetryHttpClient(DecompressingHttpClient(defaultHttpClient))
val req = HttpGet("https://"+lang+".wikipedia.org/w/api.php?format=json&action=query&prop=langlinks&lllimit=500&titles="+URLEncoder.encode(wikipage,"UTF-8"));
val response = client.execute(req);
val json = ObjectMapper().readTree(response!!.getEntity()!!.getContent());
val page = json?.get("query")?.get("pages")
if(page == null) {
throw PageMissingException()
}
for(elem in page.elements()) {
val langlinks = elem.get("langlinks")
if(langlinks != null) {
for(sp in langlinks.elements()) {
ret.put(sp.get("lang")?.textValue()!!, sp.get("*")?.textValue()!!);
}
} else {
if(elem.get("missing") != null) {
throw PageMissingException()
}
}
}
return ret;
}
} | src/main/kotlin/org/dictat/wikistat/wikidata/WikiData.kt | 1901828809 |
package org.flightofstairs.redesignedPotato
import org.flightofstairs.redesignedPotato.model.MonsterInfo
import org.flightofstairs.redesignedPotato.parsers.json.monstersFromResource
val monsters = listOf<MonsterInfo>()
.plus(monstersFromResource("/monsters/Out_of_the_Abyss.json"))
.plus(monstersFromResource("/monsters/Monster_Manual.json"))
.associateBy { it.name }
| core/src/org/flightofstairs/redesignedPotato/MonsterRegistry.kt | 390238621 |
package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_TOTAL_DAILY_DOSES
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTime
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(tableName = TABLE_TOTAL_DAILY_DOSES,
foreignKeys = [ForeignKey(
entity = TotalDailyDose::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [
Index("id"),
Index("pumpId"),
Index("pumpType"),
Index("pumpSerial"),
Index("isValid"),
Index("referenceId"),
Index("timestamp")
])
data class TotalDailyDose(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(),
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
var basalAmount: Double = 0.0,
var bolusAmount: Double = 0.0,
var totalAmount: Double = 0.0, // if zero it's calculated as basalAmount + bolusAmount
var carbs: Double = 0.0
) : TraceableDBEntry, DBEntryWithTime {
companion object
} | database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt | 3525942385 |
package info.nightscout.androidaps.plugins.general.maintenance.formats
import android.content.Context
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import info.nightscout.androidaps.core.R
import kotlinx.parcelize.Parcelize
import java.io.File
enum class PrefsMetadataKey(val key: String, @DrawableRes val icon: Int, @StringRes val label: Int) {
FILE_FORMAT("format", R.drawable.ic_meta_format, R.string.metadata_label_format),
CREATED_AT("created_at", R.drawable.ic_meta_date, R.string.metadata_label_created_at),
AAPS_VERSION("aaps_version", R.drawable.ic_meta_version, R.string.metadata_label_aaps_version),
AAPS_FLAVOUR("aaps_flavour", R.drawable.ic_meta_flavour, R.string.metadata_label_aaps_flavour),
DEVICE_NAME("device_name", R.drawable.ic_meta_name, R.string.metadata_label_device_name),
DEVICE_MODEL("device_model", R.drawable.ic_meta_model, R.string.metadata_label_device_model),
ENCRYPTION("encryption", R.drawable.ic_meta_encryption, R.string.metadata_label_encryption);
companion object {
private val keyToEnumMap = HashMap<String, PrefsMetadataKey>()
init {
for (value in values()) keyToEnumMap[value.key] = value
}
fun fromKey(key: String): PrefsMetadataKey? =
if (keyToEnumMap.containsKey(key)) {
keyToEnumMap[key]
} else {
null
}
}
fun formatForDisplay(context: Context, value: String): String {
return when (this) {
FILE_FORMAT -> when (value) {
EncryptedPrefsFormat.FORMAT_KEY_ENC -> context.getString(R.string.metadata_format_new)
EncryptedPrefsFormat.FORMAT_KEY_NOENC -> context.getString(R.string.metadata_format_debug)
else -> context.getString(R.string.metadata_format_other)
}
CREATED_AT -> value.replace("T", " ").replace("Z", " (UTC)")
else -> value
}
}
}
@Parcelize
data class PrefMetadata(var value: String, var status: PrefsStatus, var info: String? = null) : Parcelable
typealias PrefMetadataMap = Map<PrefsMetadataKey, PrefMetadata>
data class Prefs(val values: Map<String, String>, var metadata: PrefMetadataMap)
interface PrefsFormat {
fun savePreferences(file: File, prefs: Prefs, masterPassword: String? = null)
fun loadPreferences(file: File, masterPassword: String? = null): Prefs
fun loadMetadata(contents: String? = null): PrefMetadataMap
fun isPreferencesFile(file: File, preloadedContents: String? = null): Boolean
}
enum class PrefsStatus(@DrawableRes val icon: Int) {
OK(R.drawable.ic_meta_ok),
WARN(R.drawable.ic_meta_warning),
ERROR(R.drawable.ic_meta_error),
UNKNOWN(R.drawable.ic_meta_error),
DISABLED(R.drawable.ic_meta_error)
}
class PrefFileNotFoundError(message: String) : Exception(message)
class PrefIOError(message: String) : Exception(message)
class PrefFormatError(message: String) : Exception(message)
| core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt | 680500304 |
package io.github.feelfreelinux.wykopmobilny.di.components
import dagger.Component
import io.github.feelfreelinux.wykopmobilny.di.AppModule
import io.github.feelfreelinux.wykopmobilny.di.modules.NetworkModule
import io.github.feelfreelinux.wykopmobilny.di.modules.PresentersModule
import io.github.feelfreelinux.wykopmobilny.di.modules.RepositoryModule
import io.github.feelfreelinux.wykopmobilny.di.modules.ViewPresentersModule
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.NotificationViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.PMMessageViewHolder
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.favorite.FavoriteButton
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.favorite.entry.EntryFavoriteButton
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base.BaseVoteButton
import io.github.feelfreelinux.wykopmobilny.ui.widgets.entry.comment.CommentWidget
import io.github.feelfreelinux.wykopmobilny.ui.widgets.entry.EntryWidget
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.entry.EntryVoteButton
import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.entry.comment.EntryCommentVoteButton
import io.github.feelfreelinux.wykopmobilny.ui.widgets.InputToolbar
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.AddEntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.comment.EditEntryCommentActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.edit.EditEntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation.NavigationActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry.EntryActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.BaseFeedList
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.hot.HotFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag.TagActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsBroadcastReceiver
import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsJob
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.hashtags.HashTagsNotificationsListFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification.NotificationsListFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.PhotoViewActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversation.ConversationActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversationslist.ConversationsListFragment
import io.github.feelfreelinux.wykopmobilny.ui.widgets.WykopImageView
import io.github.feelfreelinux.wykopmobilny.ui.widgets.drawerheaderview.DrawerHeaderWidget
import javax.inject.Singleton
@Singleton
@Component( modules = arrayOf(AppModule::class,
NetworkModule::class,
RepositoryModule::class,
PresentersModule::class,
ViewPresentersModule::class) )
interface Injector {
fun inject(loginScreenActivity: LoginScreenActivity)
fun inject(mainNavigationActivity: NavigationActivity)
fun inject(hotFragment: HotFragment)
fun inject(entryActivity: EntryActivity)
fun inject(tagActivity: TagActivity)
fun inject(entryVoteButton: EntryVoteButton)
fun inject(entryCommentVoteButton: EntryCommentVoteButton)
fun inject(entryView: EntryWidget)
fun inject(commentView : CommentWidget)
fun inject(addEntryActivity: AddEntryActivity)
fun inject(entryFavoriteButton: EntryFavoriteButton)
fun inject(baseVoteButton: BaseVoteButton)
fun inject(favoriteButton: FavoriteButton)
fun inject(baseFeedList: BaseFeedList)
fun inject(inputToolbar: InputToolbar)
fun inject(photoViewActivity: PhotoViewActivity)
fun inject(editEntryActivity: EditEntryActivity)
fun inject(wykopNotificationsJob: WykopNotificationsJob)
fun inject(wykopNotificationsBroadcastReceiver: WykopNotificationsBroadcastReceiver)
fun inject(editEntryCommentActivity: EditEntryCommentActivity)
fun inject(drawerHeaderWidget: DrawerHeaderWidget)
fun inject(conversationsListActivity: ConversationsListFragment)
fun inject(conversationActivity: ConversationActivity)
fun inject(notificationViewHolder: NotificationViewHolder)
fun inject(notificationsListFragment: NotificationsListFragment)
fun inject(hashTagsNotificationsListFragment: HashTagsNotificationsListFragment)
fun inject(wykopImageView: WykopImageView)
fun inject(pmMessageViewHolder: PMMessageViewHolder)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/di/components/Injector.kt | 1868027964 |
package com.cdev.showtracker.model
import com.google.gson.annotations.SerializedName
/**
* Created by aszabo on 21.05.2017.
*/
data class Network(
@SerializedName("id") val id: Int,
@SerializedName("name") val name: String) {
override fun toString(): String {
return name
}
} | app/src/main/java/com/cdev/showtracker/model/Network.kt | 2042195889 |
package info.nightscout.androidaps.plugins.general.automation.elements
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
class InputString(var value: String = "") : Element() {
private val textWatcher: TextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
value = s.toString()
}
}
override fun addToLayout(root: LinearLayout) {
root.addView(
EditText(root.context).apply {
setText(value)
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addTextChangedListener(textWatcher)
gravity = Gravity.CENTER_HORIZONTAL
})
}
} | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt | 1989936963 |
/*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.compressed.extractcontents
import android.os.Environment
import java.io.File
class ListPasswordProtectedRarTest : PasswordProtectedRarTest() {
override val archiveFile: File = File(
Environment.getExternalStorageDirectory(), "test-archive-encrypted-list.$archiveType"
)
}
| app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/ListPasswordProtectedRarTest.kt | 261898683 |
package com.prt2121.everywhere.meetup.model
/**
* Created by pt2121 on 1/18/16.
*/
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class Group(
@SerializedName("score")
@Expose
var score: Double,
@SerializedName("id")
@Expose
var id: Int,
@SerializedName("name")
@Expose
var name: String,
@SerializedName("link")
@Expose
var link: String,
@SerializedName("urlname")
@Expose
var urlname: String,
@SerializedName("description")
@Expose
var description: String,
@SerializedName("created")
@Expose
var created: Long,
@SerializedName("city")
@Expose
var city: String,
@SerializedName("country")
@Expose
var country: String,
@SerializedName("state")
@Expose
var state: String,
@SerializedName("join_mode")
@Expose
var joinMode: String,
@SerializedName("visibility")
@Expose
var visibility: String,
@SerializedName("lat")
@Expose
var lat: Double,
@SerializedName("lon")
@Expose
var lon: Double,
@SerializedName("members")
@Expose
var members: Int,
@SerializedName("organizer")
@Expose
var organizer: Organizer,
@SerializedName("who")
@Expose
var who: String,
@SerializedName("group_photo")
@Expose
var groupPhoto: GroupPhoto,
@SerializedName("timezone")
@Expose
var timezone: String,
@SerializedName("next_event")
@Expose
var nextEvent: NextEvent,
@SerializedName("category")
@Expose
var category: Category,
@SerializedName("photos")
@Expose
var photos: List<GroupPhoto> = emptyList()
) | Everywhere/app/src/main/kotlin/com/prt2121/everywhere/meetup/model/Group.kt | 3356777765 |
package com.fsck.k9.backend.jmap
import rs.ltt.jmap.client.JmapClient
import rs.ltt.jmap.common.method.call.email.SetEmailMethodCall
import rs.ltt.jmap.common.method.response.email.SetEmailMethodResponse
import rs.ltt.jmap.common.util.Patches
import timber.log.Timber
class CommandMove(
private val jmapClient: JmapClient,
private val accountId: String
) {
fun moveMessages(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Moving %d messages to %s", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.set("mailboxIds", mapOf(targetFolderServerId to true))
updateEmails(messageServerIds, mailboxPatch)
}
fun moveMessagesAndMarkAsRead(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Moving %d messages to %s and marking them as read", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.builder()
.set("mailboxIds", mapOf(targetFolderServerId to true))
.set("keywords/\$seen", true)
.build()
updateEmails(messageServerIds, mailboxPatch)
}
fun copyMessages(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Copying %d messages to %s", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.set("mailboxIds/$targetFolderServerId", true)
updateEmails(messageServerIds, mailboxPatch)
}
private fun updateEmails(messageServerIds: List<String>, patch: Map<String, Any>?) {
val session = jmapClient.session.get()
val maxObjectsInSet = session.maxObjectsInSet
messageServerIds.chunked(maxObjectsInSet).forEach { emailIds ->
val updates = emailIds.map { emailId ->
emailId to patch
}.toMap()
val setEmailCall = jmapClient.call(
SetEmailMethodCall.builder()
.accountId(accountId)
.update(updates)
.build()
)
setEmailCall.getMainResponseBlocking<SetEmailMethodResponse>()
}
}
}
| backend/jmap/src/main/java/com/fsck/k9/backend/jmap/CommandMove.kt | 3087041970 |
package com.intellij.workspaceModel.storage.entities.test.api
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.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentAbEntityImpl: ParentAbEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val children: List<ChildAbstractBaseEntity>
get() = snapshot.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentAbEntityData?): ModifiableWorkspaceEntityBase<ParentAbEntity>(), ParentAbEntity.Builder {
constructor(): this(ParentAbEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentAbEntity 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
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field ParentAbEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field ParentAbEntity#children should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ParentAbEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var children: List<ChildAbstractBaseEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildAbstractBaseEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<ChildAbstractBaseEntity> ?: emptyList()
}
}
set(value) {
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.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): ParentAbEntityData = result ?: super.getEntityData() as ParentAbEntityData
override fun getEntityClass(): Class<ParentAbEntity> = ParentAbEntity::class.java
}
}
class ParentAbEntityData : WorkspaceEntityData<ParentAbEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentAbEntity> {
val modifiable = ParentAbEntityImpl.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): ParentAbEntity {
val entity = ParentAbEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentAbEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentAbEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentAbEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentAbEntityImpl.kt | 3814633925 |
/*
* Easy Auth0 Java Library
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
*/
package it.simonerenzo.easyauth0.models
data class Credentials(val user: User, var accessToken: String, var refreshToken: String, var expiresIn: Long) | src/main/kotlin/it/simonerenzo/easyauth0/models/Credentials.kt | 1585217975 |
// ktlint-disable filename
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
@file:Suppress("PackageName", "TopLevelName")
package arcs.sdk
object Utils : UtilsInterface {
override fun log(msg: String): Unit = throw NotImplementedError()
override fun abort(): Unit = throw NotImplementedError()
override fun assert(message: String, cond: Boolean): Unit = throw NotImplementedError()
override fun toUtf8String(bytes: ByteArray): String = throw NotImplementedError()
override fun toUtf8ByteArray(str: String): ByteArray = throw NotImplementedError()
}
| java/arcs/sdk/js/Utils.kt | 795583139 |
/*******************************************************************************
* 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
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import org.jetbrains.annotations.Nls
import java.awt.CardLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextField
import javax.swing.KeyStroke
import javax.swing.Scrollable
object PackageSearchUI {
private val MAIN_BG_COLOR: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground())
internal val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
internal val HeaderBackgroundColor = MAIN_BG_COLOR
internal val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41)
internal val UsualBackgroundColor = MAIN_BG_COLOR
internal val ListRowHighlightBackground = JBColor.namedColor("PackageSearch.SearchResult.background", 0xF2F5F9, 0x4C5052)
internal val InfoBannerBackground = JBColor.lazy {
EditorColorsManager.getInstance().globalScheme.getColor(EditorColors.NOTIFICATION_BACKGROUND)
?: JBColor(0xE6EEF7, 0x1C3956)
}
internal val MediumHeaderHeight = JBValue.Float(30f)
internal val SmallHeaderHeight = JBValue.Float(24f)
@Suppress("MagicNumber") // Thanks, Swing
internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
init()
}
override fun getBackground() = HeaderBackgroundColor
}
internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = CardLayout()
cards.forEach { add(it) }
init()
}
override fun getBackground() = backgroundColor
}
internal fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
init()
}
override fun getBackground() = backgroundColor
}
internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = BoxLayout(this, axis)
init()
}
override fun getBackground() = backgroundColor
}
internal fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
init()
}
override fun getBackground() = backgroundColor
}
fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) {
init {
init()
}
override fun getBackground() = UsualBackgroundColor
}
fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply {
init()
}
internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply {
font = StartupUiUtil.getLabelFont()
if (text != null) this.text = text
init()
}
internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply {
font = StartupUiUtil.getLabelFont()
init()
}
internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when {
isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) }
else -> JBColor.lazy { UIUtil.getListForeground() }
}
internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when {
isSelected -> getTextColorPrimary(isSelected)
else -> GRAY_COLOR
}
internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) {
setHeightPreScaled(component, height.scaled(), keepWidth)
}
internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) {
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height)
}
}
internal fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = UsualBackgroundColor
}
}
internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(
key,
object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
}
)
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = UsualBackgroundColor
}
}
internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
internal fun JComponent.updateAndRepaint() {
invalidate()
repaint()
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt | 1441665816 |
// 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.
@file:JvmName("ServiceContainerUtil")
package com.intellij.testFramework
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.messages.MessageBusOwner
import org.jetbrains.annotations.TestOnly
private val testDescriptor by lazy { DefaultPluginDescriptor("test") }
@TestOnly
fun <T : Any> ComponentManager.registerServiceInstance(serviceInterface: Class<T>, instance: T) {
(this as ComponentManagerImpl).registerServiceInstance(serviceInterface, instance, testDescriptor)
}
/**
* Register a new service or replace an existing service with a specified instance for testing purposes.
* Registration will be rolled back when parentDisposable is disposed. In most of the cases,
* [com.intellij.testFramework.UsefulTestCase.getTestRootDisposable] should be specified.
*/
@TestOnly
fun <T : Any> ComponentManager.registerOrReplaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
val previous = this.getService(serviceInterface)
if (previous != null) {
replaceService(serviceInterface, instance, parentDisposable)
} else {
(this as ComponentManagerImpl).registerServiceInstance(serviceInterface, instance, testDescriptor)
if (instance is Disposable) {
Disposer.register(parentDisposable, instance)
} else {
Disposer.register(parentDisposable) {
this.unregisterComponent(serviceInterface)
}
}
}
}
@TestOnly
fun <T : Any> ComponentManager.replaceService(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
(this as ComponentManagerImpl).replaceServiceInstance(serviceInterface, instance, parentDisposable)
}
@TestOnly
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T, parentDisposable: Disposable?) {
(this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, parentDisposable)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@TestOnly
@Deprecated("Pass parentDisposable")
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T) {
(this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, null)
}
@TestOnly
@JvmOverloads
fun ComponentManager.registerComponentImplementation(componentInterface: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean = false) {
(this as ComponentManagerImpl).registerComponentImplementation(componentInterface, componentImplementation, shouldBeRegistered)
}
@TestOnly
fun <T : Any> ComponentManager.registerExtension(name: BaseExtensionPointName<*>, instance: T, parentDisposable: Disposable) {
extensionArea.getExtensionPoint<T>(name.name).registerExtension(instance, parentDisposable)
}
@TestOnly
fun ComponentManager.getServiceImplementationClassNames(prefix: String): List<String> {
val result = ArrayList<String>()
processAllServiceDescriptors(this) { serviceDescriptor ->
val implementation = serviceDescriptor.implementation ?: return@processAllServiceDescriptors
if (implementation.startsWith(prefix)) {
result.add(implementation)
}
}
return result
}
fun processAllServiceDescriptors(componentManager: ComponentManager, consumer: (ServiceDescriptor) -> Unit) {
for (plugin in PluginManagerCore.getLoadedPlugins()) {
val pluginDescriptor = plugin as IdeaPluginDescriptorImpl
val containerDescriptor = when (componentManager) {
is Application -> pluginDescriptor.appContainerDescriptor
is Project -> pluginDescriptor.projectContainerDescriptor
else -> pluginDescriptor.moduleContainerDescriptor
}
containerDescriptor.services.forEach {
if ((componentManager as? ComponentManagerImpl)?.isServiceSuitable(it) != false &&
(it.os == null || componentManager.isSuitableForOs(it.os))) {
consumer(it)
}
}
}
}
fun createSimpleMessageBusOwner(owner: String): MessageBusOwner {
return object : MessageBusOwner {
override fun createListener(descriptor: ListenerDescriptor) = throw UnsupportedOperationException()
override fun isDisposed() = false
override fun toString() = owner
}
} | platform/testFramework/src/com/intellij/testFramework/ServiceContainerUtil.kt | 3589325655 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertExtensionToFunctionTypeFix(element: KtTypeReference, type: KotlinType) : KotlinQuickFixAction<KtTypeReference>(element) {
private val targetTypeStringShort = type.renderType(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS)
private val targetTypeStringLong = type.renderType(IdeDescriptorRenderers.SOURCE_CODE)
override fun getText() = KotlinBundle.message("convert.supertype.to.0", targetTypeStringShort)
override fun getFamilyName() = KotlinBundle.message("convert.extension.function.type.to.regular.function.type")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replaced = element.replaced(KtPsiFactory(project).createType(targetTypeStringLong))
ShortenReferences.DEFAULT.process(replaced)
}
private fun KotlinType.renderType(renderer: DescriptorRenderer) = buildString {
append('(')
arguments.dropLast(1).joinTo(this@buildString, ", ") { renderer.renderType(it.type) }
append(") -> ")
append(renderer.renderType([email protected]()))
}
companion object Factory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val casted = Errors.SUPERTYPE_IS_EXTENSION_FUNCTION_TYPE.cast(diagnostic)
val element = casted.psiElement
val type = element.analyze(BodyResolveMode.PARTIAL).get(BindingContext.TYPE, element) ?: return emptyList()
if (!type.isExtensionFunctionType) return emptyList()
return listOf(ConvertExtensionToFunctionTypeFix(element, type))
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertExtensionToFunctionTypeFix.kt | 3597946226 |
/*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.ui.internal.version
import androidx.annotation.CheckResult
import com.pyamsoft.pydroid.bootstrap.version.VersionModule
import com.pyamsoft.pydroid.ui.internal.app.ComposeThemeFactory
import com.pyamsoft.pydroid.ui.version.VersionUpgradeAvailable
internal interface VersionCheckComponent {
fun inject(component: VersionUpgradeAvailable)
interface Factory {
@CheckResult fun create(): VersionCheckComponent
data class Parameters
internal constructor(
internal val module: VersionModule,
internal val composeTheme: ComposeThemeFactory,
internal val versionCheckState: MutableVersionCheckViewState,
)
}
class Impl private constructor(private val params: Factory.Parameters) : VersionCheckComponent {
override fun inject(component: VersionUpgradeAvailable) {
component.viewModel =
VersionCheckViewModeler(
state = params.versionCheckState,
interactor = params.module.provideInteractor(),
interactorCache = params.module.provideInteractorCache(),
)
}
internal class FactoryImpl internal constructor(private val params: Factory.Parameters) :
Factory {
override fun create(): VersionCheckComponent {
return Impl(params)
}
}
}
}
| ui/src/main/java/com/pyamsoft/pydroid/ui/internal/version/VersionCheckComponent.kt | 1669744738 |
package de.bettinggame.application
import de.bettinggame.domain.*
import org.junit.Before
import org.junit.runner.RunWith
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import java.time.OffsetDateTime
import java.util.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@RunWith(MockitoJUnitRunner::class)
class TeamServiceTest {
@Mock
lateinit var teamRepository: TeamRepository
@Mock
lateinit var gameRepository: GameRepository
lateinit var teamService: TeamService
val teamOneId = "1"
val teamTwoId = "2"
val teamThreeId = "3"
val teamGermany = Team(teamOneId, Multilingual("Deutschland", "Germany"), "DE", Group.F)
val teamFrance = Team(teamTwoId, Multilingual("Frankreich", "France"), "FR", Group.H)
val teamMexico = Team(teamThreeId, Multilingual("Mexiko", "Mexico"), "MX", Group.F)
@Before
fun setUp() {
val games = createGamesForTeams()
given(teamRepository.findAllByGroupCharNotNull()).willReturn(listOf(teamGermany, teamFrance, teamMexico))
given(gameRepository.findByTeamInPreliminaryLevel(teamGermany)).willReturn(games)
given(gameRepository.findByTeamInPreliminaryLevel(teamMexico)).willReturn(games)
teamService = TeamService(teamRepository, gameRepository)
}
@Test
fun testGetAllGroupsWithTeams() {
val allGroupsWithTeams = teamService.getAllGroupsWithTeams()
assertEquals(2, allGroupsWithTeams.size, "2 groups expected")
val iterator = allGroupsWithTeams.iterator()
val groupF = iterator.next()
assertEquals(Group.F.name, groupF.groupChar)
assertEquals(2, groupF.teams.size)
assertEquals(teamGermany.teamKey, groupF.teams[0].teamKey)
val germany = groupF.teams[0]
assertEquals(4, germany.points)
assertEquals(4, germany.goals)
assertEquals(1, germany.goalsAgainst)
val mexico = groupF.teams[1]
assertEquals(1, mexico.points)
assertEquals(1, mexico.goals)
assertEquals(4, mexico.goalsAgainst)
assertEquals(teamMexico.teamKey, groupF.teams[1].teamKey)
val groupH = iterator.next()
assertEquals(Group.H.name, groupH.groupChar)
assertEquals(1, groupH.teams.size)
assertEquals(teamFrance.teamKey, groupH.teams[0].teamKey)
}
@Test
fun testTeamToCompare() {
// compare points
val team1 = TeamTo("team1", "t1", 3, 5, 2)
val team2 = TeamTo("team2", "t2", 4, 6, 1)
assertTrue { team1.compareTo(team2) > 0 }
// compare goal difference
val team3 = TeamTo("team3", "t3", 3, 5, 2)
val team4 = TeamTo("team4", "t4", 3, 6, 1)
assertTrue { team3.compareTo(team4) > 0 }
// compare scored goals
val team5 = TeamTo("team5", "t5", 3, 7, 2)
val team6 = TeamTo("team6", "t6", 3, 6, 3)
assertTrue { team5.compareTo(team6) < 0 }
val team7 = TeamTo("team7", "t7", 3, 6, 3)
val team8 = TeamTo("team8", "t8", 3, 6, 3)
assertTrue { team7.compareTo(team8) == 0 }
}
private fun createGamesForTeams(): List<Game> {
return listOf(
Game(
UUID.randomUUID().toString(),
OffsetDateTime.now(),
createLocation(),
TournamentLevel.PRELIMINARY,
teamGermany,
teamMexico,
3,
0
),
Game(
UUID.randomUUID().toString(),
OffsetDateTime.now(),
createLocation(),
TournamentLevel.PRELIMINARY,
teamMexico,
teamGermany,
1,
1
),
)
}
private fun createLocation(): Location {
return Location(UUID.randomUUID().toString(), "x", Multilingual("location", "location"), Multilingual("Stadt", "city"),
Multilingual("land", "country"))
}
}
| src/test/kotlin/de/bettinggame/application/TeamTests.kt | 780584245 |
package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.PolymorphicDomainObjectContainer
import org.gradle.api.Task
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.TaskContainer
import org.gradle.kotlin.dsl.support.uncheckedCast
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class NamedDomainObjectContainerExtensionsTest {
data class DomainObject(var foo: String? = null, var bar: Boolean? = null)
@Test
fun `can use monomorphic container api`() {
val alice = DomainObject()
val bob = DomainObject()
val john = DomainObject()
val marty = mockDomainObjectProviderFor(DomainObject())
val doc = mockDomainObjectProviderFor(DomainObject())
val container = mock<NamedDomainObjectContainer<DomainObject>> {
on { getByName("alice") } doReturn alice
on { create("bob") } doReturn bob
on { maybeCreate("john") } doReturn john
on { named("marty") } doReturn marty
on { register("doc") } doReturn doc
on { getByName(eq("alice"), any<Action<DomainObject>>()) } doReturn alice
on { create(eq("bob"), any<Action<DomainObject>>()) } doReturn bob
}
// regular syntax
container.getByName("alice") {
foo = "alice-foo"
}
container.create("bob") {
foo = "bob-foo"
}
container.maybeCreate("john")
container.named("marty")
container.register("doc")
// invoke syntax
container {
getByName("alice") {
foo = "alice-foo"
}
create("bob") {
foo = "bob-foo"
}
maybeCreate("john")
named("marty")
register("doc")
}
}
@Test
fun `can use polymorphic container api`() {
val alice = DomainObjectBase.Foo()
val bob = DomainObjectBase.Bar()
val default = DomainObjectBase.Default()
val marty = DomainObjectBase.Foo()
val martyProvider = mockDomainObjectProviderFor(marty)
val doc = DomainObjectBase.Bar()
val docProvider = mockDomainObjectProviderFor<DomainObjectBase>(doc)
val docProviderAsBarProvider = uncheckedCast<NamedDomainObjectProvider<DomainObjectBase.Bar>>(docProvider)
val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> {
on { getByName("alice") } doReturn alice
on { maybeCreate("alice", DomainObjectBase.Foo::class.java) } doReturn alice
on { create(eq("bob"), eq(DomainObjectBase.Bar::class.java), any<Action<DomainObjectBase.Bar>>()) } doReturn bob
on { create("john") } doReturn default
on { create("john", DomainObjectBase.Default::class.java) } doReturn default
onNamedWithAction("marty", DomainObjectBase.Foo::class, martyProvider)
on { register(eq("doc"), eq(DomainObjectBase.Bar::class.java)) } doReturn docProviderAsBarProvider
onRegisterWithAction("doc", DomainObjectBase.Bar::class, docProviderAsBarProvider)
}
// regular syntax
container.getByName<DomainObjectBase.Foo>("alice") {
foo = "alice-foo-2"
}
container.maybeCreate<DomainObjectBase.Foo>("alice")
container.create<DomainObjectBase.Bar>("bob") {
bar = true
}
container.create("john")
container.named("marty", DomainObjectBase.Foo::class) {
foo = "marty-foo"
}
container.named<DomainObjectBase.Foo>("marty") {
foo = "marty-foo-2"
}
container.register<DomainObjectBase.Bar>("doc") {
bar = true
}
// invoke syntax
container {
getByName<DomainObjectBase.Foo>("alice") {
foo = "alice-foo-2"
}
maybeCreate<DomainObjectBase.Foo>("alice")
create<DomainObjectBase.Bar>("bob") {
bar = true
}
create("john")
named("marty", DomainObjectBase.Foo::class) {
foo = "marty-foo"
}
named<DomainObjectBase.Foo>("marty") {
foo = "marty-foo-2"
}
register<DomainObjectBase.Bar>("doc") {
bar = true
}
}
}
@Test
fun `can configure monomorphic container`() {
val alice = DomainObject()
val aliceProvider = mockDomainObjectProviderFor(alice)
val bob = DomainObject()
val bobProvider = mockDomainObjectProviderFor(bob)
val container = mock<NamedDomainObjectContainer<DomainObject>> {
on { named("alice") } doReturn aliceProvider
on { named("bob") } doReturn bobProvider
}
container {
"alice" {
foo = "alice-foo"
}
"alice" {
// will configure the same object as the previous block
bar = true
}
"bob" {
foo = "bob-foo"
bar = false
}
}
assertThat(
alice,
equalTo(DomainObject("alice-foo", true))
)
assertThat(
bob,
equalTo(DomainObject("bob-foo", false))
)
}
sealed class DomainObjectBase {
data class Foo(var foo: String? = null) : DomainObjectBase()
data class Bar(var bar: Boolean? = null) : DomainObjectBase()
data class Default(val isDefault: Boolean = true) : DomainObjectBase()
}
@Test
fun `can configure polymorphic container`() {
val alice = DomainObjectBase.Foo()
val aliceProvider = mockDomainObjectProviderFor(alice)
val bob = DomainObjectBase.Bar()
val bobProvider = mockDomainObjectProviderFor(bob)
val default: DomainObjectBase = DomainObjectBase.Default()
val defaultProvider = mockDomainObjectProviderFor(default)
val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> {
onNamedWithAction("alice", DomainObjectBase.Foo::class, aliceProvider)
on { named(eq("bob"), eq(DomainObjectBase.Bar::class.java)) } doReturn bobProvider
on { named(eq("jim")) } doReturn defaultProvider
on { named(eq("steve")) } doReturn defaultProvider
}
container {
val a = "alice"(DomainObjectBase.Foo::class) {
foo = "foo"
}
val b = "bob"(type = DomainObjectBase.Bar::class)
val j = "jim" {}
val s = "steve"() // can invoke without a block, but must invoke
assertThat(a.get(), sameInstance(alice))
assertThat(b.get(), sameInstance(bob))
assertThat(j.get(), sameInstance(default))
assertThat(s.get(), sameInstance(default))
}
assertThat(
alice,
equalTo(DomainObjectBase.Foo("foo"))
)
assertThat(
bob,
equalTo(DomainObjectBase.Bar())
)
}
@Test
fun `can create and configure tasks`() {
val clean = mock<Delete>()
val cleanProvider = mockTaskProviderFor(clean)
val tasks = mock<TaskContainer> {
on { create(eq("clean"), eq(Delete::class.java), any<Action<Delete>>()) } doReturn clean
on { getByName("clean") } doReturn clean
onNamedWithAction("clean", Delete::class, cleanProvider)
}
tasks {
create<Delete>("clean") {
delete("some")
}
getByName<Delete>("clean") {
delete("stuff")
}
"clean"(type = Delete::class) {
delete("things")
}
}
tasks.getByName<Delete>("clean") {
delete("build")
}
inOrder(clean) {
verify(clean).delete("stuff")
verify(clean).delete("things")
verify(clean).delete("build")
}
}
@Test
fun `can create element within configuration block via delegated property`() {
val tasks = mock<TaskContainer> {
on { create("hello") } doReturn mock<Task>()
}
tasks {
@Suppress("unused_variable")
val hello by creating
}
verify(tasks).create("hello")
}
@Test
fun `can get element of specific type within configuration block via delegated property`() {
val task = mock<Exec>()
val tasks = mock<TaskContainer> {
on { getByName("hello") } doReturn task
}
@Suppress("unused_variable")
tasks {
val hello by getting(Exec::class)
}
verify(tasks).getByName("hello")
}
}
| subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/NamedDomainObjectContainerExtensionsTest.kt | 1718498556 |
package iii_conventions
import util.TODO
import util.doc26
fun todoTask27(): Nothing = TODO(
"""
Task 27.
Uncomment the commented code and make it compile.
To make '..' work implement a 'MyDate.rangeTo()' extension function returning DateRange.
Add all changes to the file MyDate.kt.
""",
documentation = doc26()
)
fun checkInRange2(date: MyDate, first: MyDate, last: MyDate): Boolean {
return date in first..last
}
| src/iii_conventions/_27_RangeTo.kt | 3228814190 |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.basics.classanalysis
import org.gradle.api.attributes.Attribute
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.Remapper
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry
private
val ignoredPackagePatterns = PackagePatterns(setOf("java"))
object Attributes {
val artifactType = Attribute.of("artifactType", String::class.java)
val minified = Attribute.of("minified", Boolean::class.javaObjectType)
}
class JarAnalyzer(
private val shadowPackage: String,
private val keepPackages: Set<String>,
private val unshadedPackages: Set<String>,
private val ignorePackages: Set<String>
) {
fun analyze(jarFile: File, classesDir: File, manifestFile: File, buildReceipt: File): ClassGraph {
val classGraph = classGraph()
val jarUri = URI.create("jar:${jarFile.toPath().toUri()}")
FileSystems.newFileSystem(jarUri, emptyMap<String, Any>()).use { jarFileSystem ->
jarFileSystem.rootDirectories.forEach {
visitClassDirectory(it, classGraph, classesDir, manifestFile.toPath(), buildReceipt.toPath())
}
}
return classGraph
}
private
fun classGraph() =
ClassGraph(
PackagePatterns(keepPackages),
PackagePatterns(unshadedPackages),
PackagePatterns(ignorePackages),
shadowPackage
)
private
fun visitClassDirectory(dir: Path, classes: ClassGraph, classesDir: File, manifest: Path, buildReceipt: Path) {
Files.walkFileTree(
dir,
object : FileVisitor<Path> {
private
var seenManifest: Boolean = false
override fun preVisitDirectory(dir: Path?, attrs: BasicFileAttributes?) =
FileVisitResult.CONTINUE
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
when {
file.isClassFilePath() -> {
visitClassFile(file)
}
file.isBuildReceipt() -> {
Files.copy(file, buildReceipt)
}
file.isUnseenManifestFilePath() -> {
seenManifest = true
Files.copy(file, manifest)
}
}
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path?, exc: IOException?) =
FileVisitResult.TERMINATE
override fun postVisitDirectory(dir: Path?, exc: IOException?) =
FileVisitResult.CONTINUE
private
fun Path.isClassFilePath() =
toString().endsWith(".class")
private
fun Path.isBuildReceipt() =
toString() == "/org/gradle/build-receipt.properties"
private
fun Path.isUnseenManifestFilePath() =
toString() == "/${JarFile.MANIFEST_NAME}" && !seenManifest
private
fun visitClassFile(file: Path) {
try {
val reader = ClassReader(Files.newInputStream(file))
val details = classes[reader.className]
details.visited = true
val classWriter = ClassWriter(0)
reader.accept(
ClassRemapper(
classWriter,
object : Remapper() {
override fun map(name: String): String {
if (ignoredPackagePatterns.matches(name)) {
return name
}
val dependencyDetails = classes[name]
if (dependencyDetails !== details) {
details.dependencies.add(dependencyDetails)
}
return dependencyDetails.outputClassName
}
}
),
ClassReader.EXPAND_FRAMES
)
classesDir.resolve(details.outputClassFilename).apply {
parentFile.mkdirs()
writeBytes(classWriter.toByteArray())
}
} catch (exception: Exception) {
throw ClassAnalysisException("Could not transform class from ${file.toFile()}", exception)
}
}
}
)
}
}
fun JarOutputStream.addJarEntry(entryName: String, sourceFile: File) {
putNextEntry(ZipEntry(entryName))
BufferedInputStream(FileInputStream(sourceFile)).use { inputStream -> inputStream.copyTo(this) }
closeEntry()
}
| build-logic/basics/src/main/kotlin/gradlebuild/basics/classanalysis/AnalyzeAndShade.kt | 2662981368 |
@file:JvmName("Util")
package kr.bydelta.koala
/**
* 세종 품사표기 표준안을 Enum Class로 담았습니다.
*
* @since 1.x
*/
enum class POS {
/** ([NOUNS]: 체언) ''일반명사'': 일반 개념을 표시하는 명사. **/
NNG,
/** ([NOUNS]: 체언) ''고유명사'' : 낱낱의 특정한 사물이나 사람을 다른 것들과 구별하여 부르기 위하여 고유의 기호를 붙인 이름. **/
NNP,
/** ([NOUNS]: 체언) ''일반 의존명사'' : 의미가 형식적이어서 다른 말 아래에 기대어 쓰이는 명사.
*
* ‘것1’, ‘따름1’, ‘뿐1’, ‘데1’ 따위가 있다.
* */
NNB,
/** ([NOUNS]: 체언) ''단위성 의존명사'' : 수효나 분량 따위의 단위를 나타내는 의존 명사.
*
* ‘쌀 한 말, 쇠고기 한 근, 굴비 한 두름, 북어 한 쾌, 고무신 한 켤레, 광목 한 필’에서 ‘말3’, ‘근3’, ‘두름1’, ‘쾌1’, ‘켤레2’, ‘필2’
* */
NNM,
/** ([NOUNS]: 체언) ''수사'' : 사물의 수량이나 순서를 나타내는 품사. 양수사와 서수사가 있다. **/
NR,
/** ([NOUNS]: 체언) ''대명사'' : 사람이나 사물의 이름을 대신 나타내는 말. 또는 그런 말들을 지칭하는 품사 **/
NP,
/** ([PREDICATES]: 용언) ''동사'' : 사물의 동작이나 작용을 나타내는 품사. **/
VV,
/** ([PREDICATES]: 용언) ''형용사'' : 사물의 성질이나 상태를 나타내는 품사. **/
VA,
/** ([PREDICATES]: 용언) ''보조용언'' : 본용언과 연결되어 그것의 뜻을 보충하는 역할을 하는 용언. 보조 동사, 보조 형용사가 있다.
*
* ‘ 가지고 싶다’의 ‘싶다’, ‘먹어 보다’의 ‘보다1’ 따위이다.
* */
VX,
/** ([PREDICATES]: 용언) ''긍정지정사(이다)'': 무엇이 무엇이라고 지정하는 단어. (이다) **/
VCP,
/** ([PREDICATES]: 용언) ''부정지정사(아니다)'': 무엇이 무엇이 아니라고 지정하는 단어. (아니다) **/
VCN,
/** ([MODIFIERS]: 수식언) ''관형사'' : 체언 앞에 놓여서, 그 체언의 내용을 자세히 꾸며 주는 품사. **/
MM,
/** ([MODIFIERS]: 수식언) ''부사'' : 용언 또는 다른 말 앞에 놓여 그 뜻을 분명하게 하는 품사. **/
MAG,
/** ([MODIFIERS]: 수식언) ''접속부사'' : 앞의 체언이나 문장의 뜻을 뒤의 체언이나 문장에 이어 주면서 뒤의 말을 꾸며 주는 부사.
*
* ‘ 그러나’, ‘그런데’, ‘그리고’, ‘하지만’ 따위가 있다.
* */
MAJ,
/** (독립언) ''감탄사'' : 말하는 이의 본능적인 놀람이나 느낌, 부름, 응답 따위를 나타내는 말의 부류이다. **/
IC,
/** ([POSTPOSITIONS]: 관계언) ''주격 조사'' : 문장 안에서, 체언이 서술어의 주어임을 표시하는 격 조사.
*
* ‘이/가’, ‘께서’, ‘에서2’ 따위가 있다.
* */
JKS,
/** ([POSTPOSITIONS]: 관계언) ''보격 조사'' : 문장 안에서, 체언이 보어임을 표시하는 격 조사.
*
* ‘철수는 위대한 학자가 되었다.’에서의 ‘가11’, ‘그는 보통 인물이 아니다.’에서의 ‘이27’ 따위이다.
* */
JKC,
/** ([POSTPOSITIONS]: 관계언) ''관형격 조사'' : 문장 안에서, 앞에 오는 체언이 뒤에 오는 체언의 관형어임을 보이는 조사. **/
JKG,
/** ([POSTPOSITIONS]: 관계언) ''목적격 조사'' : 문장 안에서, 체언이 서술어의 목적어임을 표시하는 격 조사. ‘을/를’이 있다. **/
JKO,
/** ([POSTPOSITIONS]: 관계언) ''부사격 조사'' : 문장 안에서, 체언이 부사어임을 보이는 조사.
*
* ‘ 에4’, ‘에서2’, ‘(으)로’, ‘와/과’, ‘보다4’ 따위가 있다. **/
JKB,
/** ([POSTPOSITIONS]: 관계언) ''호격 조사'' :
* 문장 안에서, 체언이 부름의 자리에 놓이게 하여 독립어가 되게 하는 조사.
*
* ‘영숙아’의 ‘아9’, ‘철수야’의 ‘야12’ 따위가 있다. **/
JKV,
/** ([POSTPOSITIONS]: 관계언) ''인용격 조사'': 앞의 말이 인용됨을 나타내는 조사. **/
JKQ,
/** ([POSTPOSITIONS]: 관계언) ''접속 조사'' : 둘 이상의 단어나 구 따위를 같은 자격으로 이어 주는 구실을 하는 조사.
*
* ‘와4’, ‘과12’, ‘하고5’, ‘(이)나’, ‘(이)랑’ 따위가 있다. **/
JC,
/** ([POSTPOSITIONS]: 관계언) ''보조사'' : 체언, 부사, 활용 어미 따위에 붙어서 어떤 특별한 의미를 더해 주는 조사.
*
* ‘은5’, ‘는1’, ‘도15’, ‘만14’, ‘까지3’, ‘마저’, ‘조차8’, ‘부터’ 따위가 있다.
* */
JX,
/** ([ENDINGS]: 어미) ''선어말 어미'' : 어말 어미 앞에 나타나는 어미.
*
* * ‘-시-23’, ‘-옵-1’ 따위와 같이 높임법에 관한 것과
* * ‘-았-’, ‘-는-2’, ‘-더-2’, ‘-겠-’ 따위와 같이 시상(時相)에 관한 것이 있다.
* */
EP,
/** ([ENDINGS]: 어미) ''종결 어미'' : 한 문장을 종결되게 하는 어말 어미.
*
* * 동사에는 평서형ㆍ감탄형ㆍ의문형ㆍ명령형ㆍ청유형이 있고,
* * 형용사에는 평서형ㆍ감탄형ㆍ의문형이 있다.
* */
EF,
/** ([ENDINGS]: 어미) ''연결 어미'' 어간에 붙어 다음 말에 연결하는 구실을 하는 어미.
*
* ‘-게10’, ‘-고25’, ‘-(으)며’, ‘-(으)면’, ‘-(으)니’, ‘-아/어’, ‘-지23’ 따위가 있다.
* */
EC,
/** ([ENDINGS]: 어미) ''명사형 전성어미'': 용언의 어간에 붙어 명사의 기능을 수행하게 하는 어미. **/
ETN,
/** ([ENDINGS]: 어미) ''관형형 전성어미'': 용언의 어간에 붙어 관형사의 기능을 수행하게 하는 어미. **/
ETM,
/** ([AFFIXES]: 접사) ''체언 접두사'' : 파생어를 만드는 접사로, 어근이나 단어의 앞에 붙어 새로운 단어가 되게 하는 말. **/
XPN,
/** ([AFFIXES]: 접사) ''용언 접두사'' : 파생어를 만드는 접사로, 어근이나 단어의 앞에 붙어 새로운 단어가 되게 하는 말. **/
XPV,
/** ([AFFIXES]: 접사) ''명사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 명사가 되게 하는 말.
* */
XSN,
/** ([AFFIXES]: 접사) ''동사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 동사가 되게 하는 말.
* */
XSV,
/** ([AFFIXES]: 접사) ''형용사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 형용사가 되게 하는 말.
* */
XSA,
/** ([AFFIXES]: 접사) ''부사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 부사가 되게 하는 말.
* */
XSM,
/** ([AFFIXES]: 접사) ''기타 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 단어가 되게 하는 말.
* */
XSO,
/** ''어근'' :
* 단어를 분석할 때, 실질적 의미를 나타내는 중심이 되는 부분.
*
* ‘덮개’의 ‘덮-’, ‘어른스럽다’의 ‘어른1’ 따위이다.
* */
XR,
/** ([SYMBOLS]: 기호) 종결기호: 마침/물음/느낌표 **/
SF,
/** ([SYMBOLS]: 기호) 연결기호: 쉼표/가운뎃점/빗금 **/
SP,
/** ([SYMBOLS]: 기호) 묶음기호: 괄호/묶음표/따옴표 **/
SS,
/** ([SYMBOLS]: 기호) 생략기호: 줄임표 **/
SE,
/** ([SYMBOLS]: 기호) 붙임기호: 물결표/줄임표/빠짐표 **/
SO,
/** ([SYMBOLS]: 기호) 기타기호 **/
SW,
/** 명사 추정 범주 **/
NF,
/** 동사 추정 범주 **/
NV,
/** 분석 불능 범주 **/
NA,
/** 외국어 **/
SL,
/** 한자 **/
SH,
/** 숫자 **/
SN,
/** 임시기호(내부처리용) **/
TEMP;
/**
* Static variables
*/
companion object {
/** 전체 **/
@JvmStatic
val ALL = values().toSet()
/** 체언 **/
@JvmStatic
val NOUNS = setOf(NNG, NNP, NNB, NNM, NR, NP)
/** 용언 **/
@JvmStatic
val PREDICATES = setOf(VV, VA, VX, VCP, VCN)
/** 수식언 **/
@JvmStatic
val MODIFIERS = setOf(MM, MAG, MAJ)
/** 관계언(조사) **/
@JvmStatic
val POSTPOSITIONS = setOf(JKS, JKC, JKG, JKO, JKB, JKV, JKQ, JC, JX)
/** 어미 **/
@JvmStatic
val ENDINGS = setOf(EP, EF, EC, ETN, ETM)
/** 접사 **/
@JvmStatic
val AFFIXES = setOf(XPN, XPV, XSN, XSV, XSM, XSA, XSO)
/** 접미사 **/
@JvmStatic
val SUFFIXES = setOf(XSN, XSV, XSM, XSA, XSO)
/** 기호 **/
@JvmStatic
val SYMBOLS = setOf(SF, SP, SS, SE, SW, SO)
/** 미확인 단어 **/
@JvmStatic
val UNKNOWNS = setOf(NF, NV, NA)
}
/**
* 이 값이 체언([NOUNS])인지 확인합니다.
*
* @since 1.x
* @return 체언인 경우 True
*/
fun isNoun(): Boolean = this in NOUNS
/**
* 이 값이 용언([PREDICATES])인지 확인합니다.
*
* @since 1.x
* @return 용언인 경우 True
*/
fun isPredicate(): Boolean = this in PREDICATES
/**
* 이 값이 수식언([MODIFIERS])인지 확인합니다.
*
* @since 1.x
* @return 수식언인 경우 True
*/
fun isModifier(): Boolean = this in MODIFIERS
/**
* 이 값이 관계언(조사; [POSTPOSITIONS])인지 확인합니다.
*
* @since 1.x
* @return 관계언인 경우 True
*/
fun isPostPosition(): Boolean = this in POSTPOSITIONS
/**
* 이 값이 어미([ENDINGS])인지 확인합니다.
*
* @since 1.x
* @return 어미인 경우 True
*/
fun isEnding(): Boolean = this in ENDINGS
/**
* 이 값이 접사([AFFIXES])인지 확인합니다.
*
* @since 1.x
* @return 접사인 경우 True
*/
fun isAffix(): Boolean = this in AFFIXES
/**
* 이 값이 접미사([SUFFIXES])인지 확인합니다.
*
* @since 1.x
* @return 접미사인 경우 True
*/
fun isSuffix(): Boolean = this in SUFFIXES
/**
* 이 값이 기호([SYMBOLS])인지 확인합니다.
*
* @since 1.x
* @return 기호인 경우 True
*/
fun isSymbol(): Boolean = this in SYMBOLS
/**
* 이 값이 미확인 단어([UNKNOWNS])인지 확인합니다.
*
* @since 1.x
* @return 미확인 단어인 경우 True
*/
fun isUnknown(): Boolean = this in UNKNOWNS
/**
* 이 값이 주어진 [tag]로 시작하는지 확인합니다.
*
* @since 2.0.0
* @return 그러한 경우 True
*/
fun startsWith(tag: CharSequence): Boolean {
val xtag = tag.toString().toUpperCase()
return if (xtag == "N") name.startsWith(xtag) && !isUnknown() else name.startsWith(xtag)
}
}
/**
* 전체 형태소의 개수
*/
internal inline val POS_SIZE get() = POS.values().size
/**
* (Extension) 이 String 값에 주어진 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* POS.NN in "N"
* \\ 또는
* "N".contains(POS.NN)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* POS.NN in "N"
* \\ 또는
* "N".contains(POS.NN)
* ```
*
* ### Java
* ```java
* Util.contains("N", POS.NN)
* ```
*
* @since 2.0.0
* @param[tag] 하위 분류인지 확인할 형태소 품사표기 값
* @return 하위 분류에 해당한다면 true
*/
operator fun CharSequence.contains(tag: POS): Boolean = tag.startsWith(this)
/*************************************************************/
/**
* 세종 구문구조 표지자를 Enum class로 담았습니다.
*
* @since 2.0.0
*/
enum class PhraseTag {
/**
* 구문구조 표지자: 문장
*/
S,
/**
* 구문구조 표지자: 체언 구
*
* 문장에서 주어 따위의 기능을 하는 명사, 대명사, 수사 또는 이 역할을 하는 구
*/
NP,
/**
* 구문구조 표지자: 용언 구
*
* 문장에서 서술어의 기능을 하는 동사, 형용사 또는 이 역할을 하는 구
*/
VP,
/**
* 구문구조 표지자: 긍정지정사구
*
* 무엇이 무엇이라고 지정하는 단어(이다) 또는 이 역할을 하는 구
*/
VNP,
/**
* 구문구조 표지자: 부사구
*
* 용언구 또는 다른 말 앞에 놓여 그 뜻을 분명하게 하는 단어 또는 이 역할을 하는 구
*/
AP,
/**
* 구문구조 표지자: 관형사구
*
* 체언구 앞에 놓여서, 그 체언구의 내용을 자세히 꾸며 주는 단어 또는 이 역할을 하는 구
*/
DP,
/**
* 구문구조 표지자: 감탄사구
*
* 말하는 이의 본능적인 놀람이나 느낌, 부름, 응답 따위를 나타내는 단어 또는 이 역할을 하는 구
*/
IP,
/**
* 구문구조 표지자: 의사(Pseudo) 구
*
* 인용부호와 괄호를 제외한 나머지 부호나, 조사, 어미가 단독으로 어절을 이룰 때 (즉, 구를 보통 이루지 않는 것이 구를 이루는 경우)
*/
X,
/**
* 구문구조 표지자: 왼쪽 인용부호
*
* 열림 인용부호
*/
L,
/**
* 구문구조 표지자: 오른쪽 인용부호
*
* 닫힘 인용부호
*/
R,
/**
* 구문구조 표지자: 인용절
*
* 인용 부호 내부에 있는 인용된 절. 세종 표지에서는 Q, U, W, Y, Z가 사용되나 KoalaNLP에서는 하나로 통일함.
*/
Q
}
/**
* (Extension) 주어진 목록에 주어진 구문구조 표지 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* PhraseTag.NP in listOf("S", "NP")
* \\ 또는
* listOf("S", "NP").contains(PhraseTag.NP)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* PhraseTag.NP in Seq("S", "NP")
* \\ 또는
* Seq("S", "NP").contains(PhraseTag.NP)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("S")
* list.add("NP")
* Util.contains(list, PhraseTag.NP)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 구문구조 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: PhraseTag): Boolean = this.any { it == tag.name }
/********************************************************/
/**
* 의존구문구조 기능표지자를 담은 Enum class입니다.
* (ETRI 표준안)
*
* [참고](http://aiopen.etri.re.kr/data/1.%20%EC%9D%98%EC%A1%B4%20%EA%B5%AC%EB%AC%B8%EB%B6%84%EC%84%9D%EC%9D%84%20%EC%9C%84%ED%95%9C%20%ED%95%9C%EA%B5%AD%EC%96%B4%20%EC%9D%98%EC%A1%B4%EA%B4%80%EA%B3%84%20%EA%B0%80%EC%9D%B4%EB%93%9C%EB%9D%BC%EC%9D%B8%20%EB%B0%8F%20%EC%97%91%EC%86%8C%EB%B8%8C%EB%A0%88%EC%9D%B8%20%EC%96%B8%EC%96%B4%EB%B6%84%EC%84%9D%20%EB%A7%90%EB%AD%89%EC%B9%98.pdf)
*
* @since 1.x
*/
enum class DependencyTag {
/** ''주어'': 술어가 나타내는 동작이나 상태의 주체가 되는 말
*
* 주격 체언구(NP_SBJ), 명사 전성 용언구(VP_SBJ), 명사절(S_SBJ) */
SBJ,
/** ''목적어'': 타동사가 쓰인 문장에서 동작의 대상이 되는 말
*
* 목적격 체언구(NP_OBJ), 명사 전성 용언구(VP_OBJ), 명사절(S_OBJ) */
OBJ,
/** ''보어'': 주어와 서술어만으로는 뜻이 완전하지 못한 문장에서, 그 불완전한 곳을 보충하여 뜻을 완전하게 하는 수식어.
*
* 보격 체언구(NP_CMP), 명사 전성 용언구(VP_CMP), 인용절(S_CMP) */
CMP,
/** 체언 수식어(관형격). 관형격 체언구(NP_MOD), 관형형 용언구(VP_MOD), 관형절(S_MOD) */
MOD,
/** 용언 수식어(부사격). 부사격 체언구(NP_AJT), 부사격 용언구(VP_AJT) 문말어미+부사격 조사(S_AJT) */
AJT,
/** ''접속어'': 단어와 단어, 구절과 구절, 문장과 문장을 이어 주는 구실을 하는 문장 성분.
*
* 접속격 체언(NP_CNJ) */
CNJ,
/** 삽입어구 */
PRN,
/** 정의되지 않음 */
UNDEF,
/** ROOT 지시자 */
ROOT
}
/**
* (Extension) 주어진 목록에 주어진 의존구문 표지 [tag]가 포함되는지 확인.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* DependencyTag.SBJ in listOf("SBJ", "MOD")
* \\ 또는
* listOf("SBJ", "MOD").contains(DependencyTag.SBJ)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* DependencyTag.SBJ in Seq("SBJ", "MOD")
* \\ 또는
* Seq("SBJ", "MOD").contains(DependencyTag.SBJ)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("SBJ")
* list.add("MOD")
* Util.contains(list, DependencyTag.SBJ)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 의존구조 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: DependencyTag): Boolean = this.any { it == tag.name }
/************************************************************/
/**
* 의미역(Semantic Role) 분석 표지를 담은 Enum class입니다.
* (ETRI 표준안)
*
* @since 2.0.0
*/
enum class RoleType {
/**
* (필수격) **행동주, 경험자.** 술어로 기술된 행동을 하거나 경험한 대상.
*
* 예: {"진흥왕은" 화랑도를 개편했다.}에서 _<진흥왕은>_, {"쑨원은" 삼민주의를 내세웠다.}에서 _<쑨원은>_
*/
ARG0,
/**
* (필수격) **피동작주, 대상.** 술어로 기술된 행동을 당한 대상 (주로 목적격, 피동작 대상). '이동'에 관한 행동에 의해서 위치의 변화가 되거나, '생성/소멸' 사건의 결과로 존재가 변화하는 대상.
*
* 예: {진흥왕은 "화랑도를" 개편했다.}에서 _<화랑도를>_, {"범인은" 사거리에서 발견되었다.}에서 _<범인은>_, {밤거리에는 "인적이" 드물다.}에서 _<인적이>_.
*/
ARG1,
/**
* (필수격) **시작점, 수혜자, 결과.** 술어로 기술된 행동의 시작점, 행동으로 인해 수혜를 받는 대상, 행동을 기술하기 위해 필요한 장소.
*
* 예: {영희가 "철수에게서" 그 선물을 받았다.}에서 _<철수에게서>_.
*/
ARG2,
/**
* (필수격) **착점.** 술어로 기술된 행동의 도착점.
*
* 예: {연이가 "동창회에" 참석했다.}에서 _<동창회에>_. {근이가 "학교에" 갔다.}에서 _<학교에>_.
*/
ARG3,
/**
* (부가격) **장소.** 술어로 기술된 행동이 발생하는 공간. 주로 술어가 '이동'이 아닌 상태를 나타내고, '~에(서)' 조사와 함께 쓰이는 경우.
*
* 예: {친구들이 "서울에" 많이 산다.}에서 _<서울에>_.
*/
ARGM_LOC,
/**
* (부가격) **방향.** 술어가 '이동' 상태를 나타낼 때, '~(으)로' 조사와 함께 쓰이는 경우.
*
* 예: {달이 "서쪽으로" 기울었다.}에서 _<서쪽으로>_. */
ARGM_DIR,
/**
* (부가격) **조건.** 술어의 행동이 발생되는 조건이나 인물, 사물 따위의 자격을 나타내는 경우. 주로 '~중에', '~가운데에', '~보다', '~에 대해'
*
* 예: {"과세 대상 금액이 많을수록" 높은 세율을 적용한다.}에서 _<많을수록>_. */
ARGM_CND,
/**
* (부가격) **방법.** 술어의 행동을 수행하는 방법. 또는 술어가 특정 언어에 의한 것을 나타낼 때, 그 언어. (구체적인 사물이 등장하는 경우는 [ARGM_INS] 참고)
*
* 예: {그는 "큰 소리로" 떠들었다.}에서 _<소리로>_. */
ARGM_MNR,
/**
* (부가격) **시간.** 술어의 행동이 발생한 시간 등과 같이 술어와 관련된 시간. 명확한 날짜, 시기, 시대를 지칭하는 경우.
*
* 단, 기간의 범위를 나타내는 경우, 즉 ~에서 ~까지의 경우는 시점([ARG2])과 착점([ARG3])으로 분석함.
*
* 예: {진달래는 "이른 봄에" 핀다.}에서 _<봄에>_. */
ARGM_TMP,
/**
* (부가격) **범위.** 크기 또는 높이 등의 수치나 정도를 논하는 경우. '가장', '최고', '매우', '더욱' 등을 나타내는 경우.
*
* 예: {그 악기는 "4개의" 현을 가진다.}에서 _<4개의>_. */
ARGM_EXT,
/**
* (부가격) **보조서술.** 대상과 같은 의미이거나 대상의 상태를 나타내면서 술어를 수식하는 것. 주로 '~로서'. 또는 '최초로'와 같이 술어의 정해진 순서를 나타내는 경우.
*
* 예: {석회암 지대에서 "깔대기 모양으로" 파인 웅덩이가 생겼다.}에서 _<모양으로>_. */
ARGM_PRD,
/**
* (부가격) **목적.** 술어의 주체가 가진 목표. 또는 행위의 의도. 주로 '~를 위해'. 발생 이유([ARGM_CAU])와 유사함에 주의.
*
* 예: {주나라의 백이와 숙제는 "절개를 지키고자" 수양산에 거처했다.}에서 _<지키고자>_. */
ARGM_PRP,
/**
* (부가격) **발생 이유.** 술어가 발생한 이유. '~때문에'를 대신할 수 있는 조사가 붙은 경우. 목적([ARGM_PRP])과 혼동되나, 목적은 아닌 것.
*
* 예: {지난 밤 "강풍으로" 가로수가 넘어졌다.}에서 _<강풍으로>_. */
ARGM_CAU,
/**
* (부가격) **담화 연결.** 문장 접속 부사. (그러나, 그리고, 즉 등.)
*
* 예: {"하지만" 여기서 동, 서는 중국과 유럽을 뜻한다.}에서 _<하지만>_. */
ARGM_DIS,
/**
* (부가격) **부사적 어구.** ('마치', '물론', '역시' 등)
*
* 예: {산의 능선이 "마치" 닭벼슬을 쓴 용의 형상을 닮았다.}에서 _<마치>_. */
ARGM_ADV,
/**
* (부가격) **부정.** 술어에 부정의 의미를 더하는 경우.
*
* 예: {산은 불에 타지 "않았다."}에서 _<않았다.>_. */
ARGM_NEG,
/**
* (부가격) **도구.** 술어의 행동을 할 때 사용되는 도구. 방법([ARGM_MNR])보다 구체적인 사물이 등장할 때.
*
* 예: {"하얀 천으로" 상자를 덮었다.}에서 _<천으로>_. */
ARGM_INS
}
/**
* (Extension) 주어진 목록에 주어진 의미역 표지 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* RoleType.ARG0 in listOf("ARG0", "ARGM_LOC")
* \\ 또는
* listOf("ARG0", "ARGM_LOC").contains(RoleType.ARG0)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* RoleType.ARG0 in Seq("ARG0", "ARGM_LOC")
* \\ 또는
* Seq("ARG0", "ARGM_LOC").contains(RoleType.ARG0)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("ARG0")
* list.add("ARGM_LOC")
* Util.contains(list, RoleType.ARG0)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 의미역 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: RoleType): Boolean = this.any { it == tag.name }
/************************************************************/
/**
* 대분류 개체명(Named Entity) 유형을 담은 Enum class입니다.
* (ETRI 표준안)
*
* @since 2.0.0
*/
enum class CoarseEntityType {
/**
* 사람의 이름
*/
PS,
/**
* 장소의 이름
*/
LC,
/**
* 단체의 이름
*/
OG,
/**
* 작품/물품의 이름
*/
AF,
/**
* 기간/날짜의 이름
*/
DT,
/**
* 시간/간격의 이름
*/
TI,
/**
* 문명/문화활동에 사용되는 명칭
*/
CV,
/**
* 동물의 이름
*/
AM,
/**
* 식물의 이름
*/
PT,
/**
* 수량의 값, 서수 또는 이름
*/
QT,
/**
* 학문분야 또는 학파, 예술사조 등의 이름
*/
FD,
/**
* 이론, 법칙, 원리 등의 이름
*/
TR,
/**
* 사회적 활동, 운동, 사건 등의 이름
*/
EV,
/**
* 화학적 구성물의 이름
*/
MT,
/**
* 용어
*/
TM
}
/**
* (Extension) 주어진 목록에 주어진 개체명 유형 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* CoarseEntityType.PL in listOf("PS", "PL")
* \\ 또는
* listOf("PS", "PL").contains(CoarseEntityType.PL)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* CoarseEntityType.PL in Seq("PS", "PL")
* \\ 또는
* Seq("PS", "PL").contains(CoarseEntityType.PL)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("PS")
* list.add("PL")
* Util.contains(list, CoarseEntityType.PL)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 개체명 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: CoarseEntityType): Boolean = this.any { it == tag.name }
| core/src/main/kotlin/kr/bydelta/koala/types.kt | 3915162278 |
package org.wordpress.android.ui.reader.utils
import java.util.Date
import javax.inject.Inject
class DateProvider @Inject constructor() {
fun getCurrentDate() = Date()
}
| WordPress/src/main/java/org/wordpress/android/ui/reader/utils/DateProvider.kt | 752758390 |
package org.wordpress.android.ui.reader.discover.interests
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.models.ReaderTag
import org.wordpress.android.models.ReaderTagList
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsFragment.EntryPoint
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonDisabledUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonEnabledUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonHiddenUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ContentUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ErrorUiState.ConnectionErrorUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ErrorUiState.RequestFailedErrorUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.InitialLoadingUiState
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication
import org.wordpress.android.ui.reader.repository.ReaderTagRepository
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.reader.viewmodels.ReaderViewModel
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.viewmodel.Event
import javax.inject.Inject
class ReaderInterestsViewModel @Inject constructor(
private val readerTagRepository: ReaderTagRepository,
private val readerTracker: ReaderTracker
) : ViewModel() {
private var isStarted = false
private lateinit var currentLanguage: String
private var parentViewModel: ReaderViewModel? = null
private var entryPoint = EntryPoint.DISCOVER
private var userTags = ReaderTagList()
private val _uiState: MutableLiveData<UiState> = MutableLiveData()
val uiState: LiveData<UiState> = _uiState
private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>()
val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents
private val _closeReaderInterests = MutableLiveData<Event<Unit>>()
val closeReaderInterests: LiveData<Event<Unit>> = _closeReaderInterests
private var userTagsFetchedSuccessfully = false
fun start(
currentLanguage: String,
parentViewModel: ReaderViewModel?,
entryPoint: EntryPoint
) {
if (isStarted && this.currentLanguage == currentLanguage) {
return
}
isStarted = true
this.currentLanguage = currentLanguage
this.parentViewModel = parentViewModel
this.entryPoint = entryPoint
parentViewModel?.dismissQuickStartSnackbarIfNeeded()
loadUserTags()
}
private fun loadUserTags() {
updateUiState(InitialLoadingUiState)
viewModelScope.launch {
when (val result = readerTagRepository.getUserTags()) {
is ReaderRepositoryCommunication.SuccessWithData<*> -> {
userTagsFetchedSuccessfully = true
userTags = result.data as ReaderTagList
when (entryPoint) {
EntryPoint.DISCOVER -> checkAndLoadInterests(userTags)
EntryPoint.SETTINGS -> loadInterests(userTags)
}
}
is ReaderRepositoryCommunication.Error -> {
if (result is ReaderRepositoryCommunication.Error.NetworkUnavailable) {
updateUiState(ConnectionErrorUiState)
} else if (result is ReaderRepositoryCommunication.Error.RemoteRequestFailure) {
updateUiState(RequestFailedErrorUiState)
}
}
ReaderRepositoryCommunication.Started -> Unit // Do nothing
ReaderRepositoryCommunication.Success -> Unit // Do nothing
}
}
}
private fun checkAndLoadInterests(userTags: ReaderTagList) {
if (userTags.isEmpty()) {
loadInterests(userTags)
} else {
parentViewModel?.onCloseReaderInterests()
}
}
private fun loadInterests(userTags: ReaderTagList) {
updateUiState(InitialLoadingUiState)
viewModelScope.launch {
val newUiState: UiState? = when (val result = readerTagRepository.getInterests()) {
is ReaderRepositoryCommunication.SuccessWithData<*> -> {
readerTracker.track(AnalyticsTracker.Stat.SELECT_INTERESTS_SHOWN)
val tags = (result.data as ReaderTagList).filter { checkAndExcludeTag(userTags, it) }
val distinctTags = ReaderTagList().apply { addAll(tags.distinctBy { it.tagSlug }) }
when (entryPoint) {
EntryPoint.DISCOVER -> ContentUiState(
interestsUiState = transformToInterestsUiState(distinctTags),
interests = distinctTags,
doneButtonUiState = DoneButtonDisabledUiState(),
titleVisible = true
)
EntryPoint.SETTINGS -> ContentUiState(
interestsUiState = transformToInterestsUiState(distinctTags),
interests = distinctTags,
doneButtonUiState = DoneButtonDisabledUiState(R.string.reader_btn_done),
titleVisible = false
)
}
}
is ReaderRepositoryCommunication.Error.NetworkUnavailable -> {
ConnectionErrorUiState
}
is ReaderRepositoryCommunication.Error.RemoteRequestFailure -> {
RequestFailedErrorUiState
}
else -> {
null
}
}
newUiState?.let {
updateUiState(it)
}
}
}
private fun checkAndExcludeTag(userTags: ReaderTagList, tag: ReaderTag): Boolean {
var contain = false
userTags.forEach { excludedTag ->
if (excludedTag.tagSlug.equals(tag.tagSlug)) {
contain = true
return@forEach
}
}
return !contain
}
fun onInterestAtIndexToggled(index: Int, isChecked: Boolean) {
uiState.value?.let {
val currentUiState = uiState.value as ContentUiState
val updatedInterestsUiState = getUpdatedInterestsUiState(index, isChecked)
updateUiState(
currentUiState.copy(
interestsUiState = updatedInterestsUiState,
doneButtonUiState = currentUiState.getDoneButtonState(
entryPoint = entryPoint,
isInterestChecked = isChecked
)
)
)
parentViewModel?.completeQuickStartFollowSiteTaskIfNeeded()
}
}
fun onDoneButtonClick() {
val contentUiState = uiState.value as ContentUiState
updateUiState(
contentUiState.copy(
progressBarVisible = true,
doneButtonUiState = DoneButtonDisabledUiState(R.string.reader_btn_done)
)
)
trackInterests(contentUiState.getSelectedInterests())
viewModelScope.launch {
readerTagRepository.clearTagLastUpdated(ReaderTag.createDiscoverPostCardsTag())
when (val result = readerTagRepository.saveInterests(contentUiState.getSelectedInterests())) {
is ReaderRepositoryCommunication.Success -> {
when (entryPoint) {
EntryPoint.DISCOVER -> parentViewModel?.onCloseReaderInterests()
EntryPoint.SETTINGS -> _closeReaderInterests.value = Event(Unit)
}
}
is ReaderRepositoryCommunication.Error -> {
if (result is ReaderRepositoryCommunication.Error.NetworkUnavailable) {
_snackbarEvents.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.no_network_message)))
)
} else if (result is ReaderRepositoryCommunication.Error.RemoteRequestFailure) {
_snackbarEvents.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.reader_error_request_failed_title)))
)
}
updateUiState(
contentUiState.copy(
progressBarVisible = false,
doneButtonUiState = DoneButtonEnabledUiState(R.string.reader_btn_done)
)
)
}
is ReaderRepositoryCommunication.Started -> Unit // Do nothing
is ReaderRepositoryCommunication.SuccessWithData<*> -> Unit // Do nothing
}
}
}
fun onRetryButtonClick() {
if (!userTagsFetchedSuccessfully) {
loadUserTags()
} else {
loadInterests(userTags)
}
}
private fun transformToInterestsUiState(interests: ReaderTagList) =
interests.map { interest ->
TagUiState(interest.tagTitle, interest.tagSlug)
}
private fun getUpdatedInterestsUiState(index: Int, isChecked: Boolean): List<TagUiState> {
val currentUiState = uiState.value as ContentUiState
val newInterestsUiState = currentUiState.interestsUiState.toMutableList()
newInterestsUiState[index] = currentUiState.interestsUiState[index].copy(isChecked = isChecked)
return newInterestsUiState
}
private fun updateUiState(uiState: UiState) {
_uiState.value = uiState
}
private fun trackInterests(tags: List<ReaderTag>) {
tags.forEach {
val source = when (entryPoint) {
EntryPoint.DISCOVER -> ReaderTracker.SOURCE_DISCOVER
EntryPoint.SETTINGS -> ReaderTracker.SOURCE_SETTINGS
}
readerTracker.trackTag(
AnalyticsTracker.Stat.READER_TAG_FOLLOWED,
it.tagSlug,
source
)
}
readerTracker.trackTagQuantity(AnalyticsTracker.Stat.SELECT_INTERESTS_PICKED, tags.size)
}
fun onBackButtonClick() {
when (entryPoint) {
EntryPoint.DISCOVER -> parentViewModel?.onCloseReaderInterests()
EntryPoint.SETTINGS -> _closeReaderInterests.value = Event(Unit)
}
}
sealed class UiState(
open val doneButtonUiState: DoneButtonUiState = DoneButtonHiddenUiState,
open val progressBarVisible: Boolean = false,
open val titleVisible: Boolean = false,
val errorLayoutVisible: Boolean = false
) {
object InitialLoadingUiState : UiState(
progressBarVisible = true
)
data class ContentUiState(
val interestsUiState: List<TagUiState>,
val interests: ReaderTagList,
override val progressBarVisible: Boolean = false,
override val doneButtonUiState: DoneButtonUiState,
override val titleVisible: Boolean
) : UiState(
progressBarVisible = false,
titleVisible = titleVisible,
errorLayoutVisible = false
)
sealed class ErrorUiState constructor(
val titleRes: Int
) : UiState(
progressBarVisible = false,
errorLayoutVisible = true
) {
object ConnectionErrorUiState : ErrorUiState(R.string.no_network_message)
object RequestFailedErrorUiState : ErrorUiState(R.string.reader_error_request_failed_title)
}
private fun getCheckedInterestsUiState(): List<TagUiState> {
return if (this is ContentUiState) {
interestsUiState.filter { it.isChecked }
} else {
emptyList()
}
}
fun getSelectedInterests(): List<ReaderTag> {
return if (this is ContentUiState) {
interests.filter {
getCheckedInterestsUiState().map { checkedInterestUiState ->
checkedInterestUiState.slug
}.contains(it.tagSlug)
}
} else {
emptyList()
}
}
fun getDoneButtonState(
entryPoint: EntryPoint,
isInterestChecked: Boolean = false
): DoneButtonUiState {
return if (this is ContentUiState) {
val disableDoneButton = interests.isEmpty() ||
(getCheckedInterestsUiState().size == 1 && !isInterestChecked)
if (disableDoneButton) {
when (entryPoint) {
EntryPoint.DISCOVER -> DoneButtonDisabledUiState()
EntryPoint.SETTINGS -> DoneButtonDisabledUiState(R.string.reader_btn_done)
}
} else {
DoneButtonEnabledUiState()
}
} else {
DoneButtonHiddenUiState
}
}
}
sealed class DoneButtonUiState(
@StringRes open val titleRes: Int = R.string.reader_btn_done,
val enabled: Boolean = false,
val visible: Boolean = true
) {
data class DoneButtonEnabledUiState(
@StringRes override val titleRes: Int = R.string.reader_btn_done
) : DoneButtonUiState(
enabled = true
)
data class DoneButtonDisabledUiState(
@StringRes override val titleRes: Int = R.string.reader_btn_select_few_interests
) : DoneButtonUiState(
enabled = false
)
object DoneButtonHiddenUiState : DoneButtonUiState(
visible = false
)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt | 319208351 |
package org.wordpress.android.ui.photopicker
import android.app.Activity
import android.content.Intent
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.RequestCodes
import org.wordpress.android.ui.media.MediaBrowserType
import org.wordpress.android.ui.media.MediaBrowserType.FEATURED_IMAGE_PICKER
import org.wordpress.android.ui.media.MediaBrowserType.WP_STORIES_MEDIA_PICKER
import org.wordpress.android.ui.mediapicker.MediaPickerActivity
import org.wordpress.android.ui.mediapicker.MediaPickerSetup
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.ENABLED
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.HIDDEN
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.STORIES
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.DEVICE
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.GIF_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.STOCK_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.WP_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaType
import org.wordpress.android.ui.mediapicker.MediaType.AUDIO
import org.wordpress.android.ui.mediapicker.MediaType.DOCUMENT
import org.wordpress.android.ui.mediapicker.MediaType.IMAGE
import org.wordpress.android.ui.mediapicker.MediaType.VIDEO
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
class MediaPickerLauncher @Inject constructor(
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) {
fun showFeaturedImagePicker(
activity: Activity,
site: SiteModel?,
localPostId: Int
) {
val availableDataSources = if (site != null && site.isUsingWpComRestApi) {
setOf(WP_LIBRARY, STOCK_LIBRARY, GIF_LIBRARY)
} else {
setOf(WP_LIBRARY, GIF_LIBRARY)
}
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = availableDataSources,
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = true,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site,
localPostId
)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showSiteIconPicker(
activity: Activity,
site: SiteModel?
) {
val intent = buildSitePickerIntent(activity, site)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
@Suppress("DEPRECATION")
fun showSiteIconPicker(
fragment: Fragment,
site: SiteModel?
) {
val intent = buildSitePickerIntent(fragment.requireActivity(), site)
fragment.startActivityForResult(intent, RequestCodes.SITE_ICON_PICKER)
}
private fun buildSitePickerIntent(
activity: Activity,
site: SiteModel?
): Intent {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(WP_LIBRARY),
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site,
null
)
return intent
}
fun showPhotoPickerForResult(
activity: Activity,
browserType: MediaBrowserType,
site: SiteModel?,
localPostId: Int?
) {
val intent = MediaPickerActivity.buildIntent(
activity,
buildLocalMediaPickerSetup(browserType),
site,
localPostId
)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showStoriesPhotoPickerForResultAndTrack(activity: Activity, site: SiteModel?) {
analyticsTrackerWrapper.track(Stat.MEDIA_PICKER_OPEN_FOR_STORIES)
showStoriesPhotoPickerForResult(activity, site)
}
@Suppress("DEPRECATION")
fun showStoriesPhotoPickerForResult(
activity: Activity,
site: SiteModel?
) {
ActivityLauncher.showPhotoPickerForResult(activity, WP_STORIES_MEDIA_PICKER, site, null)
}
@Suppress("DEPRECATION")
fun showGravatarPicker(fragment: Fragment) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(),
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
fragment.requireContext(),
mediaPickerSetup
)
fragment.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showFilePicker(activity: Activity, canMultiselect: Boolean = true, site: SiteModel) {
showFilePicker(
activity,
site,
canMultiselect,
mutableSetOf(IMAGE, VIDEO, AUDIO, DOCUMENT),
RequestCodes.FILE_LIBRARY,
R.string.photo_picker_choose_file
)
}
fun showAudioFilePicker(activity: Activity, canMultiselect: Boolean = false, site: SiteModel) {
showFilePicker(
activity,
site,
canMultiselect,
mutableSetOf(AUDIO),
RequestCodes.AUDIO_LIBRARY,
R.string.photo_picker_choose_audio
)
}
private fun showFilePicker(
activity: Activity,
site: SiteModel,
canMultiselect: Boolean = false,
allowedTypes: Set<MediaType>,
requestCode: Int,
@StringRes title: Int
) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(),
canMultiselect = canMultiselect,
requiresStoragePermissions = true,
allowedTypes = allowedTypes,
cameraSetup = HIDDEN,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(
intent,
requestCode
)
}
fun viewWPMediaLibraryPickerForResult(activity: Activity, site: SiteModel, browserType: MediaBrowserType) {
val intent = MediaPickerActivity.buildIntent(
activity,
buildWPMediaLibraryPickerSetup(browserType),
site
)
val requestCode: Int = if (browserType.canMultiselect()) {
RequestCodes.MULTI_SELECT_MEDIA_PICKER
} else {
RequestCodes.SINGLE_SELECT_MEDIA_PICKER
}
activity.startActivityForResult(intent, requestCode)
}
fun showStockMediaPickerForResult(
activity: Activity,
site: SiteModel,
requestCode: Int,
allowMultipleSelection: Boolean
) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = STOCK_LIBRARY,
availableDataSources = setOf(),
canMultiselect = allowMultipleSelection,
requiresStoragePermissions = false,
allowedTypes = setOf(IMAGE),
cameraSetup = HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = true,
title = R.string.photo_picker_stock_media
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(intent, requestCode)
}
fun showGifPickerForResult(
activity: Activity,
site: SiteModel,
allowMultipleSelection: Boolean
) {
val requestCode = if (allowMultipleSelection) {
RequestCodes.GIF_PICKER_MULTI_SELECT
} else {
RequestCodes.GIF_PICKER_SINGLE_SELECT
}
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = GIF_LIBRARY,
availableDataSources = setOf(),
canMultiselect = allowMultipleSelection,
requiresStoragePermissions = false,
allowedTypes = setOf(IMAGE),
cameraSetup = HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = true,
title = R.string.photo_picker_gif
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(intent, requestCode)
}
private fun buildLocalMediaPickerSetup(browserType: MediaBrowserType): MediaPickerSetup {
val allowedTypes = mutableSetOf<MediaType>()
if (browserType.isImagePicker) {
allowedTypes.add(IMAGE)
}
if (browserType.isVideoPicker) {
allowedTypes.add(VIDEO)
}
val title = if (browserType.isImagePicker && browserType.isVideoPicker) {
R.string.photo_picker_photo_or_video_title
} else if (browserType.isVideoPicker) {
R.string.photo_picker_video_title
} else {
R.string.photo_picker_title
}
return MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = if (browserType.isWPStoriesPicker) setOf(WP_LIBRARY) else setOf(),
canMultiselect = browserType.canMultiselect(),
requiresStoragePermissions = true,
allowedTypes = allowedTypes,
cameraSetup = if (browserType.isWPStoriesPicker) STORIES else HIDDEN,
systemPickerEnabled = true,
editingEnabled = browserType.isImagePicker,
queueResults = browserType == FEATURED_IMAGE_PICKER,
defaultSearchView = false,
title = title
)
}
private fun buildWPMediaLibraryPickerSetup(browserType: MediaBrowserType): MediaPickerSetup {
val allowedTypes = mutableSetOf<MediaType>()
if (browserType.isImagePicker) {
allowedTypes.add(IMAGE)
}
if (browserType.isVideoPicker) {
allowedTypes.add(VIDEO)
}
if (browserType.isAudioPicker) {
allowedTypes.add(AUDIO)
}
if (browserType.isDocumentPicker) {
allowedTypes.add(DOCUMENT)
}
return MediaPickerSetup(
primaryDataSource = WP_LIBRARY,
availableDataSources = setOf(),
canMultiselect = browserType.canMultiselect(),
requiresStoragePermissions = false,
allowedTypes = allowedTypes,
cameraSetup = if (browserType.isWPStoriesPicker) STORIES else HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = false,
title = R.string.wp_media_title
)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/photopicker/MediaPickerLauncher.kt | 2421808103 |
package forpdateam.ru.forpda.entity.app.profile
import android.content.SharedPreferences
import com.jakewharton.rxrelay2.BehaviorRelay
import forpdateam.ru.forpda.common.Html
import forpdateam.ru.forpda.entity.EntityWrapper
import forpdateam.ru.forpda.entity.remote.profile.ProfileModel
import forpdateam.ru.forpda.extensions.nullString
import forpdateam.ru.forpda.model.data.remote.api.ApiUtils
import io.reactivex.Observable
import org.json.JSONArray
import org.json.JSONObject
class UserHolder(
private val sharedPreferences: SharedPreferences
) : IUserHolder {
private val currentUserRelay = BehaviorRelay.createDefault(EntityWrapper(user))
override var user: ProfileModel?
get() {
return sharedPreferences
.getString("current_user", null)
?.let {
val jsonProfile = JSONObject(it)
ProfileModel().apply {
id = jsonProfile.getInt("id")
sign = ApiUtils.coloredFromHtml(jsonProfile.nullString("sign"))
about = ApiUtils.spannedFromHtml(jsonProfile.nullString("about"))
avatar = jsonProfile.nullString("avatar")
nick = jsonProfile.nullString("nick")
status = jsonProfile.nullString("status")
group = jsonProfile.nullString("group")
note = jsonProfile.nullString("note")
jsonProfile.getJSONArray("contacts")?.also {
for (i in 0 until it.length()) {
val jsonContact = it.getJSONObject(i)
contacts.add(ProfileModel.Contact().apply {
type = ProfileModel.ContactType.valueOf(jsonContact.getString("type"))
url = jsonContact.nullString("url")
title = jsonContact.nullString("title")
})
}
}
jsonProfile.getJSONArray("info")?.also {
for (i in 0 until it.length()) {
val jsonInfo = it.getJSONObject(i)
info.add(ProfileModel.Info().apply {
type = ProfileModel.InfoType.valueOf(jsonInfo.getString("type"))
value = jsonInfo.nullString("value")
})
}
}
jsonProfile.getJSONArray("stats")?.also {
for (i in 0 until it.length()) {
val jsonStat = it.getJSONObject(i)
stats.add(ProfileModel.Stat().apply {
type = ProfileModel.StatType.valueOf(jsonStat.getString("type"))
url = jsonStat.nullString("url")
value = jsonStat.nullString("value")
})
}
}
jsonProfile.getJSONArray("devices")?.also {
for (i in 0 until it.length()) {
val jsonDevice = it.getJSONObject(i)
devices.add(ProfileModel.Device().apply {
url = jsonDevice.nullString("url")
name = jsonDevice.nullString("name")
accessory = jsonDevice.nullString("accessory")
})
}
}
jsonProfile.getJSONArray("warnings")?.also {
for (i in 0 until it.length()) {
val jsonContact = it.getJSONObject(i)
warnings.add(ProfileModel.Warning().apply {
type = ProfileModel.WarningType.valueOf(jsonContact.getString("type"))
date = jsonContact.nullString("date")
title = jsonContact.nullString("title")
content = ApiUtils.spannedFromHtml(jsonContact.nullString("content"))
})
}
}
}
}
}
set(value) {
currentUserRelay.accept(EntityWrapper(value))
val result = value?.let { profile ->
JSONObject().apply {
put("id", profile.id)
put("sign", profile.sign?.let { Html.toHtml(it) })
put("about", profile.about?.let { Html.toHtml(it) })
put("avatar", profile.avatar)
put("nick", profile.nick)
put("status", profile.status)
put("group", profile.group)
put("note", profile.note)
put("contacts", JSONArray().apply {
profile.contacts.forEach { contact ->
put(JSONObject().apply {
put("type", contact.type.toString())
put("url", contact.url)
put("title", contact.title)
})
}
})
put("info", JSONArray().apply {
profile.info.forEach { info ->
put(JSONObject().apply {
put("type", info.type.toString())
put("value", info.value)
})
}
})
put("stats", JSONArray().apply {
profile.stats.forEach { stat ->
put(JSONObject().apply {
put("type", stat.type.toString())
put("url", stat.url)
put("value", stat.value)
})
}
})
put("devices", JSONArray().apply {
profile.devices.forEach { device ->
put(JSONObject().apply {
put("url", device.url)
put("name", device.name)
put("accessory", device.accessory)
})
}
})
put("warnings", JSONArray().apply {
profile.warnings.forEach { warning ->
put(JSONObject().apply {
put("type", warning.type)
put("date", warning.date)
put("title", warning.title)
put("content", warning.content?.let { Html.toHtml(it) })
})
}
})
}
}
if (result == null) {
sharedPreferences.edit().remove("current_user").apply()
} else {
sharedPreferences.edit().putString("current_user", result.toString()).apply()
}
}
override fun observeCurrentUser(): Observable<EntityWrapper<ProfileModel?>> = currentUserRelay
}
| app/src/main/java/forpdateam/ru/forpda/entity/app/profile/UserHolder.kt | 1774782985 |
package com.joe.zatuji.module.login.register
import com.joe.zatuji.base.IBaseView
import com.joe.zatuji.repo.bean.User
/**
* Description:
* author:Joey
* date:2018/11/20
*/
interface IRegisterView: IBaseView {
fun showAvatar(url:String)
fun showRegisterHint(email:String)
fun registerSuccess(it: User)
} | app/src/main/java/com/joe/zatuji/module/login/register/IRegisterView.kt | 1311315395 |
// 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.workspaceModel.storage.impl.url
import com.intellij.workspaceModel.storage.impl.IntIdGenerator
import com.intellij.workspaceModel.storage.impl.VirtualFileNameStore
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import it.unimi.dsi.fastutil.Hash.Strategy
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import it.unimi.dsi.fastutil.ints.IntArrayList
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet
open class VirtualFileUrlManagerImpl : VirtualFileUrlManager {
private val idGenerator = IntIdGenerator()
private var emptyUrl: VirtualFileUrl? = null
private val fileNameStore = VirtualFileNameStore()
private val id2NodeMapping = Int2ObjectOpenHashMap<FilePathNode>()
private val rootNode = FilePathNode(0, 0)
@Synchronized
override fun fromUrl(url: String): VirtualFileUrl {
if (url.isEmpty()) return getEmptyUrl()
return add(url)
}
override fun fromUrlSegments(urls: List<String>): VirtualFileUrl {
if (urls.isEmpty()) return getEmptyUrl()
return addSegments(null, urls)
}
override fun fromPath(path: String): VirtualFileUrl {
return fromUrl("file://${toSystemIndependentName(path)}")
}
private fun toSystemIndependentName(fileName: String): String {
return fileName.replace('\\', '/')
}
@Synchronized
override fun getParentVirtualUrl(vfu: VirtualFileUrl): VirtualFileUrl? {
vfu as VirtualFileUrlImpl
return id2NodeMapping.get(vfu.id)?.parent?.getVirtualFileUrl(this)
}
@Synchronized
override fun getSubtreeVirtualUrlsById(vfu: VirtualFileUrl): List<VirtualFileUrl> {
vfu as VirtualFileUrlImpl
return id2NodeMapping.get(vfu.id).getSubtreeNodes().map { it.getVirtualFileUrl(this) }
}
@Synchronized
fun getUrlById(id: Int): String {
if (id <= 0) return ""
var node = id2NodeMapping[id]
val contentIds = IntArrayList()
while (node != null) {
contentIds.add(node.contentId)
node = node.parent
}
if (contentIds.size == 1) {
return fileNameStore.getNameForId(contentIds.getInt(0))?.let {
return@let if (it.isEmpty()) "/" else it
} ?: ""
}
val builder = StringBuilder()
for (index in contentIds.size - 1 downTo 0) {
builder.append(fileNameStore.getNameForId(contentIds.getInt(index)))
if (index != 0) builder.append("/")
}
return builder.toString()
}
@Synchronized
internal fun append(parentVfu: VirtualFileUrl, relativePath: String): VirtualFileUrl {
parentVfu as VirtualFileUrlImpl
return add(relativePath, id2NodeMapping.get(parentVfu.id))
}
protected open fun createVirtualFileUrl(id: Int, manager: VirtualFileUrlManagerImpl): VirtualFileUrl {
return VirtualFileUrlImpl(id, manager)
}
fun getCachedVirtualFileUrls(): List<VirtualFileUrl> = id2NodeMapping.values.mapNotNull { it.getCachedVirtualFileUrl() }
internal fun add(path: String, parentNode: FilePathNode? = null): VirtualFileUrl {
val segments = splitNames(path)
return addSegments(parentNode, segments)
}
private fun addSegments(parentNode: FilePathNode?, segments: List<String>): VirtualFileUrl {
var latestNode: FilePathNode? = parentNode ?: findRootNode(segments.first())
val latestElement = segments.size - 1
for (index in segments.indices) {
val nameId = fileNameStore.generateIdForName(segments[index])
// Latest node can be NULL only if it's root node
if (latestNode == null) {
val nodeId = idGenerator.generateId()
val newNode = FilePathNode(nodeId, nameId)
id2NodeMapping[nodeId] = newNode
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) {
rootNode.addChild(newNode)
return newNode.getVirtualFileUrl(this)
}
latestNode = newNode
rootNode.addChild(newNode)
continue
}
if (latestNode === findRootNode(latestNode.contentId)) {
if (latestNode.contentId == nameId) {
if (index == latestElement) return latestNode.getVirtualFileUrl(this)
continue
}
}
val node = latestNode.findChild(nameId)
if (node == null) {
val nodeId = idGenerator.generateId()
val newNode = FilePathNode(nodeId, nameId, latestNode)
id2NodeMapping[nodeId] = newNode
latestNode.addChild(newNode)
latestNode = newNode
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) return newNode.getVirtualFileUrl(this)
}
else {
// If it's the latest name of folder or files, save entity Id as node value
if (index == latestElement) return node.getVirtualFileUrl(this)
latestNode = node
}
}
return getEmptyUrl()
}
internal fun remove(path: String) {
val node = findLatestFilePathNode(path)
if (node == null) {
println("File not found")
return
}
if (!node.isEmpty()) return
var currentNode: FilePathNode = node
do {
val parent = currentNode.parent
if (parent == null) {
if (currentNode === findRootNode(currentNode.contentId) && currentNode.isEmpty()) {
removeNameUsage(currentNode.contentId)
id2NodeMapping.remove(currentNode.nodeId)
rootNode.removeChild(currentNode)
}
return
}
parent.removeChild(currentNode)
removeNameUsage(currentNode.contentId)
id2NodeMapping.remove(currentNode.nodeId)
currentNode = parent
}
while (currentNode.isEmpty())
}
internal fun update(oldPath: String, newPath: String) {
val latestPathNode = findLatestFilePathNode(oldPath)
if (latestPathNode == null) return
remove(oldPath)
add(newPath)
}
private fun getEmptyUrl(): VirtualFileUrl {
if (emptyUrl == null) {
emptyUrl = createVirtualFileUrl(0, this)
}
return emptyUrl!!
}
private fun removeNameUsage(contentId: Int) {
val name = fileNameStore.getNameForId(contentId)
assert(name != null)
fileNameStore.removeName(name!!)
}
private fun findLatestFilePathNode(path: String): FilePathNode? {
val segments = splitNames(path)
var latestNode: FilePathNode? = findRootNode(segments.first())
val latestElement = segments.size - 1
for (index in segments.indices) {
val nameId = fileNameStore.getIdForName(segments[index]) ?: return null
// Latest node can be NULL only if it's root node
if (latestNode == null) return null
if (latestNode === findRootNode(latestNode.contentId)) {
if (latestNode.contentId == nameId) {
if (index == latestElement) return latestNode else continue
}
}
latestNode.findChild(nameId)?.let {
if (index == latestElement) return it
latestNode = it
} ?: return null
}
return null
}
private fun findRootNode(segment: String): FilePathNode? {
val segmentId = fileNameStore.getIdForName(segment) ?: return null
return rootNode.findChild(segmentId)
}
private fun findRootNode(contentId: Int): FilePathNode? = rootNode.findChild(contentId)
private fun splitNames(path: String): List<String> = path.split('/', '\\')
fun print() = rootNode.print()
fun isEqualOrParentOf(parentNodeId: Int, childNodeId: Int): Boolean {
if (parentNodeId == 0 && childNodeId == 0) return true
var current = childNodeId
while (current > 0) {
if (parentNodeId == current) return true
current = id2NodeMapping[current]?.parent?.nodeId ?: return false
}
/*
TODO It may look like this + caching + invalidating
val segmentName = getSegmentName(id).toString()
val parent = id2parent.getValue(id)
val parentParent = id2parent.getValue(parent)
return if (parentParent <= 0) {
val fileSystem = VirtualFileManager.getInstance().getFileSystem(getSegmentName(parent).toString())
fileSystem?.findFileByPath(segmentName)
} else {
getVirtualFileById(parent)?.findChild(segmentName)
}
}
*/
return false
}
internal inner class FilePathNode(val nodeId: Int, val contentId: Int, val parent: FilePathNode? = null) {
private var virtualFileUrl: VirtualFileUrl? = null
private var children: ObjectOpenCustomHashSet<FilePathNode>? = null
fun findChild(nameId: Int): FilePathNode? {
return children?.get(FilePathNode(0, nameId))
}
fun getSubtreeNodes(): List<FilePathNode> {
return getSubtreeNodes(mutableListOf())
}
private fun getSubtreeNodes(subtreeNodes: MutableList<FilePathNode>): List<FilePathNode> {
children?.forEach {
subtreeNodes.add(it)
it.getSubtreeNodes(subtreeNodes)
}
return subtreeNodes
}
fun addChild(newNode: FilePathNode) {
createChildrenList()
children!!.add(newNode)
}
fun removeChild(node: FilePathNode) {
children?.remove(node)
}
fun getVirtualFileUrl(virtualFileUrlManager: VirtualFileUrlManagerImpl): VirtualFileUrl {
val cachedValue = virtualFileUrl
if (cachedValue != null) return cachedValue
val url = virtualFileUrlManager.createVirtualFileUrl(nodeId, virtualFileUrlManager)
virtualFileUrl = url
return url
}
fun getCachedVirtualFileUrl(): VirtualFileUrl? = virtualFileUrl
fun isEmpty() = children == null || children!!.isEmpty()
private fun createChildrenList() {
if (children == null) children = ObjectOpenCustomHashSet(HASHING_STRATEGY)
}
fun print(): String {
val buffer = StringBuilder()
print(buffer, "", "")
return buffer.toString()
}
private fun print(buffer: StringBuilder, prefix: String, childrenPrefix: String) {
val name = [email protected](contentId)
if (name != null) buffer.append("$prefix $name\n")
val iterator = children?.iterator() ?: return
while (iterator.hasNext()) {
val next = iterator.next()
if (name == null) {
next.print(buffer, childrenPrefix, childrenPrefix)
continue
}
if (iterator.hasNext()) {
next.print(buffer, "$childrenPrefix |- ", "$childrenPrefix | ")
}
else {
next.print(buffer, "$childrenPrefix '- ", "$childrenPrefix ")
}
}
}
}
private companion object {
val HASHING_STRATEGY: Strategy<FilePathNode> = object : Strategy<FilePathNode> {
override fun equals(node1: FilePathNode?, node2: FilePathNode?): Boolean {
if (node1 === node2) {
return true
}
if (node1 == null || node2 == null) {
return false
}
return node1.contentId == node2.contentId
}
override fun hashCode(node: FilePathNode?): Int = node?.contentId ?: 0
}
}
} | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/url/VirtualFileUrlManagerImpl.kt | 2115722459 |
// FIR_IDENTICAL
// FIR_COMPARISON
class LocalClass
fun LocalClass.ext(action: () -> Unit) {}
fun LocalClass.extAnother(action: () -> Unit) {}
fun usage(l: LocalClass) {
l.ext<caret> {}
}
// EXIST: ext
// EXIST: extAnother
| plugins/kotlin/completion/tests/testData/basic/common/primitiveCompletion/extensionRecompletion.kt | 767004756 |
/*
* Copyright 2018 Google LLC. 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
*
* 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.subscriptions.data.network
import com.example.subscriptions.data.SubscriptionStatus
import com.example.subscriptions.data.network.firebase.ServerFunctions
import kotlinx.coroutines.flow.StateFlow
/**
* Execute network requests on the network thread.
* Fetch data from a remote server object.
*/
class SubRemoteDataSource private constructor(
private val serverFunctions: ServerFunctions
) {
/**
* True when there are pending network requests.
*/
val loading: StateFlow<Boolean>
get() = serverFunctions.loading
/**
* Live Data with the basic content.
*/
val basicContent = serverFunctions.basicContent
/**
* Live Data with the premium content.
*/
val premiumContent = serverFunctions.premiumContent
/**
* GET basic content.
*/
suspend fun updateBasicContent() = serverFunctions.updateBasicContent()
/**
* GET premium content.
*/
suspend fun updatePremiumContent() = serverFunctions.updatePremiumContent()
/**
* GET request for subscription status.
*/
suspend fun fetchSubscriptionStatus() = serverFunctions.fetchSubscriptionStatus()
/**
* POST request to register subscription.
*/
suspend fun registerSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
return serverFunctions.registerSubscription(
product = product,
purchaseToken = purchaseToken
)
}
/**
* POST request to transfer a subscription that is owned by someone else.
*/
suspend fun postTransferSubscriptionSync(product: String, purchaseToken: String) {
serverFunctions.transferSubscription(product = product, purchaseToken = purchaseToken)
}
/**
* POST request to register an Instance ID.
*/
suspend fun postRegisterInstanceId(instanceId: String) {
serverFunctions.registerInstanceId(instanceId)
}
/**
* POST request to unregister an Instance ID.
*/
suspend fun postUnregisterInstanceId(instanceId: String) {
serverFunctions.unregisterInstanceId(instanceId)
}
/**
* POST request to acknowledge a subscription.
*/
suspend fun postAcknowledgeSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
return serverFunctions.acknowledgeSubscription(
product = product,
purchaseToken = purchaseToken
)
}
companion object {
@Volatile
private var INSTANCE: SubRemoteDataSource? = null
fun getInstance(
callableFunctions: ServerFunctions
): SubRemoteDataSource =
INSTANCE ?: synchronized(this) {
INSTANCE ?: SubRemoteDataSource(callableFunctions).also { INSTANCE = it }
}
}
}
| ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/SubRemoteDataSource.kt | 2951883615 |
package <%= appPackage %>.data.test.factory
import <%= appPackage %>.data.model.BufferooEntity
import <%= appPackage %>.data.test.factory.DataFactory.Factory.randomLong
import <%= appPackage %>.data.test.factory.DataFactory.Factory.randomUuid
import <%= appPackage %>.domain.model.Bufferoo
/**
* Factory class for Bufferoo related instances
*/
class BufferooFactory {
companion object Factory {
fun makeBufferooEntity(): BufferooEntity {
return BufferooEntity(randomLong(), randomUuid(), randomUuid(), randomUuid())
}
fun makeBufferoo(): Bufferoo {
return Bufferoo(randomLong(), randomUuid(), randomUuid(), randomUuid())
}
fun makeBufferooEntityList(count: Int): List<BufferooEntity> {
val bufferooEntities = mutableListOf<BufferooEntity>()
repeat(count) {
bufferooEntities.add(makeBufferooEntity())
}
return bufferooEntities
}
fun makeBufferooList(count: Int): List<Bufferoo> {
val bufferoos = mutableListOf<Bufferoo>()
repeat(count) {
bufferoos.add(makeBufferoo())
}
return bufferoos
}
}
} | templates/buffer-clean-architecture-components-kotlin/data/src/test/java/org/buffer/android/boilerplate/data/test/factory/BufferooFactory.kt | 1918463692 |
package com.nardai.practice.model
import javax.persistence.Entity
import javax.persistence.Id
@Entity
data class Setting(
@Id
val key: String = "N/A",
val text: String = "N/A") {
}
| src/main/java/com/nardai/practice/model/Setting.kt | 2901655652 |
package com.eden.orchid.taxonomies.components
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.components.OrchidComponent
import com.eden.orchid.taxonomies.models.TaxonomiesModel
import com.eden.orchid.taxonomies.models.Taxonomy
import com.eden.orchid.utilities.resolve
@Description("Show a list of all Taxonomies.", name = "Taxonomy")
class TaxonomyComponent : OrchidComponent("taxonomy") {
@Option
@Description("The Taxonomy to include terms from.")
lateinit var taxonomyType: String
val model: TaxonomiesModel by lazy {
context.resolve<TaxonomiesModel>()
}
val taxonomy: Taxonomy?
get() {
return model.taxonomies[taxonomyType]
}
}
| plugins/OrchidTaxonomies/src/main/kotlin/com/eden/orchid/taxonomies/components/TaxonomyComponent.kt | 482689284 |
package com.meiji.daily.module.zhuanlan
import com.meiji.daily.di.component.AppComponent
import com.meiji.daily.di.scope.FragmentScoped
import dagger.Component
/**
* Created by Meiji on 2017/12/21.
*/
@FragmentScoped
@Component(modules = arrayOf(ZhuanlanModule::class), dependencies = arrayOf(AppComponent::class))
interface ZhuanlanComponent {
// 与 dependencies 有冲突
// @Component.Builder
// interface Builder {
// Builder injectView(ZhuanlanView view);
//
// Builder injectType(int type);
//
// ZhuanlanComponent build();
// }
fun inject(view: ZhuanlanView)
}
| app/src/main/java/com/meiji/daily/module/zhuanlan/ZhuanlanComponent.kt | 885144391 |
// JVM_TARGET: 17
@JvmRecord
data class R(val x: Int) {
init {
if (x <= 0) throw RuntimeException()
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/newJavaFeatures/recordClass/explicitCanonicalConstructorCheckAfter.kt | 4134227755 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.ElementDescriptionUtil
import com.intellij.psi.PsiElement
import com.intellij.refactoring.util.RefactoringDescriptionLocation
import com.intellij.ui.breadcrumbs.BreadcrumbsProvider
import com.intellij.usageView.UsageViewShortNameLocation
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.unwrapIfLabeled
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import kotlin.reflect.KClass
class KotlinBreadcrumbsInfoProvider : BreadcrumbsProvider {
override fun isShownByDefault(): Boolean = !UISettings.getInstance().showMembersInNavigationBar
private abstract class ElementHandler<TElement : KtElement>(val type: KClass<TElement>) {
abstract fun elementInfo(element: TElement): String
abstract fun elementTooltip(element: TElement): String
open fun accepts(element: TElement): Boolean = true
}
private object LambdaHandler : ElementHandler<KtFunctionLiteral>(KtFunctionLiteral::class) {
override fun elementInfo(element: KtFunctionLiteral): String {
val lambdaExpression = element.parent as KtLambdaExpression
val unwrapped = lambdaExpression.unwrapIfLabeled()
val label = lambdaExpression.labelText()
val lambdaText = "$label{$ellipsis}"
when (val parent = unwrapped.parent) {
is KtLambdaArgument -> {
val callExpression = parent.parent as? KtCallExpression
val callName = callExpression?.getCallNameExpression()?.getReferencedName()
if (callName != null) {
val receiverText = callExpression.getQualifiedExpressionForSelector()?.let {
it.receiverExpression.text.orEllipsis(TextKind.INFO) + it.operationSign.value
} ?: ""
return buildString {
append(receiverText)
append(callName)
if (callExpression.valueArgumentList != null) {
appendCallArguments(callExpression)
} else {
if (label.isNotEmpty()) append(" ")
}
append(lambdaText)
}
}
}
is KtProperty -> {
val name = parent.nameAsName
if (unwrapped == parent.initializer && name != null) {
val valOrVar = if (parent.isVar) "var" else "val"
return "$valOrVar ${name.render()} = $lambdaText"
}
}
}
return lambdaText
}
private fun StringBuilder.appendCallArguments(callExpression: KtCallExpression) {
var argumentText = "($ellipsis)"
val arguments = callExpression.getValueArgumentsInParentheses()
when (arguments.size) {
0 -> argumentText = "()"
1 -> {
val argument = arguments.single()
val argumentExpression = argument.getArgumentExpression()
if (!argument.isNamed() && argument.getSpreadElement() == null && argumentExpression != null) {
argumentText = "(" + argumentExpression.shortText(TextKind.INFO) + ")"
}
}
}
append(argumentText)
append(" ")
}
//TODO
override fun elementTooltip(element: KtFunctionLiteral): String {
return ElementDescriptionUtil.getElementDescription(element, RefactoringDescriptionLocation.WITH_PARENT)
}
}
private object AnonymousObjectHandler : ElementHandler<KtObjectDeclaration>(KtObjectDeclaration::class) {
override fun accepts(element: KtObjectDeclaration) = element.isObjectLiteral()
override fun elementInfo(element: KtObjectDeclaration) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtObjectDeclaration) = element.buildText(TextKind.TOOLTIP)
private fun KtObjectDeclaration.buildText(kind: TextKind): String {
return buildString {
append("object")
val superTypeEntries = superTypeListEntries
if (superTypeEntries.isNotEmpty()) {
append(" : ")
if (kind == TextKind.INFO) {
val entry = superTypeEntries.first()
entry.typeReference?.text?.truncateStart(kind)?.let { append(it) }
if (superTypeEntries.size > 1) {
if (!endsWith(ellipsis)) {
append(",$ellipsis")
}
}
} else {
append(superTypeEntries.joinToString(separator = ", ") { it.typeReference?.text ?: "" }.truncateEnd(kind))
}
}
}
}
}
private object AnonymousFunctionHandler : ElementHandler<KtNamedFunction>(KtNamedFunction::class) {
override fun accepts(element: KtNamedFunction) = element.name == null
override fun elementInfo(element: KtNamedFunction) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtNamedFunction) = element.buildText(TextKind.TOOLTIP)
private fun KtNamedFunction.buildText(kind: TextKind): String {
return "fun(" +
valueParameters.joinToString(separator = ", ") { if (kind == TextKind.INFO) it.name ?: "" else it.text }.truncateEnd(
kind
) +
")"
}
}
private object PropertyAccessorHandler : ElementHandler<KtPropertyAccessor>(KtPropertyAccessor::class) {
override fun elementInfo(element: KtPropertyAccessor): String {
return DeclarationHandler.elementInfo(element.property) + "." + (if (element.isGetter) "get" else "set")
}
override fun elementTooltip(element: KtPropertyAccessor): String {
return DeclarationHandler.elementTooltip(element)
}
}
private object DeclarationHandler : ElementHandler<KtDeclaration>(KtDeclaration::class) {
override fun accepts(element: KtDeclaration): Boolean {
if (element is KtProperty) {
return element.parent is KtFile || element.parent is KtClassBody // do not show local variables
}
return true
}
override fun elementInfo(element: KtDeclaration): String {
when {
element is KtProperty -> {
return (if (element.isVar) "var " else "val ") + element.nameAsName?.render()
}
element is KtObjectDeclaration && element.isCompanion() -> {
return buildString {
append("companion object")
element.nameIdentifier?.let { append(" "); append(it.text) }
}
}
else -> {
val description = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE)
val suffix = if (element is KtFunction) "()" else null
return if (suffix != null) description + suffix else description
}
}
}
override fun elementTooltip(element: KtDeclaration): String = try {
ElementDescriptionUtil.getElementDescription(element, RefactoringDescriptionLocation.WITH_PARENT)
} catch (e: IndexNotReadyException) {
KotlinBundle.message("breadcrumbs.tooltip.indexing")
}
}
private abstract class ConstructWithExpressionHandler<TElement : KtElement>(
private val constructName: String,
type: KClass<TElement>
) : ElementHandler<TElement>(type) {
protected abstract fun extractExpression(element: TElement): KtExpression?
protected abstract fun labelOwner(element: TElement): KtExpression?
override fun elementInfo(element: TElement) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: TElement) = element.buildText(TextKind.TOOLTIP)
protected fun TElement.buildText(kind: TextKind): String {
return buildString {
append(labelOwner(this@buildText)?.labelText() ?: "")
append(constructName)
val expression = extractExpression(this@buildText)
if (expression != null) {
append(" (")
append(expression.shortText(kind))
append(")")
}
}
}
}
private object IfThenHandler : ConstructWithExpressionHandler<KtContainerNode>("if", KtContainerNode::class) {
override fun accepts(element: KtContainerNode): Boolean {
return element.node.elementType == KtNodeTypes.THEN
}
override fun extractExpression(element: KtContainerNode): KtExpression? {
return (element.parent as KtIfExpression).condition
}
override fun labelOwner(element: KtContainerNode): KtExpression? = null
override fun elementInfo(element: KtContainerNode): String {
return elseIfPrefix(element) + super.elementInfo(element)
}
override fun elementTooltip(element: KtContainerNode): String {
return elseIfPrefix(element) + super.elementTooltip(element)
}
private fun elseIfPrefix(then: KtContainerNode): String {
return if ((then.parent as KtIfExpression).isElseIf()) "if $ellipsis else " else ""
}
}
private object ElseHandler : ElementHandler<KtContainerNode>(KtContainerNode::class) {
override fun accepts(element: KtContainerNode): Boolean {
return element.node.elementType == KtNodeTypes.ELSE
&& (element.parent as KtIfExpression).`else` !is KtIfExpression // filter out "else if"
}
override fun elementInfo(element: KtContainerNode): String {
val ifExpression = element.parent as KtIfExpression
val then = ifExpression.thenNode
val ifInfo = if (ifExpression.isElseIf() || then == null) "if" else IfThenHandler.elementInfo(then)
return "$ifInfo $ellipsis else"
}
override fun elementTooltip(element: KtContainerNode): String {
val ifExpression = element.parent as KtIfExpression
val thenNode = ifExpression.thenNode ?: return "else"
return "else (of '" + IfThenHandler.elementTooltip(thenNode) + "')" //TODO
}
private val KtIfExpression.thenNode: KtContainerNode?
get() = children.firstOrNull { it.node.elementType == KtNodeTypes.THEN } as KtContainerNode?
}
private object TryHandler : ElementHandler<KtBlockExpression>(KtBlockExpression::class) {
override fun accepts(element: KtBlockExpression) = element.parent is KtTryExpression
override fun elementInfo(element: KtBlockExpression) = "try"
override fun elementTooltip(element: KtBlockExpression): String {
return buildString {
val tryExpression = element.parent as KtTryExpression
append("try {$ellipsis}")
for (catchClause in tryExpression.catchClauses) {
append("\ncatch(")
append(catchClause.catchParameter?.typeReference?.text ?: "")
append(") {$ellipsis}")
}
if (tryExpression.finallyBlock != null) {
append("\nfinally {$ellipsis}")
}
}
}
}
private object CatchHandler : ElementHandler<KtCatchClause>(KtCatchClause::class) {
override fun elementInfo(element: KtCatchClause): String {
val text = element.catchParameter?.typeReference?.text ?: ""
return "catch ($text)"
}
override fun elementTooltip(element: KtCatchClause): String {
return elementInfo(element)
}
}
private object FinallyHandler : ElementHandler<KtFinallySection>(KtFinallySection::class) {
override fun elementInfo(element: KtFinallySection) = "finally"
override fun elementTooltip(element: KtFinallySection) = "finally"
}
private object WhileHandler : ConstructWithExpressionHandler<KtContainerNode>("while", KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtWhileExpression
override fun extractExpression(element: KtContainerNode) = (element.bodyOwner() as KtWhileExpression).condition
override fun labelOwner(element: KtContainerNode) = element.bodyOwner()
}
private object DoWhileHandler : ConstructWithExpressionHandler<KtContainerNode>("do $ellipsis while", KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtDoWhileExpression
override fun extractExpression(element: KtContainerNode) = (element.bodyOwner() as KtDoWhileExpression).condition
override fun labelOwner(element: KtContainerNode) = element.bodyOwner()
}
private object WhenHandler : ConstructWithExpressionHandler<KtWhenExpression>("when", KtWhenExpression::class) {
override fun extractExpression(element: KtWhenExpression) = element.subjectExpression
override fun labelOwner(element: KtWhenExpression): KtExpression? = null
}
private object WhenEntryHandler : ElementHandler<KtExpression>(KtExpression::class) {
override fun accepts(element: KtExpression) = element.parent is KtWhenEntry
override fun elementInfo(element: KtExpression) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtExpression) = element.buildText(TextKind.TOOLTIP)
private fun KtExpression.buildText(kind: TextKind): String {
with(parent as KtWhenEntry) {
if (isElse) {
return "else ->"
} else {
val condition = conditions.firstOrNull() ?: return "->"
val firstConditionText = condition.buildText(kind)
return if (conditions.size == 1) {
"$firstConditionText ->"
} else {
//TODO: show all conditions for tooltip
(if (firstConditionText.endsWith(ellipsis)) firstConditionText else "$firstConditionText,$ellipsis") + " ->"
}
}
}
}
private fun KtWhenCondition.buildText(kind: TextKind): String {
return when (this) {
is KtWhenConditionIsPattern -> {
(if (isNegated) "!is" else "is") + " " + (typeReference?.text?.truncateEnd(kind) ?: "")
}
is KtWhenConditionInRange -> {
(if (isNegated) "!in" else "in") + " " + (rangeExpression?.text?.truncateEnd(kind) ?: "")
}
is KtWhenConditionWithExpression -> {
expression?.text?.truncateStart(kind) ?: ""
}
else -> error("Unknown when entry condition type: ${this}")
}
}
}
private object ForHandler : ElementHandler<KtContainerNode>(KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtForExpression
override fun elementInfo(element: KtContainerNode) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtContainerNode) = element.buildText(TextKind.TOOLTIP)
private fun KtContainerNode.buildText(kind: TextKind): String {
with(bodyOwner() as KtForExpression) {
val parameterText = loopParameter?.nameAsName?.render() ?: destructuringDeclaration?.text ?: return "for"
val collectionText = loopRange?.text ?: ""
val text = ("$parameterText in $collectionText").truncateEnd(kind)
return labelText() + "for($text)"
}
}
}
@Suppress("UNCHECKED_CAST")
private fun handler(e: PsiElement): ElementHandler<in KtElement>? {
if (e !is KtElement) return null
val handler = Holder.handlers.firstOrNull { it.type.java.isInstance(e) && (it as ElementHandler<in KtElement>).accepts(e) }
return handler as ElementHandler<in KtElement>?
}
override fun getLanguages() = arrayOf(KotlinLanguage.INSTANCE)
override fun acceptElement(e: PsiElement) = !DumbService.isDumb(e.project) && handler(e) != null
override fun getElementInfo(e: PsiElement): String {
if (DumbService.isDumb(e.project)) return ""
return handler(e)!!.elementInfo(e as KtElement)
}
override fun getElementTooltip(e: PsiElement): String {
if (DumbService.isDumb(e.project)) return ""
return handler(e)!!.elementTooltip(e as KtElement)
}
override fun getParent(e: PsiElement): PsiElement? {
val node = e.node ?: return null
return when (node.elementType) {
KtNodeTypes.PROPERTY_ACCESSOR ->
e.parent.parent
else ->
e.parent
}
}
private object Holder {
val handlers: List<ElementHandler<*>> = listOf<ElementHandler<*>>(
LambdaHandler,
AnonymousObjectHandler,
AnonymousFunctionHandler,
PropertyAccessorHandler,
DeclarationHandler,
IfThenHandler,
ElseHandler,
TryHandler,
CatchHandler,
FinallyHandler,
WhileHandler,
DoWhileHandler,
WhenHandler,
WhenEntryHandler,
ForHandler
)
}
}
internal enum class TextKind(val maxTextLength: Int) {
INFO(16), TOOLTIP(100)
}
internal fun KtExpression.shortText(kind: TextKind): String {
return if (this is KtNameReferenceExpression) text else text.truncateEnd(kind)
}
//TODO: line breaks
internal fun String.orEllipsis(kind: TextKind): String {
return if (length <= kind.maxTextLength) this else ellipsis
}
internal fun String.truncateEnd(kind: TextKind): String {
val maxLength = kind.maxTextLength
return if (length > maxLength) substring(0, maxLength - ellipsis.length) + ellipsis else this
}
internal fun String.truncateStart(kind: TextKind): String {
val maxLength = kind.maxTextLength
return if (length > maxLength) ellipsis + substring(length - maxLength - 1) else this
}
internal const val ellipsis = "${Typography.ellipsis}"
internal fun KtContainerNode.bodyOwner(): KtExpression? {
return if (node.elementType == KtNodeTypes.BODY) parent as KtExpression else null
}
internal fun KtExpression.labelText(): String {
var result = ""
var current = parent
while (current is KtLabeledExpression) {
result = current.getLabelName() + "@ " + result
current = current.parent
}
return result
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinBreadcrumbsInfoProvider.kt | 1628931930 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.browsers.impl
import com.intellij.ide.browsers.*
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.DumbService
import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ContainerUtil
import java.util.*
private val URL_PROVIDER_EP = ExtensionPointName<WebBrowserUrlProvider>("com.intellij.webBrowserUrlProvider")
class WebBrowserServiceImpl : WebBrowserService() {
companion object {
fun getProviders(request: OpenInBrowserRequest): Sequence<WebBrowserUrlProvider> {
val dumbService = DumbService.getInstance(request.project)
return URL_PROVIDER_EP.extensionList.asSequence().filter {
(!dumbService.isDumb || DumbService.isDumbAware(it)) && it.canHandleElement(request)
}
}
fun getDebuggableUrls(context: PsiElement?): Collection<Url> {
try {
val request = if (context == null) null else createOpenInBrowserRequest(context)
if (request == null || WebBrowserXmlService.getInstance().isXmlLanguage(request.file.viewProvider.baseLanguage)) {
return emptyList()
}
else {
// it is client responsibility to set token
request.isAppendAccessToken = false
request.reloadMode = ReloadMode.DISABLED
return getProviders(request)
.map { getUrls(it, request) }
.filter(Collection<*>::isNotEmpty).firstOrNull()
?: emptyList()
}
}
catch (ignored: WebBrowserUrlProvider.BrowserException) {
return emptyList()
}
}
@JvmStatic
fun getDebuggableUrl(context: PsiElement?): Url? = ContainerUtil.getFirstItem(getDebuggableUrls(context))
}
override fun getUrlsToOpen(request: OpenInBrowserRequest, preferLocalUrl: Boolean): Collection<Url> {
val isHtmlOrXml = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(request.file)
if (!preferLocalUrl || !isHtmlOrXml) {
val dumbService = DumbService.getInstance(request.project)
for (urlProvider in URL_PROVIDER_EP.extensionList) {
if ((!dumbService.isDumb || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(request)) {
val urls = getUrls(urlProvider, request)
if (!urls.isEmpty()) {
return urls
}
}
}
if (!isHtmlOrXml && !request.isForceFileUrlIfNoUrlProvider) {
return emptyList()
}
}
val file = if (!request.file.viewProvider.isPhysical) null else request.virtualFile
return if (file is LightVirtualFile || file == null) emptyList() else listOf(Urls.newFromVirtualFile(file))
}
}
private fun getUrls(provider: WebBrowserUrlProvider?, request: OpenInBrowserRequest): Collection<Url> {
if (provider != null) {
request.result?.let { return it }
try {
return provider.getUrls(request)
}
catch (e: WebBrowserUrlProvider.BrowserException) {
if (!WebBrowserXmlService.getInstance().isHtmlFile(request.file)) {
throw e
}
}
}
return emptyList()
} | platform/platform-impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.kt | 2216473159 |
package com.jetbrains.performancePlugin.commands
import com.intellij.ide.actions.cache.ProjectRecoveryScope
import com.intellij.ide.actions.cache.RecoveryAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.playback.PlaybackContext
import com.intellij.openapi.ui.playback.commands.AbstractCommand
import com.intellij.util.indexing.RefreshIndexableFilesAction
import com.intellij.util.indexing.ReindexAction
import com.intellij.util.indexing.RescanIndexesAction
import com.jetbrains.performancePlugin.utils.ActionCallbackProfilerStopper
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.toPromise
private val LOG = Logger.getInstance(RecoveryActionCommand::class.java)
class RecoveryActionCommand(text: String, line: Int) : AbstractCommand(text, line) {
companion object {
const val PREFIX = CMD_PREFIX + "recovery"
private val ALLOWED_ACTIONS = listOf("REFRESH", "RESCAN", "REINDEX")
}
override fun _execute(context: PlaybackContext): Promise<Any?> {
val actionCallback = ActionCallbackProfilerStopper()
val args = text.split(" ".toRegex(), 2).toTypedArray()
val project = context.project
val recoveryAction: RecoveryAction = when (args[1]) {
"REFRESH" -> RefreshIndexableFilesAction()
"RESCAN" -> RescanIndexesAction()
"REINDEX" -> ReindexAction()
else -> error("The argument ${args[1]} to the command is incorrect. Allowed actions: $ALLOWED_ACTIONS")
}
recoveryAction.perform(ProjectRecoveryScope(project)).handle { res, err ->
if (err != null) {
LOG.error(err)
return@handle
}
if (res.problems.isNotEmpty()) {
LOG.error("${recoveryAction.actionKey} found and fixed ${res.problems.size} problems, samples: " +
res.problems.take(10).joinToString(", ") { it.message })
}
LOG.info("Command $PREFIX ${args[1]} finished")
actionCallback.setDone()
}
return actionCallback.toPromise()
}
}
| plugins/performanceTesting/src/com/jetbrains/performancePlugin/commands/RecoveryActionCommand.kt | 970155844 |
// 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.webSymbols.inspections.impl
import com.intellij.lang.Language
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.ExtensionPointUtil
import com.intellij.openapi.extensions.RequiredElement
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.util.xmlb.annotations.Attribute
internal class WebSymbolsHighlightInLanguageEP {
@Attribute("language")
@RequiredElement
@JvmField
var language: String? = null
companion object {
private val EP_NAME = ExtensionPointName<WebSymbolsHighlightInLanguageEP>("com.intellij.webSymbols.highlightInLanguage")
fun shouldHighlight(language: Language): Boolean =
language.isKindOf(language.id)
private val languages: ClearableLazyValue<Set<String>> = ExtensionPointUtil.dropLazyValueOnChange(
ClearableLazyValue.create {
EP_NAME.extensionList.mapNotNull { it.language }.toSet()
}, EP_NAME, null
)
}
} | platform/webSymbols/src/com/intellij/webSymbols/inspections/impl/WebSymbolsHighlightInLanguageEP.kt | 2750848171 |
// 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.openapi.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.SerializableScheme
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.ExternalizableSchemeAdapter
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import org.jdom.Element
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import javax.swing.KeyStroke
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private const val KEY_MAP = "keymap"
private const val KEYBOARD_SHORTCUT = "keyboard-shortcut"
private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut"
private const val KEYBOARD_GESTURE_KEY = "keystroke"
private const val KEYBOARD_GESTURE_MODIFIER = "modifier"
private const val KEYSTROKE_ATTRIBUTE = "keystroke"
private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke"
private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke"
private const val ACTION = "action"
private const val VERSION_ATTRIBUTE = "version"
private const val PARENT_ATTRIBUTE = "parent"
private const val NAME_ATTRIBUTE = "name"
private const val ID_ATTRIBUTE = "id"
private const val MOUSE_SHORTCUT = "mouse-shortcut"
fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl {
val result = KeymapImpl(dataHolder)
result.name = name
result.schemeState = SchemeState.UNCHANGED
return result
}
open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null)
: ExternalizableSchemeAdapter(), Keymap, SerializableScheme {
@Volatile
private var parent: KeymapImpl? = null
private var unknownParentName: String? = null
open var canModify: Boolean = true
@JvmField
internal var schemeState: SchemeState? = null
override fun getSchemeState(): SchemeState? = schemeState
private val actionIdToShortcuts = ConcurrentHashMap<String, List<Shortcut>>()
get() {
val dataHolder = dataHolder
if (dataHolder != null) {
this.dataHolder = null
readExternal(dataHolder.read())
}
return field
}
private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! }
/**
* @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap.
*/
val ownActionIds: Array<String>
get() = actionIdToShortcuts.keys.toTypedArray()
private fun <T> cachedShortcuts(mapper: (Shortcut) -> T?): ReadWriteProperty<Any?, Map<T, MutableList<String>>> =
object : ReadWriteProperty<Any?, Map<T, MutableList<String>>> {
private var cache: Map<T, MutableList<String>>? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): Map<T, MutableList<String>> =
cache ?: mapShortcuts(mapper).also { cache = it }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Map<T, MutableList<String>>) {
cache = null
}
private fun mapShortcuts(mapper: (Shortcut) -> T?): Map<T, MutableList<String>> {
fun addActionToShortcutMap(actionId: String, map: MutableMap<T, MutableList<String>>) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
mapper(shortcut)?.let {
val ids = map.getOrPut(it) { SmartList() }
if (!ids.contains(actionId)) {
ids.add(actionId)
}
}
}
}
val map = HashMap<T, MutableList<String>>()
actionIdToShortcuts.keys.forEach { addActionToShortcutMap(it, map) }
keymapManager.boundActions.forEach { addActionToShortcutMap(it, map) }
return map
}
}
// Accesses to these caches are non-synchronized, so must be performed
// from EDT only (where all the modifications are currently done)
private var keystrokeToActionIds: Map<KeyStroke, MutableList<String>> by cachedShortcuts { (it as? KeyboardShortcut)?.firstKeyStroke }
private var mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>> by cachedShortcuts { it as? MouseShortcut }
private var gestureToActionIds: Map<KeyboardModifierGestureShortcut, MutableList<String>> by cachedShortcuts { it as? KeyboardModifierGestureShortcut }
override fun getPresentableName(): String = name
override fun deriveKeymap(newName: String): KeymapImpl =
if (canModify()) {
val newKeymap = copy()
newKeymap.name = newName
newKeymap
}
else {
val newKeymap = KeymapImpl()
newKeymap.parent = this
newKeymap.name = newName
newKeymap
}
fun copy(): KeymapImpl =
dataHolder?.let { KeymapImpl(name, it) }
?: copyTo(KeymapImpl())
fun copyTo(otherKeymap: KeymapImpl): KeymapImpl {
otherKeymap.cleanShortcutsCache()
otherKeymap.actionIdToShortcuts.clear()
otherKeymap.actionIdToShortcuts.putAll(actionIdToShortcuts)
// after actionIdToShortcuts (on first access we lazily read itself)
otherKeymap.parent = parent
otherKeymap.name = name
otherKeymap.canModify = canModify()
return otherKeymap
}
override fun getParent(): KeymapImpl? = parent
final override fun canModify(): Boolean = canModify
override fun addShortcut(actionId: String, shortcut: Shortcut) {
addShortcut(actionId, shortcut, false)
}
fun addShortcut(actionId: String, shortcut: Shortcut, fromSettings: Boolean) {
actionIdToShortcuts.compute(actionId) { id, list ->
var result: List<Shortcut>? = list
if (result == null) {
val boundShortcuts = keymapManager.getActionBinding(id)?.let { actionIdToShortcuts[it] }
result = boundShortcuts ?: parent?.getShortcutList(id)?.map { convertShortcut(it) } ?: emptyList()
}
if (!result.contains(shortcut)) {
result = result + shortcut
}
if (result.areShortcutsEqualToParent(id)) null else result
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun cleanShortcutsCache() {
keystrokeToActionIds = emptyMap()
mouseShortcutToActionIds = emptyMap()
gestureToActionIds = emptyMap()
schemeState = SchemeState.POSSIBLY_CHANGED
}
override fun removeAllActionShortcuts(actionId: String) {
for (shortcut in getShortcuts(actionId)) {
removeShortcut(actionId, shortcut)
}
}
override fun removeShortcut(actionId: String, toDelete: Shortcut) {
removeShortcut(actionId, toDelete, false)
}
fun removeShortcut(actionId: String, toDelete: Shortcut, fromSettings: Boolean) {
val fromBinding = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
actionIdToShortcuts.compute(actionId) { id, list ->
when {
list == null -> {
val inherited = fromBinding ?: parent?.getShortcutList(id)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited == null || !inherited.contains(toDelete)) null
else inherited - toDelete
}
!list.contains(toDelete) -> list
parent == null -> if (list.size == 1) null else ContainerUtil.newUnmodifiableList(list - toDelete)
else -> {
val result = list - toDelete
if (result.areShortcutsEqualToParent(id)) null else ContainerUtil.newUnmodifiableList(result)
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun List<Shortcut>.areShortcutsEqualToParent(actionId: String) =
parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getShortcutList(actionId).mapSmart { convertShortcut(it) }) }
private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> {
actionIdToShortcuts[actionId]?.let {
return it
}
val result = SmartList<Shortcut>()
keymapManager.getActionBinding(actionId)?.let {
result.addAll(getOwnOrBoundShortcuts(it))
}
return result
}
private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> {
// first, get keystrokes from our own map
val list = SmartList<String>()
for ((key, value) in gestureToActionIds) {
if (shortcut.startsWith(key)) {
list.addAll(value)
}
}
if (parent != null) {
val ids = parent!!.getActionIds(shortcut)
if (ids.isNotEmpty()) {
for (id in ids) {
// add actions from the parent keymap only if they are absent in this keymap
if (!actionIdToShortcuts.containsKey(id)) {
list.add(id)
}
}
}
}
sortInRegistrationOrder(list)
return list
}
override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> {
return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToActionIds }, KeymapImpl::convertKeyStroke))
}
override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> {
val ids = getActionIds(firstKeyStroke)
var actualBindings: MutableList<String>? = null
for (id in ids) {
val shortcuts = getShortcuts(id)
for (shortcut in shortcuts) {
if (shortcut !is KeyboardShortcut) {
continue
}
if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) {
if (actualBindings == null) {
actualBindings = SmartList()
}
actualBindings.add(id)
break
}
}
}
return ArrayUtilRt.toStringArray(actualBindings)
}
override fun getActionIds(shortcut: Shortcut): Array<String> {
return when (shortcut) {
is KeyboardShortcut -> {
val first = shortcut.firstKeyStroke
val second = shortcut.secondKeyStroke
if (second == null) getActionIds(first) else getActionIds(first, second)
}
is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
else -> ArrayUtilRt.EMPTY_STRING_ARRAY
}
}
override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean {
var convertedShortcut = shortcut
var keymap = this
do {
val list = keymap.mouseShortcutToActionIds[convertedShortcut]
if (list != null && list.contains(actionId)) {
return true
}
val parent = keymap.parent ?: return false
convertedShortcut = keymap.convertMouseShortcut(shortcut)
keymap = parent
}
while (true)
}
override fun getActionIds(shortcut: MouseShortcut): List<String> {
return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut)
}
@RequiresEdt
private fun <T> getActionIds(shortcut: T,
shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>,
convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> {
// first, get keystrokes from our own map
var list = shortcutToActionIds(this)[shortcut]
val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList()
var isOriginalListInstance = list != null
for (id in parentIds) {
// add actions from the parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (actionIdToShortcuts.containsKey(id)) continue
val key = keymapManager.getActionBinding(id)
if (key != null && actionIdToShortcuts.containsKey(key)) continue
if (list == null) {
list = SmartList()
}
else if (isOriginalListInstance) {
list = SmartList(list)
isOriginalListInstance = false
}
if (!list.contains(id)) {
list.add(id)
}
}
sortInRegistrationOrder(list ?: return emptyList())
return list
}
fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId)
override fun getShortcuts(actionId: String?): Array<Shortcut> =
getShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getShortcutList(actionId: String?): List<Shortcut> {
if (actionId == null) {
return emptyList()
}
// it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts
// todo why not convert on add? why we don't need to convert our own shortcuts?
return actionIdToShortcuts[actionId]
?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getShortcutList(actionId)?.mapSmart { convertShortcut(it) }
?: emptyList()
}
fun getOwnShortcuts(actionId: String): Array<Shortcut> {
val own = actionIdToShortcuts[actionId] ?: return Shortcut.EMPTY_ARRAY
return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray()
}
fun hasShortcutDefined(actionId: String): Boolean =
actionIdToShortcuts[actionId] != null || parent?.hasShortcutDefined(actionId) == true
// you must clear `actionIdToShortcuts` before calling
protected open fun readExternal(keymapElement: Element) {
if (KEY_MAP != keymapElement.name) {
throw InvalidDataException("unknown element: $keymapElement")
}
name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)!!
unknownParentName = null
keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName ->
var parentScheme = findParentScheme(parentSchemeName)
if (parentScheme == null && parentSchemeName == "Default for Mac OS X") {
// https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197
parentScheme = findParentScheme("Mac OS X")
}
if (parentScheme == null) {
logger<KeymapImpl>().warn("Cannot find parent scheme $parentSchemeName for scheme $name")
unknownParentName = parentSchemeName
notifyAboutMissingKeymap(parentSchemeName, IdeBundle.message("notification.content.cannot.find.parent.keymap", parentSchemeName, name), true)
}
else {
parent = parentScheme as KeymapImpl
canModify = true
}
}
val actionIds = HashSet<String>()
val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode)
for (actionElement in keymapElement.children) {
if (actionElement.name != ACTION) {
throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name")
}
val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name")
actionIds.add(id)
val shortcuts = SmartList<Shortcut>()
for (shortcutElement in actionElement.children) {
if (KEYBOARD_SHORTCUT == shortcutElement.name) {
// Parse first keystroke
val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name")
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) {
continue
}
val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue
// Parse second keystroke
var secondKeyStroke: KeyStroke? = null
val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE)
if (secondKeyStrokeStr != null) {
secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue
}
shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke))
}
else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) {
val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException(
"Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name")
val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue
val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER)
var modifier: KeyboardGestureAction.ModifierType? = null
if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.dblClick
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.hold
}
if (modifier == null) {
throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name")
}
shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke))
}
else if (MOUSE_SHORTCUT == shortcutElement.name) {
val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name")
try {
shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString))
}
catch (e: InvalidDataException) {
throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name")
}
}
else {
throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name")
}
}
// creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts)
actionIdToShortcuts[id] = Collections.unmodifiableList(shortcuts)
}
ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds)
cleanShortcutsCache()
}
protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName)
override fun writeScheme(): Element {
dataHolder?.let {
return it.read()
}
val keymapElement = Element(KEY_MAP)
keymapElement.setAttribute(VERSION_ATTRIBUTE, "1")
keymapElement.setAttribute(NAME_ATTRIBUTE, name)
(parent?.name ?: unknownParentName)?.let {
keymapElement.setAttribute(PARENT_ATTRIBUTE, it)
}
writeOwnActionIds(keymapElement)
schemeState = SchemeState.UNCHANGED
return keymapElement
}
private fun writeOwnActionIds(keymapElement: Element) {
val ownActionIds = ownActionIds
Arrays.sort(ownActionIds)
for (actionId in ownActionIds) {
val shortcuts = actionIdToShortcuts[actionId] ?: continue
val actionElement = Element(ACTION)
actionElement.setAttribute(ID_ATTRIBUTE, actionId)
for (shortcut in shortcuts) {
when (shortcut) {
is KeyboardShortcut -> {
val element = Element(KEYBOARD_SHORTCUT)
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke))
shortcut.secondKeyStroke?.let {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it))
}
actionElement.addContent(element)
}
is MouseShortcut -> {
val element = Element(MOUSE_SHORTCUT)
element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut))
actionElement.addContent(element)
}
is KeyboardModifierGestureShortcut -> {
val element = Element(KEYBOARD_GESTURE_SHORTCUT)
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke))
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name)
actionElement.addContent(element)
}
else -> throw IllegalStateException("unknown shortcut class: $shortcut")
}
}
keymapElement.addContent(actionElement)
}
}
fun clearOwnActionsIds() {
actionIdToShortcuts.clear()
cleanShortcutsCache()
}
fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId)
fun clearOwnActionsId(actionId: String) {
actionIdToShortcuts.remove(actionId)
cleanShortcutsCache()
}
override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList)
override fun getActionIdList(): Set<String> {
val ids = LinkedHashSet<String>()
ids.addAll(actionIdToShortcuts.keys)
var parent = parent
while (parent != null) {
ids.addAll(parent.actionIdToShortcuts.keys)
parent = parent.parent
}
return ids
}
override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> {
val result = HashMap<String, MutableList<KeyboardShortcut>>()
for (id in getActionIds(keyboardShortcut.firstKeyStroke)) {
if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) {
continue
}
val useShortcutOf = keymapManager.getActionBinding(id)
if (useShortcutOf != null && useShortcutOf == actionId) {
continue
}
for (shortcut1 in getShortcutList(id)) {
if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) {
continue
}
if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) {
continue
}
result.getOrPut(id) { SmartList() }.add(shortcut1)
}
}
return result
}
protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke
protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut
protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut
private fun fireShortcutChanged(actionId: String, fromSettings: Boolean) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).shortcutChanged(this, actionId, fromSettings)
}
override fun toString(): String = presentableName
override fun equals(other: Any?): Boolean {
if (other !is KeymapImpl) return false
if (other === this) return true
if (name != other.name) return false
if (canModify != other.canModify) return false
if (parent != other.parent) return false
if (actionIdToShortcuts != other.actionIdToShortcuts) return false
return true
}
override fun hashCode(): Int = name.hashCode()
}
private fun sortInRegistrationOrder(ids: MutableList<String>) {
ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator)
}
// compare two lists in any order
private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean {
if (shortcuts1.size != shortcuts2.size) {
return false
}
for (shortcut in shortcuts1) {
if (!shortcuts2.contains(shortcut)) {
return false
}
}
return true
}
@Suppress("SpellCheckingInspection") private const val macOSKeymap = "com.intellij.plugins.macoskeymap"
@Suppress("SpellCheckingInspection") private const val gnomeKeymap = "com.intellij.plugins.gnomekeymap"
@Suppress("SpellCheckingInspection") private const val kdeKeymap = "com.intellij.plugins.kdekeymap"
@Suppress("SpellCheckingInspection") private const val xwinKeymap = "com.intellij.plugins.xwinkeymap"
@Suppress("SpellCheckingInspection") private const val eclipseKeymap = "com.intellij.plugins.eclipsekeymap"
@Suppress("SpellCheckingInspection") private const val emacsKeymap = "com.intellij.plugins.emacskeymap"
@Suppress("SpellCheckingInspection") private const val netbeansKeymap = "com.intellij.plugins.netbeanskeymap"
@Suppress("SpellCheckingInspection") private const val qtcreatorKeymap = "com.intellij.plugins.qtcreatorkeymap"
@Suppress("SpellCheckingInspection") private const val resharperKeymap = "com.intellij.plugins.resharperkeymap"
@Suppress("SpellCheckingInspection") private const val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap"
@Suppress("SpellCheckingInspection") private const val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap"
private const val visualStudio2022Keymap = "com.intellij.plugins.visualstudio2022keymap"
@Suppress("SpellCheckingInspection") private const val xcodeKeymap = "com.intellij.plugins.xcodekeymap"
@Suppress("SpellCheckingInspection") private const val visualAssistKeymap = "com.intellij.plugins.visualassistkeymap"
@Suppress("SpellCheckingInspection") private const val riderKeymap = "com.intellij.plugins.riderkeymap"
@Suppress("SpellCheckingInspection") private const val vsCodeKeymap = "com.intellij.plugins.vscodekeymap"
@Suppress("SpellCheckingInspection") private const val vsForMacKeymap = "com.intellij.plugins.vsformackeymap"
internal fun notifyAboutMissingKeymap(keymapName: String, @NlsContexts.NotificationContent message: String, isParent: Boolean) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
connection.disconnect()
ApplicationManager.getApplication().invokeLater(
{
// TODO remove when PluginAdvertiser implements that
val pluginId = when (keymapName) {
"Mac OS X",
"Mac OS X 10.5+" -> macOSKeymap
"Default for GNOME" -> gnomeKeymap
"Default for KDE" -> kdeKeymap
"Default for XWin" -> xwinKeymap
"Eclipse",
"Eclipse (Mac OS X)" -> eclipseKeymap
"Emacs" -> emacsKeymap
"NetBeans 6.5" -> netbeansKeymap
"QtCreator",
"QtCreator OSX" -> qtcreatorKeymap
"ReSharper",
"ReSharper OSX" -> resharperKeymap
"Sublime Text",
"Sublime Text (Mac OS X)" -> sublimeKeymap
"Visual Studio",
"Visual Studio OSX" -> visualStudioKeymap
"Visual Studio 2022" -> visualStudio2022Keymap
"Visual Assist",
"Visual Assist OSX" -> visualAssistKeymap
"Xcode" -> xcodeKeymap
"Visual Studio for Mac" -> vsForMacKeymap
"Rider",
"Rider OSX"-> riderKeymap
"VSCode",
"VSCode OSX"-> vsCodeKeymap
else -> null
}
val action: AnAction = when (pluginId) {
null -> object : NotificationAction(IdeBundle.message("action.text.search.for.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
//TODO enableSearch("$keymapName /tag:Keymap")?.run()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java)
}
}
else -> object : NotificationAction(IdeBundle.message("action.text.install.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener {
override fun keymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().invokeLater {
if (keymap.name == keymapName) {
connect.disconnect()
val successMessage = if (isParent) IdeBundle.message("notification.content.keymap.successfully.installed", keymapName)
else {
KeymapManagerEx.getInstanceEx().activeKeymap = keymap
IdeBundle.message("notification.content.keymap.successfully.activated", keymapName)
}
Notification("KeymapInstalled", successMessage,
NotificationType.INFORMATION).notify(e.project)
}
}
}
})
val plugins = mutableSetOf(PluginId.getId(pluginId))
when (pluginId) {
gnomeKeymap, kdeKeymap -> plugins += PluginId.getId(xwinKeymap)
resharperKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualAssistKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualStudio2022Keymap -> plugins += PluginId.getId(visualStudioKeymap)
xcodeKeymap, vsForMacKeymap -> plugins += PluginId.getId(macOSKeymap)
}
installAndEnable(project, plugins) { }
notification.expire()
}
}
}
Notification("KeymapMissing", IdeBundle.message("notification.group.missing.keymap"),
message, NotificationType.ERROR)
.addAction(action)
.notify(project)
},
ModalityState.NON_MODAL)
}
})
}
| platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt | 460537592 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.testGenerator.generator
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.base.test.KotlinRoot
import org.jetbrains.kotlin.test.*
import org.jetbrains.kotlin.testGenerator.model.*
import org.junit.runner.RunWith
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.base.test.TestRoot
import java.io.File
import java.nio.file.Files
import java.util.*
object TestGenerator {
fun write(workspace: TWorkspace, isUpToDateCheck: Boolean = false) {
for (group in workspace.groups) {
for (suite in group.suites) {
write(suite, group, isUpToDateCheck)
}
}
}
private fun write(suite: TSuite, group: TGroup, isUpToDateCheck: Boolean) {
val packageName = suite.generatedClassName.substringBeforeLast('.')
val rootModelName = suite.generatedClassName.substringAfterLast('.')
val content = buildCode {
appendCopyrightComment()
newLine()
appendLine("package $packageName;")
newLine()
appendImports(getImports(suite, group))
appendGeneratedComment()
appendAnnotation(TAnnotation<SuppressWarnings>("all"))
appendAnnotation(TAnnotation<TestRoot>(group.modulePath))
appendAnnotation(TAnnotation<TestDataPath>("\$CONTENT_ROOT"))
val singleModel = suite.models.singleOrNull()
if (singleModel != null) {
append(SuiteElement.create(group, suite, singleModel, rootModelName, isNested = false))
} else {
appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java))
appendBlock("public abstract class $rootModelName extends ${suite.abstractTestClass.simpleName}") {
val children = suite.models
.map { SuiteElement.create(group, suite, it, it.testClassName, isNested = true) }
appendList(children, separator = "\n\n")
}
}
newLine()
}
val filePath = suite.generatedClassName.replace('.', '/') + ".java"
val file = File(group.testSourcesRoot, filePath)
write(file, postProcessContent(content), isUpToDateCheck)
}
private fun write(file: File, content: String, isUpToDateCheck: Boolean) {
val oldContent = file.takeIf { it.isFile }?.readText() ?: ""
if (normalizeContent(content) != normalizeContent(oldContent)) {
if (isUpToDateCheck) error("'${file.name}' is not up to date\nUse 'Generate Kotlin Tests' run configuration")
Files.createDirectories(file.toPath().parent)
file.writeText(content)
val path = file.toRelativeStringSystemIndependent(KotlinRoot.DIR)
println("Updated $path")
}
}
private fun normalizeContent(content: String): String = content.replace(Regex("\\R"), "\n")
private fun getImports(suite: TSuite, group: TGroup): List<String> {
val imports = mutableListOf<String>()
imports += TestDataPath::class.java.canonicalName
imports += JUnit3RunnerWithInners::class.java.canonicalName
if (suite.models.any { it.passTestDataPath }) {
imports += KotlinTestUtils::class.java.canonicalName
}
imports += TestMetadata::class.java.canonicalName
imports += TestRoot::class.java.canonicalName
imports += RunWith::class.java.canonicalName
imports.addAll(suite.imports)
if (suite.models.any { it.targetBackend != TargetBackend.ANY }) {
imports += TargetBackend::class.java.canonicalName
}
val superPackageName = suite.abstractTestClass.`package`.name
val selfPackageName = suite.generatedClassName.substringBeforeLast('.')
if (superPackageName != selfPackageName) {
imports += suite.abstractTestClass.kotlin.java.canonicalName
}
if (group.isCompilerTestData) {
imports += "static ${TestKotlinArtifacts::class.java.canonicalName}.${TestKotlinArtifacts::compilerTestData.name}"
}
return imports
}
private fun postProcessContent(text: String): String {
return text.lineSequence()
.map { it.trimEnd() }
.joinToString(System.getProperty("line.separator"))
}
private fun Code.appendImports(imports: List<String>) {
if (imports.isNotEmpty()) {
imports.forEach { appendLine("import $it;") }
newLine()
}
}
private fun Code.appendCopyrightComment() {
val year = GregorianCalendar()[Calendar.YEAR]
appendLine("// Copyright 2000-$year JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.")
}
private fun Code.appendGeneratedComment() {
appendDocComment("""
This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}.
DO NOT MODIFY MANUALLY.
""".trimIndent())
}
} | plugins/kotlin/util/test-generator-api/test/org/jetbrains/kotlin/testGenerator/generator/TestGenerator.kt | 3385195105 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.assignment
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.assignment.plugin.AbstractAssignPluginResolutionAltererExtension
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.scripting.definitions.isScript
class IdeAssignPluginResolutionAltererExtension(private val project: Project) : AbstractAssignPluginResolutionAltererExtension() {
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> {
if (modifierListOwner == null) {
return emptyList()
}
val cache = project.service<AssignmentAnnotationNamesCache>()
if (modifierListOwner.containingFile.isScript()) {
return cache.getNamesForPsiFile(modifierListOwner.containingFile)
} else {
val module = modifierListOwner.module ?: return emptyList()
return cache.getNamesForModule(module)
}
}
}
| plugins/kotlin/compiler-plugins/assignment/common/src/org/jetbrains/kotlin/idea/compilerPlugin/assignment/IdeAssignPluginResolutionAltererExtension.kt | 3786030329 |
package test
class Foo
fun test(list: List<Foo>) {
for (<caret>foo: Foo in list) {}
}
| plugins/kotlin/idea/tests/testData/codeInsight/expressionType/LoopVariableWithType.kt | 2634387073 |
package org.thoughtcrime.securesms.contacts.paged
data class ContactSearchSelectionResult(val key: ContactSearchKey, val isSelectable: Boolean)
| app/src/main/java/org/thoughtcrime/securesms/contacts/paged/ContactSearchSelectionResult.kt | 1813372772 |
/*
* Copyright 2017 Google Inc. 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
*
* 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.flexbox.test
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
/**
* Adapter for the tests for nested RecyclerViews.
* This Adapter is used for the inner RecyclerView.
*/
internal class NestedInnerAdapter(private val innerPosition: Int, private val itemCount: Int)
: RecyclerView.Adapter<NestedInnerAdapter.InnerViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NestedInnerAdapter.InnerViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.viewholder_textview, parent, false)
return InnerViewHolder(view)
}
override fun onBindViewHolder(holder: InnerViewHolder, position: Int) {
holder.textView.text = holder.textView.resources.getString(R.string.item_description, innerPosition, position)
}
override fun getItemCount() = itemCount
internal class InnerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.textview)
}
}
| flexbox/src/androidTest/java/com/google/android/flexbox/test/NestedInnerAdapter.kt | 3175913596 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import java.io.*
import java.lang.reflect.*
import java.util.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*
@Suppress("DEPRECATION")
class ServerJacksonBlockingTest {
private val dispatcher = UnsafeDispatcher()
private val environment = createTestEnvironment {
parentCoroutineContext = dispatcher
}
@AfterTest
fun cleanup() {
dispatcher.close()
}
@Test
fun testReceive(): Unit = withApplication(environment) {
application.intercept(ApplicationCallPipeline.Setup) {
withContext(dispatcher) {
proceed()
}
}
application.install(ContentNegotiation) {
jackson()
}
application.routing {
post("/") {
assertEquals(K(77), call.receive())
call.respondText("OK")
}
}
runBlocking {
assertEquals(
"OK",
client.post("/") {
setBody("{\"i\": 77}")
contentType(ContentType.Application.Json)
}.body()
)
}
}
data class K(var i: Int)
private class UnsafeDispatcher : CoroutineDispatcher(), Closeable {
private val dispatcher = Executors.newCachedThreadPool().asCoroutineDispatcher()
override fun dispatch(context: CoroutineContext, block: Runnable) {
dispatcher.dispatch(context + dispatcher) {
markParkingProhibited()
block.run()
}
}
override fun close() {
dispatcher.close()
}
private val prohibitParkingFunction: Method? by lazy {
try {
Class.forName("io.ktor.utils.io.jvm.javaio.PollersKt")
.getMethod("prohibitParking")
} catch (cause: Throwable) {
null
}
}
private fun markParkingProhibited() {
try {
prohibitParkingFunction?.invoke(null)
} catch (cause: Throwable) {
}
}
}
}
| ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/test/ServerJacksonBlockingTest.kt | 1249353695 |
package fi.evident.fab.proq2
import java.io.IOException
import java.io.OutputStream
class LittleEndianBinaryStreamWriter(private val os: OutputStream) {
@Throws(IOException::class)
fun writeBytes(bytes: ByteArray) {
os.write(bytes)
}
@Throws(IOException::class)
fun writeInt(i: Int) {
writeBytes(byteArrayOf(
(i and 0xFF).toByte(),
(i shr 8 and 0xFF).toByte(),
(i shr 16 and 0xFF).toByte(),
(i shr 24 and 0xFF).toByte()))
}
@Throws(IOException::class)
fun writeFloat(value: Float) {
writeInt(java.lang.Float.floatToIntBits(value))
}
}
| src/main/kotlin/fi/evident/fab/proq2/LittleEndianBinaryStreamWriter.kt | 2941421508 |
/*
* 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.client.engine.ios.certificates
@Deprecated(
"Please use 'Darwin' engine instead",
replaceWith = ReplaceWith("CertificatePinner", "io.ktor.client.engine.darwin.certificates.CertificatePinner")
)
public typealias CertificatePinner = io.ktor.client.engine.darwin.certificates.CertificatePinner
@Deprecated(
"Please use 'Darwin' engine instead",
replaceWith = ReplaceWith("PinnedCertificate", "io.ktor.client.engine.darwin.certificates.PinnedCertificate")
)
public typealias PinnedCertificate = io.ktor.client.engine.darwin.certificates.PinnedCertificate
| ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/ios/certificates/CertificatePinner.kt | 2987132363 |
package com.beust.kobalt.maven
import com.beust.kobalt.TestModule
import com.beust.kobalt.misc.KobaltExecutors
import com.beust.kobalt.misc.Versions
import org.testng.Assert
import org.testng.annotations.*
import java.util.concurrent.ExecutorService
import javax.inject.Inject
import kotlin.properties.Delegates
@Guice(modules = arrayOf(TestModule::class))
class DependencyTest @Inject constructor(val executors: KobaltExecutors) {
@DataProvider
fun dpVersions(): Array<Array<out Any>> {
return arrayOf(
arrayOf("0.1", "0.1.1"),
arrayOf("0.1", "1.4"),
arrayOf("6.9.4", "6.9.5"),
arrayOf("1.7", "1.38"),
arrayOf("1.70", "1.380"),
arrayOf("3.8.1", "4.5"),
arrayOf("18.0-rc1", "19.0"),
arrayOf("3.0.5.RELEASE", "3.0.6")
)
}
private var executor: ExecutorService by Delegates.notNull()
@BeforeClass
public fun bc() {
executor = executors.newExecutor("DependencyTest", 5)
}
@AfterClass
public fun ac() {
executor.shutdown()
}
@Test(dataProvider = "dpVersions")
public fun versionSorting(k: String, v: String) {
val dep1 = Versions.toLongVersion(k)
val dep2 = Versions.toLongVersion(v)
Assert.assertTrue(dep1.compareTo(dep2) < 0)
Assert.assertTrue(dep2.compareTo(dep1) > 0)
}
}
| src/test/kotlin/com/beust/kobalt/maven/DependencyTest.kt | 803711935 |
package eu.kanade.tachiyomi.ui.setting.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.databinding.SettingsSearchControllerBinding
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.setting.SettingsController
/**
* This controller shows and manages the different search result in settings search.
* [SettingsSearchAdapter.OnTitleClickListener] called when preference is clicked in settings search
*/
class SettingsSearchController :
NucleusController<SettingsSearchControllerBinding, SettingsSearchPresenter>(),
SettingsSearchAdapter.OnTitleClickListener {
/**
* Adapter containing search results grouped by lang.
*/
private var adapter: SettingsSearchAdapter? = null
private lateinit var searchView: SearchView
init {
setHasOptionsMenu(true)
}
override fun createBinding(inflater: LayoutInflater) = SettingsSearchControllerBinding.inflate(inflater)
override fun getTitle(): String? {
return presenter.query
}
/**
* Create the [SettingsSearchPresenter] used in controller.
*
* @return instance of [SettingsSearchPresenter]
*/
override fun createPresenter(): SettingsSearchPresenter {
return SettingsSearchPresenter()
}
/**
* Adds items to the options menu.
*
* @param menu menu containing options.
* @param inflater used to load the menu xml.
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.settings_main, menu)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
// Initialize search menu
val searchItem = menu.findItem(R.id.action_search)
searchView = searchItem.actionView as SearchView
searchView.maxWidth = Int.MAX_VALUE
searchView.queryHint = applicationContext?.getString(R.string.action_search_settings)
searchItem.expandActionView()
setItems(getResultSet())
searchItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
router.popCurrentController()
return false
}
}
)
searchView.setOnQueryTextListener(
object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
setItems(getResultSet(query))
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
setItems(getResultSet(newText))
return false
}
}
)
searchView.setQuery(presenter.preferences.lastSearchQuerySearchSettings().get(), true)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
adapter = SettingsSearchAdapter(this)
binding.recycler.layoutManager = LinearLayoutManager(view.context)
binding.recycler.adapter = adapter
// load all search results
SettingsSearchHelper.initPreferenceSearchResultCollection(presenter.preferences.context)
}
override fun onDestroyView(view: View) {
adapter = null
super.onDestroyView(view)
}
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
adapter?.onSaveInstanceState(outState)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
adapter?.onRestoreInstanceState(savedViewState)
}
/**
* returns a list of `SettingsSearchItem` to be shown as search results
* Future update: should we add a minimum length to the query before displaying results? Consider other languages.
*/
fun getResultSet(query: String? = null): List<SettingsSearchItem> {
if (!query.isNullOrBlank()) {
return SettingsSearchHelper.getFilteredResults(query)
.map { SettingsSearchItem(it, null) }
}
return mutableListOf()
}
/**
* Add search result to adapter.
*
* @param searchResult result of search.
*/
fun setItems(searchResult: List<SettingsSearchItem>) {
adapter?.updateDataSet(searchResult)
}
/**
* Opens a catalogue with the given search.
*/
override fun onTitleClick(ctrl: SettingsController) {
searchView.query.let {
presenter.preferences.lastSearchQuerySearchSettings().set(it.toString())
}
router.pushController(ctrl.withFadeTransaction())
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/setting/search/SettingsSearchController.kt | 435973515 |
package com.airbnb.lottie.sample.compose.examples
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.sample.compose.R
@Composable
fun CachingExamplesPage() {
UsageExamplePageScaffold {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
) {
ExampleCard("Default Caching", "Lottie caches compositions by default") {
Example1()
}
ExampleCard("Day/Night", "Animations in raw/res will automatically respect day and night mode") {
Example2()
}
ExampleCard("Skip Cache", "Skip the cache") {
Example3()
}
}
}
}
@Composable
private fun Example1() {
// By default, Lottie will cache compositions with a key derived from your LottieCompositionSpec.
// If you request the composition multiple times or request it again at some point later, it
// will return the previous composition. LottieComposition itself it stateless. All stateful
// actions should happen within LottieAnimation.
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart))
LottieAnimation(composition)
}
@Composable
private fun Example2() {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.sun_moon))
LottieAnimation(composition)
}
@Composable
private fun Example3() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.we_accept_inline_image),
// Don't cache this composition. You may want to do this for animations that have images
// because the bitmaps are much larger to store than the rest of the animation.
cacheKey = null,
)
LottieAnimation(composition)
} | sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/CachingExamplesPage.kt | 3529311893 |
/*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.novatec.testit.logrecorder.assertion.matchers.message
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class RegexMessageMatcherTests {
@Test
fun `message matching the RegEx matches`() {
assertThat(matcherFor("Foo.+").matches("Foo bar XUR")).isTrue()
}
@Test
fun `matching is done case sensitive`() {
assertThat(matcherFor("foo.+").matches("Foo bar XUR")).isFalse()
}
@Test
fun `message not matching the RegEx does not match`() {
assertThat(matcherFor("Bar.+").matches("Foo bar XUR")).isFalse()
}
@Test
fun `has an expressive toString value`() {
assertThat(matcherFor("foo.+").toString()).isEqualTo("""matches ["foo.+"]""")
}
fun matcherFor(regex: String) = RegexMessageMatcher(regex)
}
| logrecorder/logrecorder-assertions/src/test/kotlin/info/novatec/testit/logrecorder/assertion/matchers/message/RegexMessageMatcherTests.kt | 3900923483 |
package engineer.carrot.warren.warren.ssl
import engineer.carrot.warren.warren.loggerFor
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
internal class DangerZoneTrustAllX509TrustManager() : X509TrustManager {
private val LOGGER = loggerFor<DangerZoneTrustAllX509TrustManager>()
@Throws(CertificateException::class)
override fun checkClientTrusted(x509Certificates: Array<X509Certificate>, s: String) {
throw CertificateException("Forcible Trust Manager is not made to verify client certificates")
}
@Throws(CertificateException::class)
override fun checkServerTrusted(x509Certificates: Array<X509Certificate>, s: String) {
LOGGER.warn("DANGER ZONE: forcefully trusting all presented X509 certificates. This is not secure.")
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
}
| src/main/kotlin/engineer/carrot/warren/warren/ssl/DangerZoneTrustAllX509TrustManager.kt | 3224248727 |
package com.example.android.architecture.blueprints.todoapp.data
import com.example.android.architecture.blueprints.todoapp.util.isNotNullNorEmpty
import java.util.UUID
data class Task(
val id: String = UUID.randomUUID().toString(),
val title: String?,
val description: String?,
val completed: Boolean = false
) {
val titleForList =
if (title.isNotNullNorEmpty()) {
title
} else {
description
}
val active = !completed
val empty = title.isNullOrEmpty() && description.isNullOrEmpty()
} | app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/Task.kt | 2343178275 |
package com.github.tommykw.colorpicker
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
/**
* Created by tommy on 2016/06/03.
*/
class ColorPicker @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
val colors = intArrayOf(Color.RED, Color.GREEN, Color.BLUE)
val strokeSize = 2 * context.resources.displayMetrics.density
val rainbowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
val rainbowBackgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
val pickPaint = Paint(Paint.ANTI_ALIAS_FLAG)
var pick = 0.5f
var verticalGridSize = 0f
var rainbowBaseline = 0f
var showPreview = false
var listener: OnColorChangedListener? = null
override fun onDraw(canvas: Canvas) {
drawPicker(canvas)
drawColorAim(canvas, rainbowBaseline, verticalGridSize.toInt() / 2, verticalGridSize * 0.5f, color)
if (showPreview) {
drawColorAim(canvas, verticalGridSize, (verticalGridSize / 1.4f).toInt(), verticalGridSize * 0.7f, color)
}
}
private fun drawPicker(canvas: Canvas) {
val lineX = verticalGridSize / 2f
val lineY = rainbowBaseline.toFloat()
rainbowPaint.strokeWidth = verticalGridSize / 1.5f + strokeSize
rainbowBackgroundPaint.strokeWidth = rainbowPaint.strokeWidth + strokeSize
canvas.drawLine(lineX, lineY, width - lineX, lineY, rainbowBackgroundPaint)
canvas.drawLine(lineX, lineY, width - lineX, lineY, rainbowPaint)
}
private fun drawColorAim(canvas: Canvas, baseLine: Float, offset: Int, size: Float, color: Int) {
val circleCenterX = offset + pick * (canvas.width - offset * 2)
canvas.drawCircle(circleCenterX, baseLine, size, pickPaint.apply { this.color = Color.WHITE })
canvas.drawCircle(circleCenterX, baseLine, size - strokeSize, pickPaint.apply { this.color = color })
}
@SuppressLint("DrawAllocation")
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val height = measuredHeight
val width = measuredWidth
val shader = LinearGradient(
height / 4.0f,
height / 2.0f,
width - height / 4.0f,
height / 2.0f,
colors,
null,
Shader.TileMode.CLAMP
)
verticalGridSize = height / 3f
rainbowPaint.shader = shader
rainbowBaseline = verticalGridSize / 2f + verticalGridSize * 2
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val action = event.action
if (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_DOWN) {
pick = event.x / measuredWidth.toFloat()
if (pick < 0) {
pick = 0f
} else if (pick > 1) {
pick = 1f
}
listener?.onColorChanged(color)
showPreview = true
} else if (action == MotionEvent.ACTION_UP) {
showPreview = false
}
postInvalidateOnAnimation()
return true
}
val color: Int
get() = Utils.interpreterColor(pick, colors)
fun setOnColorChangedListener(listener: OnColorChangedListener) {
this.listener = listener
}
interface OnColorChangedListener {
fun onColorChanged(color: Int)
}
} | app/src/main/java/com/github/tommykw/colorpicker/ColorPicker.kt | 2750294600 |
/*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.elementlist.constructor
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.annotationprocessing.DateConverter
import java.util.Date
/**
* @author Hannes Dorfmann
*/
@Xml
class BookConstructor(
@param:Attribute val id: Int,
@param:PropertyElement val author: String,
@param:PropertyElement val title: String,
@param:PropertyElement val genre: String,
@param:PropertyElement(name = "publish_date", converter = DateConverter::class) val publishDate: Date,
@param:PropertyElement val price: Double,
@param:PropertyElement val description: String
)
| annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/elementlist/constructor/BookConstructor.kt | 1435373640 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote
import android.net.Uri
import com.google.android.ground.rx.annotations.Cold
import io.reactivex.Flowable
import io.reactivex.Single
import java.io.File
/**
* Defines API for accessing files in remote storage. Implementations must ensure all subscriptions
* are run in a background thread (i.e., not the Android main thread).
*/
interface RemoteStorageManager {
/** Returns a URL that can be used to download a file at the specified path in remote storage. */
fun getDownloadUrl(remoteDestinationPath: String): @Cold Single<Uri>
/** Uploads file to a remote path, streaming progress in the returned [Flowable]. */
fun uploadMediaFromFile(
file: File,
remoteDestinationPath: String
): @Cold Flowable<TransferProgress>
}
| ground/src/main/java/com/google/android/ground/persistence/remote/RemoteStorageManager.kt | 1213008612 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.accounts
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.github.util.GithubNotifications
/**
* Handles default Github account for project
*
* TODO: auto-detection
*/
@State(name = "GithubDefaultAccount", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class GithubProjectDefaultAccountHolder(private val project: Project,
private val accountManager: GithubAccountManager) : PersistentStateComponent<AccountState> {
var account: GithubAccount? = null
init {
ApplicationManager.getApplication()
.messageBus
.connect(project)
.subscribe(GithubAccountManager.ACCOUNT_REMOVED_TOPIC, object : AccountRemovedListener {
override fun accountRemoved(removedAccount: GithubAccount) {
if (account == removedAccount) account = null
}
})
}
override fun getState(): AccountState {
return AccountState().apply { defaultAccountId = account?.id }
}
override fun loadState(state: AccountState) {
account = state.defaultAccountId?.let(::findAccountById)
}
private fun findAccountById(id: String): GithubAccount? {
val account = accountManager.accounts.find { it.id == id }
if (account == null) runInEdt {
GithubNotifications.showWarning(project, "Missing Default Github Account", "",
GithubNotifications.getConfigureAction(project))
}
return account
}
}
internal class AccountState {
var defaultAccountId: String? = null
}
| plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubProjectDefaultAccountHolder.kt | 2326626346 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.templates
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.Writer
import org.jetbrains.kotlin.tools.projectWizard.core.asPath
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.ModuleIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.runTaskIrs
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.moduleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
object ConsoleJvmApplicationTemplate : Template() {
@NonNls
override val id: String = "consoleJvmApp"
override val title: String = KotlinNewProjectWizardBundle.message("module.template.console.jvm.title")
override val description: String = KotlinNewProjectWizardBundle.message("module.template.console.jvm.description")
private const val fileToCreate = "Main.kt"
override val filesToOpenInEditor = listOf(fileToCreate)
override fun isApplicableTo(module: Module, projectKind: ProjectKind, reader: Reader): Boolean =
module.configurator.moduleType == ModuleType.jvm
override fun Writer.getIrsToAddToBuildFile(
module: ModuleIR
) = buildList<BuildSystemIR> {
+runTaskIrs("MainKt")
}
override fun Reader.getFileTemplates(module: ModuleIR) =
buildList<FileTemplateDescriptorWithPath> {
+(FileTemplateDescriptor("$id/main.kt.vm", fileToCreate.asPath()) asSrcOf SourcesetType.main)
}
}
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/templates/ConsoleJvmApplicationTemplate.kt | 4199955489 |
package me.serce.solidity.ide.inspections
import com.intellij.codeInsight.daemon.impl.actions.AbstractBatchSuppressByNoInspectionCommentFix
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.codeInspection.SuppressionUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import me.serce.solidity.lang.psi.SolElement
import me.serce.solidity.lang.psi.ancestors
import me.serce.solidity.lang.psi.parentOfType
class SolInspectionSuppressor : InspectionSuppressor {
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<out SuppressQuickFix> = arrayOf(
SuppressInspectionFix(toolId),
SuppressInspectionFix(SuppressionUtil.ALL)
)
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean =
element.ancestors
.filterIsInstance<SolElement>()
.any { isSuppressedByComment(it, toolId) }
private fun isSuppressedByComment(element: PsiElement, toolId: String): Boolean {
val comment = PsiTreeUtil.skipSiblingsBackward(element, PsiWhiteSpace::class.java) as? PsiComment
if (comment == null) {
return false
}
val matcher = SuppressionUtil.SUPPRESS_IN_LINE_COMMENT_PATTERN.matcher(comment.text)
return matcher.matches() && SuppressionUtil.isInspectionToolIdMentioned(matcher.group(1), toolId)
}
private class SuppressInspectionFix(ID: String)
: AbstractBatchSuppressByNoInspectionCommentFix(ID, ID == SuppressionUtil.ALL) {
init {
text = when (ID) {
SuppressionUtil.ALL -> "Suppress all inspections for item"
else -> "Suppress for item"
}
}
override fun getContainer(context: PsiElement?) = context?.parentOfType<SolElement>(strict = false)
}
}
| src/main/kotlin/me/serce/solidity/ide/inspections/SolInspectionSuppressor.kt | 607204935 |
internal class C {
private val aaa = 0
private val bbb = 0
private val ccc = 0
private val ddd = 0
fun getAaa(): Int {
return bbb
}
fun getBbb(): Int {
return ccc
}
fun getCcc(): Int {
return ddd
}
fun getDdd(): Int {
return 0
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/PropertyAndFieldConflicts.kt | 3988434432 |
package foo
val v = ::NestedJava | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/callableReferences/nestedToTopLevel/after/foo/KotlinReferences.kt | 2682060461 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.