content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.groupdocs.ui.di import com.groupdocs.ui.manager.PathManager import com.groupdocs.ui.manager.PathManagerImpl import com.groupdocs.ui.modules.compare.CompareController import com.groupdocs.ui.modules.compare.CompareControllerImpl import com.groupdocs.ui.modules.config.ConfigController import com.groupdocs.ui.modules.config.ConfigControllerImpl import com.groupdocs.ui.modules.description.DescriptionController import com.groupdocs.ui.modules.description.DescriptionControllerImpl import com.groupdocs.ui.modules.download.DownloadController import com.groupdocs.ui.modules.download.DownloadControllerImpl import com.groupdocs.ui.modules.page.PageController import com.groupdocs.ui.modules.page.PageControllerImpl import com.groupdocs.ui.modules.tree.TreeController import com.groupdocs.ui.modules.tree.TreeControllerImpl import com.groupdocs.ui.modules.upload.UploadController import com.groupdocs.ui.modules.upload.UploadControllerImpl import com.groupdocs.ui.usecase.* import org.koin.core.module.dsl.bind import org.koin.core.module.dsl.singleOf import org.koin.dsl.module object ModulesInjection { val controllerBeans = module { singleOf(::ConfigControllerImpl) { bind<ConfigController>() } singleOf(::TreeControllerImpl) { bind<TreeController>() } singleOf(::DownloadControllerImpl) { bind<DownloadController>() } singleOf(::UploadControllerImpl) { bind<UploadController>() } singleOf(::CompareControllerImpl) { bind<CompareController>() } singleOf(::PageControllerImpl) { bind<PageController>() } singleOf(::DescriptionControllerImpl) { bind<DescriptionController>() } } val usecaseBeans = module { singleOf(::GetLocalFilesUseCase) singleOf(::RetrieveLocalFilePagesStreamUseCase) singleOf(::AreFilesSupportedUseCase) singleOf(::CompareDocumentsUseCase) singleOf(::SaveStreamToFilesDirectoryUseCase) } val managerBeans = module { singleOf(::PathManagerImpl) { bind<PathManager>() } } }
Demos/Ktor/src/main/kotlin/com/groupdocs/ui/di/ModulesInjection.kt
3662671114
package com.hewking.custom import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.View import com.hewking.custom.util.dp2px /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/10/24 0024 * 修改人员:hewking * 修改时间:2018/10/24 0024 * 修改备注: * Version: 1.0.0 */ class TagRectView(ctx : Context,attrs : AttributeSet) : View(ctx,attrs) { private val mPaint by lazy { Paint().apply { isAntiAlias = true style = Paint.Style.FILL color = Color.RED strokeWidth = dp2px(1f).toFloat() } } init { val typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.CalendarView) typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val wMode = MeasureSpec.getMode(widthMeasureSpec) var width = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (wMode == MeasureSpec.AT_MOST) { width = dp2px(15f) } if (hMode == MeasureSpec.AT_MOST) { height = dp2px(30f) } setMeasuredDimension(width,height) if (isInEditMode) { setMeasuredDimension(100,200) } } private val path : Path by lazy { Path() } override fun onDraw(canvas: Canvas?) { canvas?:return val smallH = height / 3f val biggerH = height / 3f * 2 path.moveTo(0f,smallH) path.rLineTo(0f,biggerH) path.rLineTo(width.toFloat(),-smallH) path.rLineTo(0f,-biggerH) path.close() canvas.drawPath(path,mPaint) } }
app/src/main/java/com/hewking/custom/TagRectView.kt
656652778
package core.select import kotlinx.coroutines.* import kotlinx.coroutines.selects.select import java.util.* //延迟值可以使用 onAwait 子句查询。 让我们启动一个异步函数,它在随机的延迟后会延迟返回字符串: fun CoroutineScope.asyncString(time: Int) = async { delay(time.toLong()) "Waited for $time ms" } //让我们随机启动十余个异步函数,每个都延迟随机的时间。 fun CoroutineScope.asyncStringsList(): List<Deferred<String>> { val random = Random(3) return List(12) { asyncString(random.nextInt(1000)) } } /* 现在 main 函数在等待第一个函数完成,并统计仍处于激活状态的延迟值的数量。注意,我们在这里使用 select 表达式事实上是作为一种 Kotlin DSL, 所以我们可以用任意代码为它提供子句。在这种情况下,我们遍历一个延迟值的队列,并为每个延迟值提供 onAwait 子句的调用。 */ fun main() = runBlocking<Unit> { //sampleStart val list = asyncStringsList() val result = select<String> { list.withIndex().forEach { (index, deferred) -> deferred.onAwait { answer -> "Deferred $index produced answer '$answer'" } } } println("result = $result ----") val countActive = list.count { it.isActive } println("$countActive coroutines are still active") //sampleEnd }
Kotlin/Kotlin-Coroutines/src/main/kotlin/core/select/04_SelectingDeferredValues.kt
4166019462
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki.backend import BackendProto.Backend import com.ichi2.libanki.backend.BackendUtils.from_json_bytes import com.ichi2.libanki.backend.BackendUtils.to_json_bytes import com.ichi2.libanki.str import com.ichi2.utils.JSONArray import com.ichi2.utils.JSONObject import net.ankiweb.rsdroid.BackendV1 import net.ankiweb.rsdroid.exceptions.BackendNotFoundException class RustConfigBackend(private val backend: BackendV1) { fun getJson(): Any { return from_json_bytes(backend.allConfig) } fun setJson(value: JSONObject) { val builder = Backend.Json.newBuilder() builder.json = to_json_bytes(value) backend.allConfig = builder.build() } fun get_string(key: str): String { try { return BackendUtils.jsonToString(backend.getConfigJson(key)) } catch (ex: BackendNotFoundException) { throw IllegalStateException("'$key' not found", ex) } } fun get_array(key: str): JSONArray { try { return BackendUtils.jsonToArray(backend.getConfigJson(key)) } catch (ex: BackendNotFoundException) { throw IllegalStateException("'$key' not found", ex) } } fun get_object(key: str): JSONObject { try { return from_json_bytes(backend.getConfigJson(key)) } catch (ex: BackendNotFoundException) { throw IllegalStateException("'$key' not found", ex) } } fun set(key: str, value: Any) { backend.setConfigJson(key, to_json_bytes(value)) } fun remove(key: str) { backend.removeConfig(key) } fun has(key: str): Boolean { return try { this.get_string(key) true } catch (ex: IllegalStateException) { false } } fun not_has_or_is_null(key: str): Boolean { return try { val ret = this.get_string(key) return ret == "null" } catch (ex: IllegalStateException) { true } } }
AnkiDroid/src/main/java/com/ichi2/libanki/backend/RustConfigBackend.kt
2945586205
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.request import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.datasource.DataFrom.MEMORY import com.github.panpf.sketch.request.DownloadData import com.github.panpf.sketch.request.DownloadRequest import com.github.panpf.sketch.request.DownloadResult import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.util.UnknownException import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DownloadResultTest { @Test fun test() { val context = getTestContext() val request1 = DownloadRequest(context, "http://sample.com/sample.jpeg") DownloadResult.Success(request1, DownloadData(byteArrayOf(), MEMORY)).apply { Assert.assertSame(request1, request) Assert.assertNotNull(data) Assert.assertEquals(MEMORY, dataFrom) } DownloadResult.Error(request1, UnknownException("")).apply { Assert.assertSame(request1, request) Assert.assertTrue(exception is UnknownException) } } }
sketch/src/androidTest/java/com/github/panpf/sketch/test/request/DownloadResultTest.kt
1644035870
package com.popalay.cardme.presentation.screens.splash import android.os.Bundle import com.popalay.cardme.domain.interactor.SplashInteractor import com.popalay.cardme.presentation.base.BaseActivity import com.popalay.cardme.presentation.screens.home.HomeActivity import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject class SplashActivity : BaseActivity() { @Inject lateinit var splashInteractor: SplashInteractor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) splashInteractor.start() .observeOn(AndroidSchedulers.mainThread()) .doOnComplete { startActivity(HomeActivity.getIntent(this)) finish() } .subscribeBy() } }
presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/splash/SplashActivity.kt
430548439
package com.matejdro.wearmusiccenter.common.actions object StandardActions { const val ACTION_PLAY = "com.matejdro.wearmusiccenter.actions.playback.PlayAction" const val ACTION_PAUSE = "com.matejdro.wearmusiccenter.actions.playback.PauseAction" const val ACTION_SKIP_TO_PREV = "com.matejdro.wearmusiccenter.actions.playback.SkipToPrevAction" const val ACTION_SKIP_TO_NEXT = "com.matejdro.wearmusiccenter.actions.playback.SkipToNextAction" const val ACTION_VOLUME_UP = "com.matejdro.wearmusiccenter.actions.volume.IncreaseVolumeAction" const val ACTION_VOLUME_DOWN = "com.matejdro.wearmusiccenter.actions.volume.DecreaseVolumeAction" const val ACTION_OPEN_MENU = "com.matejdro.wearmusiccenter.actions.OpenMenuAction" const val ACTION_SKIP_30_SECONDS = "com.matejdro.wearmusiccenter.actions.playback.SkipThirtySecondsAction" const val ACTION_REVERSE_30_SECONDS = "com.matejdro.wearmusiccenter.actions.playback.ReverseThirtySecondsAction" }
common/src/main/java/com/matejdro/wearmusiccenter/common/actions/StandardActions.kt
1338506954
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader.userlists import android.accounts.AccountManager import android.content.Context import android.content.SharedPreferences import android.support.v4.content.FixedAsyncTaskLoader import android.util.Log import org.mariotaku.kpreferences.get import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.twitter.model.PageableResponseList import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.microblog.library.twitter.model.UserList import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG import de.vanita5.twittnuker.constant.loadItemLimitKey import de.vanita5.twittnuker.extension.model.api.microblog.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.loader.iface.IPaginationLoader import de.vanita5.twittnuker.model.ParcelableUserList import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.CursorPagination import de.vanita5.twittnuker.model.pagination.Pagination import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.util.collection.NoDuplicatesArrayList import de.vanita5.twittnuker.util.dagger.GeneralComponent import java.util.* import javax.inject.Inject abstract class BaseUserListsLoader( context: Context, protected val accountKey: UserKey?, data: List<ParcelableUserList>? ) : FixedAsyncTaskLoader<List<ParcelableUserList>>(context), IPaginationLoader { @Inject lateinit var preferences: SharedPreferences protected val data = NoDuplicatesArrayList<ParcelableUserList>() private val profileImageSize = context.getString(R.string.profile_image_size) override var pagination: Pagination? = null override var nextPagination: Pagination? = null protected set override var prevPagination: Pagination? = null protected set init { GeneralComponent.get(context).inject(this) if (data != null) { this.data.addAll(data) } } @Throws(MicroBlogException::class) abstract fun getUserLists(twitter: MicroBlog, paging: Paging): List<UserList> override fun loadInBackground(): List<ParcelableUserList> { if (accountKey == null) return emptyList() var listLoaded: List<UserList>? = null try { val am = AccountManager.get(context) val details = AccountUtils.getAccountDetails(am, accountKey, true) ?: return data val twitter = details.newMicroBlogInstance(context, MicroBlog::class.java) val paging = Paging() paging.count(preferences[loadItemLimitKey].coerceIn(0, 100)) pagination?.applyTo(paging) listLoaded = getUserLists(twitter, paging) } catch (e: MicroBlogException) { Log.w(LOGTAG, e) } if (listLoaded != null) { val listSize = listLoaded.size if (listLoaded is PageableResponseList<*>) { nextPagination = CursorPagination.valueOf(listLoaded.nextCursor) prevPagination = CursorPagination.valueOf(listLoaded.previousCursor) val dataSize = data.size for (i in 0 until listSize) { val list = listLoaded[i] data.add(list.toParcelable(accountKey, (dataSize + i).toLong(), isFollowing(list), profileImageSize)) } } else { for (i in 0 until listSize) { val list = listLoaded[i] data.add(listLoaded[i].toParcelable(accountKey, i.toLong(), isFollowing(list), profileImageSize)) } } } Collections.sort(data) return data } override fun onStartLoading() { forceLoad() } protected open fun isFollowing(list: UserList): Boolean { return list.isFollowing } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/userlists/BaseUserListsLoader.kt
3343081861
package it.bitprepared.loginapp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_result.* const val KEY_RESULT_SQ = "result_sq" class ResultActivity : AppCompatActivity() { private var resultSq: String? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) resultSq = if (savedInstanceState == null) { intent.extras.getString(KEY_RESULT_SQ) } else { savedInstanceState.getSerializable(KEY_RESULT_SQ) as String } if (resultSq == null) return when (resultSq) { WHITE -> result_image.setImageResource(R.drawable.rad2) YELLOW -> result_image.setImageResource(R.drawable.rad5) RED -> result_image.setImageResource(R.drawable.rad3) GREEN -> result_image.setImageResource(R.drawable.rad4) } result_sq.text = resultSq } }
app/src/main/java/it/bitprepared/loginapp/ResultActivity.kt
2272609526
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.task import android.content.Context import android.widget.Toast import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.mapToArray import de.vanita5.microblog.library.MicroBlog import de.vanita5.twittnuker.R import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.api.microblog.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.ParcelableUserList import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.event.UserListMembersChangedEvent class AddUserListMembersTask( context: Context, accountKey: UserKey, private val listId: String, private val users: Array<out ParcelableUser> ) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val userIds = users.mapToArray(ParcelableUser::key) val result = microBlog.addUserListMembers(listId, UserKey.getIds(userIds)) return result.toParcelable(account.key) } override fun onSucceed(callback: Any?, result: ParcelableUserList) { val message: String if (users.size == 1) { val user = users.first() val nameFirst = preferences[nameFirstKey] val displayName = userColorNameManager.getDisplayName(user.key, user.name, user.screen_name, nameFirst) message = context.getString(R.string.message_toast_added_user_to_list, displayName, result.name) } else { val res = context.resources message = res.getQuantityString(R.plurals.added_N_users_to_list, users.size, users.size, result.name) } Toast.makeText(context, message, Toast.LENGTH_SHORT).show() bus.post(UserListMembersChangedEvent(UserListMembersChangedEvent.Action.ADDED, result, users)) } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/AddUserListMembersTask.kt
14755765
package com.matejdro.wearmusiccenter.actions.tasker import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.drawable.Drawable import android.os.PersistableBundle import androidx.appcompat.content.res.AppCompatResources import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.actions.PhoneAction import com.matejdro.wearmusiccenter.view.ActivityResultReceiver import com.matejdro.wearmusiccenter.view.buttonconfig.ActionPickerViewModel import com.matejdro.wearutils.tasker.TaskerIntent class TaskerTaskPickerAction : PhoneAction, ActivityResultReceiver { constructor(context: Context) : super(context) constructor(context: Context, bundle: PersistableBundle) : super(context, bundle) private var prevActionPicker: ActionPickerViewModel? = null override fun retrieveTitle(): String = context.getString(R.string.tasker_task) override val defaultIcon: Drawable get() { return try { context.packageManager.getApplicationIcon(TaskerIntent.TASKER_PACKAGE_MARKET) } catch (ignored: PackageManager.NameNotFoundException) { AppCompatResources.getDrawable(context, android.R.drawable.sym_def_app_icon)!! } } override fun onActionPicked(actionPicker: ActionPickerViewModel) { prevActionPicker = actionPicker actionPicker.startActivityForResult(TaskerIntent.getTaskSelectIntent(), this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != Activity.RESULT_OK) { return } val taskName = data?.dataString ?: return val taskerAction = TaskerTaskAction(context, taskName) prevActionPicker?.selectedAction?.value = taskerAction } }
mobile/src/main/java/com/matejdro/wearmusiccenter/actions/tasker/TaskerTaskPickerAction.kt
950400540
package com.sapuseven.untis.models.untis.masterdata import android.content.ContentValues import android.database.Cursor import com.sapuseven.untis.annotations.Table import com.sapuseven.untis.annotations.TableColumn import com.sapuseven.untis.data.databases.TABLE_NAME_HOLIDAYS import com.sapuseven.untis.interfaces.TableModel import kotlinx.serialization.Serializable @Serializable @Table(TABLE_NAME_HOLIDAYS) data class Holiday( @field:TableColumn("INTEGER NOT NULL") val id: Int = 0, @field:TableColumn("VARCHAR(255) NOT NULL") val name: String = "", @field:TableColumn("VARCHAR(255) NOT NULL") val longName: String = "", @field:TableColumn("VARCHAR(255) NOT NULL") val startDate: String = "", @field:TableColumn("VARCHAR(255) NOT NULL") val endDate: String = "" ) : TableModel { companion object { const val TABLE_NAME = TABLE_NAME_HOLIDAYS } override val tableName = TABLE_NAME override val elementId = id override fun generateValues(): ContentValues { val values = ContentValues() values.put("id", id) values.put("name", name) values.put("longName", longName) values.put("startDate", startDate) values.put("endDate", endDate) return values } override fun parseCursor(cursor: Cursor): TableModel { return Holiday( cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("longName")), cursor.getString(cursor.getColumnIndex("startDate")), cursor.getString(cursor.getColumnIndex("endDate")) ) } }
app/src/main/java/com/sapuseven/untis/models/untis/masterdata/Holiday.kt
1314309600
package me.manulorenzo.keddit.constants /** * Created by Manuel Lorenzo on 04/11/2016. */ object AdapterConstants { val NEWS = 1 val LOADING = 2 }
app/src/main/java/me/manulorenzo/keddit/constants/AdapterConstants.kt
1316880869
package com.projectcitybuild.features.bans.listeners import com.projectcitybuild.DateTimeFormatterMock import com.projectcitybuild.GameBanMock import com.projectcitybuild.features.bans.usecases.AuthoriseConnectionUseCase import com.projectcitybuild.modules.errorreporting.ErrorReporter import com.projectcitybuild.modules.logger.PlatformLogger import com.projectcitybuild.plugin.listeners.BanConnectionListener import com.projectcitybuild.stubs.IPBanMock import kotlinx.coroutines.test.runTest import org.bukkit.event.player.AsyncPlayerPreLoginEvent import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyString import org.mockito.ArgumentMatchers.eq import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.powermock.api.mockito.PowerMockito.mock import org.powermock.api.mockito.PowerMockito.`when` import java.net.InetAddress import java.util.UUID class BanConnectionListenerTest { private lateinit var listener: BanConnectionListener private lateinit var authoriseConnectionListener: AuthoriseConnectionUseCase private lateinit var errorReporter: ErrorReporter @BeforeEach fun setUp() { authoriseConnectionListener = mock(AuthoriseConnectionUseCase::class.java) errorReporter = mock(ErrorReporter::class.java) listener = BanConnectionListener( authoriseConnectionListener, mock(PlatformLogger::class.java), DateTimeFormatterMock(), errorReporter, ) } private fun loginEvent(uuid: UUID, ip: String = "127.0.0.1"): AsyncPlayerPreLoginEvent { val socketAddress = mock(InetAddress::class.java).also { `when`(it.toString()).thenReturn(ip) } return mock(AsyncPlayerPreLoginEvent::class.java).also { `when`(it.address).thenReturn(socketAddress) `when`(it.uniqueId).thenReturn(uuid) } } @Test fun `cancels login event if player is banned`() = runTest { arrayOf( AuthoriseConnectionUseCase.Ban.UUID(GameBanMock()), AuthoriseConnectionUseCase.Ban.IP(IPBanMock()), ).forEach { ban -> val uuid = UUID.randomUUID() val ip = "127.0.0.1" val event = loginEvent(uuid, ip) `when`(authoriseConnectionListener.getBan(uuid, ip)).thenReturn(ban) listener.onAsyncPreLogin(event) verify(event).disallow(eq(AsyncPlayerPreLoginEvent.Result.KICK_BANNED), anyString()) } } @Test fun `does not cancel login event if player is not banned`() = runTest { val uuid = UUID.randomUUID() val ip = "127.0.0.1" val event = loginEvent(uuid, ip) `when`(authoriseConnectionListener.getBan(uuid, ip)).thenReturn(null) listener.onAsyncPreLogin(event) verify(event, never()).disallow(any(AsyncPlayerPreLoginEvent.Result::class.java), any()) } @Test fun `cancels login event if cannot fetch ban`() = runTest { val uuid = UUID.randomUUID() val ip = "127.0.0.1" val event = loginEvent(uuid, ip) `when`(authoriseConnectionListener.getBan(uuid, ip)).thenThrow(Exception()) listener.onAsyncPreLogin(event) verify(event).disallow(eq(AsyncPlayerPreLoginEvent.Result.KICK_OTHER), anyString()) } @Test fun `reports error if cannot fetch ban`() = runTest { val uuid = UUID.randomUUID() val ip = "127.0.0.1" val event = loginEvent(uuid, ip) val exception = Exception() `when`(authoriseConnectionListener.getBan(uuid, ip)).thenThrow(exception) listener.onAsyncPreLogin(event) verify(errorReporter).report(exception) } }
src/test/com/projectcitybuild/features/bans/listeners/BanConnectionListenerTest.kt
2521532116
/* * Copyright (c) 2017. ThanksMister LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thanksmister.iot.mqtt.alarmpanel.di import android.arch.lifecycle.ViewModelProvider import dagger.Binds import dagger.Module @Module abstract class DaggerViewModelInjectionModule { @Binds internal abstract fun bindViewModelFactory(factory: DaggerViewModelFactory): ViewModelProvider.Factory }
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/di/DaggerViewModelInjectionModule.kt
2123935506
/** * ownCloud Android client application * * @author Abel García de Prada * @author Juan Carlos Garrote Gascón * * Copyright (C) 2021 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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:></http:>//www.gnu.org/licenses/>. */ package com.owncloud.android.providers import android.content.Context interface ContextProvider { fun getBoolean(id: Int): Boolean fun getString(id: Int): String fun getInt(id: Int): Int fun getContext(): Context fun isConnected(): Boolean }
owncloudApp/src/main/java/com/owncloud/android/providers/ContextProvider.kt
2785959354
/* * Copyright 2019 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.padlock.scopes import javax.inject.Scope @Scope annotation class FragmentScope
padlock/src/main/java/com/pyamsoft/padlock/scopes/FragmentScope.kt
3835385843
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.stubs.index import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.IndexSink import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StubIndexKey import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import org.rust.lang.core.crate.impl.FakeCrate import org.rust.lang.core.psi.RsExternCrateItem import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.rustStructureOrAnyPsiModificationTracker import org.rust.lang.core.stubs.RsExternCrateItemStub import org.rust.lang.core.stubs.RsFileStub import org.rust.openapiext.checkCommitIsNotInProgress import org.rust.openapiext.getElements class RsExternCrateReexportIndex : StringStubIndexExtension<RsExternCrateItem>() { override fun getVersion(): Int = RsFileStub.Type.stubVersion override fun getKey(): StubIndexKey<String, RsExternCrateItem> = KEY companion object { val KEY: StubIndexKey<String, RsExternCrateItem> = StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RsExternCrateReexportIndex") fun index(stub: RsExternCrateItemStub, sink: IndexSink) { val externCrateItem = stub.psi val isPublic = externCrateItem?.vis != null if (!isPublic) return sink.occurrence(KEY, externCrateItem.referenceName) } fun findReexports(project: Project, crateRoot: RsMod): List<RsExternCrateItem> { checkCommitIsNotInProgress(project) return CachedValuesManager.getCachedValue(crateRoot) { val targetCrate = crateRoot.containingCrate val reexports = if (targetCrate !is FakeCrate) { getElements(KEY, targetCrate.normName, project, GlobalSearchScope.allScope(project)) .filter { externCrateItem -> externCrateItem.reference.resolve() == crateRoot } } else { emptyList() } CachedValueProvider.Result.create(reexports, crateRoot.rustStructureOrAnyPsiModificationTracker) } } } }
src/main/kotlin/org/rust/lang/core/stubs/index/RsExternCrateReexportIndex.kt
2239944
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.import import org.rust.* import org.rust.cargo.project.workspace.CargoWorkspace.Edition import org.rust.ide.experiments.RsExperiments.EVALUATE_BUILD_SCRIPTS import org.rust.ide.experiments.RsExperiments.PROC_MACROS import org.rust.ide.utils.import.Testmarks class AutoImportFixTest : AutoImportFixTestBase() { fun `test import struct`() = checkAutoImportFixByText(""" mod foo { pub struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { pub struct Foo; } fn main() { let f = Foo/*caret*/; } """) fun `test import enum variant 1`() = checkAutoImportFixByText(""" mod foo { pub enum Foo { A } } fn main() { <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::A; } """, """ use crate::foo::Foo; mod foo { pub enum Foo { A } } fn main() { Foo/*caret*/::A; } """) fun `test import enum variant 2`() = checkAutoImportFixByText(""" mod foo { pub enum Foo { A } } fn main() { let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>; } """, """ use crate::foo::Foo::A; mod foo { pub enum Foo { A } } fn main() { let a = A/*caret*/; } """) fun `test import enum variant 3`() = checkAutoImportFixByText(""" enum Foo { A } fn main() { let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>; } """, """ use crate::Foo::A; enum Foo { A } fn main() { let a = A/*caret*/; } """) fun `test import enum variant of reexported enum`() = checkAutoImportFixByText(""" mod inner1 { pub use inner2::Foo; mod inner2 { pub enum Foo { A } } } fn main() { let _ = <error descr="Unresolved reference: `A`">A/*caret*/</error>; } """, """ use crate::inner1::Foo::A; mod inner1 { pub use inner2::Foo; mod inner2 { pub enum Foo { A } } } fn main() { let _ = A; } """) fun `test import function`() = checkAutoImportFixByText(""" mod foo { pub fn bar() -> i32 { 0 } } fn main() { let f = <error descr="Unresolved reference: `bar`">bar/*caret*/</error>(); } """, """ use crate::foo::bar; mod foo { pub fn bar() -> i32 { 0 } } fn main() { let f = bar/*caret*/(); } """) fun `test import function method`() = checkAutoImportFixByText(""" mod foo { pub struct Foo; impl Foo { pub fn foo() {} } } fn main() { <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::foo(); } """, """ use crate::foo::Foo; mod foo { pub struct Foo; impl Foo { pub fn foo() {} } } fn main() { Foo/*caret*/::foo(); } """) fun `test import generic item`() = checkAutoImportFixByText(""" mod foo { pub struct Foo<T>(T); } fn f<T>(foo: <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error><T>) {} """, """ use crate::foo::Foo; mod foo { pub struct Foo<T>(T); } fn f<T>(foo: Foo/*caret*/<T>) {} """) fun `test import item with type params (struct literal)`() = checkAutoImportFixByText(""" mod foo { pub struct Foo<T> { x: T } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::<i32> {}; } """, """ use crate::foo::Foo; mod foo { pub struct Foo<T> { x: T } } fn main() { let f = Foo/*caret*/::<i32> {}; } """) fun `test import item with type params (tuple struct literal)`() = checkAutoImportFixByText(""" mod foo { pub struct Foo<T>(T); impl<T> Foo<T> { fn bar() {} } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::<i32>::bar(); } """, """ use crate::foo::Foo; mod foo { pub struct Foo<T>(T); impl<T> Foo<T> { fn bar() {} } } fn main() { let f = Foo/*caret*/::<i32>::bar(); } """) fun `test import item with type params (pat struct)`() = checkAutoImportFixByText(""" mod foo { pub struct Foo<T> { x: T } } fn main() { let <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::<i32> { x } = (); } """, """ use crate::foo::Foo; mod foo { pub struct Foo<T> { x: T } } fn main() { let Foo/*caret*/::<i32> { x } = (); } """) fun `test import item with type params (pat tuple struct)`() = checkAutoImportFixByText(""" mod foo { pub struct Foo<T>(T); impl<T> Foo<T> { fn bar() {} } } fn main() { let <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>::<i32>::bar(x) = (); } """, """ use crate::foo::Foo; mod foo { pub struct Foo<T>(T); impl<T> Foo<T> { fn bar() {} } } fn main() { let Foo/*caret*/::<i32>::bar(x) = (); } """) fun `test import module`() = checkAutoImportFixByText(""" mod foo { pub mod bar { pub fn foo_bar() -> i32 { 0 } } } fn main() { let f = <error descr="Unresolved reference: `bar`">bar/*caret*/</error>::foo_bar(); } """, """ use crate::foo::bar; mod foo { pub mod bar { pub fn foo_bar() -> i32 { 0 } } } fn main() { let f = bar/*caret*/::foo_bar(); } """) fun `test insert use item after existing use items`() = checkAutoImportFixByText(""" use crate::foo::Bar; mod foo { pub struct Bar; } mod bar { pub struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::bar::Foo; use crate::foo::Bar; mod foo { pub struct Bar; } mod bar { pub struct Foo; } fn main() { let f = Foo/*caret*/; } """) fun `test insert use item after inner attributes`() = checkAutoImportFixByText(""" #![allow(non_snake_case)] mod foo { pub struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ #![allow(non_snake_case)] use crate::foo::Foo; mod foo { pub struct Foo; } fn main() { let f = Foo/*caret*/; } """) fun `test insert use item after outer attributes`() = checkAutoImportFixByText(""" mod foo { pub struct Foo; } mod tests { fn foo() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } } """, """ mod foo { pub struct Foo; } mod tests { use crate::foo::Foo; fn foo() { let f = Foo/*caret*/; } } """) fun `test import item from nested module`() = checkAutoImportFixByText(""" mod foo { pub mod bar { pub struct Foo; } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::bar::Foo; mod foo { pub mod bar { pub struct Foo; } } fn main() { let f = Foo/*caret*/; } """) fun `test don't try to import private item`() = checkAutoImportFixIsUnavailable(""" mod foo { struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """) fun `test don't try to import from private mod`() = checkAutoImportFixIsUnavailable(""" mod foo { mod bar { pub struct Foo; } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """) fun `test import private item from parent mod`() = checkAutoImportFixByText(""" mod a1 { struct Foo; mod a2 { fn main() { let _ = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } } } """, """ mod a1 { struct Foo; mod a2 { use crate::a1::Foo; fn main() { let _ = Foo; } } } """) @CheckTestmarkHit(Testmarks.IgnorePrivateImportInParentMod::class) fun `test don't try to import private reexport from parent mod 1`() = checkAutoImportFixByText(""" mod a1 { use crate::b1::b2::Foo; mod a2 { fn main() { let _ = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } } } mod b1 { pub mod b2 { pub struct Foo; } } """, """ mod a1 { use crate::b1::b2::Foo; mod a2 { use crate::b1::b2::Foo; fn main() { let _ = Foo; } } } mod b1 { pub mod b2 { pub struct Foo; } } """) @CheckTestmarkHit(Testmarks.IgnorePrivateImportInParentMod::class) fun `test don't try to import private reexport from parent mod 2`() = checkAutoImportFixByText(""" mod a1 { use crate::b1::b2::b3; mod a2 { fn main() { let _ = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } } } mod b1 { pub mod b2 { pub mod b3 { pub struct Foo; } } } """, """ mod a1 { use crate::b1::b2::b3; mod a2 { use crate::b1::b2::b3::Foo; fn main() { let _ = Foo; } } } mod b1 { pub mod b2 { pub mod b3 { pub struct Foo; } } } """) @CheckTestmarkHit(Testmarks.IgnorePrivateImportInParentMod::class) fun `test don't try to import private reexport from crate root`() = checkAutoImportFixByText(""" use mod1::func; mod mod1 { pub fn func() {} } mod inner { fn test() { /*error descr="Unresolved reference: `func`"*//*caret*/func/*error**/(); } } """, """ use mod1::func; mod mod1 { pub fn func() {} } mod inner { use crate::mod1::func; fn test() { func(); } } """) fun `test complex module structure`() = checkAutoImportFixByText(""" mod aaa { mod bbb { fn foo() { let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } } } mod ccc { pub mod ddd { pub struct Foo; } mod eee { struct Foo; } } """, """ mod aaa { mod bbb { use crate::ccc::ddd::Foo; fn foo() { let x = Foo/*caret*/; } } } mod ccc { pub mod ddd { pub struct Foo; } mod eee { struct Foo; } } """) fun `test complex module structure with file modules`() = checkAutoImportFixByFileTree(""" //- aaa/mod.rs mod bbb; //- aaa/bbb/mod.rs fn foo() { let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } //- ccc/mod.rs pub mod ddd; mod eee; //- ccc/ddd/mod.rs pub struct Foo; //- ccc/eee/mod.rs struct Foo; //- main.rs mod aaa; mod ccc; """, """ //- aaa/bbb/mod.rs use crate::ccc::ddd::Foo; fn foo() { let x = Foo/*caret*/; } """) fun `test import module declared via module declaration`() = checkAutoImportFixByFileTree(""" //- foo/bar.rs fn foo_bar() {} //- main.rs mod foo { pub mod bar; } fn main() { <error descr="Unresolved reference: `bar`">bar/*caret*/</error>::foo_bar(); } """, """ //- main.rs use crate::foo::bar; mod foo { pub mod bar; } fn main() { bar/*caret*/::foo_bar(); } """) fun `test filter import candidates 1`() = checkAutoImportFixByText(""" mod foo1 { pub fn bar() {} } mod foo2 { pub mod bar { pub fn foo_bar() {} } } fn main() { <error descr="Unresolved reference: `bar`">bar/*caret*/</error>(); } """, """ use crate::foo1::bar; mod foo1 { pub fn bar() {} } mod foo2 { pub mod bar { pub fn foo_bar() {} } } fn main() { bar/*caret*/(); } """) fun `test filter import candidates 2`() = checkAutoImportFixByText(""" mod foo1 { pub fn bar() {} } mod foo2 { pub mod bar { pub fn foo_bar() {} } } fn main() { <error descr="Unresolved reference: `bar`">bar/*caret*/</error>::foo_bar(); } """, """ use crate::foo2::bar; mod foo1 { pub fn bar() {} } mod foo2 { pub mod bar { pub fn foo_bar() {} } } fn main() { bar/*caret*/::foo_bar(); } """) fun `test filter members without owner prefix`() = checkAutoImportFixIsUnavailable(""" mod foo { pub struct Foo; impl Foo { pub fn foo() {} } } fn main() { <error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """) fun `test import item if it can't be resolved`() = checkAutoImportFixByText(""" mod foo { pub mod bar { } } fn main() { <error descr="Unresolved reference: `bar`">bar/*caret*/</error>::unresolved(); } """, """ use crate::foo::bar; mod foo { pub mod bar { } } fn main() { bar::unresolved(); } """) fun `test sort resolved paths before unresolved paths`() = checkAutoImportVariantsByText(""" mod mod1 { pub mod inner {} } mod mod2 { pub mod inner { pub fn foo() {} } } fn main() { inner/*caret*/::foo(); } """, listOf("crate::mod2::inner", "crate::mod1::inner")) fun `test sort resolved paths before unresolved paths (macros)`() = checkAutoImportVariantsByText(""" mod mod1 { pub mod inner {} } mod mod2 { pub mod inner { pub macro foo() {} } } fn main() { inner/*caret*/::foo!(); } """, listOf("crate::mod2::inner", "crate::mod1::inner")) fun `test don't import trait assoc function if its import is useless`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Bar { fn bar(); } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::bar(); } """) fun `test trait method with self parameter`() = checkAutoImportFixByText(""" mod foo { pub trait Bar { fn bar(&self); } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::bar(); } """, """ use crate::foo::Bar; mod foo { pub trait Bar { fn bar(&self); } } fn main() { Bar::bar(); } """) fun `test trait method with parameter contains Self type`() = checkAutoImportFixByText(""" mod foo { pub trait Bar { fn bar() -> Self; } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::bar(); } """, """ use crate::foo::Bar; mod foo { pub trait Bar { fn bar() -> Self; } } fn main() { Bar/*caret*/::bar(); } """) fun `test don't import trait associated const`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Bar { const BAR: i32; } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::BAR(); } """) fun `test trait const containing Self type`() = checkAutoImportFixByText(""" mod foo { pub trait Bar { const C: Self; } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::C; } """, """ use crate::foo::Bar; mod foo { pub trait Bar { const C: Self; } } fn main() { Bar/*caret*/::C; } """) fun `test don't import trait associated type`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Bar { type Item; } } fn main() { let _: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>::Item; } """) fun `test import reexported item`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::Bar; mod bar { pub struct Bar; } } fn main() { <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::Bar; mod foo { pub use self::bar::Bar; mod bar { pub struct Bar; } } fn main() { Bar/*caret*/; } """) fun `test import reexported item with alias`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::Bar as Foo; mod bar { pub struct Bar; } } fn main() { <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { pub use self::bar::Bar as Foo; mod bar { pub struct Bar; } } fn main() { Foo/*caret*/; } """) fun `test import reexported item via use group`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::{Baz, Qwe}; mod bar { pub struct Baz; pub struct Qwe; } } fn main() { let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>; } """, """ use crate::foo::Baz; mod foo { pub use self::bar::{Baz, Qwe}; mod bar { pub struct Baz; pub struct Qwe; } } fn main() { let a = Baz/*caret*/; } """) fun `test import reexported item via 'self'`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::Baz::{self}; mod bar { pub struct Baz; } } fn main() { let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>; } """, """ use crate::foo::Baz; mod foo { pub use self::bar::Baz::{self}; mod bar { pub struct Baz; } } fn main() { let a = Baz/*caret*/; } """) fun `test import reexported item with complex reexport`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::{Baz as Foo, Qwe}; mod bar { pub struct Baz; pub struct Qwe; } } fn main() { let a = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { pub use self::bar::{Baz as Foo, Qwe}; mod bar { pub struct Baz; pub struct Qwe; } } fn main() { let a = Foo/*caret*/; } """) fun `test module reexport`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::baz; mod bar { pub mod baz { pub struct FooBar; } } } fn main() { let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>; } """, """ use crate::foo::baz::FooBar; mod foo { pub use self::bar::baz; mod bar { pub mod baz { pub struct FooBar; } } } fn main() { let x = FooBar/*caret*/; } """) @CheckTestmarkHit(AutoImportFix.Testmarks.PathInUseItem::class) fun `test do not import path in use item`() = checkAutoImportFixIsUnavailable(""" mod bar { pub struct Bar; } use <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; """) fun `test multiple import`() = checkAutoImportFixByTextWithMultipleChoice(""" mod foo { pub struct Foo; pub mod bar { pub struct Foo; } } mod baz { pub struct Foo; mod qwe { pub struct Foo; } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, listOf("crate::baz::Foo", "crate::foo::Foo", "crate::foo::bar::Foo"), "crate::baz::Foo", """ use crate::baz::Foo; mod foo { pub struct Foo; pub mod bar { pub struct Foo; } } mod baz { pub struct Foo; mod qwe { pub struct Foo; } } fn main() { let f = Foo/*caret*/; } """) fun `test multiple import with reexports`() = checkAutoImportFixByTextWithMultipleChoice(""" mod foo { pub struct Foo; } mod bar { pub use self::baz::Foo; mod baz { pub struct Foo; } } mod qwe { pub use self::xyz::Bar as Foo; mod xyz { pub struct Bar; } } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, listOf("crate::bar::Foo", "crate::foo::Foo", "crate::qwe::Foo"), "crate::bar::Foo", """ use crate::bar::Foo; mod foo { pub struct Foo; } mod bar { pub use self::baz::Foo; mod baz { pub struct Foo; } } mod qwe { pub use self::xyz::Bar as Foo; mod xyz { pub struct Bar; } } fn main() { let f = Foo/*caret*/; } """) fun `test double module reexport`() = checkAutoImportFixByText(""" mod foo { pub mod bar { pub struct FooBar; } } mod baz { pub mod qqq { pub use crate::foo::bar; } } mod xxx { pub use crate::baz::qqq; } fn main() { let a = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>; } """, """ use crate::foo::bar::FooBar; mod foo { pub mod bar { pub struct FooBar; } } mod baz { pub mod qqq { pub use crate::foo::bar; } } mod xxx { pub use crate::baz::qqq; } fn main() { let a = FooBar/*caret*/; } """) fun `test cyclic module reexports`() = checkAutoImportFixByText(""" pub mod x { pub use crate::y; pub struct Z; } pub mod y { pub use crate::x; } fn main() { let x = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>; } """, """ use crate::x::Z; pub mod x { pub use crate::y; pub struct Z; } pub mod y { pub use crate::x; } fn main() { let x = Z/*caret*/; } """) fun `test crazy cyclic module reexports`() = checkAutoImportFixByTextWithMultipleChoice(""" pub mod x { pub use crate::u; pub mod y { pub use crate::u::v; pub struct Z; } } pub mod u { pub use crate::x::y; pub mod v { pub use crate::x; } } fn main() { let z = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>; } """, listOf("crate::u::y::Z", "crate::x::y::Z"), "crate::u::y::Z", """ use crate::u::y::Z; pub mod x { pub use crate::u; pub mod y { pub use crate::u::v; pub struct Z; } } pub mod u { pub use crate::x::y; pub mod v { pub use crate::x; } } fn main() { let z = Z/*caret*/; } """) fun `test filter imports`() = checkAutoImportFixByTextWithMultipleChoice(""" mod foo { pub use self::bar::FooBar; pub mod bar { pub struct FooBar; } } mod baz { pub use crate::foo::bar::FooBar; } mod quuz { pub use crate::foo::bar; } fn main() { let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>; } """, listOf("crate::baz::FooBar", "crate::foo::FooBar"), "crate::baz::FooBar", """ use crate::baz::FooBar; mod foo { pub use self::bar::FooBar; pub mod bar { pub struct FooBar; } } mod baz { pub use crate::foo::bar::FooBar; } mod quuz { pub use crate::foo::bar; } fn main() { let x = FooBar/*caret*/; } """) fun `test filter by namespace - type`() = checkAutoImportFixByText(""" mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } fn foo(x: <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>) {} """, """ use crate::struct_mod::Foo; mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } fn foo(x: Foo/*caret*/) {} """) // should suggest only `enum_mod::Bar::Foo` fun `test filter by namespace - value`() = checkAutoImportFixByTextWithMultipleChoice(""" mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } mod type_alias_mod { pub type Foo = Bar; struct Bar { x: i32 } } fn main() { let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, listOf("crate::enum_mod::Bar::Foo", "crate::struct_mod::Foo", "crate::type_alias_mod::Foo"), "crate::enum_mod::Bar::Foo", """ use crate::enum_mod::Bar::Foo; mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } mod type_alias_mod { pub type Foo = Bar; struct Bar { x: i32 } } fn main() { let x = Foo/*caret*/; } """) fun `test filter by namespace - trait`() = checkAutoImportFixByText(""" mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } fn foo<T: <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>>(x: T) {} """, """ use crate::trait_mod::Foo; mod struct_mod { pub struct Foo { foo: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } fn foo<T: Foo/*caret*/>(x: T) {} """) fun `test filter by namespace - struct literal`() = checkAutoImportFixByTextWithMultipleChoice(""" mod struct_mod { pub struct Foo; } mod block_struct_mod { pub struct Foo { x: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } mod enum_struct_mod { pub enum Bar { Foo { foo: i32 } } } mod type_alias_mod { pub type Foo = Bar; struct Bar { x: i32 } } fn main() { let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error> { }; } """, listOf("crate::block_struct_mod::Foo", "crate::enum_struct_mod::Bar::Foo", "crate::type_alias_mod::Foo"), "crate::enum_struct_mod::Bar::Foo", """ use crate::enum_struct_mod::Bar::Foo; mod struct_mod { pub struct Foo; } mod block_struct_mod { pub struct Foo { x: i32 } } mod enum_mod { pub enum Bar { Foo } } mod trait_mod { pub trait Foo {} } mod enum_struct_mod { pub enum Bar { Foo { foo: i32 } } } mod type_alias_mod { pub type Foo = Bar; struct Bar { x: i32 } } fn main() { let x = Foo/*caret*/ { }; } """) fun `test import item with correct namespace when multiple namespaces available`() = checkAutoImportFixByTextWithoutHighlighting(""" mod inner { pub struct foo {} pub fn foo() {} } fn test(a: foo/*caret*/) {} """, """ use crate::inner::foo; mod inner { pub struct foo {} pub fn foo() {} } fn test(a: foo/*caret*/) {} """) fun `test import trait method`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = 123.<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = 123.foo/*caret*/(); } """) fun `test import default trait method`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } fn main() { let x = 123.<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } fn main() { let x = 123.foo/*caret*/(); } """) fun `test import trait method UFCS of primitive`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = i32::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(123); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = i32::foo/*caret*/(123); } """) fun `test import trait method UFCS of struct`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } struct S; fn main() { let x = S::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(123); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } struct S; fn main() { let x = S::foo/*caret*/(123); } """) fun `test import trait method UFCS of explicit type-qualified path`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = <i32>::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(123); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } fn main() { let x = <i32>::foo/*caret*/(123); } """) fun `test import trait associated constant`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { const C: i32; } impl<T> Foo for T { const C: i32 = 0; } } fn main() { let x = i32::<error descr="Unresolved reference: `C`">C/*caret*/</error>(123); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { const C: i32; } impl<T> Foo for T { const C: i32 = 0; } } fn main() { let x = i32::C/*caret*/(123); } """) fun `test import trait default method UFCS`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } fn main() { let x = i32::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(123); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } fn main() { let x = i32::foo/*caret*/(123); } """) fun `test import trait default method UFCS 2`() = checkAutoImportFixByFileTree(""" //- lib.rs pub trait Trait { fn foo() {} } impl<T> Trait for T {} //- main.rs pub use test_package::Trait; mod inner { fn main() { i32::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } } """, """ //- lib.rs pub trait Trait { fn foo() {} } impl<T> Trait for T {} //- main.rs pub use test_package::Trait; mod inner { use test_package::Trait; fn main() { i32::foo(); } } """) fun `test import trait default assoc function`() = checkAutoImportFixByText(""" mod foo { pub struct S; pub trait Foo { fn foo() {} } impl<T> Foo for T {} } fn main() { let x = <error descr="Unresolved reference: `S`">S/*caret*/</error>::foo(); } """, """ use crate::foo::S; mod foo { pub struct S; pub trait Foo { fn foo() {} } impl<T> Foo for T {} } fn main() { let x = S/*caret*/::foo(); } """) fun `test import reexported trait method`() = checkAutoImportFixByText(""" mod foo { pub use self::bar::baz; mod bar { pub mod baz { pub trait FooBar { fn foo_bar(&self); } impl<T> FooBar for T { fn foo_bar(&self) {} } } } } fn main() { let x = 123.<error descr="Unresolved reference: `foo_bar`">foo_bar/*caret*/</error>(); } """, """ use crate::foo::baz::FooBar; mod foo { pub use self::bar::baz; mod bar { pub mod baz { pub trait FooBar { fn foo_bar(&self); } impl<T> FooBar for T { fn foo_bar(&self) {} } } } } fn main() { let x = 123.foo_bar/*caret*/(); } """) fun `test do not try to import non trait method`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } } struct Bar; impl Bar { fn foo(&self) {} } fn main() { let x = Bar.foo/*caret*/(); } """) fun `test multiple trait method import`() = checkAutoImportFixByTextWithMultipleChoice(""" mod foo { pub trait Foo { fn foo(&self); } pub trait Bar { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } impl<T> Bar for T { fn foo(&self) {} } } fn main() { let x = 123.<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, listOf("crate::foo::Bar", "crate::foo::Foo"), "crate::foo::Bar", """ use crate::foo::Bar; mod foo { pub trait Foo { fn foo(&self); } pub trait Bar { fn foo(&self); } impl<T> Foo for T { fn foo(&self) {} } impl<T> Bar for T { fn foo(&self) {} } } fn main() { let x = 123.foo/*caret*/(); } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import trait method, use direct path`() = checkAutoImportFixByFileTree(""" //- dep-lib/lib.rs pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} //- lib.rs pub extern crate dep_lib_target; //- main.rs fn main() { let x = 123.<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, """ //- main.rs use dep_lib_target::Foo; fn main() { let x = 123.foo(); } """) fun `test suggest single method`() = checkAutoImportFixByText(""" struct Foo; struct Bar; #[lang="deref"] trait Deref { type Target; } impl Deref for Bar { type Target = Foo; } mod a { pub trait X { fn do_x(&self); } impl X for crate::Foo { fn do_x(&self) {} } impl X for crate::Bar { fn do_x(&self) {} } } fn main() { Bar.<error>do_x/*caret*/</error>(); } """, """ use crate::a::X; struct Foo; struct Bar; #[lang="deref"] trait Deref { type Target; } impl Deref for Bar { type Target = Foo; } mod a { pub trait X { fn do_x(&self); } impl X for crate::Foo { fn do_x(&self) {} } impl X for crate::Bar { fn do_x(&self) {} } } fn main() { Bar.do_x/*caret*/(); } """) /** Issue [2822](https://github.com/intellij-rust/intellij-rust/issues/2822) */ fun `test do not try to import trait object method`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self) {} } } fn bar(t: &dyn foo::Foo) { t.foo/*caret*/(); } """) fun `test do not try to import trait bound method`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self) {} } } fn bar<T: foo::Foo>(t: T) { t.foo/*caret*/(); } """) /** Issue [2863](https://github.com/intellij-rust/intellij-rust/issues/2863) */ fun `test do not try to import aliased trait`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } use foo::Foo as _Foo; fn main() { 123.foo/*caret*/(); } """) fun `test do not try to import underscore aliased trait`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self) {} } impl<T> Foo for T {} } use foo::Foo as _; fn main() { 123.foo/*caret*/(); } """) fun `test do not try to import trait for method call inside impl of that trait`() = checkAutoImportFixIsUnavailable(""" mod foo { pub trait Foo { fn foo(&self) {} } } struct S2; impl foo::Foo for S2 { fn foo(&self) {} } struct S1(S2); impl foo::Foo for S1 { fn foo(&self) { self.0.foo/*caret*/() } } """) fun `test import item in root module (edition 2018)`() = checkAutoImportFixByText(""" mod foo { pub struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { pub struct Foo; } fn main() { let f = Foo/*caret*/; } """) fun `test import item from root module (edition 2018)`() = checkAutoImportFixByText(""" struct Foo; mod bar { type T = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ struct Foo; mod bar { use crate::Foo; type T = Foo; } """) fun `test import inside nested module`() = checkAutoImportFixByText(""" mod b { pub struct S; } mod c { fn x() -> <error descr="Unresolved reference: `S`">S/*caret*/</error> { } } """, """ mod b { pub struct S; } mod c { use crate::b::S; fn x() -> S { } } """) fun `test import inside nested pub module`() = checkAutoImportFixByText(""" mod b { pub struct S; } pub mod c { fn x() -> <error descr="Unresolved reference: `S`">S/*caret*/</error> {} } """, """ mod b { pub struct S; } pub mod c { use crate::b::S; fn x() -> S {} } """) fun `test import inside nested module with multiple choice`() = checkAutoImportFixByTextWithMultipleChoice(""" mod a { pub struct S; } mod b { pub struct S; } mod c { fn x() -> <error descr="Unresolved reference: `S`">S/*caret*/</error> { } } """, listOf("crate::a::S", "crate::b::S"), "crate::b::S", """ mod a { pub struct S; } mod b { pub struct S; } mod c { use crate::b::S; fn x() -> S { } } """) fun `test import with wildcard reexport 1`() = checkAutoImportFixByText(""" mod c { pub use self::a::*; mod a { pub struct A; } } fn main() { let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>; } """, """ use crate::c::A; mod c { pub use self::a::*; mod a { pub struct A; } } fn main() { let a = A; } """) fun `test import with wildcard reexport 2`() = checkAutoImportFixByText(""" mod c { pub use self::a::{{*}}; mod a { pub struct A; } } fn main() { let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>; } """, """ use crate::c::A; mod c { pub use self::a::{{*}}; mod a { pub struct A; } } fn main() { let a = A; } """) fun `test group imports`() = checkAutoImportFixByText(""" // comment use crate::foo::Foo; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ // comment use crate::foo::{Bar, Foo}; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = Bar/*caret*/; } """) fun `test add import to existing group`() = checkAutoImportFixByText(""" // comment use crate::foo::{Bar, Foo}; mod foo { pub struct Foo; pub struct Bar; pub struct Baz; } fn main() { let f = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>; } """, """ // comment use crate::foo::{Bar, Baz, Foo}; mod foo { pub struct Foo; pub struct Bar; pub struct Baz; } fn main() { let f = Baz/*caret*/; } """) fun `test group imports only at the last level`() = checkAutoImportFixByText(""" use crate::foo::Foo; mod foo { pub struct Foo; pub mod bar { pub struct Bar; } } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::bar::Bar; use crate::foo::Foo; mod foo { pub struct Foo; pub mod bar { pub struct Bar; } } fn main() { let f = Bar/*caret*/; } """) fun `test group imports only if the other import doesn't have a modifier`() = checkAutoImportFixByText(""" pub use crate::foo::Foo; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::Bar; pub use crate::foo::Foo; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = Bar/*caret*/; } """) fun `test group imports only if the other import doesn't have an attribute`() = checkAutoImportFixByText(""" #[attribute = "value"] use crate::foo::Foo; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::Bar; #[attribute = "value"] use crate::foo::Foo; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = Bar/*caret*/; } """) fun `test group imports with aliases 1`() = checkAutoImportFixByText(""" use crate::foo::Foo as F; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::{Bar, Foo as F}; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = Bar/*caret*/; } """) fun `test group imports with aliases 2`() = checkAutoImportFixByText(""" use crate::foo::{Bar as B, Foo as F}; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>; } """, """ use crate::foo::{Bar as B, Bar, Foo as F}; mod foo { pub struct Foo; pub struct Bar; } fn main() { let f = Bar/*caret*/; } """) fun `test group imports with nested groups`() = checkAutoImportFixByText(""" use crate::foo::{{Bar, Foo}}; mod foo { pub struct Foo; pub struct Bar; pub struct Baz; } fn main() { let f = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>; } """, """ use crate::foo::{{Bar, Foo}, Baz}; mod foo { pub struct Foo; pub struct Bar; pub struct Baz; } fn main() { let f = Baz/*caret*/; } """) fun `test insert import at correct location`() = checkAutoImportFixByText(""" use crate::aaa::A; use crate::bbb::B; use crate::ddd::D; pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } pub mod ddd { pub struct D; } fn main() { let _ = <error descr="Unresolved reference: `C`">C/*caret*/</error>; } """, """ use crate::aaa::A; use crate::bbb::B; use crate::ccc::C; use crate::ddd::D; pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } pub mod ddd { pub struct D; } fn main() { let _ = C/*caret*/; } """) fun `test insert import at correct location (unsorted imports)`() = checkAutoImportFixByText(""" use crate::aaa::A; use crate::ddd::D; use crate::bbb::B; pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } pub mod ddd { pub struct D; } fn main() { let _ = <error descr="Unresolved reference: `C`">C/*caret*/</error>; } """, """ use crate::aaa::A; use crate::ddd::D; use crate::bbb::B; use crate::ccc::C; pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } pub mod ddd { pub struct D; } fn main() { let _ = C/*caret*/; } """, checkOptimizeImports = false) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test insert import from different crate at correct location`() = checkAutoImportFixByFileTree(""" //- dep-lib/lib.rs pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } //- main.rs use dep_lib_target::aaa::A; use dep_lib_target::ccc::C; fn main() { let _ = <error descr="Unresolved reference: `B`">B/*caret*/</error>; } """, """ //- dep-lib/lib.rs pub mod aaa { pub struct A; } pub mod bbb { pub struct B; } pub mod ccc { pub struct C; } //- main.rs use dep_lib_target::aaa::A; use dep_lib_target::bbb::B; use dep_lib_target::ccc::C; fn main() { let _ = B/*caret*/; } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @CheckTestmarkHit(Testmarks.DoctestInjectionImport::class) fun `test import outer item in doctest injection`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /// ``` /// foo/*caret*/(); /// ``` pub fn foo() {} """, """ //- lib.rs /// ``` /// use test_package::foo; /// foo(); /// ``` pub fn foo() {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @CheckTestmarkHit(Testmarks.DoctestInjectionImport::class) fun `test import outer item in doctest injection with tildes`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /// ~~~ /// foo/*caret*/(); /// ~~~ pub fn foo() {} """, """ //- lib.rs /// ~~~ /// use test_package::foo; /// foo(); /// ~~~ pub fn foo() {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @CheckTestmarkHit(Testmarks.DoctestInjectionImport::class) fun `test import outer item in doctest injection in star comment`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /** * ``` * foo/*caret*/(); * ``` */ pub fn foo() {} """, """ //- lib.rs /** * ``` * use test_package::foo; * foo(); * ``` */ pub fn foo() {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @CheckTestmarkHit(Testmarks.DoctestInjectionImport::class) fun `test import second outer item in doctest injection`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /// ``` /// use test_package::foo; /// foo(); /// bar/*caret*/(); /// ``` pub fn foo() {} pub fn bar() {} """, """ //- lib.rs /// ``` /// use test_package::{bar, foo}; /// foo(); /// bar(); /// ``` pub fn foo() {} pub fn bar() {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import second outer item without grouping in doctest injection`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /// ``` /// use test_package::foo; /// foo(); /// baz/*caret*/(); /// ``` pub fn foo() {} pub mod bar { pub fn baz() {} } """, """ //- lib.rs /// ``` /// use test_package::bar::baz; /// use test_package::foo; /// foo(); /// baz(); /// ``` pub fn foo() {} pub mod bar { pub fn baz() {} } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @CheckTestmarkHit(Testmarks.DoctestInjectionImport::class) fun `test import outer item in doctest injection with inner module`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs /// ``` /// mod bar { /// fn baz() { /// foo/*caret*/(); /// } /// } /// ``` pub fn foo() {} """, """ //- lib.rs /// ``` /// mod bar { /// use test_package::foo; /// fn baz() { /// foo(); /// } /// } /// ``` pub fn foo() {} """) @ExpandMacros fun `test import struct from macro`() = checkAutoImportFixByText(""" mod foo { macro_rules! foo { () => { pub struct Foo; }; } foo!(); } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { macro_rules! foo { () => { pub struct Foo; }; } foo!(); } fn main() { let f = Foo/*caret*/; } """) fun `test import trait for bound (type-related path)`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self) {} } } struct S<T>(T); fn foo<T>(a: S<T>) where S<T>: foo::Foo { <S<T>>::<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(&a); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self) {} } } struct S<T>(T); fn foo<T>(a: S<T>) where S<T>: foo::Foo { <S<T>>::foo/*caret*/(&a); } """) fun `test import trait for bound (method call)`() = checkAutoImportFixByText(""" mod foo { pub trait Foo { fn foo(&self) {} } } struct S<T>(T); fn foo<T>(a: S<T>) where S<T>: foo::Foo { a.<error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, """ use crate::foo::Foo; mod foo { pub trait Foo { fn foo(&self) {} } } struct S<T>(T); fn foo<T>(a: S<T>) where S<T>: foo::Foo { a.foo(); } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) @MockEdition(Edition.EDITION_2015) fun `test import item from a renamed crate (2015 edition)`() = checkAutoImportFixByFileTree(""" //- dep-lib-to-be-renamed/lib.rs pub mod foo { pub struct Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """, """ //- main.rs extern crate dep_lib_renamed; use dep_lib_renamed::foo::Bar; fn foo(t: Bar/*caret*/) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import item from a renamed crate (2018 edition)`() = checkAutoImportFixByFileTree(""" //- dep-lib-to-be-renamed/lib.rs pub mod foo { pub struct Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """, """ //- main.rs use dep_lib_renamed::foo::Bar; fn foo(t: Bar/*caret*/) {} """) fun `test import 'pub(crate)' from the same crate`() = checkAutoImportFixByText(""" mod foo { pub(crate) struct Foo; } fn main() { let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ use crate::foo::Foo; mod foo { pub(crate) struct Foo; } fn main() { let f = Foo/*caret*/; } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import 'pub(crate)' item from dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs pub mod foo { pub(crate) struct Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import an item from 'pub(crate)' mod in dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs pub(crate) mod foo { pub struct Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import an item reexported from 'pub(crate)' mod in dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs mod foo { pub struct Bar; } pub(crate) mod baz { pub use crate::foo::Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import 'pub(crate)' item reexported from dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs mod foo { pub(crate) struct Bar; } pub mod baz { pub use crate::foo::Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import an item reexported by 'pub(crate) use' in dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs mod foo { pub struct Bar; } pub mod baz { pub(crate) use crate::foo::Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import an item reexported by intermediate 'pub(crate) use' in dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-lib/lib.rs mod foo { pub struct Bar; } mod baz { pub(crate) use crate::foo::Bar; } pub mod quux { pub use crate::baz::Bar; } //- main.rs fn foo(t: <error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import an item reexported by 'pub(crate) extern crate' in dependency crate`() = checkAutoImportFixIsUnavailableByFileTree(""" //- trans-lib/lib.rs pub struct FooBar; //- dep-lib/lib.rs pub(crate) extern crate trans_lib; //- lib.rs extern crate dep_lib_target; fn foo(x: <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>) {} """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test do not try to import item from transitive dependency`() = checkAutoImportFixIsUnavailableByFileTree(""" //- trans-lib/lib.rs pub mod mod1 { pub struct Foo; } //- dep-lib/lib.rs //- lib.rs fn main() { let _ = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import item from transitive dependency reexported by dependency`() = checkAutoImportFixByFileTree(""" //- trans-lib/lib.rs pub mod mod1 { pub struct Foo; } //- dep-lib/lib.rs pub use trans_lib::mod1; //- lib.rs fn main() { let _ = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>; } """, """ //- trans-lib/lib.rs pub mod mod1 { pub struct Foo; } //- dep-lib/lib.rs pub use trans_lib::mod1; //- lib.rs use dep_lib_target::mod1::Foo; fn main() { let _ = Foo; } """) fun `test import macro`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs #[macro_export] macro_rules! foo { () => {} } //- main.rs fn main() { foo/*caret*/!(); } """, """ //- lib.rs #[macro_export] macro_rules! foo { () => {} } //- main.rs use test_package::foo; fn main() { foo!(); } """) fun `test import macro 2`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs pub macro foo() {} //- main.rs fn main() { foo/*caret*/!(); } """, """ //- lib.rs pub macro foo() {} //- main.rs use test_package::foo; fn main() { foo!(); } """) // e.g. `lazy_static` fun `test import macro with same name as dependency`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- lib.rs #[macro_export] macro_rules! test_package { () => {} } //- main.rs fn main() { test_package/*caret*/!(); } """, """ //- lib.rs #[macro_export] macro_rules! test_package { () => {} } //- main.rs use test_package::test_package; fn main() { test_package!(); } """) fun `test do not import function as macro path`() = checkAutoImportFixIsUnavailableByFileTree(""" //- lib.rs pub fn func() {} //- main.rs fn main() { <error descr="Unresolved reference: `func`">func/*caret*/</error>!(); } """) @MockAdditionalCfgOptions("intellij_rust") fun `test do not import cfg-disabled item`() = checkAutoImportFixIsUnavailableByFileTree(""" //- foo.rs pub fn func() {} //- main.rs #[cfg(not(intellij_rust))] mod foo; fn main() { <error descr="Unresolved reference: `func`">func/*caret*/</error>!(); } """) fun `test use absolute path when extern crate has same name as child mod`() = checkAutoImportFixByFileTree(""" //- lib.rs pub fn func() {} //- main.rs mod test_package {} fn main() { <error descr="Unresolved reference: `func`">func/*caret*/</error>(); } """, """ //- main.rs use ::test_package::func; mod test_package {} fn main() { func(); } """) fun `test UFCS with unnamed trait import inside another trait impl`() = checkAutoImportFixIsUnavailable(""" mod inner { pub struct Foo {} pub trait Trait { fn func() {} } impl Trait for Foo {} } use inner::Trait as _; trait OtherTrait { fn other_func(); } impl OtherTrait for () { fn other_func() { inner::Foo::func/*caret*/(); } } """) fun `test correctly transform unnamed import to use group`() = checkAutoImportFixByTextWithoutHighlighting(""" use crate::inner::Trait as _; mod inner { pub trait Trait {} pub fn func() {} } fn main() { /*caret*/func(); } """, """ use crate::inner::{func, Trait as _}; mod inner { pub trait Trait {} pub fn func() {} } fn main() { func(); } """) fun `test import inside included file`() = checkAutoImportFixByFileTree(""" //- foo.rs fn func() { <error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } //- lib.rs include!("foo.rs"); mod inner { pub fn foo() {} } """, """ //- foo.rs use crate::inner::foo; fn func() { foo(); } //- lib.rs include!("foo.rs"); mod inner { pub fn foo() {} } """) fun `test import raw identifier (item name)`() = checkAutoImportFixByTextWithoutHighlighting(""" mod inner { pub fn r#type() {} } fn main() { r#type/*caret*/(); } """, """ use crate::inner::r#type; mod inner { pub fn r#type() {} } fn main() { r#type(); } """) fun `test import raw identifier (mod name)`() = checkAutoImportFixByTextWithoutHighlighting(""" mod r#type { pub fn foo() {} } fn main() { foo/*caret*/(); } """, """ use crate::r#type::foo; mod r#type { pub fn foo() {} } fn main() { foo(); } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import raw identifier (crate name)`() = checkAutoImportFixByFileTree(""" //- loop/lib.rs pub fn foo() {} //- main.rs fn main() { <error descr="Unresolved reference: `foo`">foo/*caret*/</error>(); } """, """ //- loop/lib.rs pub fn foo() {} //- main.rs use r#loop::foo; fn main() { foo(); } """) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test filter single mod when root path resolves to same item`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- dep-lib/lib.rs pub mod foo { pub struct Foo; } //- lib.rs pub mod foo { pub use dep_lib_target::foo::Foo; } //- main.rs fn main() { let _ = foo/*caret*/::Foo; } """, """ //- main.rs use dep_lib_target::foo; fn main() { let _ = foo::Foo; } """) @WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import attr proc macro`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- dep-proc-macro/lib.rs #[proc_macro_attribute] pub fn attr_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream { item } //- lib.rs #[attr_as_is/*caret*/] fn func() {} mod attr_as_is {} """, """ //- lib.rs use dep_proc_macro::attr_as_is; #[attr_as_is] fn func() {} mod attr_as_is {} """) fun `test don't import assoc type binding`() = checkAutoImportFixIsUnavailable(""" mod inner { pub trait Trait { type Output; } pub struct Output {} } fn func(_: impl <error descr="Unresolved reference: `Trait`">Trait</error>< <error descr="Unresolved reference: `Output`">Output/*caret*/</error>=i32 >) {} """) @WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test import derive proc macro`() = checkAutoImportFixByFileTreeWithoutHighlighting(""" //- dep-proc-macro/lib.rs #[proc_macro_derive(Builder)] pub fn builder(_item: TokenStream) -> TokenStream { "".parse().unwrap() } //- lib.rs #[derive(Builder/*caret*/)] struct Foo {} """, """ //- lib.rs use dep_proc_macro::Builder; #[derive(Builder/*caret*/)] struct Foo {} """) @WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test don't import bang proc macro as derive`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-proc-macro/lib.rs #[proc_macro] pub fn Builder(item: TokenStream) -> TokenStream { item } //- lib.rs #[derive(<error descr="Unresolved reference: `Builder`">Builder/*caret*/</error>)] struct Foo {} """) @WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS) @ProjectDescriptor(WithDependencyRustProjectDescriptor::class) fun `test no attr proc macro for bang call`() = checkAutoImportFixIsUnavailableByFileTree(""" //- dep-proc-macro/lib.rs #[proc_macro_attribute] pub fn attr_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream { item } //- lib.rs <error descr="Unresolved reference: `attr_as_is`">attr_as_is/*caret*/</error>!(); """) }
src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt
4119326527
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import com.intellij.ProjectTopics import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.util.Key import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.psi.* import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.messages.MessageBusConnection import com.intellij.util.messages.Topic import org.rust.cargo.project.model.CargoProjectsService import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.workspace.PackageOrigin import org.rust.lang.RsFileType import org.rust.lang.core.crate.Crate import org.rust.lang.core.crate.crateGraph import org.rust.lang.core.macros.MacroExpansionFileSystem import org.rust.lang.core.macros.MacroExpansionMode import org.rust.lang.core.macros.macroExpansionManagerIfCreated import org.rust.lang.core.psi.RsPsiManager.Companion.isIgnorePsiEvents import org.rust.lang.core.psi.RsPsiTreeChangeEvent.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve2.defMapService /** Don't subscribe directly or via plugin.xml lazy listeners. Use [RsPsiManager.subscribeRustStructureChange] */ private val RUST_STRUCTURE_CHANGE_TOPIC: Topic<RustStructureChangeListener> = Topic.create( "RUST_STRUCTURE_CHANGE_TOPIC", RustStructureChangeListener::class.java, Topic.BroadcastDirection.TO_PARENT ) /** Don't subscribe directly or via plugin.xml lazy listeners. Use [RsPsiManager.subscribeRustPsiChange] */ private val RUST_PSI_CHANGE_TOPIC: Topic<RustPsiChangeListener> = Topic.create( "RUST_PSI_CHANGE_TOPIC", RustPsiChangeListener::class.java, Topic.BroadcastDirection.TO_PARENT ) interface RsPsiManager { /** * A project-global modification tracker that increments on each PSI change that can affect * name resolution or type inference. It will be incremented with a change of most types of * PSI element excluding function bodies (expressions and statements) */ val rustStructureModificationTracker: ModificationTracker /** * Similar to [rustStructureModificationTracker], but it is not incremented by changes in * workspace rust files. * * @see PackageOrigin.WORKSPACE */ val rustStructureModificationTrackerInDependencies: SimpleModificationTracker fun incRustStructureModificationCount() /** This is an instance method because [RsPsiManager] should be created prior to event subscription */ fun subscribeRustStructureChange(connection: MessageBusConnection, listener: RustStructureChangeListener) { connection.subscribe(RUST_STRUCTURE_CHANGE_TOPIC, listener) } /** This is an instance method because [RsPsiManager] should be created prior to event subscription */ fun subscribeRustPsiChange(connection: MessageBusConnection, listener: RustPsiChangeListener) { connection.subscribe(RUST_PSI_CHANGE_TOPIC, listener) } companion object { private val IGNORE_PSI_EVENTS: Key<Boolean> = Key.create("IGNORE_PSI_EVENTS") fun <T> withIgnoredPsiEvents(psi: PsiFile, f: () -> T): T { setIgnorePsiEvents(psi, true) try { return f() } finally { setIgnorePsiEvents(psi, false) } } fun isIgnorePsiEvents(psi: PsiFile): Boolean = psi.getUserData(IGNORE_PSI_EVENTS) == true private fun setIgnorePsiEvents(psi: PsiFile, ignore: Boolean) { psi.putUserData(IGNORE_PSI_EVENTS, if (ignore) true else null) } } } interface RustStructureChangeListener { fun rustStructureChanged(file: PsiFile?, changedElement: PsiElement?) } interface RustPsiChangeListener { fun rustPsiChanged(file: PsiFile, element: PsiElement, isStructureModification: Boolean) } class RsPsiManagerImpl(val project: Project) : RsPsiManager, Disposable { override val rustStructureModificationTracker = SimpleModificationTracker() override val rustStructureModificationTrackerInDependencies = SimpleModificationTracker() init { PsiManager.getInstance(project).addPsiTreeChangeListener(CacheInvalidator(), this) project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { incRustStructureModificationCount() } }) project.messageBus.connect().subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ -> incRustStructureModificationCount() }) } override fun dispose() {} inner class CacheInvalidator : RsPsiTreeChangeAdapter() { override fun handleEvent(event: RsPsiTreeChangeEvent) { val element = when (event) { is ChildRemoval.Before -> event.child is ChildRemoval.After -> event.parent is ChildReplacement.Before -> event.oldChild is ChildReplacement.After -> event.newChild is ChildAddition.After -> event.child is ChildMovement.After -> event.child is ChildrenChange.After -> if (!event.isGenericChange) event.parent else return is PropertyChange.After -> { when (event.propertyName) { PsiTreeChangeEvent.PROP_UNLOADED_PSI, PsiTreeChangeEvent.PROP_FILE_TYPES -> { incRustStructureModificationCount() return } PsiTreeChangeEvent.PROP_WRITABLE -> return else -> event.element ?: return } } else -> return } val file = event.file // if file is null, this is an event about VFS changes if (file == null) { val isStructureModification = element is RsFile && !isIgnorePsiEvents(element) || element is PsiDirectory && project.cargoProjects.findPackageForFile(element.virtualFile) != null if (isStructureModification) { incRustStructureModificationCount(element as? RsFile, element as? RsFile) } } else { if (file.fileType != RsFileType) return if (isIgnorePsiEvents(file)) return val isWhitespaceOrComment = element is PsiComment || element is PsiWhiteSpace if (isWhitespaceOrComment && !isMacroExpansionModeNew) { // Whitespace/comment changes are meaningful if new macro expansion engine is used return } // Most of events means that some element *itself* is changed, but ChildrenChange means // that changed some of element's children, not the element itself. In this case // we should look up for ModificationTrackerOwner a bit differently val isChildrenChange = event is ChildrenChange || event is ChildRemoval.After updateModificationCount(file, element, isChildrenChange, isWhitespaceOrComment) } } } private fun updateModificationCount( file: PsiFile, psi: PsiElement, isChildrenChange: Boolean, isWhitespaceOrComment: Boolean ) { // We find the nearest parent item or macro call (because macro call can produce items) // If found item implements RsModificationTrackerOwner, we increment its own // modification counter. Otherwise we increment global modification counter. // // So, if something is changed inside a function except an item, we will only // increment the function local modification counter. // // It may not be intuitive that if we change an item inside a function, // like this struct: `fn foo() { struct Bar; }`, we will increment the // global modification counter instead of function-local. We do not care // about it because it is a rare case and implementing it differently // is much more difficult. val owner = if (DumbService.isDumb(project)) null else psi.findModificationTrackerOwner(!isChildrenChange) // Whitespace/comment changes are meaningful for macros only // (b/c they affect range mappings and body hashes) if (isWhitespaceOrComment) { if (owner !is RsMacroCall && owner !is RsMacroDefinitionBase && !RsProcMacroPsiUtil.canBeInProcMacroCallBody(psi)) return } val isStructureModification = owner == null || !owner.incModificationCount(psi) if (!isStructureModification && owner is RsMacroCall && (!isMacroExpansionModeNew || !owner.isTopLevelExpansion)) { return updateModificationCount(file, owner, isChildrenChange = false, isWhitespaceOrComment = false) } if (isStructureModification) { incRustStructureModificationCount(file, psi) } project.messageBus.syncPublisher(RUST_PSI_CHANGE_TOPIC).rustPsiChanged(file, psi, isStructureModification) } private val isMacroExpansionModeNew get() = project.macroExpansionManagerIfCreated?.macroExpansionMode is MacroExpansionMode.New override fun incRustStructureModificationCount() = incRustStructureModificationCount(null, null) private fun incRustStructureModificationCount(file: PsiFile? = null, psi: PsiElement? = null) { rustStructureModificationTracker.incModificationCount() if (!isWorkspaceFile(file)) { rustStructureModificationTrackerInDependencies.incModificationCount() } project.messageBus.syncPublisher(RUST_STRUCTURE_CHANGE_TOPIC).rustStructureChanged(file, psi) } private fun isWorkspaceFile(file: PsiFile?): Boolean { if (file !is RsFile) return false val virtualFile = file.virtualFile ?: return false val crates = if (virtualFile.fileSystem is MacroExpansionFileSystem) { val crateId = project.macroExpansionManagerIfCreated?.getCrateForExpansionFile(virtualFile) ?: return false listOf(crateId) } else { project.defMapService.findCrates(file) } if (crates.isEmpty()) return false val crateGraph = project.crateGraph if (crates.any { crateGraph.findCrateById(it)?.origin != PackageOrigin.WORKSPACE }) return false return true } } val Project.rustPsiManager: RsPsiManager get() = service() /** @see RsPsiManager.rustStructureModificationTracker */ val Project.rustStructureModificationTracker: ModificationTracker get() = rustPsiManager.rustStructureModificationTracker /** * Returns [RsPsiManager.rustStructureModificationTracker] if [Crate.origin] == [PackageOrigin.WORKSPACE] or * [RsPsiManager.rustStructureModificationTrackerInDependencies] otherwise */ val Crate.rustStructureModificationTracker: ModificationTracker get() = if (origin == PackageOrigin.WORKSPACE) { project.rustStructureModificationTracker } else { project.rustPsiManager.rustStructureModificationTrackerInDependencies } /** * Returns [RsPsiManager.rustStructureModificationTracker] or [PsiModificationTracker.MODIFICATION_COUNT] * if `this` element is inside language injection */ val RsElement.rustStructureOrAnyPsiModificationTracker: ModificationTracker get() { val containingFile = containingFile return when { // The case of injected language. Injected PSI doesn't have its own event system, so can only // handle evens from outer PSI. For example, Rust language is injected to Kotlin's string // literal. If a user change the literal, we can only be notified that the literal is changed. // So we have to invalidate the cached value on any PSI change containingFile.virtualFile is VirtualFileWindow -> PsiManager.getInstance(containingFile.project).modificationTracker containingFile.containingRsFileSkippingCodeFragments?.crate?.origin == PackageOrigin.WORKSPACE -> containingFile.project.rustStructureModificationTracker else -> containingFile.project.rustPsiManager.rustStructureModificationTrackerInDependencies } }
src/main/kotlin/org/rust/lang/core/psi/RsPsiManager.kt
4129339242
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.idea import com.intellij.ide.util.importProject.ModuleDescriptor import com.intellij.ide.util.importProject.ProjectDescriptor import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot import com.intellij.ide.util.projectWizard.importSources.DetectedSourceRoot import com.intellij.ide.util.projectWizard.importSources.ProjectFromSourcesBuilder import com.intellij.ide.util.projectWizard.importSources.ProjectStructureDetector import org.rust.cargo.CargoConstants import org.rust.ide.module.CargoConfigurationWizardStep import org.rust.ide.module.RsModuleType import java.io.File import javax.swing.Icon class RsProjectStructureDetector : ProjectStructureDetector() { override fun detectRoots( dir: File, children: Array<out File>, base: File, result: MutableList<DetectedProjectRoot> ): DirectoryProcessingResult { if (children.any { it.name == CargoConstants.MANIFEST_FILE }) { result.add(object : DetectedProjectRoot(dir) { override fun getRootTypeName(): String = "Rust" }) } return DirectoryProcessingResult.SKIP_CHILDREN } override fun setupProjectStructure( roots: MutableCollection<DetectedProjectRoot>, projectDescriptor: ProjectDescriptor, builder: ProjectFromSourcesBuilder ) { val root = roots.singleOrNull() if (root == null || builder.hasRootsFromOtherDetectors(this) || projectDescriptor.modules.isNotEmpty()) { return } val moduleDescriptor = ModuleDescriptor(root.directory, RsModuleType.INSTANCE, emptyList<DetectedSourceRoot>()) projectDescriptor.modules = listOf(moduleDescriptor) } override fun createWizardSteps( builder: ProjectFromSourcesBuilder, projectDescriptor: ProjectDescriptor, stepIcon: Icon? ): List<ModuleWizardStep> { return listOf(CargoConfigurationWizardStep(builder.context) { projectDescriptor.modules.firstOrNull()?.addConfigurationUpdater(it) }) } }
idea/src/main/kotlin/org/rust/ide/idea/RsProjectStructureDetector.kt
1740516705
package com.jerieljan.ktspring.repositories import com.jerieljan.ktspring.models.User import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository @Repository interface UserRepository : MongoRepository<User, String>
src/main/kotlin/com/jerieljan/ktspring/repositories/UserRepository.kt
1359773115
package org.tsdes.advanced.graphql.newsgraphql.resolver import com.coxautodev.graphql.tools.GraphQLMutationResolver import com.google.common.base.Throwables import graphql.execution.DataFetcherResult import graphql.servlet.GenericGraphQLError import org.springframework.stereotype.Component import org.tsdes.advanced.examplenews.NewsRepository import org.tsdes.advanced.graphql.newsgraphql.type.InputNewsType import org.tsdes.advanced.graphql.newsgraphql.type.InputUpdateNewsType import javax.validation.ConstraintViolationException @Component class MutationResolver( private val crud: NewsRepository ) : GraphQLMutationResolver { fun createNews(input: InputNewsType): DataFetcherResult<String> { val id = try { /* the fields in 'input' cannot be null, because, if they were, this code would never be reached, as validation already failed when parsing the GraphQL request */ crud.createNews(input.authorId!!, input.text!!, input.country!!) } catch (e: Exception) { val cause = Throwables.getRootCause(e) val msg = if (cause is ConstraintViolationException) { "Violated constraints: ${cause.message}" }else { "${e.javaClass}: ${e.message}" } return DataFetcherResult<String>("", listOf(GenericGraphQLError(msg))) } return DataFetcherResult(id.toString(), listOf()) } fun updateNewsById(pathId: String, input: InputUpdateNewsType): DataFetcherResult<Boolean> { val id: Long try { id = pathId.toLong() } catch (e: Exception) { return DataFetcherResult<Boolean>(false, listOf( GenericGraphQLError("No News with id $pathId exists"))) } if (!crud.existsById(id)) { return DataFetcherResult<Boolean>(false, listOf( GenericGraphQLError("No News with id $id exists"))) } try { crud.update(id, input.text!!, input.authorId!!, input.country!!, input.creationTime!!) } catch (e: Exception) { val cause = Throwables.getRootCause(e) if (cause is ConstraintViolationException) { return DataFetcherResult<Boolean>(false, listOf( GenericGraphQLError("Violated constraints: ${cause.message}"))) } throw e } return DataFetcherResult(true, listOf()) } fun deleteNewsById(pathId: String): Boolean { val id: Long try { id = pathId.toLong() } catch (e: Exception) { return false } if (!crud.existsById(id)) { return false } crud.deleteById(id) return true } }
advanced/graphql/news-graphql/src/main/kotlin/org/tsdes/advanced/graphql/newsgraphql/resolver/MutationResolver.kt
992795382
/** * Quite useful [String] */ @SinceKotlin("1.1") fun `availableSince1.1`(): String = "1.1 rulezz"
core/testdata/functions/sinceKotlin.kt
3691288988
package com.sotwtm.example.simple import android.os.Bundle import com.sotwtm.example.R import com.sotwtm.example.databinding.ActivitySimpleDaggerBinding import com.sotwtm.support.activity.AppHelpfulDataBindingActivity import javax.inject.Inject /** * A simple example showing how to inject with dagger by SotwtmSupportLib * @author sheungon * */ class SimpleDaggerActivity : AppHelpfulDataBindingActivity<ActivitySimpleDaggerBinding>() { override val layoutResId: Int = R.layout.activity_simple_dagger @Inject override lateinit var dataBinder: SimpleDaggerActivityDataBinder override val coordinatorLayoutId: Int = R.id.coordinator_layout override fun initDataBinding(dataBinding: ActivitySimpleDaggerBinding, savedInstanceState: Bundle?) { dataBinding.dataBinder = dataBinder } }
example/src/main/java/com/sotwtm/example/simple/SimpleDaggerActivity.kt
885300590
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.demos import androidx.compose.integration.demos.common.ActivityDemo import androidx.compose.integration.demos.common.ComposableDemo import androidx.compose.integration.demos.common.DemoCategory import androidx.compose.material.samples.AlertDialogSample import androidx.compose.material.samples.BackdropScaffoldSample import androidx.compose.material.samples.BottomDrawerSample import androidx.compose.material.samples.CustomAlertDialogSample import androidx.compose.material.samples.ModalBottomSheetSample import androidx.compose.material.samples.ModalDrawerSample import androidx.compose.material.samples.BottomSheetScaffoldSample import androidx.compose.material.samples.ContentAlphaSample import androidx.compose.material.samples.CustomPullRefreshSample import androidx.compose.material.samples.PullRefreshIndicatorTransformSample import androidx.compose.material.samples.PullRefreshSample import androidx.compose.material.samples.ScaffoldWithBottomBarAndCutout import androidx.compose.material.samples.ScaffoldWithCoroutinesSnackbar import androidx.compose.material.samples.ScaffoldWithSimpleSnackbar import androidx.compose.material.samples.SimpleScaffoldWithTopBar val MaterialDemos = DemoCategory( "Material", listOf( DemoCategory( "AlertDialog", listOf( ComposableDemo("Default dialog") { AlertDialogSample() }, ComposableDemo("Custom buttons") { CustomAlertDialogSample() } ) ), ComposableDemo("App Bars") { AppBarDemo() }, ComposableDemo("Backdrop") { BackdropScaffoldSample() }, ComposableDemo("Badge") { BadgeDemo() }, ComposableDemo("Bottom Navigation") { BottomNavigationDemo() }, DemoCategory( "Bottom Sheets", listOf( ComposableDemo("Bottom Sheet") { BottomSheetScaffoldSample() }, ComposableDemo("Modal Bottom Sheet") { ModalBottomSheetSample() }, ) ), ComposableDemo("Buttons & FABs") { ButtonDemo() }, ComposableDemo("Chips") { ChipDemo() }, DemoCategory( "Navigation drawer", listOf( ComposableDemo("Modal drawer") { ModalDrawerSample() }, ComposableDemo("Bottom drawer") { BottomDrawerSample() } ) ), ComposableDemo("Elevation") { ElevationDemo() }, ComposableDemo("Content alpha") { ContentAlphaSample() }, DemoCategory( "ListItems", listOf( ComposableDemo("ListItems") { ListItemDemo() }, ComposableDemo("Mixing RTL and LTR") { MixedRtlLtrListItemDemo() } ) ), ComposableDemo("Material Theme") { MaterialThemeDemo() }, DemoCategory( "Menus", listOf( ComposableDemo("Dropdown Menu positioning") { MenuDemo() }, ComposableDemo("ExposedDropdownMenu") { ExposedDropdownMenuDemo() } ) ), ComposableDemo("Navigation Rail") { NavigationRailDemo() }, DemoCategory( "Playground", listOf( ComposableDemo("Color Picker") { ColorPickerDemo() }, ActivityDemo("Dynamic Theme", DynamicThemeActivity::class) ) ), ComposableDemo("Progress Indicators") { ProgressIndicatorDemo() }, DemoCategory( "Scaffold", listOf( ComposableDemo("Scaffold with top bar") { SimpleScaffoldWithTopBar() }, ComposableDemo("Scaffold with docked FAB") { ScaffoldWithBottomBarAndCutout() }, ComposableDemo("Scaffold with snackbar") { ScaffoldWithSimpleSnackbar() } ) ), ComposableDemo("Selection Controls") { SelectionControlsDemo() }, ComposableDemo("Slider") { SliderDemo() }, ComposableDemo("Snackbar") { ScaffoldWithCoroutinesSnackbar() }, ComposableDemo("Swipe to dismiss") { SwipeToDismissDemo() }, ComposableDemo("Tabs") { TabDemo() }, DemoCategory( "TextFields", listOf( ComposableDemo("FilledTextField/OutlinedTextField") { MaterialTextFieldDemo() }, ComposableDemo("Multiple text fields") { TextFieldsDemo() }, ComposableDemo("Textfield decoration box") { DecorationBoxDemos() }, ComposableDemo("Alignment inside text fields") { VerticalAlignmentsInTextField() } ) ), DemoCategory( "PullRefresh", listOf( ComposableDemo("PullRefresh") { PullRefreshSample() }, ComposableDemo("Custom PullRefresh") { CustomPullRefreshSample() }, ComposableDemo("Custom Indicator") { PullRefreshIndicatorTransformSample() } ) ) ) )
compose/material/material/integration-tests/material-demos/src/main/java/androidx/compose/material/demos/MaterialDemos.kt
467228539
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.example.android.supportv4.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.app.Activity import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Bundle import android.os.SystemClock import android.util.Log import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import android.view.ViewGroup import android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS import android.view.animation.LinearInterpolator import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.CheckBox import android.widget.Spinner import android.widget.TextView import android.widget.ToggleButton import androidx.annotation.RequiresApi import androidx.core.graphics.Insets import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsAnimationCompat import androidx.core.view.WindowInsetsAnimationControlListenerCompat import androidx.core.view.WindowInsetsAnimationControllerCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsCompat.Type.ime import androidx.core.view.WindowInsetsCompat.Type.navigationBars import androidx.core.view.WindowInsetsCompat.Type.statusBars import androidx.core.view.WindowInsetsCompat.Type.systemBars import androidx.core.view.WindowInsetsControllerCompat import com.example.android.supportv4.R import java.util.ArrayList import kotlin.concurrent.thread import kotlin.math.abs import kotlin.math.max import kotlin.math.min @SuppressLint("InlinedApi") @RequiresApi(21) class WindowInsetsControllerPlayground : Activity() { private val TAG: String = "WindowInsets_Playground" val mTransitions = ArrayList<Transition>() var currentType: Int? = null private lateinit var mRoot: View private lateinit var editRow: ViewGroup private lateinit var visibility: TextView private lateinit var buttonsRow: ViewGroup private lateinit var buttonsRow2: ViewGroup private lateinit var fitSystemWindow: CheckBox private lateinit var isDecorView: CheckBox internal lateinit var info: TextView lateinit var graph: View val values = mutableListOf(0f) @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_insets_controller) setActionBar(findViewById(R.id.toolbar)) mRoot = findViewById(R.id.root) editRow = findViewById(R.id.editRow) visibility = findViewById(R.id.visibility) buttonsRow = findViewById(R.id.buttonRow) buttonsRow2 = findViewById(R.id.buttonRow2) info = findViewById(R.id.info) fitSystemWindow = findViewById(R.id.decorFitsSystemWindows) isDecorView = findViewById(R.id.isDecorView) addPlot() WindowCompat.setDecorFitsSystemWindows(window, fitSystemWindow.isChecked) WindowCompat.getInsetsController(window, window.decorView).systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE Log.e( TAG, "FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS: " + ( window.attributes.flags and FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS != 0 ) ) fitSystemWindow.apply { isChecked = false setOnCheckedChangeListener { _, isChecked -> WindowCompat.setDecorFitsSystemWindows(window, isChecked) if (isChecked) { mRoot.setPadding(0, 0, 0, 0) } } } mTransitions.add(Transition(findViewById(R.id.scrollView))) mTransitions.add(Transition(editRow)) setupTypeSpinner() setupHideShowButtons() setupAppearanceButtons() setupBehaviorSpinner() setupLayoutButton() setupIMEAnimation() setupActionButton() isDecorView.setOnCheckedChangeListener { _, _ -> setupIMEAnimation() } } private fun addPlot() { val stroke = 20 val p2 = Paint() p2.color = Color.RED p2.strokeWidth = 1f p2.style = Paint.Style.FILL graph = object : View(this) { override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val mx = (values.maxOrNull() ?: 0f) + 1 val mn = values.minOrNull() ?: 0f val ct = values.size.toFloat() val h = height - stroke * 2 val w = width - stroke * 2 values.forEachIndexed { i, f -> val x = (i / ct) * w + stroke val y = ((f - mn) / (mx - mn)) * h + stroke canvas.drawCircle(x, y, stroke.toFloat(), p2) } } } graph.minimumWidth = 300 graph.minimumHeight = 100 graph.setBackgroundColor(Color.GRAY) findViewById<ViewGroup>(R.id.graph_container).addView( graph, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200) ) } private fun setupAppearanceButtons() { mapOf<String, (Boolean) -> Unit>( "LIGHT_NAV" to { isLight -> WindowCompat.getInsetsController(window, mRoot).isAppearanceLightNavigationBars = isLight }, "LIGHT_STAT" to { isLight -> WindowCompat.getInsetsController(window, mRoot).isAppearanceLightStatusBars = isLight }, ).forEach { (name, callback) -> buttonsRow.addView( ToggleButton(this).apply { text = name textOn = text textOff = text setOnCheckedChangeListener { _, isChecked -> callback(isChecked) } isChecked = true callback(true) } ) } } private var visibilityThreadRunning = true @SuppressLint("SetTextI18n") override fun onResume() { super.onResume() thread { visibilityThreadRunning = true while (visibilityThreadRunning) { visibility.post { visibility.text = currentType?.let { ViewCompat.getRootWindowInsets(mRoot)?.isVisible(it).toString() } + " " + window.attributes.flags + " " + SystemClock.elapsedRealtime() } Thread.sleep(500) } } } override fun onPause() { super.onPause() visibilityThreadRunning = false } private fun setupActionButton() { findViewById<View>(R.id.floating_action_button).setOnClickListener { v: View? -> WindowCompat.getInsetsController(window, v!!).controlWindowInsetsAnimation( ime(), -1, LinearInterpolator(), null /* cancellationSignal */, object : WindowInsetsAnimationControlListenerCompat { override fun onReady( controller: WindowInsetsAnimationControllerCompat, types: Int ) { val anim = ValueAnimator.ofFloat(0f, 1f) anim.duration = 1500 anim.addUpdateListener { animation: ValueAnimator -> controller.setInsetsAndAlpha( controller.shownStateInsets, animation.animatedValue as Float, anim.animatedFraction ) } anim.addListener( object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) controller.finish(true) } }) anim.start() } override fun onCancelled( controller: WindowInsetsAnimationControllerCompat? ) { } override fun onFinished( controller: WindowInsetsAnimationControllerCompat ) { } } ) } } private fun setupIMEAnimation() { mRoot.setOnTouchListener(createOnTouchListener()) if (isDecorView.isChecked) { ViewCompat.setWindowInsetsAnimationCallback(mRoot, null) ViewCompat.setWindowInsetsAnimationCallback(window.decorView, createAnimationCallback()) // Why it doesn't work on the root view? } else { ViewCompat.setWindowInsetsAnimationCallback(window.decorView, null) ViewCompat.setWindowInsetsAnimationCallback(mRoot, createAnimationCallback()) } } private fun createAnimationCallback(): WindowInsetsAnimationCompat.Callback { return object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) { override fun onPrepare(animation: WindowInsetsAnimationCompat) { mTransitions.forEach { it.onPrepare(animation) } } override fun onProgress( insets: WindowInsetsCompat, runningAnimations: List<WindowInsetsAnimationCompat> ): WindowInsetsCompat { val systemInsets = insets.getInsets(systemBars()) mRoot.setPadding( systemInsets.left, systemInsets.top, systemInsets.right, systemInsets.bottom ) mTransitions.forEach { it.onProgress(insets) } return insets } override fun onStart( animation: WindowInsetsAnimationCompat, bounds: WindowInsetsAnimationCompat.BoundsCompat ): WindowInsetsAnimationCompat.BoundsCompat { mTransitions.forEach { obj -> obj.onStart() } return bounds } override fun onEnd(animation: WindowInsetsAnimationCompat) { mTransitions.forEach { it.onFinish(animation) } } } } private fun setupHideShowButtons() { findViewById<Button>(R.id.btn_show).apply { setOnClickListener { view -> currentType?.let { type -> WindowCompat.getInsetsController(window, view).show(type) } } } findViewById<Button>(R.id.btn_hide).apply { setOnClickListener { view -> currentType?.let { type -> WindowCompat.getInsetsController(window, view).hide(type) } } } } private fun setupLayoutButton() { arrayOf( "STABLE" to View.SYSTEM_UI_FLAG_LAYOUT_STABLE, "STAT" to View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, "NAV" to View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION ).forEach { (name, flag) -> buttonsRow2.addView( ToggleButton(this).apply { text = name textOn = text textOff = text setOnCheckedChangeListener { _, isChecked -> val systemUiVisibility = window.decorView.systemUiVisibility window.decorView.systemUiVisibility = if (isChecked) systemUiVisibility or flag else systemUiVisibility and flag.inv() } isChecked = false } ) } window.decorView.systemUiVisibility = window.decorView.systemUiVisibility and ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION ) .inv() } private fun createOnTouchListener(): View.OnTouchListener { return object : View.OnTouchListener { private val mViewConfiguration = ViewConfiguration.get(this@WindowInsetsControllerPlayground) var mAnimationController: WindowInsetsAnimationControllerCompat? = null var mCurrentRequest: WindowInsetsAnimationControlListenerCompat? = null var mRequestedController = false var mDown = 0f var mCurrent = 0f var mDownInsets = Insets.NONE var mShownAtDown = false @SuppressLint("ClickableViewAccessibility") override fun onTouch( v: View, event: MotionEvent ): Boolean { mCurrent = event.y when (event.action) { MotionEvent.ACTION_DOWN -> { mDown = event.y val rootWindowInsets = ViewCompat.getRootWindowInsets(v)!! mDownInsets = rootWindowInsets.getInsets(ime()) mShownAtDown = rootWindowInsets.isVisible(ime()) mRequestedController = false mCurrentRequest = null } MotionEvent.ACTION_MOVE -> { if (mAnimationController != null) { updateInset() } else if (abs(mDown - event.y) > mViewConfiguration.scaledTouchSlop && !mRequestedController ) { mRequestedController = true val listener = object : WindowInsetsAnimationControlListenerCompat { override fun onReady( controller: WindowInsetsAnimationControllerCompat, types: Int ) { if (mCurrentRequest === this) { mAnimationController = controller updateInset() } else { controller.finish(mShownAtDown) } } override fun onFinished( controller: WindowInsetsAnimationControllerCompat ) { mAnimationController = null } override fun onCancelled( controller: WindowInsetsAnimationControllerCompat? ) { mAnimationController = null } } mCurrentRequest = listener WindowCompat .getInsetsController(window, v) .controlWindowInsetsAnimation( ime(), 1000, LinearInterpolator(), null /* cancellationSignal */, listener ) } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { if (mAnimationController != null) { val isCancel = event.action == MotionEvent.ACTION_CANCEL mAnimationController!!.finish( if (isCancel) mShownAtDown else !mShownAtDown ) mAnimationController = null } mRequestedController = false mCurrentRequest = null } } return true } fun updateInset() { var inset = (mDownInsets.bottom + (mDown - mCurrent)).toInt() val hidden = mAnimationController!!.hiddenStateInsets.bottom val shown = mAnimationController!!.shownStateInsets.bottom val start = if (mShownAtDown) shown else hidden val end = if (mShownAtDown) hidden else shown inset = max(inset, hidden) inset = min(inset, shown) mAnimationController!!.setInsetsAndAlpha( Insets.of(0, 0, 0, inset), 1f, (inset - start) / (end - start).toFloat() ) } } } private fun setupTypeSpinner() { val types = mapOf( "System" to systemBars(), "IME" to ime(), "Navigation" to navigationBars(), "Status" to statusBars(), "All" to (systemBars() or ime()) ) findViewById<Spinner>(R.id.spn_insets_type).apply { adapter = ArrayAdapter( context, android.R.layout.simple_spinner_dropdown_item, types.keys.toTypedArray() ) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { if (parent != null) { currentType = types[parent.selectedItem] } } } } } private fun setupBehaviorSpinner() { val types = mapOf( "BY TOUCH" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH, "BY SWIPE" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE, "TRANSIENT" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE, ) findViewById<Spinner>(R.id.spn_behavior).apply { adapter = ArrayAdapter( context, android.R.layout.simple_spinner_dropdown_item, types.keys.toTypedArray() ) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { if (parent != null && view != null) { WindowCompat.getInsetsController(window, view) .systemBarsBehavior = types[selectedItem]!! } } } setSelection(0) } } inner class Transition(private val view: View) { private var mEndBottom = 0 private var mStartBottom = 0 private var mInsetsAnimation: WindowInsetsAnimationCompat? = null private val debug = view.id == R.id.editRow @SuppressLint("SetTextI18n") fun onPrepare(animation: WindowInsetsAnimationCompat) { if (animation.typeMask and ime() != 0) { mInsetsAnimation = animation } mStartBottom = view.bottom if (debug) { values.clear() info.text = "Prepare: start=$mStartBottom, end=$mEndBottom" } } fun onProgress(insets: WindowInsetsCompat) { view.y = (mStartBottom + insets.getInsets(ime() or systemBars()).bottom).toFloat() if (debug) { Log.d(TAG, view.y.toString()) values.add(view.y) graph.invalidate() } } @SuppressLint("SetTextI18n") fun onStart() { mEndBottom = view.bottom if (debug) { info.text = "${info.text}\nStart: start=$mStartBottom, end=$mEndBottom" } } fun onFinish(animation: WindowInsetsAnimationCompat) { if (mInsetsAnimation == animation) { mInsetsAnimation = null } } } }
samples/Support4Demos/src/main/java/com/example/android/supportv4/view/WindowInsetsControllerPlayground.kt
1476231463
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.tooling.animation.clock import androidx.compose.animation.core.AnimationVector import androidx.compose.animation.core.TargetBasedAnimation import androidx.compose.animation.tooling.ComposeAnimatedProperty import androidx.compose.animation.tooling.TransitionInfo import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.animation.AnimateXAsStateComposeAnimation import androidx.compose.ui.tooling.animation.states.TargetState import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp /** * [ComposeAnimationClock] for [AnimateXAsStateComposeAnimation]. */ internal class AnimateXAsStateClock<T, V : AnimationVector>( override val animation: AnimateXAsStateComposeAnimation<T, V> ) : ComposeAnimationClock<AnimateXAsStateComposeAnimation<T, V>, TargetState<T>> { override var state = TargetState( animation.animationObject.value, animation.animationObject.value ) set(value) { field = value currAnimation = getCurrentAnimation() setClockTime(0) } private var currentValue: T = animation.toolingState.value private set(value) { field = value animation.toolingState.value = value } private var currAnimation: TargetBasedAnimation<T, V> = getCurrentAnimation() @Suppress("UNCHECKED_CAST") override fun setStateParameters(par1: Any, par2: Any?) { fun parametersAreValid(par1: Any?, par2: Any?): Boolean { return currentValue != null && par1 != null && par2 != null && par1::class == par2::class } fun parametersHasTheSameType(value: Any, par1: Any, par2: Any): Boolean { return value::class == par1::class && value::class == par2::class } if (!parametersAreValid(par1, par2)) return if (parametersHasTheSameType(currentValue!!, par1, par2!!)) { state = TargetState(par1 as T, par2 as T) return } if (par1 is List<*> && par2 is List<*>) { try { state = when (currentValue) { is IntSize -> TargetState( IntSize(par1[0] as Int, par1[1] as Int), IntSize(par2[0] as Int, par2[1] as Int) ) is IntOffset -> TargetState( IntOffset(par1[0] as Int, par1[1] as Int), IntOffset(par2[0] as Int, par2[1] as Int) ) is Size -> TargetState( Size(par1[0] as Float, par1[1] as Float), Size(par2[0] as Float, par2[1] as Float) ) is Offset -> TargetState( Offset(par1[0] as Float, par1[1] as Float), Offset(par2[0] as Float, par2[1] as Float) ) is Rect -> TargetState( Rect( par1[0] as Float, par1[1] as Float, par1[2] as Float, par1[3] as Float ), Rect( par2[0] as Float, par2[1] as Float, par2[2] as Float, par2[3] as Float ), ) is Color -> TargetState( Color( par1[0] as Float, par1[1] as Float, par1[2] as Float, par1[3] as Float ), Color( par2[0] as Float, par2[1] as Float, par2[2] as Float, par2[3] as Float ), ) is Dp -> { if (parametersHasTheSameType(currentValue!!, par1[0]!!, par2[0]!!)) TargetState(par1[0], par2[0]) else TargetState( (par1[0] as Float).dp, (par2[0] as Float).dp ) } else -> { if (parametersAreValid(par1[0], par2[0]) && parametersHasTheSameType(currentValue!!, par1[0]!!, par2[0]!!) ) TargetState(par1[0], par2[0]) else return } } as TargetState<T> } catch (_: IndexOutOfBoundsException) { return } catch (_: ClassCastException) { return } catch (_: IllegalArgumentException) { return } catch (_: NullPointerException) { return } } } override fun getAnimatedProperties(): List<ComposeAnimatedProperty> { return listOf(ComposeAnimatedProperty(animation.label, currentValue as Any)) } override fun getMaxDurationPerIteration(): Long { return nanosToMillis(currAnimation.durationNanos) } override fun getMaxDuration(): Long { return nanosToMillis(currAnimation.durationNanos) } override fun getTransitions(stepMillis: Long): List<TransitionInfo> { return listOf( currAnimation.createTransitionInfo( animation.label, animation.animationSpec, stepMillis ) ) } private var clockTimeNanos = 0L set(value) { field = value currentValue = currAnimation.getValueFromNanos(value) } override fun setClockTime(animationTimeNanos: Long) { clockTimeNanos = animationTimeNanos } private fun getCurrentAnimation(): TargetBasedAnimation<T, V> { return TargetBasedAnimation( animationSpec = animation.animationSpec, initialValue = state.initial, targetValue = state.target, typeConverter = animation.animationObject.typeConverter, initialVelocity = animation.animationObject.velocity ) } }
compose/ui/ui-tooling/src/androidMain/kotlin/androidx/compose/ui/tooling/animation/clock/AnimateXAsStateClock.kt
561023046
package org.jetbrains.io.jsonRpc import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.TypeAdapter import com.google.gson.TypeAdapterFactory import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NotNullLazyValue import com.intellij.util.ArrayUtil import com.intellij.util.ArrayUtilRt import com.intellij.util.Consumer import com.intellij.util.SmartList import gnu.trove.THashMap import gnu.trove.TIntArrayList import io.netty.buffer.* import org.jetbrains.concurrency.Promise import org.jetbrains.io.JsonReaderEx import org.jetbrains.io.JsonUtil import org.jetbrains.io.releaseIfError import java.io.IOException import java.lang.reflect.Method import java.util.concurrent.atomic.AtomicInteger private val LOG = Logger.getInstance(JsonRpcServer::class.java) private val INT_LIST_TYPE_ADAPTER_FACTORY = object : TypeAdapterFactory { private var typeAdapter: IntArrayListTypeAdapter<TIntArrayList>? = null override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { if (type.type !== TIntArrayList::class.java) { return null } if (typeAdapter == null) { typeAdapter = IntArrayListTypeAdapter<TIntArrayList>() } @Suppress("CAST_NEVER_SUCCEEDS") return typeAdapter as TypeAdapter<T>? } } private val gson by lazy { GsonBuilder() .registerTypeAdapterFactory(INT_LIST_TYPE_ADAPTER_FACTORY) .disableHtmlEscaping() .create() } class JsonRpcServer(private val clientManager: ClientManager) : MessageServer { private val messageIdCounter = AtomicInteger() private val domains = THashMap<String, NotNullLazyValue<*>>() fun registerDomain(name: String, commands: NotNullLazyValue<*>, overridable: Boolean = false, disposable: Disposable? = null) { if (domains.containsKey(name)) { if (overridable) { return } else { throw IllegalArgumentException("$name is already registered") } } domains.put(name, commands) if (disposable != null) { Disposer.register(disposable, Disposable { domains.remove(name) }) } } override fun messageReceived(client: Client, message: CharSequence) { if (LOG.isDebugEnabled) { LOG.debug("IN $message") } val reader = JsonReaderEx(message) reader.beginArray() val messageId = if (reader.peek() == JsonToken.NUMBER) reader.nextInt() else -1 val domainName = reader.nextString() if (domainName.length == 1) { val promise = client.messageCallbackMap.remove(messageId) if (domainName[0] == 'r') { if (promise == null) { LOG.error("Response with id $messageId was already processed") return } promise.setResult(JsonUtil.nextAny(reader)) } else { promise!!.setError("error") } return } val domainHolder = domains[domainName] if (domainHolder == null) { processClientError(client, "Cannot find domain $domainName", messageId) return } val domain = domainHolder.value val command = reader.nextString() if (domain is JsonServiceInvocator) { domain.invoke(command, client, reader, messageId, message) return } val parameters: Array<Any> if (reader.hasNext()) { val list = SmartList<Any>() JsonUtil.readListBody(reader, list) parameters = ArrayUtil.toObjectArray(list) } else { parameters = ArrayUtilRt.EMPTY_OBJECT_ARRAY } val isStatic = domain is Class<*> val methods: Array<Method> if (isStatic) { methods = (domain as Class<*>).declaredMethods } else { methods = domain.javaClass.methods } for (method in methods) { if (method.name == command) { method.isAccessible = true val result = method.invoke(if (isStatic) null else domain, *parameters) if (messageId != -1) { if (result is ByteBuf) { result.releaseIfError { client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = result)) } } else { client.send(encodeMessage(client.byteBufAllocator, messageId, params = if (result == null) ArrayUtil.EMPTY_OBJECT_ARRAY else arrayOf(result))) } } return } } processClientError(client, "Cannot find method $domain.$command", messageId) } private fun processClientError(client: Client, error: String, messageId: Int) { try { LOG.error(error) } finally { if (messageId != -1) { sendErrorResponse(client, messageId, error) } } } fun sendResponse(client: Client, messageId: Int, rawData: ByteBuf? = null) { client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = rawData)) } fun sendErrorResponse(client: Client, messageId: Int, message: CharSequence?) { client.send(encodeMessage(client.byteBufAllocator, messageId, "e", params = arrayOf(message))) } fun sendWithRawPart(client: Client, domain: String, command: String, rawData: ByteBuf, params: Array<*>): Boolean { return client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, rawData = rawData, params = params)).cause() == null } fun send(client: Client, domain: String, command: String, vararg params: Any?) { client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, params = params)) } fun <T> call(client: Client, domain: String, command: String, vararg params: Any?): Promise<T> { val messageId = messageIdCounter.andIncrement val message = encodeMessage(client.byteBufAllocator, messageId, domain, command, params = params) return client.send(messageId, message)!! } fun send(domain: String, command: String, vararg params: Any?) { if (clientManager.hasClients()) { val messageId = -1 val message = encodeMessage(ByteBufAllocator.DEFAULT, messageId, domain, command, params = params) clientManager.send<Any?>(messageId, message) } } private fun encodeMessage(byteBufAllocator: ByteBufAllocator, messageId: Int = -1, domain: String? = null, command: String? = null, rawData: ByteBuf? = null, params: Array<*> = ArrayUtil.EMPTY_OBJECT_ARRAY): ByteBuf { val buffer = doEncodeMessage(byteBufAllocator, messageId, domain, command, params, rawData) if (LOG.isDebugEnabled) { LOG.debug("OUT ${buffer.toString(Charsets.UTF_8)}") } return buffer } private fun doEncodeMessage(byteBufAllocator: ByteBufAllocator, id: Int, domain: String?, command: String?, params: Array<*>, rawData: ByteBuf?): ByteBuf { var buffer = byteBufAllocator.ioBuffer() buffer.writeByte('[') var sb: StringBuilder? = null if (id != -1) { sb = StringBuilder() buffer.writeAscii(sb.append(id)) sb.setLength(0) } if (domain != null) { if (id != -1) { buffer.writeByte(',') } buffer.writeByte('"').writeAscii(domain).writeByte('"') if (command != null) { buffer.writeByte(',').writeByte('"').writeAscii(command).writeByte('"') } } var effectiveBuffer = buffer if (params.isNotEmpty() || rawData != null) { buffer.writeByte(',').writeByte('[') encodeParameters(buffer, params, sb) if (rawData != null) { if (params.isNotEmpty()) { buffer.writeByte(',') } effectiveBuffer = byteBufAllocator.compositeBuffer().addComponent(buffer).addComponent(rawData) buffer = byteBufAllocator.ioBuffer() } buffer.writeByte(']') } buffer.writeByte(']') return effectiveBuffer.addBuffer(buffer) } private fun encodeParameters(buffer: ByteBuf, params: Array<*>, _sb: StringBuilder?) { var sb = _sb var writer: JsonWriter? = null var hasPrev = false for (param in params) { if (hasPrev) { buffer.writeByte(',') } else { hasPrev = true } // gson - SOE if param has type class com.intellij.openapi.editor.impl.DocumentImpl$MyCharArray, so, use hack if (param is CharSequence) { JsonUtil.escape(param, buffer) } else if (param == null) { buffer.writeAscii("null") } else if (param is Boolean) { buffer.writeAscii(param.toString()) } else if (param is Number) { if (sb == null) { sb = StringBuilder() } if (param is Int) { sb.append(param.toInt()) } else if (param is Long) { sb.append(param.toLong()) } else if (param is Float) { sb.append(param.toFloat()) } else if (param is Double) { sb.append(param.toDouble()) } else { sb.append(param.toString()) } buffer.writeAscii(sb) sb.setLength(0) } else if (param is Consumer<*>) { if (sb == null) { sb = StringBuilder() } @Suppress("UNCHECKED_CAST") (param as Consumer<StringBuilder>).consume(sb) ByteBufUtilEx.writeUtf8(buffer, sb) sb.setLength(0) } else { if (writer == null) { writer = JsonWriter(ByteBufUtf8Writer(buffer)) } (gson.getAdapter(param.javaClass) as TypeAdapter<Any>).write(writer, param) } } } } private fun ByteBuf.writeByte(c: Char) = writeByte(c.toInt()) private fun ByteBuf.writeAscii(s: CharSequence): ByteBuf { ByteBufUtil.writeAscii(this, s) return this } private class IntArrayListTypeAdapter<T> : TypeAdapter<T>() { override fun write(out: JsonWriter, value: T) { var error: IOException? = null out.beginArray() (value as TIntArrayList).forEach { value -> try { out.value(value.toLong()) } catch (e: IOException) { error = e } error == null } error?.let { throw it } out.endArray() } override fun read(`in`: com.google.gson.stream.JsonReader) = throw UnsupportedOperationException() } // addComponent always add sliced component, so, we must add last buffer only after all writes private fun ByteBuf.addBuffer(buffer: ByteBuf): ByteBuf { if (this !== buffer) { (this as CompositeByteBuf).addComponent(buffer) writerIndex(capacity()) } return this } fun JsonRpcServer.registerFromEp() { for (domainBean in JsonRpcDomainBean.EP_NAME.extensions) { registerDomain(domainBean.name, domainBean.value, domainBean.overridable) } }
platform/built-in-server/src/org/jetbrains/io/jsonRpc/JsonRpcServer.kt
3423609015
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.amf.v0 import com.pedro.rtmp.utils.* import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlin.jvm.Throws /** * Created by pedro on 19/07/22. * * A string encoded in UTF-8 where 4 first bytes indicate string size */ open class AmfLongString(var value: String = ""): AmfData() { private var bodySize: Int = value.toByteArray(Charsets.UTF_8).size + 2 @Throws(IOException::class) override fun readBody(input: InputStream) { //read value size as UInt32 bodySize = input.readUInt32() //read value in UTF-8 val bytes = ByteArray(bodySize) bodySize += 2 input.readUntil(bytes) value = String(bytes, Charsets.UTF_8) } @Throws(IOException::class) override fun writeBody(output: OutputStream) { val bytes = value.toByteArray(Charsets.UTF_8) //write value size as UInt32. Value size not included output.writeUInt32(bodySize - 2) //write value bytes in UTF-8 output.write(bytes) } override fun getType(): AmfType = AmfType.LONG_STRING override fun getSize(): Int = bodySize override fun toString(): String { return "AmfLongString value: $value" } }
rtmp/src/main/java/com/pedro/rtmp/amf/v0/AmfLongString.kt
1960831765
package org.catinthedark.example.handlers import org.catinthedark.shared.event_bus.Handler import org.catinthedark.server.Holder @Handler(priority = 0) fun onMovement(msg: String, h: Holder<GameContext>) { h.context.data += 1 Thread.sleep(1000) println("Move '$msg'. Holder: $h") } @Handler(priority = 1) fun onMovement2(msg: String, h: Holder<GameContext>) { h.context.data += 1 println("Move2 '$msg'. Holder: $h") }
example-test/src/main/kotlin/org/catinthedark/example/handlers/Movements.kt
3536325794
package nerd.tuxmobil.fahrplan.congress.schedule import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.recyclerview.widget.RecyclerView import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.models.Session internal interface SessionViewEventsHandler : View.OnCreateContextMenuListener, View.OnClickListener internal class SessionViewColumnAdapter( private val sessions: List<Session>, private val layoutParamsBySession: Map<Session, LinearLayout.LayoutParams>, private val drawer: SessionViewDrawer, private val eventsHandler: SessionViewEventsHandler ) : RecyclerView.Adapter<SessionViewColumnAdapter.SessionViewHolder>() { override fun onBindViewHolder(viewHolder: SessionViewHolder, position: Int) { val session = sessions[position] viewHolder.itemView.tag = session viewHolder.itemView.layoutParams = layoutParamsBySession[session] drawer.updateSessionView(viewHolder.itemView, session) } override fun getItemCount(): Int = sessions.size override fun onCreateViewHolder(parent: ViewGroup, position: Int): SessionViewHolder { val sessionLayout = LayoutInflater.from(parent.context).inflate(R.layout.session_layout, parent, false) as LinearLayout sessionLayout.setOnCreateContextMenuListener(eventsHandler) sessionLayout.setOnClickListener(eventsHandler) return SessionViewHolder(sessionLayout) } class SessionViewHolder(sessionLayout: LinearLayout) : RecyclerView.ViewHolder(sessionLayout) }
app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/SessionViewColumnAdapter.kt
4140330892
/* * Copyright 2017 Adam Jordens * * 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.jordens.sleepybaby import org.springframework.boot.context.properties.ConfigurationProperties import java.net.URL @ConfigurationProperties(prefix = "feedings") data class FeedingConfigurationProperties(var source: String = "", var name: String = "") { fun sourceAsUrl() = URL(source) } @ConfigurationProperties(prefix = "jwt") data class JWTConfigurationProperties(var secret: String = "", var expiration: Int = 0)
jvm/sleepybaby-api/src/main/kotlin/org/jordens/sleepybaby/SleepyBabyConfigurationProperties.kt
2668947858
package ksp.kos.ideaplugin class KerboScriptFindUsagesProviderTest : KerboScriptPlatformTestBase() { override val subdir: String = "findUsages" fun testBasic() { val usages = myFixture.testFindUsagesUsingAction("Basic.ks") val expected = setOf( " PRINT param.", " PRINT param().", " LOCAL var TO param.", " LOCAL var TO param().", ) assertEquals(expected, usages.map { it.presentation.plainText }.toSet()) } }
IDEA/src/test/kotlin/ksp/kos/ideaplugin/KerboScriptFindUsagesProviderTest.kt
2339613553
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.users.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.String /** * @param id - ID of school, university, company group * @param name - Name of occupation * @param type - Type of occupation */ data class UsersOccupation( @SerializedName("id") val id: Int? = null, @SerializedName("name") val name: String? = null, @SerializedName("type") val type: String? = null )
api/src/main/java/com/vk/sdk/api/users/dto/UsersOccupation.kt
1519200070
package org.jetbrains.haskell.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.psi.util.PsiTreeUtil /** * Created by atsky on 11/21/14. */ public class WhereBindings(node : ASTNode) : ASTWrapperPsiElement(node) { fun getSignatureDeclarationsList() : List<SignatureDeclaration> { return PsiTreeUtil.getChildrenOfTypeAsList(this, javaClass()) } fun getValueDefinitionList() : List<ValueDefinition> { return PsiTreeUtil.getChildrenOfTypeAsList(this, javaClass()) } }
plugin/src/org/jetbrains/haskell/psi/WhereBindings.kt
4090098619
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.users.dto import com.google.gson.annotations.SerializedName import kotlin.String enum class UsersReportType( val value: String ) { @SerializedName("porn") PORN("porn"), @SerializedName("spam") SPAM("spam"), @SerializedName("insult") INSULT("insult"), @SerializedName("advertisement") ADVERTISEMENT("advertisement"); }
api/src/main/java/com/vk/sdk/api/users/dto/UsersReportType.kt
2895530980
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.notes.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.base.dto.BaseBoolInt import kotlin.Int import kotlin.String import kotlin.collections.List /** * @param comments - Comments number * @param date - Date when the note has been created in Unixtime * @param id - Note ID * @param ownerId - Note owner's ID * @param title - Note title * @param viewUrl - URL of the page with note preview * @param readComments * @param canComment - Information whether current user can comment the note * @param text - Note text * @param textWiki - Note text in wiki format * @param privacyView * @param privacyComment */ data class NotesNote( @SerializedName("comments") val comments: Int, @SerializedName("date") val date: Int, @SerializedName("id") val id: Int, @SerializedName("owner_id") val ownerId: UserId, @SerializedName("title") val title: String, @SerializedName("view_url") val viewUrl: String, @SerializedName("read_comments") val readComments: Int? = null, @SerializedName("can_comment") val canComment: BaseBoolInt? = null, @SerializedName("text") val text: String? = null, @SerializedName("text_wiki") val textWiki: String? = null, @SerializedName("privacy_view") val privacyView: List<String>? = null, @SerializedName("privacy_comment") val privacyComment: List<String>? = null )
api/src/main/java/com/vk/sdk/api/notes/dto/NotesNote.kt
376581804
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.declarations import com.felipebz.flr.tests.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest class FunctionDeclarationTest : RuleTest() { @BeforeEach fun init() { setRootRule(PlSqlGrammar.FUNCTION_DECLARATION) } @Test fun matchesSimpleFunction() { assertThat(p).matches("" + "function test return number is\n" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesSimpleFunctionAlternative() { assertThat(p).matches("" + "function test return number as\n" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesFunctionWithParameter() { assertThat(p).matches("" + "function test(parameter in number) return number is\n" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesFunctionWithMultipleParameters() { assertThat(p).matches("" + "function test(parameter1 in number, parameter2 in number) return number is\n" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesFunctionWithVariableDeclaration() { assertThat(p).matches("" + "function test return number is\n" + "var number;" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesFunctionWithMultipleVariableDeclaration() { assertThat(p).matches("" + "function test return number is\n" + "var number;" + "var2 number;" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesDeterministicFunction() { assertThat(p).matches("" + "function test return number deterministic is\n" + "begin\n" + "return 0;\n" + "end;") } @Test fun matchesPipelinedFunction() { assertThat(p).matches("" + "function test return number pipelined is\n" + "begin\n" + "return 0;\n" + "end;") } }
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/declarations/FunctionDeclarationTest.kt
3847683318
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.declarations import com.felipebz.flr.tests.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest class CallSpecificationTest : RuleTest() { @BeforeEach fun init() { setRootRule(PlSqlGrammar.CALL_SPECIFICATION) } @Test fun matchesJavaCallSpec() { assertThat(p).matches("language java name 'foo';") } @Test fun matchesLanguageCNameLibrary() { assertThat(p).matches("language c name \"foo\" library bar;") } @Test fun matchesLanguageCLibraryName() { assertThat(p).matches("language c library bar name \"foo\";") } @Test fun matchesExternal() { assertThat(p).matches("external name \"foo\" library bar;") } @Test fun matchesAgentIn() { assertThat(p).matches("language c library bar name \"foo\" agent in (agent);") } @Test fun matchesAgentInMultiple() { assertThat(p).matches("language c library bar name \"foo\" agent in (agent, agent2);") } @Test fun matchesWithContext() { assertThat(p).matches("language c library bar name \"foo\" with context;") } @Test fun matchesParameterContext() { assertThat(p).matches("language c library bar name \"foo\" parameters (context);") } @Test fun matchesParameterSelf() { assertThat(p).matches("language c library bar name \"foo\" parameters (self);") assertThat(p).matches("language c library bar name \"foo\" parameters (self tdo);") assertThat(p).matches("language c library bar name \"foo\" parameters (self indicator);") assertThat(p).matches("language c library bar name \"foo\" parameters (self indicator struct);") assertThat(p).matches("language c library bar name \"foo\" parameters (self indicator tdo);") assertThat(p).matches("language c library bar name \"foo\" parameters (self length);") assertThat(p).matches("language c library bar name \"foo\" parameters (self duration);") assertThat(p).matches("language c library bar name \"foo\" parameters (self maxlen);") assertThat(p).matches("language c library bar name \"foo\" parameters (self charsetid);") assertThat(p).matches("language c library bar name \"foo\" parameters (self charsetform);") } @Test fun matchesParameterSimple() { assertThat(p).matches("language c library bar name \"foo\" parameters (x int);") } @Test fun matchesMultipleParameters() { assertThat(p).matches("language c library bar name \"foo\" parameters (x int, y int);") } @Test fun matchesParameterReturn() { assertThat(p).matches("language c library bar name \"foo\" parameters (return int);") } @Test fun matchesParameterWithProperty() { assertThat(p).matches("language c library bar name \"foo\" parameters (x length int);") } @Test fun matchesParameterByReference() { assertThat(p).matches("language c library bar name \"foo\" parameters (x by reference int);") } }
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/declarations/CallSpecificationTest.kt
2443066294
/* * Copyright 2016-2022 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 examples.kotlin.mybatis3.canonical import org.apache.ibatis.annotations.Mapper import org.apache.ibatis.annotations.Result import org.apache.ibatis.annotations.ResultMap import org.apache.ibatis.annotations.Results import org.apache.ibatis.annotations.SelectProvider import org.apache.ibatis.type.EnumOrdinalTypeHandler import org.apache.ibatis.type.JdbcType import org.mybatis.dynamic.sql.select.render.SelectStatementProvider import org.mybatis.dynamic.sql.util.SqlProviderAdapter /** * * This is a mapper that shows coding a join * */ @Mapper interface PersonWithAddressMapper { @SelectProvider(type = SqlProviderAdapter::class, method = "select") @Results( id = "PersonWithAddressResult", value = [ Result(column = "A_ID", property = "id", jdbcType = JdbcType.INTEGER, id = true), Result(column = "first_name", property = "firstName", jdbcType = JdbcType.VARCHAR), Result( column = "last_name", property = "lastName", jdbcType = JdbcType.VARCHAR, typeHandler = LastNameTypeHandler::class ), Result(column = "birth_date", property = "birthDate", jdbcType = JdbcType.DATE), Result( column = "employed", property = "employed", jdbcType = JdbcType.VARCHAR, typeHandler = YesNoTypeHandler::class ), Result(column = "occupation", property = "occupation", jdbcType = JdbcType.VARCHAR), Result(column = "address_id", property = "address.id", jdbcType = JdbcType.INTEGER), Result(column = "street_address", property = "address.streetAddress", jdbcType = JdbcType.VARCHAR), Result(column = "city", property = "address.city", jdbcType = JdbcType.VARCHAR), Result(column = "state", property = "address.state", jdbcType = JdbcType.CHAR), Result( column = "address_type", property = "address.addressType", jdbcType = JdbcType.INTEGER, typeHandler = EnumOrdinalTypeHandler::class ) ] ) fun selectMany(selectStatement: SelectStatementProvider): List<PersonWithAddress> @SelectProvider(type = SqlProviderAdapter::class, method = "select") @ResultMap("PersonWithAddressResult") fun selectOne(selectStatement: SelectStatementProvider): PersonWithAddress? }
src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonWithAddressMapper.kt
816609687
package com.fieldbook.tracker.database.dao import com.fieldbook.tracker.database.Migrator.Companion.sVisibleObservationVariableViewName import com.fieldbook.tracker.database.Migrator.ObservationVariable import com.fieldbook.tracker.database.Migrator.ObservationVariableAttribute import com.fieldbook.tracker.database.models.ObservationVariableModel import com.fieldbook.tracker.database.query import com.fieldbook.tracker.database.toFirst import com.fieldbook.tracker.database.toTable import com.fieldbook.tracker.database.withDatabase import com.fieldbook.tracker.objects.TraitObject class VisibleObservationVariableDao { companion object { fun getVisibleTrait(): Array<String> = withDatabase { db -> db.query(sVisibleObservationVariableViewName, select = arrayOf("observation_variable_name"), orderBy = "position").toTable().map { it -> it["observation_variable_name"].toString() }.toTypedArray() } ?: emptyArray<String>() // fun getVisibleTraitObjects(): Array<ObservationVariableModel> = withDatabase { db -> // // val rows = db.query(sVisibleObservationVariableViewName, // orderBy = "position").toTable() // // val variables: Array<ObservationVariableModel?> = arrayOfNulls(rows.size) // // rows.forEachIndexed { index, map -> // // variables[index] = ObservationVariableModel(map) // // } // // variables.mapNotNull { it }.toTypedArray() // // } ?: emptyArray() fun getFormat(): Array<String> = withDatabase { db -> db.query(sVisibleObservationVariableViewName, arrayOf(ObservationVariable.PK, "observation_variable_field_book_format", "position")).toTable().map { row -> row["observation_variable_field_book_format"] as String }.toTypedArray() } ?: emptyArray() // //todo switched name to 'getDetails' // fun getDetails(trait: String): Array<ObservationVariableModel> = withDatabase { db -> // // arrayOf(*db.query(sVisibleObservationVariableViewName, // where = "observation_variable_name LIKE $trait") // .toTable().map { // ObservationVariableModel(it) // }.toTypedArray()) // // } ?: arrayOf() fun getDetail(trait: String): TraitObject? = withDatabase { db -> //return a trait object but requires multiple queries to use the attr/values table. ObservationVariableDao.getAllTraitObjects().first { it.trait == trait }.apply { ObservationVariableValueDao.getVariableValues(id.toInt()).also { values -> values?.forEach { val attrName = ObservationVariableAttributeDao.getAttributeNameById(it[ObservationVariableAttribute.FK] as Int) when (attrName) { "validValuesMin" -> minimum = it["observation_variable_attribute_value"] as? String ?: "" "validValuesMax" -> maximum = it["observation_variable_attribute_value"] as? String ?: "" "category" -> categories = it["observation_variable_attribute_value"] as? String ?: "" } } } } } } }
app/src/main/java/com/fieldbook/tracker/database/dao/VisibleObservationVariableDao.kt
3555541719
/* * Copyright (C) 2019 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.saxon.query.s9api.binding import javax.xml.transform.ErrorListener class XQueryCompiler(private val `object`: Any, private val `class`: Class<*>) { fun setErrorListener(listener: ErrorListener) { `class`.getMethod("setErrorListener", ErrorListener::class.java).invoke(`object`, listener) } var updatingEnabled: Boolean get() = `class`.getMethod("isUpdatingEnabled").invoke(`object`) as Boolean set(value) { `class`.getMethod("setUpdatingEnabled", Boolean::class.java).invoke(`object`, value) } fun compile(query: String): XQueryExecutable { val executable = `class`.getMethod("compile", String::class.java).invoke(`object`, query) return XQueryExecutable(executable, `class`.classLoader.loadClass("net.sf.saxon.s9api.XQueryExecutable")) } }
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/XQueryCompiler.kt
3327275645
class A(y: Int) { var x = y } val A.z get() = this.x fun main(args: Array<String>) { val p1 = A::z println(p1.get(A(42))) val a = A(117) val p2 = a::z println(p2.get()) }
backend.native/tests/codegen/propertyCallableReference/valExtension.kt
1178587937
package org.stepik.android.remote.vote.model import com.google.gson.annotations.SerializedName import org.stepik.android.model.comments.Vote class VoteRequest( @SerializedName("vote") val vote: Vote )
app/src/main/java/org/stepik/android/remote/vote/model/VoteRequest.kt
3907320138
package nl.sugcube.dirtyarrows.command import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.region.showPositionMarkers import nl.sugcube.dirtyarrows.region.showRegionMarkers import nl.sugcube.dirtyarrows.util.sendError import org.bukkit.command.CommandSender /** * @author SugarCaney */ open class CommandVisualize : SubCommand<DirtyArrows>( name = "visualize", usage = "/da visualize [region]", argumentCount = 0, description = "Shows the set positions, or the corners of the region." ) { init { addPermissions("dirtyarrows.admin") addAutoCompleteMeta(0, AutoCompleteArgument.REGIONS) } override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) { val regionName = arguments.firstOrNull() // No region specified : show the current positions. if (regionName == null) { plugin.showPositionMarkers(5) return } // Region specified val region = plugin.regionManager.regionByName(regionName) if (region == null) { sender.sendError("There is no region with name '$regionName'") return } plugin.showRegionMarkers(region, 5) } override fun assertSender(sender: CommandSender) = true }
src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandVisualize.kt
3499993869
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.copyOf import org.bukkit.Effect import org.bukkit.GameMode import org.bukkit.Material import org.bukkit.entity.Arrow import org.bukkit.entity.FallingBlock import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.entity.EntityChangeBlockEvent import org.bukkit.event.entity.ProjectileLaunchEvent import org.bukkit.inventory.ItemStack import org.bukkit.material.MaterialData /** * Shoots a blob of water. * * @author SugarCaney */ open class AquaticBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.AQUATIC, canShootInProtectedRegions = false, protectionRange = 1.0, costRequirements = listOf(ItemStack(Material.WATER_BUCKET, 1)), description = "Shoot water." ) { /** * A particle will spawn from shot arrows every N ticks. */ val particleEveryNTicks = config.getInt("$node.particle-every-n-ticks") /** * Shot falling blocks mapped to their shooter. */ private val waterBlocks = HashMap<FallingBlock, Player>() override fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) { val direction = arrow.velocity.copyOf().normalize() // Spawn the lava block slightly in front of the player. val spawnLocation = arrow.location.add(direction.multiply(1.5)) player.world.spawnFallingBlock(spawnLocation, MaterialData(Material.WATER)).apply { velocity = arrow.velocity dropItem = false waterBlocks[this] = player } } override fun particle(tickNumber: Int) { if (tickNumber % particleEveryNTicks == 0) return arrows.forEach { it.world.playEffect(it.location.copyOf().add(0.5, 0.5, 0.5), Effect.STEP_SOUND, Material.WATER) } } override fun Player.consumeBowItems() { if (gameMode == GameMode.CREATIVE) return // Empty the lava bucket. inventory.firstOrNull { it?.type == Material.WATER_BUCKET } ?.let { it.type = Material.BUCKET } } @EventHandler fun lavaBlockProtection(event: EntityChangeBlockEvent) { val waterBlock = event.entity as? FallingBlock ?: return val shooter = waterBlocks[waterBlock] ?: return if (waterBlock.location.isInProtectedRegion(shooter)) { event.isCancelled = true waterBlocks.remove(waterBlock) waterBlock.remove() } } }
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/AquaticBow.kt
3711112689
package com.mindera.skeletoid.network import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import com.mindera.skeletoid.utils.extensions.mock import org.junit.Test import org.mockito.Mockito import kotlin.test.assertFalse import kotlin.test.assertTrue class ConnectivityTest { @Test fun testIsNotConnected() { val context = mock<Context>() assertFalse(Connectivity.isConnected(context)) } @Test fun testIsNotConnectedForNoNetworkInfo() { val context = mock<Context>() val connectivityManager = mock<ConnectivityManager>() Mockito.`when`(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager) assertFalse(Connectivity.isConnected(context)) } @Test fun testIsConnected() { val context = mock<Context>() val connectivityManager = mock<ConnectivityManager>() val activeNetworkInfo = mock<NetworkInfo>() Mockito.`when`(connectivityManager.activeNetworkInfo).thenReturn(activeNetworkInfo) Mockito.`when`(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager) assertTrue(Connectivity.isConnected(context)) } @Test fun testIsNotConnectedToWIFI() { val context = mock<Context>() assertFalse(Connectivity.isConnectedToWifi(context)) } @Test fun testIsNotConnectedToWIFIForNoNetworkInfo() { val context = mock<Context>() val connectivityManager = mock<ConnectivityManager>() Mockito.`when`(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager) assertFalse(Connectivity.isConnectedToWifi(context)) } @Test fun testIsConnectedToWIFI() { val context = mock<Context>() val connectivityManager = mock<ConnectivityManager>() val activeNetworkInfo = mock<NetworkInfo>() Mockito.`when`(activeNetworkInfo.type).thenReturn(ConnectivityManager.TYPE_WIFI) Mockito.`when`(connectivityManager.activeNetworkInfo).thenReturn(activeNetworkInfo) Mockito.`when`(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager) assertTrue(Connectivity.isConnectedToWifi(context)) } }
base/src/test/java/com/mindera/skeletoid/network/ConnectivityTest.kt
629940403
package expo.modules.updates.loader import android.net.Uri import androidx.room.Room import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import androidx.test.platform.app.InstrumentationRegistry import expo.modules.manifests.core.BareManifest import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.db.UpdatesDatabase import expo.modules.updates.db.entity.AssetEntity import expo.modules.updates.db.entity.UpdateEntity import expo.modules.updates.db.enums.UpdateStatus import expo.modules.updates.loader.Loader.LoaderCallback import expo.modules.updates.manifest.BareUpdateManifest import expo.modules.updates.manifest.UpdateManifest import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.json.JSONException import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.io.File import java.io.IOException import java.security.NoSuchAlgorithmException @RunWith(AndroidJUnit4ClassRunner::class) class EmbeddedLoaderTest { private lateinit var db: UpdatesDatabase private lateinit var configuration: UpdatesConfiguration private lateinit var manifest: UpdateManifest private lateinit var loader: EmbeddedLoader private lateinit var mockLoaderFiles: LoaderFiles private lateinit var mockCallback: LoaderCallback @Before @Throws(JSONException::class) fun setup() { val configMap = mapOf<String, Any>( "updateUrl" to Uri.parse("https://exp.host/@test/test"), "runtimeVersion" to "1.0" ) configuration = UpdatesConfiguration(null, configMap) val context = InstrumentationRegistry.getInstrumentation().targetContext db = Room.inMemoryDatabaseBuilder(context, UpdatesDatabase::class.java).build() mockLoaderFiles = mockk(relaxed = true) loader = EmbeddedLoader( context, configuration, db, File("testDirectory"), mockLoaderFiles ) manifest = BareUpdateManifest.fromBareManifest( BareManifest(JSONObject("{\"id\":\"c3c47024-0e03-4cb4-8e8b-1a0ba2260be6\",\"commitTime\":1630374791665,\"assets\":[{\"name\":\"robot-dev\",\"type\":\"png\",\"scale\":1,\"packagerHash\":\"54da1e9816c77e30ebc5920e256736f2\",\"subdirectory\":\"/assets\",\"scales\":[1],\"resourcesFilename\":\"robotdev\",\"resourcesFolder\":\"drawable\"}]}")), configuration ) every { mockLoaderFiles.readEmbeddedManifest(any(), any()) } returns manifest every { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } answers { callOriginal() } // test for exception cases mockCallback = mockk(relaxUnitFun = true) every { mockCallback.onUpdateManifestLoaded(any()) } returns true } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_SimpleCase() { loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_FailureToCopyAssets() { every { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } throws IOException("mock failed to copy asset") loader.start(mockCallback) verify(exactly = 0) { mockCallback.onSuccess(any()) } verify { mockCallback.onFailure(any()) } verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) // status embedded indicates the update wasn't able to be fully copied to the expo-updates cache Assert.assertEquals(UpdateStatus.EMBEDDED, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(0, assets.size.toLong()) } @Test @Throws(JSONException::class, IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_MultipleScales() { val multipleScalesManifest: UpdateManifest = BareUpdateManifest.fromBareManifest( BareManifest(JSONObject("{\"id\":\"d26d7f92-c7a6-4c44-9ada-4804eda7e6e2\",\"commitTime\":1630435460610,\"assets\":[{\"name\":\"robot-dev\",\"type\":\"png\",\"scale\":1,\"packagerHash\":\"54da1e9816c77e30ebc5920e256736f2\",\"subdirectory\":\"/assets\",\"scales\":[1,2],\"resourcesFilename\":\"robotdev\",\"resourcesFolder\":\"drawable\"},{\"name\":\"robot-dev\",\"type\":\"png\",\"scale\":2,\"packagerHash\":\"4ecff55cf37460b7f768dc7b72bcea6b\",\"subdirectory\":\"/assets\",\"scales\":[1,2],\"resourcesFilename\":\"robotdev\",\"resourcesFolder\":\"drawable\"}]}")), configuration ) every { mockLoaderFiles.readEmbeddedManifest(any(), any()) } returns multipleScalesManifest loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.EMBEDDED, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(JSONException::class, IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_MultipleScales_ReverseOrder() { val multipleScalesManifest: UpdateManifest = BareUpdateManifest.fromBareManifest( BareManifest(JSONObject("{\"id\":\"d26d7f92-c7a6-4c44-9ada-4804eda7e6e2\",\"commitTime\":1630435460610,\"assets\":[{\"name\":\"robot-dev\",\"type\":\"png\",\"scale\":2,\"packagerHash\":\"4ecff55cf37460b7f768dc7b72bcea6b\",\"subdirectory\":\"/assets\",\"scales\":[1,2],\"resourcesFilename\":\"robotdev\",\"resourcesFolder\":\"drawable\"},{\"name\":\"robot-dev\",\"type\":\"png\",\"scale\":1,\"packagerHash\":\"54da1e9816c77e30ebc5920e256736f2\",\"subdirectory\":\"/assets\",\"scales\":[1,2],\"resourcesFilename\":\"robotdev\",\"resourcesFolder\":\"drawable\"}]}")), configuration ) every { mockLoaderFiles.readEmbeddedManifest(any(), any()) } returns multipleScalesManifest loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.EMBEDDED, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_AssetExists_BothDbAndDisk() { // return true when asked if file 54da1e9816c77e30ebc5920e256736f2 exists every { mockLoaderFiles.fileExists(any()) } answers { firstArg<File>().toString().contains("54da1e9816c77e30ebc5920e256736f2") } val existingAsset = AssetEntity("54da1e9816c77e30ebc5920e256736f2", "png") existingAsset.relativePath = "54da1e9816c77e30ebc5920e256736f2.png" db.assetDao()._insertAsset(existingAsset) loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } // only 1 asset (bundle) should be copied since the other asset already exists verify(exactly = 1) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_AssetExists_DbOnly() { // return true when asked if file 54da1e9816c77e30ebc5920e256736f2 exists every { mockLoaderFiles.fileExists(any()) } returns false val existingAsset = AssetEntity("54da1e9816c77e30ebc5920e256736f2", "png") existingAsset.relativePath = "54da1e9816c77e30ebc5920e256736f2.png" db.assetDao()._insertAsset(existingAsset) loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } // both assets should be copied regardless of what the database says verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } // the resource asset should make it through to the inner copy method verify(exactly = 1) { mockLoaderFiles.copyResourceAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_AssetExists_DiskOnly() { // return true when asked if file 54da1e9816c77e30ebc5920e256736f2 exists every { mockLoaderFiles.fileExists(any()) } answers { firstArg<File>().toString().contains("54da1e9816c77e30ebc5920e256736f2") } Assert.assertEquals(0, db.assetDao().loadAllAssets().size.toLong()) loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } // only 1 asset (bundle) should be copied since the other asset already exists verify(exactly = 1) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) // both assets should have been added to the db even though one already existed on disk val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_UpdateExists_Ready() { val update = UpdateEntity( manifest.updateEntity!!.id, manifest.updateEntity!!.commitTime, manifest.updateEntity!!.runtimeVersion, manifest.updateEntity!!.scopeKey ) update.status = UpdateStatus.READY db.updateDao().insertUpdate(update) loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } verify(exactly = 0) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) } @Test @Throws(IOException::class, NoSuchAlgorithmException::class) fun testEmbeddedLoader_UpdateExists_Pending() { val update = UpdateEntity( manifest.updateEntity!!.id, manifest.updateEntity!!.commitTime, manifest.updateEntity!!.runtimeVersion, manifest.updateEntity!!.scopeKey ) update.status = UpdateStatus.PENDING db.updateDao().insertUpdate(update) loader.start(mockCallback) verify { mockCallback.onSuccess(any()) } verify(exactly = 0) { mockCallback.onFailure(any()) } // missing assets should still be copied verify(exactly = 2) { mockLoaderFiles.copyAssetAndGetHash(any(), any(), any()) } val updates = db.updateDao().loadAllUpdates() Assert.assertEquals(1, updates.size.toLong()) Assert.assertEquals(UpdateStatus.READY, updates[0].status) val assets = db.assetDao().loadAllAssets() Assert.assertEquals(2, assets.size.toLong()) } }
packages/expo-updates/android/src/androidTest/java/expo/modules/updates/loader/EmbeddedLoaderTest.kt
3660380963
package abi44_0_0.expo.modules.speech import abi44_0_0.expo.modules.core.Promise import java.util.* data class SpeechOptions( val language: String?, val pitch: Float?, val rate: Float?, val voice: String? ) { companion object { fun optionsFromMap(options: Map<String, Any?>?, promise: Promise): SpeechOptions? { if (options == null) { return SpeechOptions(null, null, null, null) } val language = options["language"]?.let { if (it is String) { return@let it } promise.reject("ERR_INVALID_OPTION", "Language must be a string") return null } val pitch = options["pitch"]?.let { if (it is Number) { return@let it.toFloat() } promise.reject("ERR_INVALID_OPTION", "Pitch must be a number") return null } val rate = options["rate"]?.let { if (it is Number) { return@let it.toFloat() } promise.reject("ERR_INVALID_OPTION", "Rate must be a number") return null } val voice = options["voice"]?.let { if (it is String) { return@let it } promise.reject("ERR_INVALID_OPTION", "Voice name must be a string") return null } return SpeechOptions(language, pitch, rate, voice) } } }
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/speech/SpeechOptions.kt
1004594154
@file:JvmName("RobotPlayer") @file:Suppress("PackageDirectoryMismatch") package testplayerbytecodekotlinintrinsics import battlecode.common.RobotController import kotlin.jvm.internal.Intrinsics fun run(@Suppress("UNUSED_PARAMETER") rc: RobotController) { val o = Any() // this is 100 calls. It's unrolled so that the bytecode is purely ALOAD followed by INVOKESTATIC 100 times. Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) Intrinsics.checkNotNull(o) }
src/test/battlecode/instrumenter/sample/testplayerbytecodekotlinintrinsics/RobotPlayer.kt
1636508789
package io.chesslave.eyes import io.chesslave.eyes.sikuli.SikuliVision import io.chesslave.model.* import io.chesslave.visual.rendering.BoardRenderer import io.chesslave.visual.rendering.ChessSet import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class PositionRecogniserTest(chessSet: ChessSet) : SinglePieceRecognitionTest(chessSet) { lateinit var recogniser: PositionRecogniser @Before fun setUp() { val initialPosition = Game.initialPosition().position() val initialBoard = BoardRenderer(chessSet).withPosition(initialPosition).render() val config = analyzeBoardImage(initialBoard.image) this.recogniser = PositionRecogniser(SikuliVision(), config) } @Test fun recognisePosition() { val position = positionFromText( "r|n|b|q|k|b|n|r", "p|p| | |p|p|p|p", " | | |p| | | | ", " | | | | | | | ", " | | |p|P| | | ", " | | | | |N| | ", "P|P|P| | |P|P|P", "R|N|B|Q|K|B| |R") val board = BoardRenderer(chessSet).withPosition(position).render() val got = recogniser.position(board) assertEquals(position, got) } override fun withPieceOnSquare(square: Square, piece: Piece) { val position = Position.Builder().withPiece(square, piece).build() val board = BoardRenderer(chessSet).withPosition(position).render() val got = recogniser.position(board) assertEquals(position, got) } }
backend/src/test/java/io/chesslave/eyes/PositionRecogniserTest.kt
2500609524
package vi_generics import util.TODO import java.util.* fun task41(): Nothing = TODO( """ Task41. Add a 'partitionTo' function that splits a collection into two collections according to a predicate. Uncomment the commented invocations of 'partitionTo' below and make them compile. There is a 'partition()' function in the standard library that always returns two newly created lists. You should write a function that splits the collection into two collections given as arguments. The signature of the 'toCollection()' function from the standard library may help you. """, references = { l: List<Int> -> l.partition { it > 0 } l.toCollection(HashSet<Int>()) } ) fun <T, C : MutableCollection<T>> Collection<T>.partitionTo(left: C, right: C, predicate: (T) -> Boolean): Pair<C, C> { for (element in this) { if (predicate(element)) { left.add(element) } else { right.add(element) } } return Pair(left, right) } fun List<String>.partitionWordsAndLines(): Pair<List<String>, List<String>> { return partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") } } fun Set<Char>.partitionLettersAndOtherSymbols(): Pair<Set<Char>, Set<Char>> { return partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } }
src/vi_generics/_41_GenericFunctions.kt
1262759871
/* * Copyright 2000-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.settingsRepository import com.intellij.configurationStore.ROOT_CONFIG import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.configurationStore.StreamProviderWrapper import com.intellij.configurationStore.removeMacroIfStartsWith import com.intellij.ide.actions.ExportableItem import com.intellij.ide.actions.getExportableComponentsMap import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.directoryStreamIfExists import com.intellij.util.isFile import com.intellij.util.readBytes import com.intellij.util.systemIndependentPath import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path fun copyLocalConfig(storageManager: StateStorageManagerImpl = ApplicationManager.getApplication()!!.stateStore.stateStorageManager as StateStorageManagerImpl) { val streamProvider = StreamProviderWrapper.getOriginalProvider(storageManager.streamProvider)!! as IcsManager.IcsStreamProvider val fileToComponents = getExportableComponentsMap(true, false, storageManager) fileToComponents.keys.forEachGuaranteed { file -> var fileSpec: String try { val absolutePath = file.toAbsolutePath().systemIndependentPath fileSpec = removeMacroIfStartsWith(storageManager.collapseMacros(absolutePath), ROOT_CONFIG) if (fileSpec == absolutePath) { // we have not experienced such problem yet, but we are just aware val canonicalPath = file.toRealPath().systemIndependentPath if (canonicalPath != absolutePath) { fileSpec = removeMacroIfStartsWith(storageManager.collapseMacros(canonicalPath), ROOT_CONFIG) } } } catch (e: NoSuchFileException) { return@forEachGuaranteed } val roamingType = getRoamingType(fileToComponents.get(file)!!) if (file.isFile()) { val fileBytes = file.readBytes() streamProvider.doSave(fileSpec, fileBytes, fileBytes.size, roamingType) } else { saveDirectory(file, fileSpec, roamingType, streamProvider) } } } private fun saveDirectory(parent: Path, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) { parent.directoryStreamIfExists { for (file in it) { val childFileSpec = "$parentFileSpec/${file.fileName}" if (file.isFile()) { val fileBytes = Files.readAllBytes(file) streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size, roamingType) } else { saveDirectory(file, childFileSpec, roamingType, streamProvider) } } } } private fun getRoamingType(components: Collection<ExportableItem>): RoamingType { for (component in components) { if (component is ExportableItem) { return component.roamingType } // else if (component is PersistentStateComponent<*>) { // val stateAnnotation = component.javaClass.getAnnotation(State::class.java) // if (stateAnnotation != null) { // val storages = stateAnnotation.storages // if (!storages.isEmpty()) { // return storages[0].roamingType // } // } // } } return RoamingType.DEFAULT }
plugins/settings-repository/src/copyAppSettingsToRepository.kt
3825102539
package arcs.sdk import arcs.core.entity.Handle import arcs.core.entity.ReadCollectionHandle import arcs.core.entity.ReadSingletonHandle import arcs.core.entity.Storable import arcs.core.entity.WriteCollectionHandle import arcs.core.entity.WriteSingletonHandle import kotlinx.coroutines.Job import kotlinx.coroutines.withContext /* * To facilitate safe read/write access to data handles in running arcs, particles can be * annotated with '@edge' in the manifest. This will cause the following set of changes to * the code generation output: * - The generated class will be concrete and final instead of an abstract base class. * - The particle lifecycle will be managed internally to this class; clients will not have * any access to lifecycle events. * - Handles will be exposed via the Edge*Handle interfaces given below. All edge handle methods * are asynchronous and may be invoked at any time after the particle has been created. * - All read operations will suspend as required to await handle synchronization. * - All write operations will be applied immediately to the local handle data model. They will * return a Job that will be completed once the operation has been sent to the backing store * for this handle; it is not required that join() is called on these jobs. * * Query handles are not supported at this time. */ interface EdgeReadSingletonHandle<E> { suspend fun fetch(): E? } interface EdgeWriteSingletonHandle<I> { suspend fun store(element: I): Job suspend fun clear(): Job } interface EdgeReadWriteSingletonHandle<E, I> : EdgeReadSingletonHandle<E>, EdgeWriteSingletonHandle<I> interface EdgeReadCollectionHandle<E> { suspend fun size(): Int suspend fun isEmpty(): Boolean suspend fun fetchAll(): Set<E> suspend fun fetchById(entityId: String): E? } interface EdgeWriteCollectionHandle<I> { suspend fun store(element: I): Job suspend fun storeAll(elements: Collection<I>): Job suspend fun clear(): Job suspend fun remove(element: I): Job suspend fun removeById(id: String): Job } interface EdgeReadWriteCollectionHandle<E, I> : EdgeReadCollectionHandle<E>, EdgeWriteCollectionHandle<I> /** Base class for the edge handle implementations. */ abstract class EdgeHandle { // The "real" arc handle; assigned by setHandles() in the generated particle implementation. lateinit var handle: Handle private var ready = Job() suspend fun <T> readOp(op: () -> T): T = withContext(handle.dispatcher) { ready.join() op() } suspend fun <T> writeOp(op: () -> T): T = withContext(handle.dispatcher) { op() } // Invoked by onReady in the generated particle implementation. fun moveToReady() { ready.complete() } } @Suppress("UNCHECKED_CAST") class EdgeSingletonHandle<E : Storable, I : Storable> : EdgeHandle(), EdgeReadWriteSingletonHandle<E, I> { override suspend fun fetch() = readOp { (handle as ReadSingletonHandle<E>).fetch() } override suspend fun store(element: I) = writeOp { (handle as WriteSingletonHandle<I>).store(element) } override suspend fun clear() = writeOp { (handle as WriteSingletonHandle<I>).clear() } } @Suppress("UNCHECKED_CAST") class EdgeCollectionHandle<E : Storable, I : Storable> : EdgeHandle(), EdgeReadWriteCollectionHandle<E, I> { private val readHandle: ReadCollectionHandle<E> get() = handle as ReadCollectionHandle<E> private val writeHandle: WriteCollectionHandle<I> get() = handle as WriteCollectionHandle<I> override suspend fun size() = readOp { readHandle.size() } override suspend fun isEmpty() = readOp { readHandle.isEmpty() } override suspend fun fetchAll() = readOp { readHandle.fetchAll() } override suspend fun fetchById(entityId: String) = readOp { readHandle.fetchById(entityId) } override suspend fun store(element: I) = writeOp { writeHandle.store(element) } override suspend fun storeAll(elements: Collection<I>) = writeOp { writeHandle.storeAll(elements) } override suspend fun clear() = writeOp { writeHandle.clear() } override suspend fun remove(element: I) = writeOp { writeHandle.remove(element) } override suspend fun removeById(id: String) = writeOp { writeHandle.removeById(id) } }
java/arcs/sdk/EdgeHandles.kt
2510152125
package com.fsck.k9.preferences import kotlinx.coroutines.flow.Flow /** * Retrieve and modify general settings. * * TODO: Add more settings as needed. */ interface GeneralSettingsManager { fun getSettings(): GeneralSettings fun getSettingsFlow(): Flow<GeneralSettings> fun setShowRecentChanges(showRecentChanges: Boolean) fun setAppTheme(appTheme: AppTheme) fun setMessageViewTheme(subTheme: SubTheme) fun setMessageComposeTheme(subTheme: SubTheme) fun setFixedMessageViewTheme(fixedMessageViewTheme: Boolean) }
app/core/src/main/java/com/fsck/k9/preferences/GeneralSettingsManager.kt
1042773717
package bz.stewart.bracken.db.database.index import bz.stewart.bracken.db.database.DbItem import bz.stewart.bracken.db.database.mongo.AbstractMongoDb import com.mongodb.client.MongoCollection import mu.KLogging /** * Open db, sync index, then close. */ class SyncIndex<T : DbItem>(private val db: AbstractMongoDb<T>, private val indexBuilder: (MongoCollection<T>) -> IndexedCollection<T>):IndexSyncAction { companion object : KLogging() override fun doSync(testMode:Boolean) { db.use { db.openDatabase() InlineSyncIndex(db, indexBuilder) } } }
db/src/main/kotlin/bz/stewart/bracken/db/database/index/SyncIndex.kt
2815490512
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.ex.parser.statements import com.maddyhome.idea.vim.vimscript.model.statements.IfStatement import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser import org.junit.experimental.theories.DataPoints import org.junit.experimental.theories.Theories import org.junit.experimental.theories.Theory import org.junit.runner.RunWith import kotlin.test.assertEquals import kotlin.test.assertTrue @RunWith(Theories::class) class IfStatementTests { companion object { @JvmStatic val values = listOf("", " ") @DataPoints get } @Theory fun ifTest(sp1: String, sp2: String, sp3: String, sp4: String) { val script = VimscriptParser.parse( """ if char == "\<LeftMouse>"$sp1 " empty block elseif char == "\<RightMouse>"$sp2 " one echo echo 1 else$sp3 " two echos echo 1 echo 1 endif$sp4 """.trimIndent() ) assertEquals(1, script.units.size) assertTrue(script.units[0] is IfStatement) val s = script.units[0] as IfStatement assertEquals(3, s.conditionToBody.size) assertEquals(0, s.conditionToBody[0].second.size) assertEquals(1, s.conditionToBody[1].second.size) assertEquals(2, s.conditionToBody[2].second.size) } }
src/test/java/org/jetbrains/plugins/ideavim/ex/parser/statements/IfStatementTests.kt
3940069053
package nl.jstege.adventofcode.aoccommon.utils.extensions import kotlin.math.log /** * * @author Jelle Stege */ /** * Returns the floor modulus of the arguments. * @see Math.floorMod * * @receiver The divisor for the floor modulus operation * @param y The dividend for the floor modulus operation * @return The floor modulus of the given arguments. */ infix fun Long.floorMod(y: Long): Long = Math.floorMod(this, y) /** * Allows an infix notation of a power method. * @see Math.pow * * @receiver The base of the power operation. * @param n The exponent of the power operation. * @return The result of receiver ^ n, as an integer. */ infix fun Int.pow(n: Int): Int = Math.pow(this.toDouble(), n.toDouble()).toInt() /** * Fast access to a logarithm function with a definable base. For integers. * @see Math.log * * @param n The value to take the logarithm of. * @param base The base of the logarithm, defaults to 10. */ fun log(n: Int, base: Int = 10): Int = log(n.toDouble(), base.toDouble()).toInt()
aoc-common/src/main/kotlin/nl/jstege/adventofcode/aoccommon/utils/extensions/Math.kt
2690690355
package com.timepath.hl2.io.demo import com.timepath.io.BitBuffer import com.timepath.toUnsigned import java.awt.Color import java.awt.Point import java.util.LinkedList /** * @see [https://forums.alliedmods.net/showthread.php?t=163224](null) * @see [https://github.com/LestaD/SourceEngine2007/blob/master/src_main/game/server/util.cpp.L1115](null) * @see [https://github.com/LestaD/SourceEngine2007/blob/master/se2007/game/shared/hl2/hl2_usermessages.cpp](null) * HookMessage, HOOK_HUD_MESSAGE, MsgFunc_ */ public abstract class UserMessage(private val size: Int = -1) : PacketHandler { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean = size == -1 object Geiger : UserMessage(1) { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { l["Range"] = bb.getByte().toUnsigned() * 2 return true } } object Train : UserMessage(1) { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { l["Pos"] = bb.getByte() return true } } object HudText : UserMessage() { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { l["Text"] = bb.getString() return true } } object SayText : UserMessage() object SayText2 : UserMessage() { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { val endBit = bb.positionBits() + lengthBits val client = bb.getBits(8) l["Client"] = client // 0 - raw text, 1 - sets CHAT_FILTER_PUBLICCHAT val isRaw = bb.getBits(8) != 0L l["Raw"] = isRaw // \x03 in the message for the team color of the specified clientid val kind = bb.getString() l["Kind"] = kind val from = bb.getString() l["From"] = from val msg = bb.getString() l["Text"] = msg // This message can have two optional string parameters. val args = LinkedList<String>() while (bb.positionBits() < endBit) { val arg = bb.getString() args.add(arg) } l["Args"] = args return true } } object TextMsg : UserMessage() { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { val destination = arrayOf("HUD_PRINTCONSOLE", "HUD_PRINTNOTIFY", "HUD_PRINTTALK", "HUD_PRINTCENTER") val msgDest = bb.getByte() l["Destination"] = destination[msgDest.toInt()] l["Message"] = bb.getString() // These seem to be disabled in TF2 // l.add(new Pair<Object, Object>("args[0]", bb.getString())); // l.add(new Pair<Object, Object>("args[1]", bb.getString())); // l.add(new Pair<Object, Object>("args[2]", bb.getString())); // l.add(new Pair<Object, Object>("args[3]", bb.getString())); return true } } object ResetHUD : UserMessage(1) object GameTitle : UserMessage(0) object ItemPickup : UserMessage() object ShowMenu : UserMessage() object Shake : UserMessage(13) object Fade : UserMessage(10) object VGUIMenu : UserMessage() object Rumble : UserMessage(3) object CloseCaption : UserMessage() object SendAudio : UserMessage() object VoiceMask : UserMessage(17) object RequestState : UserMessage(0) object Damage : UserMessage() object HintText : UserMessage() object KeyHintText : UserMessage() /** * Position command $position x y * x & y are from 0 to 1 to be screen resolution independent * -1 means center in each dimension * Effect command $effect * effect 0 is fade in/fade out * effect 1 is flickery credits * effect 2 is write out (training room) * Text color r g b command $color * Text color r g b command $color2 * fadein time fadeout time / hold time * $fadein (message fade in time - per character in effect 2) * $fadeout (message fade out time) * $holdtime (stay on the screen for this long) */ object HudMsg : UserMessage() { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { val pos = Point(bb.getByte().toInt(), bb.getByte().toInt()) val color = Color(bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt()) val color2 = Color(bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt()) val effect = bb.getByte().toFloat() val fadein = bb.getFloat() val fadeout = bb.getFloat() val holdtime = bb.getFloat() val fxtime = bb.getFloat() l["Text"] = bb.getString() return true } private val MAX_NETMESSAGE = 6 } object AmmoDenied : UserMessage(2) { override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean { l["Ammo"] = bb.getShort().toUnsigned() return true } } object AchievementEvent : UserMessage() object UpdateRadar : UserMessage() object VoiceSubtitle : UserMessage(3) object HudNotify : UserMessage(1) object HudNotifyCustom : UserMessage() object PlayerStatsUpdate : UserMessage() object PlayerIgnited : UserMessage(3) object PlayerIgnitedInv : UserMessage(3) object HudArenaNotify : UserMessage(2) object UpdateAchievement : UserMessage() object TrainingMsg : UserMessage() object TrainingObjective : UserMessage() object DamageDodged : UserMessage() object PlayerJarated : UserMessage(2) object PlayerExtinguished : UserMessage(2) object PlayerJaratedFade : UserMessage(2) object PlayerShieldBlocked : UserMessage(2) object BreakModel : UserMessage() object CheapBreakModel : UserMessage() object BreakModel_Pumpkin : UserMessage() object BreakModelRocketDud : UserMessage() object CallVoteFailed : UserMessage() object VoteStart : UserMessage() object VotePass : UserMessage() object VoteFailed : UserMessage(2) object VoteSetup : UserMessage() object PlayerBonusPoints : UserMessage(3) object SpawnFlyingBird : UserMessage() object PlayerGodRayEffect : UserMessage() object SPHapWeapEvent : UserMessage(4) object HapDmg : UserMessage() object HapPunch : UserMessage() object HapSetDrag : UserMessage() object HapSetConst : UserMessage() object HapMeleeContact : UserMessage(0) companion object { fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM): Boolean { val msgType = bb.getByte().toInt() val m = UserMessage[msgType] l["Message"] = m?.let { "${it.javaClass.getSimpleName()}(${msgType})" } ?: "Unknown($msgType)" val length = bb.getBits(11).toInt() l["Length"] = length l["Range"] = bb.positionBits() to bb.positionBits() + length m?.let { if (it.read(bb, l, demo, length)) return true l["Status"] = "Error" return false } l["Status"] = "TODO" bb.getBits(length) // Skip return true } fun get(i: Int): UserMessage? = values[i] private val values = mapOf( 0 to Geiger, 1 to Train, 2 to HudText, 3 to SayText, 4 to SayText2, 5 to TextMsg, 6 to ResetHUD, 7 to GameTitle, 8 to ItemPickup, 9 to ShowMenu, 10 to Shake, 11 to Fade, 12 to VGUIMenu, 13 to Rumble, 14 to CloseCaption, 15 to SendAudio, 16 to VoiceMask, 17 to RequestState, 18 to Damage, 19 to HintText, 20 to KeyHintText, 21 to HudMsg, 22 to AmmoDenied, 23 to AchievementEvent, 24 to UpdateRadar, 25 to VoiceSubtitle, 26 to HudNotify, 27 to HudNotifyCustom, 28 to PlayerStatsUpdate, 29 to PlayerIgnited, 30 to PlayerIgnitedInv, 31 to HudArenaNotify, 32 to UpdateAchievement, 33 to TrainingMsg, 34 to TrainingObjective, 35 to DamageDodged, 36 to PlayerJarated, 37 to PlayerExtinguished, 38 to PlayerJaratedFade, 39 to PlayerShieldBlocked, 40 to BreakModel, 41 to CheapBreakModel, 42 to BreakModel_Pumpkin, 43 to BreakModelRocketDud, 44 to CallVoteFailed, 45 to VoteStart, 46 to VotePass, 47 to VoteFailed, 48 to VoteSetup, 49 to PlayerBonusPoints, 50 to SpawnFlyingBird, 51 to PlayerGodRayEffect, 52 to SPHapWeapEvent, 53 to HapDmg, 54 to HapPunch, 55 to HapSetDrag, 56 to HapSetConst, 57 to HapMeleeContact ) } }
src/main/kotlin/com/timepath/hl2/io/demo/UserMessage.kt
1679782473
package org.wordpress.android.ui.about import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.automattic.about.model.AboutConfig import com.automattic.about.model.AboutFooterConfig import com.automattic.about.model.AnalyticsConfig import com.automattic.about.model.AutomatticConfig import com.automattic.about.model.HeaderConfig import com.automattic.about.model.ItemConfig import com.automattic.about.model.LegalConfig import com.automattic.about.model.RateUsConfig import com.automattic.about.model.ShareConfig import com.automattic.about.model.SocialsConfig import com.automattic.about.model.WorkWithUsConfig import org.wordpress.android.Constants import org.wordpress.android.R import org.wordpress.android.models.recommend.RecommendApiCallsProvider import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendAppName.Jetpack import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendAppName.WordPress import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendCallResult.Failure import org.wordpress.android.models.recommend.RecommendApiCallsProvider.RecommendCallResult.Success import org.wordpress.android.ui.about.UnifiedAboutNavigationAction.Dismiss import org.wordpress.android.ui.about.UnifiedAboutNavigationAction.OpenBlog import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.BuildConfigWrapper import org.wordpress.android.util.WpUrlUtilsWrapper import org.wordpress.android.util.analytics.AnalyticsUtils.RecommendAppSource.ABOUT import org.wordpress.android.viewmodel.ContextProvider import org.wordpress.android.viewmodel.Event import javax.inject.Inject class UnifiedAboutViewModel @Inject constructor( private val contextProvider: ContextProvider, private val wpUrlUtils: WpUrlUtilsWrapper, private val recommendApiCallsProvider: RecommendApiCallsProvider, private val buildConfig: BuildConfigWrapper, private val unifiedAboutTracker: UnifiedAboutTracker ) : ViewModel() { private val _onNavigation = MutableLiveData<Event<UnifiedAboutNavigationAction>>() val onNavigation: LiveData<Event<UnifiedAboutNavigationAction>> = _onNavigation fun getAboutConfig() = AboutConfig( headerConfig = HeaderConfig.fromContext(contextProvider.getContext()), shareConfigFactory = ::createShareConfig, rateUsConfig = RateUsConfig.fromContext(contextProvider.getContext()), socialsConfig = SocialsConfig( twitterUsername = if (buildConfig.isJetpackApp) JP_SOCIAL_HANDLE else WP_SOCIAL_HANDLE ), customItems = listOf( ItemConfig( name = BLOG_ITEM_NAME, title = blogTitle(), onClick = ::onBlogClick ) ), legalConfig = LegalConfig( tosUrl = wpUrlUtils.buildTermsOfServiceUrl(contextProvider.getContext()), privacyPolicyUrl = Constants.URL_PRIVACY_POLICY, acknowledgementsUrl = LICENSES_FILE_URL ), automatticConfig = AutomatticConfig(isVisible = buildConfig.isJetpackApp), workWithUsConfig = WorkWithUsConfig( title = workWithUsTitle(), subtitle = workWithUsSubTitle(), url = if (buildConfig.isJetpackApp) JP_WORK_WITH_US_URL else WP_CONTRIBUTE_URL ), aboutFooterConfig = AboutFooterConfig(isVisible = buildConfig.isJetpackApp), analyticsConfig = AnalyticsConfig( trackScreenShown = unifiedAboutTracker::trackScreenShown, trackScreenDismissed = unifiedAboutTracker::trackScreenDismissed, trackButtonTapped = unifiedAboutTracker::trackButtonTapped ), onDismiss = ::onDismiss ) private suspend fun createShareConfig(): ShareConfig { val app = if (buildConfig.isJetpackApp) Jetpack else WordPress val result = recommendApiCallsProvider.getRecommendTemplate(app.appName, ABOUT) return ShareConfig( subject = contextProvider.getContext().getString(R.string.recommend_app_subject), message = when (result) { is Failure -> { AppLog.e(T.MAIN, "Couldn't fetch recommend app template: ${result.error}") // Returning generic message containing only the apps page URL if (buildConfig.isJetpackApp) JP_APPS_URL else WP_APPS_URL } is Success -> "${result.templateData.message}\n${result.templateData.link}" } ) } private fun onDismiss() { _onNavigation.postValue(Event(Dismiss)) } private fun onBlogClick() { _onNavigation.postValue(Event(OpenBlog(if (buildConfig.isJetpackApp) JP_BLOG_URL else WP_BLOG_URL))) } private fun blogTitle() = if (buildConfig.isJetpackApp) { contextProvider.getContext().getString(R.string.about_blog) } else { contextProvider.getContext().getString(R.string.about_news) } private fun workWithUsTitle() = if (buildConfig.isJetpackApp) { contextProvider.getContext().getString(R.string.about_automattic_work_with_us_item_title) } else { contextProvider.getContext().getString(R.string.about_automattic_contribute_item_title) } private fun workWithUsSubTitle() = if (buildConfig.isJetpackApp) { contextProvider.getContext().getString(R.string.about_automattic_work_with_us_item_subtitle) } else { null } companion object { private const val BLOG_ITEM_NAME = "blog" private const val LICENSES_FILE_URL = "file:///android_asset/licenses.html" private const val WP_SOCIAL_HANDLE = "WPAndroid" private const val WP_APPS_URL = "https://apps.wordpress.com" private const val WP_BLOG_URL = "https://wordpress.org/news/" private const val WP_CONTRIBUTE_URL = "https://make.wordpress.org/mobile/handbook/" private const val JP_SOCIAL_HANDLE = "jetpack" private const val JP_APPS_URL = "https://jetpack.com/app" private const val JP_BLOG_URL = "https://jetpack.com/blog" private const val JP_WORK_WITH_US_URL = "https://automattic.com/work-with-us/" } }
WordPress/src/main/java/org/wordpress/android/ui/about/UnifiedAboutViewModel.kt
2550065691
package com.rohitsuratekar.NCBSinfo.database import android.os.AsyncTask import android.util.Log import com.rohitsuratekar.NCBSinfo.R import com.rohitsuratekar.NCBSinfo.common.Constants import com.rohitsuratekar.NCBSinfo.common.convertToList import com.rohitsuratekar.NCBSinfo.common.serverTimestamp import com.rohitsuratekar.NCBSinfo.di.Repository import com.rohitsuratekar.NCBSinfo.models.Route import java.text.SimpleDateFormat import java.util.* private const val TAG = "CheckRoute" class CheckRoutes(private val repository: Repository, private val listener: OnFinishRetrieving) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { val routes = repository.data().getAllRoutes() if (routes.isEmpty()) { makeDefaultRoutes() } else { listener.dataLoadFinished() } return null } private fun makeDefaultRoutes() { Log.i(TAG, "Making default routes.") listener.changeStatus(repository.app().getString(R.string.making_default)) val creationString = "2018-07-21 00:00:00" val modifiedString = "2020-10-08 00:00:00" val readableFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH) val creationDate = Calendar.getInstance() val modifiedDate = Calendar.getInstance() creationDate.timeInMillis = readableFormat.parse(creationString)?.time!! modifiedDate.timeInMillis = readableFormat.parse(modifiedString)?.time!! //NCBS - IISC Shuttle val r1 = makeRoute("ncbs", "iisc", "shuttle", creationDate, modifiedDate) makeTrips( r1, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_ncbs_iisc_week)) ) makeTrips( r1, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_ncbs_iisc_sunday)) ) // IISC - NCBS Shuttle val r2 = makeRoute("iisc", "ncbs", "shuttle", creationDate, modifiedDate) makeTrips( r2, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_iisc_ncbs_week)) ) makeTrips( r2, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_iisc_ncbs_sunday)) ) //NCBS - Mandara Shuttle val r3 = makeRoute("ncbs", "mandara", "shuttle", creationDate, modifiedDate) makeTrips( r3, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_ncbs_mandara_week)) ) makeTrips( r3, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_ncbs_mandara_sunday)) ) //Mandara - NCBS Shuttle val r4 = makeRoute("mandara", "ncbs", "shuttle", creationDate, modifiedDate) makeTrips( r4, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_mandara_ncbs_week)) ) makeTrips( r4, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_mandara_ncbs_sunday)) ) //NCBS - Mandara Buggy val r5 = makeRoute("ncbs", "mandara", "buggy", creationDate, modifiedDate) makeTrips( r5, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_buggy_from_ncbs)) ) //Mandara - NCBS Buggy val r6 = makeRoute("mandara", "ncbs", "buggy", creationDate, modifiedDate) makeTrips( r6, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_buggy_from_mandara)) ) //NCBS - ICTS Shuttle val r7 = makeRoute("ncbs", "icts", "shuttle", creationDate, modifiedDate) makeTrips( r7, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_ncbs_icts_week)) ) makeTrips( r7, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_ncbs_icts_sunday)) ) //ICTS-NCBS Shuttle val r8 = makeRoute("icts", "ncbs", "shuttle", creationDate, modifiedDate) makeTrips( r8, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_icts_ncbs_week)) ) makeTrips( r8, Calendar.SUNDAY, convertToList(repository.app().getString(R.string.def_icts_ncbs_sunday)) ) //NCBS-CBL TTC val r9 = makeRoute("ncbs", "cbl", "ttc", creationDate, modifiedDate) makeTrips( r9, Calendar.MONDAY, convertToList(repository.app().getString(R.string.def_ncbs_cbl)) ) val routeList = repository.data().getAllRoutes() val returnList = mutableListOf<Route>() for (r in routeList) { val tps = repository.data().getTrips(r) if (tps.isNotEmpty()) { returnList.add(Route(r, repository.data().getTrips(r))) } else { repository.data().deleteRoute(r) } } listener.returnRoutes(returnList) // If default data is reset, no need to check database update, hence update the "UPDATE_VERSION" repository.prefs().updateVersion(Constants.UPDATE_VERSION) // Finish database loading listener.dataLoadFinished() } private fun makeRoute( originString: String, destinationString: String, typeString: String, creation: Calendar, modified: Calendar ): RouteData { val route = RouteData().apply { origin = originString.toLowerCase(Locale.getDefault()) destination = destinationString.toLowerCase(Locale.getDefault()) type = typeString.toLowerCase(Locale.getDefault()) createdOn = creation.serverTimestamp() modifiedOn = modified.serverTimestamp() syncedOn = modified.serverTimestamp() favorite = "no" author = Constants.DEFAULT_AUTHOR } val no = repository.data().addRoute(route) route.routeID = no.toInt() Log.i(TAG, "New route $originString - $destinationString $typeString is made") return route } private fun makeTrips(route: RouteData, tripDay: Int, tripsList: List<String>) { val tripData = TripData().apply { routeID = route.routeID trips = tripsList day = tripDay } tripData.trips?.let { if (it.isNotEmpty()) { repository.data().addTrips(tripData) } } } } interface OnFinishRetrieving { fun dataLoadFinished() fun changeStatus(statusNote: String) fun returnRoutes(routeList: List<Route>) }
app/src/main/java/com/rohitsuratekar/NCBSinfo/database/CheckRoutes.kt
4207833995
package org.wordpress.android.ui.sitecreation.previews import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.content.res.Configuration import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import android.view.View.OnLayoutChangeListener import android.view.animation.DecelerateInterpolator import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.FullscreenErrorWithRetryBinding import org.wordpress.android.databinding.SiteCreationFormScreenBinding import org.wordpress.android.databinding.SiteCreationPreviewScreenBinding import org.wordpress.android.databinding.SiteCreationPreviewScreenDefaultBinding import org.wordpress.android.databinding.SiteCreationProgressCreatingSiteBinding import org.wordpress.android.ui.accounts.HelpActivity import org.wordpress.android.ui.sitecreation.SiteCreationBaseFormFragment import org.wordpress.android.ui.sitecreation.SiteCreationState import org.wordpress.android.ui.sitecreation.misc.OnHelpClickedListener import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewData import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewContentUiState import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewFullscreenErrorUiState import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewFullscreenProgressUiState import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewLoadingShimmerState import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewWebErrorUiState import org.wordpress.android.ui.sitecreation.services.SiteCreationService import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.AniUtils import org.wordpress.android.util.AppLog import org.wordpress.android.util.AutoForeground.ServiceEventConnection import org.wordpress.android.util.ErrorManagedWebViewClient.ErrorManagedWebViewClientListener import org.wordpress.android.util.URLFilteredWebViewClient import javax.inject.Inject private const val ARG_DATA = "arg_site_creation_data" private const val SLIDE_IN_ANIMATION_DURATION = 450L @AndroidEntryPoint class SiteCreationPreviewFragment : SiteCreationBaseFormFragment(), ErrorManagedWebViewClientListener { /** * We need to connect to the service, so the service knows when the app is in the background. The service * automatically shows system notifications when site creation is in progress and the app is in the background. */ private var serviceEventConnection: ServiceEventConnection? = null private val viewModel: SitePreviewViewModel by viewModels() private var animatorSet: AnimatorSet? = null private val isLandscape: Boolean get() = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE @Inject internal lateinit var uiHelpers: UiHelpers private var binding: SiteCreationPreviewScreenBinding? = null @Suppress("UseCheckOrError") override fun onAttach(context: Context) { super.onAttach(context) if (context !is SitePreviewScreenListener) { throw IllegalStateException("Parent activity must implement SitePreviewScreenListener.") } if (context !is OnHelpClickedListener) { throw IllegalStateException("Parent activity must implement OnHelpClickedListener.") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { // we need to manually clear the SiteCreationService state so we don't for example receive sticky events // from the previous run of the SiteCreation flow. SiteCreationService.clearSiteCreationServiceState() } } @Suppress("DEPRECATION") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (requireActivity() as AppCompatActivity).supportActionBar?.hide() viewModel.start(requireArguments()[ARG_DATA] as SiteCreationState, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (requireActivity() as AppCompatActivity).supportActionBar?.hide() viewModel.start(requireArguments()[ARG_DATA] as SiteCreationState, savedInstanceState) } override fun getContentLayout(): Int { return R.layout.site_creation_preview_screen } @Suppress("UseCheckOrError") override val screenTitle: String get() = arguments?.getString(EXTRA_SCREEN_TITLE) ?: throw IllegalStateException("Required argument screen title is missing.") override fun setBindingViewStubListener(parentBinding: SiteCreationFormScreenBinding) { parentBinding.siteCreationFormContentStub.setOnInflateListener { _, inflated -> binding = SiteCreationPreviewScreenBinding.bind(inflated) } } override fun setupContent() { binding?.siteCreationPreviewScreenDefault?.initViewModel() binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initRetryButton() binding?.siteCreationPreviewScreenDefault?.initOkButton() binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initCancelWizardButton() binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initContactSupportButton() } private fun SiteCreationPreviewScreenDefaultBinding.initViewModel() { viewModel.uiState.observe(this@SiteCreationPreviewFragment, { uiState -> uiState?.let { when (uiState) { is SitePreviewContentUiState -> updateContentLayout(uiState.data) is SitePreviewWebErrorUiState -> updateContentLayout(uiState.data) is SitePreviewLoadingShimmerState -> updateContentLayout(uiState.data) is SitePreviewFullscreenProgressUiState -> siteCreationProgressCreatingSite.updateLoadingLayout(uiState) is SitePreviewFullscreenErrorUiState -> fullscreenErrorWithRetry.updateErrorLayout(uiState) } uiHelpers.updateVisibility( siteCreationProgressCreatingSite.progressLayout, uiState.fullscreenProgressLayoutVisibility ) uiHelpers.updateVisibility(contentLayout, uiState.contentLayoutVisibility) uiHelpers.updateVisibility( siteCreationPreviewWebViewContainer.sitePreviewWebView, uiState.webViewVisibility ) uiHelpers.updateVisibility( siteCreationPreviewWebViewContainer.sitePreviewWebError, uiState.webViewErrorVisibility ) uiHelpers.updateVisibility( siteCreationPreviewWebViewContainer.sitePreviewWebViewShimmerLayout, uiState.shimmerVisibility ) uiHelpers.updateVisibility( fullscreenErrorWithRetry.errorLayout, uiState.fullscreenErrorLayoutVisibility ) } }) viewModel.preloadPreview.observe(this@SiteCreationPreviewFragment, { url -> url?.let { urlString -> siteCreationPreviewWebViewContainer.sitePreviewWebView.webViewClient = URLFilteredWebViewClient(urlString, this@SiteCreationPreviewFragment) siteCreationPreviewWebViewContainer.sitePreviewWebView.settings.userAgentString = WordPress.getUserAgent() siteCreationPreviewWebViewContainer.sitePreviewWebView.loadUrl(urlString) } }) viewModel.startCreateSiteService.observe(this@SiteCreationPreviewFragment, { startServiceData -> startServiceData?.let { SiteCreationService.createSite( requireNotNull(activity), startServiceData.previousState, startServiceData.serviceData ) } }) initClickObservers() } private fun initClickObservers() { viewModel.onHelpClicked.observe(this, { (requireActivity() as OnHelpClickedListener).onHelpClicked(HelpActivity.Origin.SITE_CREATION_CREATING) }) viewModel.onSiteCreationCompleted.observe(this, { (requireActivity() as SitePreviewScreenListener).onSiteCreationCompleted() }) viewModel.onOkButtonClicked.observe(this, { createSiteState -> createSiteState?.let { (requireActivity() as SitePreviewScreenListener).onSitePreviewScreenDismissed(createSiteState) } }) viewModel.onCancelWizardClicked.observe(this, { createSiteState -> createSiteState?.let { (requireActivity() as SitePreviewScreenListener).onSitePreviewScreenDismissed(createSiteState) } }) } private fun FullscreenErrorWithRetryBinding.initRetryButton() { errorRetry.setOnClickListener { viewModel.retry() } } private fun SiteCreationPreviewScreenDefaultBinding.initOkButton() { okButton.setOnClickListener { viewModel.onOkButtonClicked() } } private fun FullscreenErrorWithRetryBinding.initCancelWizardButton() { cancelWizardButton.setOnClickListener { viewModel.onCancelWizardClicked() } } private fun FullscreenErrorWithRetryBinding.initContactSupportButton() { contactSupport.setOnClickListener { viewModel.onHelpClicked() } } private fun SiteCreationPreviewScreenDefaultBinding.updateContentLayout(sitePreviewData: SitePreviewData) { sitePreviewData.apply { siteCreationPreviewWebViewContainer.sitePreviewWebUrlTitle.text = createSpannableUrl( requireNotNull(activity), shortUrl, subDomainIndices, domainIndices ) } if (contentLayout.visibility == View.GONE) { animateContentTransition() view?.announceForAccessibility( getString(R.string.new_site_creation_preview_title) + getString(R.string.new_site_creation_site_preview_content_description) ) } } private fun SiteCreationProgressCreatingSiteBinding.updateLoadingLayout( progressUiState: SitePreviewFullscreenProgressUiState ) { progressUiState.apply { val newText = uiHelpers.getTextOfUiString(progressText.context, loadingTextResId) AppLog.d(AppLog.T.MAIN, "Changing text - animation: $animate") if (animate) { updateLoadingTextWithFadeAnimation(newText) } else { progressText.text = newText } } } private fun SiteCreationProgressCreatingSiteBinding.updateLoadingTextWithFadeAnimation(newText: CharSequence) { val animationDuration = AniUtils.Duration.SHORT val fadeOut = AniUtils.getFadeOutAnim( progressTextLayout, animationDuration, View.VISIBLE ) val fadeIn = AniUtils.getFadeInAnim( progressTextLayout, animationDuration ) // update the text when the view isn't visible fadeIn.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { progressText.text = newText } override fun onAnimationEnd(animation: Animator?) { super.onAnimationEnd(animation) animatorSet = null } }) // Start the fade-in animation right after the view fades out fadeIn.startDelay = animationDuration.toMillis(progressTextLayout.context) animatorSet = AnimatorSet().apply { playSequentially(fadeOut, fadeIn) start() } } private fun FullscreenErrorWithRetryBinding.updateErrorLayout( errorUiStateState: SitePreviewFullscreenErrorUiState ) { errorUiStateState.apply { uiHelpers.setTextOrHide(errorTitle, titleResId) uiHelpers.setTextOrHide(errorSubtitle, subtitleResId) uiHelpers.updateVisibility(contactSupport, errorUiStateState.showContactSupport) uiHelpers.updateVisibility(cancelWizardButton, errorUiStateState.showCancelWizardButton) } } /** * Creates a spannable url with 2 different text colors for the subdomain and domain. * * @param context Context to get the color resources * @param url The url to be used to created the spannable from * @param subdomainSpan The subdomain index pair for the start and end positions * @param domainSpan The domain index pair for the start and end positions * * @return [Spannable] styled with two different colors for the subdomain and domain parts */ private fun createSpannableUrl( context: Context, url: String, subdomainSpan: Pair<Int, Int>, domainSpan: Pair<Int, Int> ): Spannable { val spannableTitle = SpannableString(url) spannableTitle.setSpan( ForegroundColorSpan(ContextCompat.getColor(context, R.color.neutral_80)), subdomainSpan.first, subdomainSpan.second, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) spannableTitle.setSpan( ForegroundColorSpan(ContextCompat.getColor(context, R.color.neutral_40)), domainSpan.first, domainSpan.second, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return spannableTitle } override fun onWebViewPageLoaded() { viewModel.onUrlLoaded() } override fun onWebViewReceivedError() { viewModel.onWebViewError() } override fun onHelp() { viewModel.onHelpClicked() } private fun SiteCreationPreviewScreenDefaultBinding.animateContentTransition() { contentLayout.addOnLayoutChangeListener( object : OnLayoutChangeListener { override fun onLayoutChange( v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ) { if (meetsHeightWidthForAnimation()) { contentLayout.removeOnLayoutChangeListener(this) val contentHeight = contentLayout.measuredHeight.toFloat() val titleAnim = createFadeInAnimator(siteCreationPreviewHeaderItem.sitePreviewTitle) val webViewAnim = createSlideInFromBottomAnimator( siteCreationPreviewWebViewContainer.webViewContainer, contentHeight ) // OK button should slide in if the container exists and fade in otherwise // difference between land & portrait val okAnim = if (isLandscape) { createFadeInAnimator(okButton) } else { createSlideInFromBottomAnimator(sitePreviewOkButtonContainer as View, contentHeight) } // There is a chance that either of the following fields can be null, // so to avoid a NPE, we only execute playTogether if they are both not null if (titleAnim != null && okAnim != null) { AnimatorSet().apply { interpolator = DecelerateInterpolator() duration = SLIDE_IN_ANIMATION_DURATION playTogether(titleAnim, webViewAnim, okAnim) start() } } } } }) } private fun SiteCreationPreviewScreenDefaultBinding.meetsHeightWidthForAnimation() = contentLayout.measuredWidth > 0 && contentLayout.measuredHeight > 0 private fun createSlideInFromBottomAnimator(view: View, contentHeight: Float): ObjectAnimator { return ObjectAnimator.ofFloat( view, "translationY", // start below the bottom edge of the display (contentHeight - view.top), 0f ) } private fun createFadeInAnimator(view: View) = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f) override fun onResume() { super.onResume() serviceEventConnection = ServiceEventConnection(context, SiteCreationService::class.java, viewModel) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) viewModel.writeToBundle(outState) } override fun onPause() { super.onPause() serviceEventConnection?.disconnect(context, viewModel) } override fun onStop() { super.onStop() if (animatorSet?.isRunning == true) { animatorSet?.cancel() } } companion object { const val TAG = "site_creation_preview_fragment_tag" fun newInstance( screenTitle: String, siteCreationData: SiteCreationState ): SiteCreationPreviewFragment { val fragment = SiteCreationPreviewFragment() val bundle = Bundle() bundle.putString(EXTRA_SCREEN_TITLE, screenTitle) bundle.putParcelable(ARG_DATA, siteCreationData) fragment.arguments = bundle return fragment } } }
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SiteCreationPreviewFragment.kt
514146715
package com.edwardharker.aircraftrecognition.model sealed class FeedbackResult { object Success : FeedbackResult() object Error : FeedbackResult() }
recognition/src/main/kotlin/com/edwardharker/aircraftrecognition/model/FeedbackResult.kt
1297974129
/* * Copyright 2022 LINE Corporation * * LINE Corporation 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: * * 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.linecorp.armeria.internal.server.annotation import com.fasterxml.jackson.annotation.JsonProperty import com.linecorp.armeria.internal.server.annotation.AnnotatedDocServicePlugin.STRING import com.linecorp.armeria.server.annotation.Description import com.linecorp.armeria.server.docs.DescriptionInfo import com.linecorp.armeria.server.docs.EnumInfo import com.linecorp.armeria.server.docs.EnumValueInfo import com.linecorp.armeria.server.docs.FieldInfo import com.linecorp.armeria.server.docs.FieldRequirement import com.linecorp.armeria.server.docs.StructInfo import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource class DataClassDefaultNameTypeInfoProviderTest { @CsvSource(value = ["true", "false"]) @ParameterizedTest fun dataClass(request: Boolean) { val provider = DefaultNamedTypeInfoProvider(request) val struct: StructInfo = (provider.newNamedTypeInfo(DescriptionResult::class.java) as StructInfo) assertThat(struct.name()).isEqualTo(DescriptionResult::class.java.name) assertThat(struct.descriptionInfo()).isEqualTo(DescriptionInfo.of("Class description")) assertThat(struct.fields()).containsExactlyInAnyOrder( FieldInfo.builder("required", STRING) .requirement(FieldRequirement.REQUIRED) .descriptionInfo(DescriptionInfo.of("required description")) .build(), FieldInfo.builder("optional", STRING) .requirement(FieldRequirement.OPTIONAL) .descriptionInfo(DescriptionInfo.of("optional description")) .build(), FieldInfo.builder("defaultValue", STRING) .requirement(FieldRequirement.REQUIRED) .descriptionInfo(DescriptionInfo.of("default value description")) .build(), FieldInfo.builder("defaultValue2", STRING) .requirement(FieldRequirement.REQUIRED) .descriptionInfo(DescriptionInfo.of("default value 2 description")) .build(), FieldInfo.builder("renamedNonnull", STRING) .requirement(FieldRequirement.REQUIRED) .descriptionInfo(DescriptionInfo.of("renamed nonnull description")) .build(), FieldInfo.builder("renamedNullable", STRING) .requirement(FieldRequirement.OPTIONAL) .descriptionInfo(DescriptionInfo.of("renamed nullable description")) .build() ) } @CsvSource(value = ["true", "false"]) @ParameterizedTest fun enumClass(request: Boolean) { val requestProvider = DefaultNamedTypeInfoProvider(request) val enumInfo: EnumInfo = (requestProvider.newNamedTypeInfo(EnumParam::class.java) as EnumInfo) assertThat(enumInfo.name()).isEqualTo(EnumParam::class.java.name) assertThat(enumInfo.descriptionInfo()).isEqualTo(DescriptionInfo.of("Enum description")) assertThat(enumInfo.values()).containsExactlyInAnyOrder( EnumValueInfo("ENUM_1", null, DescriptionInfo.of("ENUM_1 description")), EnumValueInfo("ENUM_2", null, DescriptionInfo.of("ENUM_2 description")) ) } @Description(value = "Class description") data class DescriptionResult( @Description(value = "required description") val required: String, @Description(value = "optional description") val optional: String?, @Description(value = "default value description") val defaultValue: String = "Hello", @Description(value = "default value 2 description") val defaultValue2: String = "Hello2", @JsonProperty("renamedNonnull") @Description("renamed nonnull description") val nonnullName: String, @JsonProperty("renamedNullable") @Description("renamed nullable description") val nullableName: String? ) @Description("Enum description") enum class EnumParam { @Description(value = "ENUM_1 description") ENUM_1, @Description(value = "ENUM_2 description") ENUM_2 } }
kotlin/src/test/kotlin/com/linecorp/armeria/internal/server/annotation/DataClassDefaultNameTypeInfoProviderTest.kt
2555857953
package org.wordpress.android.modules import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import org.wordpress.android.fluxc.module.DatabaseModule import org.wordpress.android.fluxc.module.OkHttpClientModule import org.wordpress.android.fluxc.module.ReleaseNetworkModule import org.wordpress.android.fluxc.module.ReleaseToolsModule @InstallIn(SingletonComponent::class) @Module( includes = [ ReleaseNetworkModule::class, OkHttpClientModule::class, ReleaseToolsModule::class, DatabaseModule::class ] ) interface FluxCModule
WordPress/src/main/java/org/wordpress/android/modules/FluxCModule.kt
3287497289
// INTENTION_TEXT: "Convert to 'onEachIndexed'" // WITH_STDLIB // AFTER-WARNING: Parameter 'index' is never used, could be renamed to _ fun test(list: List<String>) { list.<caret>onEach { s -> println(s) } }
plugins/kotlin/idea/tests/testData/intentions/convertToIndexedFunctionCall/basic/onEach.kt
3822980153
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script import org.jetbrains.kotlin.script.ScriptTemplatesProvider import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.definitions.getEnvironment import kotlin.script.experimental.host.ScriptingHostConfiguration import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration internal class ScriptTemplatesProviderAdapter(private val templatesProvider: ScriptTemplatesProvider) : ScriptDefinitionSourceAsContributor { override val id: String get() = templatesProvider.id override val definitions: Sequence<ScriptDefinition> get() { return loadDefinitionsFromTemplates( templatesProvider.templateClassNames.toList(), templatesProvider.templateClasspath, ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) { getEnvironment { templatesProvider.environment } }, templatesProvider.additionalResolverClasspath ).asSequence() } }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ScriptTemplatesProviderAdapter.kt
4139718305
// 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.refactoring.memberInfo import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.classMembers.MemberInfoBase import com.intellij.refactoring.util.classMembers.MemberInfo import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinMemberInfo @JvmOverloads constructor( member: KtNamedDeclaration, val isSuperClass: Boolean = false, val isCompanionMember: Boolean = false ) : MemberInfoBase<KtNamedDeclaration>(member) { companion object { private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { modifiers = setOf(DescriptorRendererModifier.INNER) } } init { val memberDescriptor = member.resolveToDescriptorWrapperAware() isStatic = member.parent is KtFile if ((member is KtClass || member is KtPsiClassWrapper) && isSuperClass) { if (member.isInterfaceClass()) { displayName = RefactoringBundle.message("member.info.implements.0", member.name) overrides = false } else { displayName = RefactoringBundle.message("member.info.extends.0", member.name) overrides = true } } else { displayName = RENDERER.render(memberDescriptor) if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { displayName = KotlinBundle.message("member.info.abstract.0", displayName) } if (isCompanionMember) { displayName = KotlinBundle.message("member.info.companion.0", displayName) } val overriddenDescriptors = (memberDescriptor as? CallableMemberDescriptor)?.overriddenDescriptors ?: emptySet() if (overriddenDescriptors.isNotEmpty()) { overrides = overriddenDescriptors.any { it.modality != Modality.ABSTRACT } } } } } fun lightElementForMemberInfo(declaration: KtNamedDeclaration?): PsiMember? { return when (declaration) { is KtNamedFunction -> declaration.getRepresentativeLightMethod() is KtProperty, is KtParameter -> declaration.toLightElements().let { it.firstIsInstanceOrNull<PsiMethod>() ?: it.firstIsInstanceOrNull<PsiField>() } as PsiMember? is KtClassOrObject -> declaration.toLightClass() is KtPsiClassWrapper -> declaration.psiClass else -> null } } fun MemberInfoBase<out KtNamedDeclaration>.toJavaMemberInfo(): MemberInfo? { val declaration = member val psiMember: PsiMember? = lightElementForMemberInfo(declaration) val info = MemberInfo(psiMember ?: return null, psiMember is PsiClass && overrides != null, null) info.isToAbstract = isToAbstract info.isChecked = isChecked return info } fun MemberInfo.toKotlinMemberInfo(): KotlinMemberInfo? { val declaration = member.unwrapped as? KtNamedDeclaration ?: return null return KotlinMemberInfo(declaration, declaration is KtClass && overrides != null).apply { this.isToAbstract = [email protected] } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt
3693469434
package com.kelsos.mbrc.commands.model import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.kelsos.mbrc.data.LyricsPayload import com.kelsos.mbrc.interfaces.ICommand import com.kelsos.mbrc.interfaces.IEvent import com.kelsos.mbrc.model.LyricsModel import javax.inject.Inject class UpdateLyrics @Inject constructor( private val model: LyricsModel, private val mapper: ObjectMapper ) : ICommand { override fun execute(e: IEvent) { val payload = mapper.treeToValue((e.data as JsonNode), LyricsPayload::class.java) model.status = payload.status if (payload.status == LyricsPayload.SUCCESS) { model.lyrics = payload.lyrics } else { model.lyrics = "" } } }
app/src/main/kotlin/com/kelsos/mbrc/commands/model/UpdateLyrics.kt
2157541265
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.conventionNameCalls import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.calleeName import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.types.expressions.OperatorConventions class ReplaceCallWithUnaryOperatorIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.call.with.unary.operator") ), HighPriorityAction { override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? { val operation = operation(element.calleeName) ?: return null if (!isApplicableOperation(operation)) return null val call = element.callExpression ?: return null if (call.typeArgumentList != null) return null if (call.valueArguments.isNotEmpty()) return null if (!element.isReceiverExpressionWithValue()) return null setTextGetter(KotlinBundle.lazyMessage("replace.with.0.operator", operation.value)) return call.calleeExpression?.textRange } override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) { val operation = operation(element.calleeName)?.value ?: return val receiver = element.receiverExpression element.replace(KtPsiFactory(element).createExpressionByPattern("$0$1", operation, receiver)) } private fun isApplicableOperation(operation: KtSingleValueToken): Boolean = operation !in OperatorConventions.INCREMENT_OPERATIONS private fun operation(functionName: String?): KtSingleValueToken? = functionName?.let { OperatorConventions.UNARY_OPERATION_NAMES.inverse()[Name.identifier(it)] } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithUnaryOperatorIntention.kt
195931080
// FIR_IDENTICAL // FIR_COMPARISON // WITH_STDLIB fun buildTemplates() { val kotlin = 42 printl<caret> } // ELEMENT: println // TAIL_TEXT: "() (kotlin.io)"
plugins/kotlin/completion/tests/testData/handlers/basic/ClassNameForMethodWithPackageConflict.kt
4037677737
// 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.base.codeInsight.tooling import com.intellij.openapi.roots.libraries.PersistentLibraryKind import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform import org.jetbrains.kotlin.idea.testIntegration.framework.KotlinTestFramework import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.utils.PathUtil import javax.swing.Icon abstract class AbstractJvmIdePlatformKindTooling : IdePlatformKindTooling() { override val kind = JvmIdePlatformKind override val mavenLibraryIds = listOf( PathUtil.KOTLIN_JAVA_STDLIB_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME ) override val gradlePluginId = "kotlin-platform-jvm" override val gradlePlatformIds: List<KotlinPlatform> get() = listOf(KotlinPlatform.JVM, KotlinPlatform.ANDROID) override val libraryKind: PersistentLibraryKind<*>? = null override fun acceptsAsEntryPoint(function: KtFunction) = true override fun getTestIcon(declaration: KtNamedDeclaration, allowSlowOperations: Boolean): Icon? { val urls = calculateUrls(declaration, allowSlowOperations) if (urls != null) { return KotlinTestRunLineMarkerContributor.getTestStateIcon(urls, declaration) } else if (allowSlowOperations) { return testIconProvider.getGenericTestIcon(declaration, emptyList()) } return null } private fun calculateUrls(declaration: KtNamedDeclaration, includeSlowProviders: Boolean? = null): List<String>? { val testFramework = KotlinTestFramework.getApplicableFor(declaration, includeSlowProviders?.takeUnless { it }) ?: return null val relevantProvider = includeSlowProviders == null || includeSlowProviders == testFramework.isSlow if (!relevantProvider) return null val qualifiedName = testFramework.qualifiedName(declaration) ?: return null return when (declaration) { is KtClassOrObject -> listOf("java:suite://$qualifiedName") is KtNamedFunction -> listOf( "java:test://$qualifiedName/${declaration.name}", "java:test://$qualifiedName.${declaration.name}" ) else -> null } } }
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/tooling/AbstractJvmIdePlatformKindTooling.kt
662104129
package org.snakeskin.utility.value class HistoryByte(initialValue: Byte = Byte.MIN_VALUE) { var last = initialValue @Synchronized get private set var current = initialValue @Synchronized get private set @Synchronized fun update(newValue: Byte) { last = current current = newValue } /** * Returns true if the value changed from its previous value since the last call to "update" */ fun changed(): Boolean { return current != last } //Numeric operations /** * Returns the difference between the current value and the last value * Returns an Int, as byte subtraction in Kotlin returns an Int */ fun delta(): Int { return current - last } }
SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/HistoryByte.kt
3340302449
package org.thoughtcrime.securesms.components.webrtc import android.content.Context import androidx.annotation.PluralsRes import androidx.annotation.StringRes import com.annimon.stream.OptionalLong import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.webrtc.WebRtcControls.FoldableState import org.thoughtcrime.securesms.events.CallParticipant import org.thoughtcrime.securesms.events.CallParticipant.Companion.createLocal import org.thoughtcrime.securesms.events.WebRtcViewModel import org.thoughtcrime.securesms.groups.ui.GroupMemberEntry import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.ringrtc.CameraState import org.thoughtcrime.securesms.service.webrtc.collections.ParticipantCollection import java.util.concurrent.TimeUnit /** * Represents the state of all participants, remote and local, combined with view state * needed to properly render the participants. The view state primarily consists of * if we are in System PIP mode and if we should show our video for an outgoing call. */ data class CallParticipantsState( val callState: WebRtcViewModel.State = WebRtcViewModel.State.CALL_DISCONNECTED, val groupCallState: WebRtcViewModel.GroupCallState = WebRtcViewModel.GroupCallState.IDLE, private val remoteParticipants: ParticipantCollection = ParticipantCollection(SMALL_GROUP_MAX), val localParticipant: CallParticipant = createLocal(CameraState.UNKNOWN, BroadcastVideoSink(), false), val focusedParticipant: CallParticipant = CallParticipant.EMPTY, val localRenderState: WebRtcLocalRenderState = WebRtcLocalRenderState.GONE, val isInPipMode: Boolean = false, private val showVideoForOutgoing: Boolean = false, val isViewingFocusedParticipant: Boolean = false, val remoteDevicesCount: OptionalLong = OptionalLong.empty(), private val foldableState: FoldableState = FoldableState.flat(), val isInOutgoingRingingMode: Boolean = false, val ringGroup: Boolean = false, val ringerRecipient: Recipient = Recipient.UNKNOWN, val groupMembers: List<GroupMemberEntry.FullMember> = emptyList() ) { val allRemoteParticipants: List<CallParticipant> = remoteParticipants.allParticipants val isFolded: Boolean = foldableState.isFolded val isLargeVideoGroup: Boolean = allRemoteParticipants.size > SMALL_GROUP_MAX val isIncomingRing: Boolean = callState == WebRtcViewModel.State.CALL_INCOMING val gridParticipants: List<CallParticipant> get() { return remoteParticipants.gridParticipants } val listParticipants: List<CallParticipant> get() { val listParticipants: MutableList<CallParticipant> = mutableListOf() if (isViewingFocusedParticipant && allRemoteParticipants.size > 1) { listParticipants.addAll(allRemoteParticipants) listParticipants.remove(focusedParticipant) } else { listParticipants.addAll(remoteParticipants.listParticipants) } if (foldableState.isFlat) { listParticipants.add(CallParticipant.EMPTY) } listParticipants.reverse() return listParticipants } val participantCount: OptionalLong get() { val includeSelf = groupCallState == WebRtcViewModel.GroupCallState.CONNECTED_AND_JOINED return remoteDevicesCount.map { l: Long -> l + if (includeSelf) 1L else 0L } .or { if (includeSelf) OptionalLong.of(1L) else OptionalLong.empty() } } fun getPreJoinGroupDescription(context: Context): String? { if (callState != WebRtcViewModel.State.CALL_PRE_JOIN || groupCallState.isIdle) { return null } return if (remoteParticipants.isEmpty) { describeGroupMembers( context = context, oneParticipant = if (ringGroup) R.string.WebRtcCallView__signal_will_ring_s else R.string.WebRtcCallView__s_will_be_notified, twoParticipants = if (ringGroup) R.string.WebRtcCallView__signal_will_ring_s_and_s else R.string.WebRtcCallView__s_and_s_will_be_notified, multipleParticipants = if (ringGroup) R.plurals.WebRtcCallView__signal_will_ring_s_s_and_d_others else R.plurals.WebRtcCallView__s_s_and_d_others_will_be_notified, members = groupMembers ) } else { when (remoteParticipants.size()) { 0 -> context.getString(R.string.WebRtcCallView__no_one_else_is_here) 1 -> context.getString(if (remoteParticipants[0].isSelf) R.string.WebRtcCallView__s_are_in_this_call else R.string.WebRtcCallView__s_is_in_this_call, remoteParticipants[0].getShortRecipientDisplayName(context)) 2 -> context.getString( R.string.WebRtcCallView__s_and_s_are_in_this_call, remoteParticipants[0].getShortRecipientDisplayName(context), remoteParticipants[1].getShortRecipientDisplayName(context) ) else -> { val others = remoteParticipants.size() - 2 context.resources.getQuantityString( R.plurals.WebRtcCallView__s_s_and_d_others_are_in_this_call, others, remoteParticipants[0].getShortRecipientDisplayName(context), remoteParticipants[1].getShortRecipientDisplayName(context), others ) } } } } fun getOutgoingRingingGroupDescription(context: Context): String? { if (callState == WebRtcViewModel.State.CALL_CONNECTED && groupCallState == WebRtcViewModel.GroupCallState.CONNECTED_AND_JOINED && isInOutgoingRingingMode ) { return describeGroupMembers( context = context, oneParticipant = R.string.WebRtcCallView__ringing_s, twoParticipants = R.string.WebRtcCallView__ringing_s_and_s, multipleParticipants = R.plurals.WebRtcCallView__ringing_s_s_and_d_others, members = groupMembers ) } return null } fun getIncomingRingingGroupDescription(context: Context): String? { if (callState == WebRtcViewModel.State.CALL_INCOMING && groupCallState == WebRtcViewModel.GroupCallState.RINGING && ringerRecipient.hasUuid() ) { val ringerName = ringerRecipient.getShortDisplayName(context) val membersWithoutYouOrRinger: List<GroupMemberEntry.FullMember> = groupMembers.filterNot { it.member.isSelf || ringerRecipient.requireUuid() == it.member.uuid.orNull() } return when (membersWithoutYouOrRinger.size) { 0 -> context.getString(R.string.WebRtcCallView__s_is_calling_you, ringerName) 1 -> context.getString( R.string.WebRtcCallView__s_is_calling_you_and_s, ringerName, membersWithoutYouOrRinger[0].member.getShortDisplayName(context) ) 2 -> context.getString( R.string.WebRtcCallView__s_is_calling_you_s_and_s, ringerName, membersWithoutYouOrRinger[0].member.getShortDisplayName(context), membersWithoutYouOrRinger[1].member.getShortDisplayName(context) ) else -> { val others = membersWithoutYouOrRinger.size - 2 context.resources.getQuantityString( R.plurals.WebRtcCallView__s_is_calling_you_s_s_and_d_others, others, ringerName, membersWithoutYouOrRinger[0].member.getShortDisplayName(context), membersWithoutYouOrRinger[1].member.getShortDisplayName(context), others ) } } } return null } fun needsNewRequestSizes(): Boolean { return if (groupCallState.isNotIdle) { allRemoteParticipants.any { it.videoSink.needsNewRequestingSize() } } else { false } } companion object { private const val SMALL_GROUP_MAX = 6 @JvmField val MAX_OUTGOING_GROUP_RING_DURATION = TimeUnit.MINUTES.toMillis(1) @JvmField val STARTING_STATE = CallParticipantsState() @JvmStatic fun update( oldState: CallParticipantsState, webRtcViewModel: WebRtcViewModel, enableVideo: Boolean ): CallParticipantsState { var newShowVideoForOutgoing: Boolean = oldState.showVideoForOutgoing if (enableVideo) { newShowVideoForOutgoing = webRtcViewModel.state == WebRtcViewModel.State.CALL_OUTGOING } else if (webRtcViewModel.state != WebRtcViewModel.State.CALL_OUTGOING) { newShowVideoForOutgoing = false } val isInOutgoingRingingMode = if (oldState.isInOutgoingRingingMode) { webRtcViewModel.callConnectedTime + MAX_OUTGOING_GROUP_RING_DURATION > System.currentTimeMillis() && webRtcViewModel.remoteParticipants.size == 0 } else { oldState.ringGroup && webRtcViewModel.callConnectedTime + MAX_OUTGOING_GROUP_RING_DURATION > System.currentTimeMillis() && webRtcViewModel.remoteParticipants.size == 0 && oldState.callState == WebRtcViewModel.State.CALL_OUTGOING && webRtcViewModel.state == WebRtcViewModel.State.CALL_CONNECTED } val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode( oldState = oldState, localParticipant = webRtcViewModel.localParticipant, showVideoForOutgoing = newShowVideoForOutgoing, isNonIdleGroupCall = webRtcViewModel.groupState.isNotIdle, callState = webRtcViewModel.state, numberOfRemoteParticipants = webRtcViewModel.remoteParticipants.size ) return oldState.copy( callState = webRtcViewModel.state, groupCallState = webRtcViewModel.groupState, remoteParticipants = oldState.remoteParticipants.getNext(webRtcViewModel.remoteParticipants), localParticipant = webRtcViewModel.localParticipant, focusedParticipant = getFocusedParticipant(webRtcViewModel.remoteParticipants), localRenderState = localRenderState, showVideoForOutgoing = newShowVideoForOutgoing, remoteDevicesCount = webRtcViewModel.remoteDevicesCount, ringGroup = webRtcViewModel.shouldRingGroup(), isInOutgoingRingingMode = isInOutgoingRingingMode, ringerRecipient = webRtcViewModel.ringerRecipient ) } @JvmStatic fun update(oldState: CallParticipantsState, isInPip: Boolean): CallParticipantsState { val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isInPip = isInPip) return oldState.copy(localRenderState = localRenderState, isInPipMode = isInPip) } @JvmStatic fun setExpanded(oldState: CallParticipantsState, expanded: Boolean): CallParticipantsState { val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isExpanded = expanded) return oldState.copy(localRenderState = localRenderState) } @JvmStatic fun update(oldState: CallParticipantsState, selectedPage: SelectedPage): CallParticipantsState { val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isViewingFocusedParticipant = selectedPage == SelectedPage.FOCUSED) return oldState.copy(localRenderState = localRenderState, isViewingFocusedParticipant = selectedPage == SelectedPage.FOCUSED) } @JvmStatic fun update(oldState: CallParticipantsState, foldableState: FoldableState): CallParticipantsState { val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState) return oldState.copy(localRenderState = localRenderState, foldableState = foldableState) } @JvmStatic fun update(oldState: CallParticipantsState, groupMembers: List<GroupMemberEntry.FullMember>): CallParticipantsState { return oldState.copy(groupMembers = groupMembers) } private fun determineLocalRenderMode( oldState: CallParticipantsState, localParticipant: CallParticipant = oldState.localParticipant, isInPip: Boolean = oldState.isInPipMode, showVideoForOutgoing: Boolean = oldState.showVideoForOutgoing, isNonIdleGroupCall: Boolean = oldState.groupCallState.isNotIdle, callState: WebRtcViewModel.State = oldState.callState, numberOfRemoteParticipants: Int = oldState.allRemoteParticipants.size, isViewingFocusedParticipant: Boolean = oldState.isViewingFocusedParticipant, isExpanded: Boolean = oldState.localRenderState == WebRtcLocalRenderState.EXPANDED ): WebRtcLocalRenderState { val displayLocal: Boolean = (numberOfRemoteParticipants == 0 || !isInPip) && (isNonIdleGroupCall || localParticipant.isVideoEnabled) var localRenderState: WebRtcLocalRenderState = WebRtcLocalRenderState.GONE if (isExpanded && (localParticipant.isVideoEnabled || isNonIdleGroupCall)) { return WebRtcLocalRenderState.EXPANDED } else if (displayLocal || showVideoForOutgoing) { if (callState == WebRtcViewModel.State.CALL_CONNECTED) { localRenderState = if (isViewingFocusedParticipant || numberOfRemoteParticipants > 1) { WebRtcLocalRenderState.SMALLER_RECTANGLE } else if (numberOfRemoteParticipants == 1) { WebRtcLocalRenderState.SMALL_RECTANGLE } else { if (localParticipant.isVideoEnabled) WebRtcLocalRenderState.LARGE else WebRtcLocalRenderState.LARGE_NO_VIDEO } } else if (callState != WebRtcViewModel.State.CALL_INCOMING && callState != WebRtcViewModel.State.CALL_DISCONNECTED) { localRenderState = if (localParticipant.isVideoEnabled) WebRtcLocalRenderState.LARGE else WebRtcLocalRenderState.LARGE_NO_VIDEO } } else if (callState == WebRtcViewModel.State.CALL_PRE_JOIN) { localRenderState = WebRtcLocalRenderState.LARGE_NO_VIDEO } return localRenderState } private fun getFocusedParticipant(participants: List<CallParticipant>): CallParticipant { val participantsByLastSpoke: List<CallParticipant> = participants.sortedByDescending(CallParticipant::lastSpoke) return if (participantsByLastSpoke.isEmpty()) { CallParticipant.EMPTY } else { participantsByLastSpoke.firstOrNull(CallParticipant::isScreenSharing) ?: participantsByLastSpoke[0] } } private fun describeGroupMembers( context: Context, @StringRes oneParticipant: Int, @StringRes twoParticipants: Int, @PluralsRes multipleParticipants: Int, members: List<GroupMemberEntry.FullMember> ): String { val membersWithoutYou: List<GroupMemberEntry.FullMember> = members.filterNot { it.member.isSelf } return when (membersWithoutYou.size) { 0 -> "" 1 -> context.getString( oneParticipant, membersWithoutYou[0].member.getShortDisplayName(context) ) 2 -> context.getString( twoParticipants, membersWithoutYou[0].member.getShortDisplayName(context), membersWithoutYou[1].member.getShortDisplayName(context) ) else -> { val others = membersWithoutYou.size - 2 context.resources.getQuantityString( multipleParticipants, others, membersWithoutYou[0].member.getShortDisplayName(context), membersWithoutYou[1].member.getShortDisplayName(context), others ) } } } } enum class SelectedPage { GRID, FOCUSED } }
app/src/main/java/org/thoughtcrime/securesms/components/webrtc/CallParticipantsState.kt
875446210
/* * Localizer.kt * * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.multi expect class StringResource expect class PluralsResource expect class DrawableResource internal fun stripTts(input: String): String { val b = StringBuilder() // Find the TTS-exclusive bits // They are wrapped in parentheses: ( ) var x = 0 while (x < input.length) { val start = input.indexOf("(", x) if (start == -1) break val end = input.indexOf(")", start) if (end == -1) break // Delete those characters b.append(input, x, start) x = end + 1 } if (x < input.length) b.append(input, x, input.length) val c = StringBuilder() // Find the display-exclusive bits. // They are wrapped in square brackets: [ ] x = 0 while (x < b.length) { val start = b.indexOf("[", x) if (start == -1) break val end = b.indexOf("]", start) if (end == -1) break c.append(b, x, start).append(b, start + 1, end) x = end + 1 } if (x < b.length) c.append(b, x, b.length) return c.toString() } interface LocalizerInterface { fun localizeString(res: StringResource, vararg v: Any?): String fun localizeFormatted(res: StringResource, vararg v: Any?): FormattedString = FormattedString(localizeString(res, *v)) fun localizeTts(res: StringResource, vararg v: Any?): FormattedString fun localizePlural(res: PluralsResource, count: Int, vararg v: Any?): String } expect object Localizer : LocalizerInterface
src/commonMain/kotlin/au/id/micolous/metrodroid/multi/Localizer.kt
3268836995
class Foo(@setparamann private val field: Int) {} class Foo(@`setparamann` private val field: Int) {} class Foo(@`setparam ` val field: Int) {} class Foo { @ann @setparamann var field: Int = 10 } class Foo(@setparamann @ann protected val field: Int) {} class Foo { @ann @setparamann var field: Int = 10 } class Foo { @ann @`setparamann` var field: Int = 10 } class Foo(@`setparam-` @`ann` protected val field: Int) {} class Foo(@`ann` @`setparam)` protected val field: Int) {}
grammar/testData/grammar/annotations/namePrefixAsUseSiteTargetPrefix/setparam.kt
1063799737
package com.eden.orchid.sourcedoc.permalink.pathtype import com.caseyjbrooks.clog.Clog import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.permalinks.PermalinkPathType import com.eden.orchid.sourcedoc.page.BaseSourceDocPage import javax.inject.Inject class ModulePathType @Inject constructor() : PermalinkPathType() { override fun acceptsKey(page: OrchidPage, key: String): Boolean { return key == "module" && page is BaseSourceDocPage } override fun format(page: OrchidPage, key: String): String? { if (page is BaseSourceDocPage) { return page.moduleSlug.takeIf { it.isNotBlank() } ?: page.module } return null } }
plugins/OrchidSourceDoc/src/main/kotlin/com/eden/orchid/sourcedoc/permalink/pathtype/ModulePathType.kt
1810986069
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.testFramework.IdeaTestUtil import org.jetbrains.kotlin.idea.refactoring.rename.loadTestConfiguration import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.idea.test.KotlinMultiFileTestCase import org.jetbrains.kotlin.idea.test.PluginTestCaseBase import java.io.File abstract class AbstractMultiModuleMoveTest : KotlinMultiFileTestCase() { override fun getTestRoot(): String = "/refactoring/moveMultiModule/" override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR fun doTest(path: String) { val config = loadTestConfiguration(File(path)) isMultiModule = true doTestCommittingDocuments { rootDir, _ -> val modulesWithJvmRuntime: List<Module> val modulesWithJsRuntime: List<Module> val modulesWithCommonRuntime: List<Module> PluginTestCaseBase.addJdk(testRootDisposable, IdeaTestUtil::getMockJdk18) val withRuntime = config["withRuntime"]?.asBoolean ?: false if (withRuntime) { val moduleManager = ModuleManager.getInstance(project) modulesWithJvmRuntime = (config["modulesWithRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } ?: moduleManager.modules.toList()) modulesWithJvmRuntime.forEach { ConfigLibraryUtil.configureKotlinRuntimeAndSdk(it, IdeaTestUtil.getMockJdk18()) } modulesWithJsRuntime = (config["modulesWithJsRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } ?: emptyList()) modulesWithJsRuntime.forEach { module -> ConfigLibraryUtil.configureKotlinStdlibJs(module) } modulesWithCommonRuntime = (config["modulesWithCommonRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } ?: emptyList()) modulesWithCommonRuntime.forEach { ConfigLibraryUtil.configureKotlinStdlibCommon(it) } } else { modulesWithJvmRuntime = emptyList() modulesWithJsRuntime = emptyList() modulesWithCommonRuntime = emptyList() } try { runMoveRefactoring(path, config, rootDir, project) } finally { modulesWithJvmRuntime.forEach { ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(it, IdeaTestUtil.getMockJdk18()) } modulesWithJsRuntime.forEach { ConfigLibraryUtil.unConfigureKotlinJsRuntimeAndSdk(it, IdeaTestUtil.getMockJdk18()) } modulesWithCommonRuntime.forEach { ConfigLibraryUtil.unConfigureKotlinCommonRuntime(it) } } } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/move/AbstractMultiModuleMoveTest.kt
1441344633
// 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.jsonpath.ui import com.intellij.codeInsight.actions.ReformatCodeProcessor import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.find.FindBundle import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.util.PropertiesComponent import com.intellij.json.JsonBundle import com.intellij.json.JsonFileType import com.intellij.json.psi.JsonFile import com.intellij.jsonpath.JsonPathFileType import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_EXPRESSION_KEY import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_HISTORY import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_RESULT_KEY import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_SOURCE_KEY import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.WriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.EditorKind import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupChooserBuilder import com.intellij.openapi.util.NlsActions import com.intellij.openapi.wm.IdeFocusManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.EditorTextField import com.intellij.ui.JBColor import com.intellij.ui.components.* import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.popup.PopupState import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jayway.jsonpath.Configuration import com.jayway.jsonpath.Option import com.jayway.jsonpath.spi.json.JacksonJsonProvider import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider import java.awt.BorderLayout import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.event.KeyEvent import java.util.* import java.util.function.Supplier import javax.swing.* import kotlin.collections.ArrayDeque internal abstract class JsonPathEvaluateView(protected val project: Project) : SimpleToolWindowPanel(true, true), Disposable { companion object { init { Configuration.setDefaults(object : Configuration.Defaults { private val jsonProvider = JacksonJsonProvider() private val mappingProvider = JacksonMappingProvider() override fun jsonProvider() = jsonProvider override fun mappingProvider() = mappingProvider override fun options() = EnumSet.noneOf(Option::class.java) }) } } protected val searchTextField: EditorTextField = object : EditorTextField(project, JsonPathFileType.INSTANCE) { override fun processKeyBinding(ks: KeyStroke?, e: KeyEvent?, condition: Int, pressed: Boolean): Boolean { if (e?.keyCode == KeyEvent.VK_ENTER && pressed) { evaluate() return true } return super.processKeyBinding(ks, e, condition, pressed) } override fun createEditor(): EditorEx { val editor = super.createEditor() editor.setBorder(JBUI.Borders.empty()) editor.component.border = JBUI.Borders.empty(4, 0, 3, 6) editor.component.isOpaque = false editor.backgroundColor = UIUtil.getTextFieldBackground() val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) if (psiFile != null) { psiFile.putUserData(JSON_PATH_EVALUATE_EXPRESSION_KEY, true) psiFile.putUserData(JSON_PATH_EVALUATE_SOURCE_KEY, Supplier(::getJsonFile)) } return editor } } protected val searchWrapper: JPanel = object : NonOpaquePanel(BorderLayout()) { override fun updateUI() { super.updateUI() this.background = UIUtil.getTextFieldBackground() } } val searchComponent: JComponent get() = searchTextField protected val resultWrapper: JBPanelWithEmptyText = JBPanelWithEmptyText(BorderLayout()) private val resultLabel = JBLabel(JsonBundle.message("jsonpath.evaluate.result")) private val resultEditor: Editor = initJsonEditor("result.json", true, EditorKind.PREVIEW) private val errorOutputArea: JBTextArea = JBTextArea() private val errorOutputContainer: JScrollPane = JBScrollPane(errorOutputArea) private val evalOptions: MutableSet<Option> = mutableSetOf() init { resultEditor.putUserData(JSON_PATH_EVALUATE_RESULT_KEY, true) resultEditor.setBorder(JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)) resultLabel.border = JBUI.Borders.empty(3, 6) resultWrapper.emptyText.text = JsonBundle.message("jsonpath.evaluate.no.result") errorOutputContainer.border = JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0) val historyButton = SearchHistoryButton(ShowHistoryAction(), false) val historyButtonWrapper = NonOpaquePanel(BorderLayout()) historyButtonWrapper.border = JBUI.Borders.empty(3, 6, 3, 6) historyButtonWrapper.add(historyButton, BorderLayout.NORTH) searchTextField.setFontInheritedFromLAF(false) // use font as in regular editor searchWrapper.add(historyButtonWrapper, BorderLayout.WEST) searchWrapper.add(searchTextField, BorderLayout.CENTER) searchWrapper.border = JBUI.Borders.customLine(JBColor.border(), 0, 0, 1, 0) searchWrapper.isOpaque = true errorOutputArea.isEditable = false errorOutputArea.wrapStyleWord = true errorOutputArea.lineWrap = true errorOutputArea.border = JBUI.Borders.empty(10) setExpression("$..*") } protected fun initToolbar() { val actionGroup = DefaultActionGroup() fillToolbarOptions(actionGroup) val toolbar = ActionManager.getInstance().createActionToolbar("JsonPathEvaluateToolbar", actionGroup, true) toolbar.targetComponent = this setToolbar(toolbar.component) } protected abstract fun getJsonFile(): JsonFile? protected fun resetExpressionHighlighting() { val jsonPathFile = PsiDocumentManager.getInstance(project).getPsiFile(searchTextField.document) if (jsonPathFile != null) { // reset inspections in expression DaemonCodeAnalyzer.getInstance(project).restart(jsonPathFile) } } private fun fillToolbarOptions(group: DefaultActionGroup) { val outputComboBox = object : ComboBoxAction() { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun createPopupActionGroup(button: JComponent, context: DataContext): DefaultActionGroup { val outputItems = DefaultActionGroup() outputItems.add(OutputOptionAction(false, JsonBundle.message("jsonpath.evaluate.output.values"))) outputItems.add(OutputOptionAction(true, JsonBundle.message("jsonpath.evaluate.output.paths"))) return outputItems } override fun update(e: AnActionEvent) { val presentation = e.presentation if (e.project == null) return presentation.text = if (evalOptions.contains(Option.AS_PATH_LIST)) { JsonBundle.message("jsonpath.evaluate.output.paths") } else { JsonBundle.message("jsonpath.evaluate.output.values") } } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { val panel = JPanel(GridBagLayout()) panel.add(JLabel(JsonBundle.message("jsonpath.evaluate.output.option")), GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBUI.insetsLeft(5), 0, 0)) panel.add(super.createCustomComponent(presentation, place), GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBInsets.emptyInsets(), 0, 0)) return panel } } group.add(outputComboBox) group.add(DefaultActionGroup(JsonBundle.message("jsonpath.evaluate.options"), true).apply { templatePresentation.icon = AllIcons.General.Settings add(OptionToggleAction(Option.SUPPRESS_EXCEPTIONS, JsonBundle.message("jsonpath.evaluate.suppress.exceptions"))) add(OptionToggleAction(Option.ALWAYS_RETURN_LIST, JsonBundle.message("jsonpath.evaluate.return.list"))) add(OptionToggleAction(Option.DEFAULT_PATH_LEAF_TO_NULL, JsonBundle.message("jsonpath.evaluate.nullize.missing.leaf"))) add(OptionToggleAction(Option.REQUIRE_PROPERTIES, JsonBundle.message("jsonpath.evaluate.require.all.properties"))) }) } protected fun initJsonEditor(fileName: String, isViewer: Boolean, kind: EditorKind): Editor { val sourceVirtualFile = LightVirtualFile(fileName, JsonFileType.INSTANCE, "") // require strict JSON with quotes val sourceFile = PsiManager.getInstance(project).findFile(sourceVirtualFile)!! val document = PsiDocumentManager.getInstance(project).getDocument(sourceFile)!! val editor = EditorFactory.getInstance().createEditor(document, project, sourceVirtualFile, isViewer, kind) editor.settings.isLineNumbersShown = false return editor } fun setExpression(jsonPathExpr: String) { searchTextField.text = jsonPathExpr } private fun setResult(result: String) { WriteAction.run<Throwable> { resultEditor.document.setText(result) PsiDocumentManager.getInstance(project).commitDocument(resultEditor.document) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(resultEditor.document)!! ReformatCodeProcessor(psiFile, false).run() } if (!resultWrapper.components.contains(resultEditor.component)) { resultWrapper.removeAll() resultWrapper.add(resultLabel, BorderLayout.NORTH) resultWrapper.add(resultEditor.component, BorderLayout.CENTER) resultWrapper.revalidate() resultWrapper.repaint() } resultEditor.caretModel.moveToOffset(0) } private fun setError(error: String) { errorOutputArea.text = error if (!resultWrapper.components.contains(errorOutputArea)) { resultWrapper.removeAll() resultWrapper.add(resultLabel, BorderLayout.NORTH) resultWrapper.add(errorOutputContainer, BorderLayout.CENTER) resultWrapper.revalidate() resultWrapper.repaint() } } private fun evaluate() { val evaluator = JsonPathEvaluator(getJsonFile(), searchTextField.text, evalOptions) val result = evaluator.evaluate() when (result) { is IncorrectExpression -> setError(result.message) is IncorrectDocument -> setError(result.message) is ResultNotFound -> setError(result.message) is ResultString -> setResult(result.value) else -> {} } if (result != null && result !is IncorrectExpression) { addJSONPathToHistory(searchTextField.text.trim()) } } override fun dispose() { EditorFactory.getInstance().releaseEditor(resultEditor) } private inner class OutputOptionAction(private val enablePaths: Boolean, @NlsActions.ActionText message: String) : DumbAwareAction(message) { override fun actionPerformed(e: AnActionEvent) { if (enablePaths) { evalOptions.add(Option.AS_PATH_LIST) } else { evalOptions.remove(Option.AS_PATH_LIST) } evaluate() } } private inner class OptionToggleAction(private val option: Option, @NlsActions.ActionText message: String) : ToggleAction(message) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun isSelected(e: AnActionEvent): Boolean { return evalOptions.contains(option) } override fun setSelected(e: AnActionEvent, state: Boolean) { if (state) { evalOptions.add(option) } else { evalOptions.remove(option) } evaluate() } } private class SearchHistoryButton constructor(action: AnAction, focusable: Boolean) : ActionButton(action, action.templatePresentation.clone(), ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { override fun getDataContext(): DataContext { return DataManager.getInstance().getDataContext(this) } override fun getPopState(): Int { return if (isSelected) SELECTED else super.getPopState() } override fun getIcon(): Icon { if (isEnabled && isSelected) { val selectedIcon = myPresentation.selectedIcon if (selectedIcon != null) return selectedIcon } return super.getIcon() } init { setLook(ActionButtonLook.INPLACE_LOOK) isFocusable = focusable updateIcon() } } private fun getExpressionHistory(): List<String> { return PropertiesComponent.getInstance().getValue(JSON_PATH_EVALUATE_HISTORY)?.split('\n') ?: emptyList() } private fun setExpressionHistory(history: Collection<String>) { PropertiesComponent.getInstance().setValue(JSON_PATH_EVALUATE_HISTORY, history.joinToString("\n")) } private fun addJSONPathToHistory(path: String) { if (path.isBlank()) return val history = ArrayDeque(getExpressionHistory()) if (!history.contains(path)) { history.addFirst(path) if (history.size > 10) { history.removeLast() } setExpressionHistory(history) } else { if (history.firstOrNull() == path) { return } history.remove(path) history.addFirst(path) setExpressionHistory(history) } } private inner class ShowHistoryAction : DumbAwareAction(FindBundle.message("find.search.history"), null, AllIcons.Actions.SearchWithHistory) { private val popupState: PopupState<JBPopup?> = PopupState.forPopup() override fun actionPerformed(e: AnActionEvent) { if (popupState.isRecentlyHidden) return val historyList = JBList(getExpressionHistory()) showCompletionPopup(searchWrapper, historyList, searchTextField, popupState) } init { registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("ShowSearchHistory"), searchTextField) } private fun showCompletionPopup(toolbarComponent: JComponent?, list: JList<String>, textField: EditorTextField, popupState: PopupState<JBPopup?>) { val builder: PopupChooserBuilder<*> = JBPopupFactory.getInstance().createListPopupBuilder(list) val popup = builder .setMovable(false) .setResizable(false) .setRequestFocus(true) .setItemChoosenCallback(Runnable { val selectedValue = list.selectedValue if (selectedValue != null) { textField.text = selectedValue IdeFocusManager.getGlobalInstance().requestFocus(textField, false) } }) .createPopup() popupState.prepareToShow(popup) if (toolbarComponent != null) { popup.showUnderneathOf(toolbarComponent) } else { popup.showUnderneathOf(textField) } } } }
json/src/com/intellij/jsonpath/ui/JsonPathEvaluateView.kt
2586525950
// 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.feedback.common.state import com.intellij.openapi.components.* import kotlinx.serialization.Serializable @Service(Service.Level.APP) @State(name = "DontShowAgainFeedbackService", storages = [Storage("DontShowAgainFeedbackService.xml")]) class DontShowAgainFeedbackService : PersistentStateComponent<DontShowAgainFeedbackState> { companion object { @JvmStatic fun getInstance(): DontShowAgainFeedbackService = service() } private var state: DontShowAgainFeedbackState = DontShowAgainFeedbackState() override fun getState(): DontShowAgainFeedbackState { return state } override fun loadState(state: DontShowAgainFeedbackState) { this.state = state } } @Serializable data class DontShowAgainFeedbackState( val dontShowAgainIdeVersions: MutableSet<String> = mutableSetOf() )
platform/feedback/src/com/intellij/feedback/common/state/DontShowAgainFeedbackService.kt
3931395591
fun check(i: () -> Int) { i(33, "abc ${i()} c", {}) <caret>.dec() } // SET_FALSE: CONTINUATION_INDENT_FOR_CHAINED_CALLS
plugins/kotlin/idea/tests/testData/editor/enterHandler/beforeDot/CallWithArgumentsInFirstPosition.after.inv.kt
1648631699
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport.settings import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Disposer class EdtAsyncSupplier<R>( private val supplier: () -> R, private val shouldKeepTasksAsynchronous: () -> Boolean ) : AsyncSupplier<R> { override fun supply(parentDisposable: Disposable, consumer: (R) -> Unit) { val application = ApplicationManager.getApplication() if (shouldKeepTasksAsynchronous()) { application.invokeLater({ consumer(supplier()) }) { Disposer.isDisposed(parentDisposable) } } else { application.invokeAndWait { consumer(supplier()) } } } companion object { fun invokeOnEdt(shouldKeepTasksAsynchronous: () -> Boolean, parentDisposable: Disposable, action: () -> Unit) { EdtAsyncSupplier(action, shouldKeepTasksAsynchronous) .supply(parentDisposable) {} } } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/settings/EdtAsyncSupplier.kt
767522512
package org.thoughtcrime.securesms.components.settings.app.internal import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.signal.ringrtc.CallManager import org.thoughtcrime.securesms.keyvalue.InternalValues import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.livedata.Store class InternalSettingsViewModel(private val repository: InternalSettingsRepository) : ViewModel() { private val preferenceDataStore = SignalStore.getPreferenceDataStore() private val store = Store(getState()) init { repository.getEmojiVersionInfo { version -> store.update { it.copy(emojiVersion = version) } } } val state: LiveData<InternalSettingsState> = store.stateLiveData fun setSeeMoreUserDetails(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.RECIPIENT_DETAILS, enabled) refresh() } fun setShakeToReport(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.SHAKE_TO_REPORT, enabled) refresh() } fun setDisableStorageService(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.DISABLE_STORAGE_SERVICE, enabled) refresh() } fun setGv2DoNotCreateGv2Groups(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_DO_NOT_CREATE_GV2, enabled) refresh() } fun setGv2ForceInvites(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_FORCE_INVITES, enabled) refresh() } fun setGv2IgnoreServerChanges(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_SERVER_CHANGES, enabled) refresh() } fun setGv2IgnoreP2PChanges(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_P2P_CHANGES, enabled) refresh() } fun setDisableAutoMigrationInitiation(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_INITIATION, enabled) refresh() } fun setDisableAutoMigrationNotification(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_NOTIFICATION, enabled) refresh() } fun setAllowCensorshipSetting(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.ALLOW_CENSORSHIP_SETTING, enabled) refresh() } fun setUseBuiltInEmoji(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.FORCE_BUILT_IN_EMOJI, enabled) refresh() } fun setRemoveSenderKeyMinimum(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.REMOVE_SENDER_KEY_MINIMUM, enabled) refresh() } fun setDelayResends(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.DELAY_RESENDS, enabled) refresh() } fun setInternalGroupCallingServer(server: String?) { preferenceDataStore.putString(InternalValues.CALLING_SERVER, server) refresh() } fun setInternalCallingAudioProcessingMethod(method: CallManager.AudioProcessingMethod) { preferenceDataStore.putInt(InternalValues.CALLING_AUDIO_PROCESSING_METHOD, method.ordinal) refresh() } fun setInternalCallingBandwidthMode(bandwidthMode: CallManager.BandwidthMode) { preferenceDataStore.putInt(InternalValues.CALLING_BANDWIDTH_MODE, bandwidthMode.ordinal) refresh() } fun setInternalCallingDisableTelecom(enabled: Boolean) { preferenceDataStore.putBoolean(InternalValues.CALLING_DISABLE_TELECOM, enabled) refresh() } fun toggleStories() { val newState = !SignalStore.storyValues().isFeatureDisabled SignalStore.storyValues().isFeatureDisabled = newState store.update { getState().copy(disableStories = newState) } } fun addSampleReleaseNote() { repository.addSampleReleaseNote() } private fun refresh() { store.update { getState().copy(emojiVersion = it.emojiVersion) } } private fun getState() = InternalSettingsState( seeMoreUserDetails = SignalStore.internalValues().recipientDetails(), shakeToReport = SignalStore.internalValues().shakeToReport(), gv2doNotCreateGv2Groups = SignalStore.internalValues().gv2DoNotCreateGv2Groups(), gv2forceInvites = SignalStore.internalValues().gv2ForceInvites(), gv2ignoreServerChanges = SignalStore.internalValues().gv2IgnoreServerChanges(), gv2ignoreP2PChanges = SignalStore.internalValues().gv2IgnoreP2PChanges(), disableAutoMigrationInitiation = SignalStore.internalValues().disableGv1AutoMigrateInitiation(), disableAutoMigrationNotification = SignalStore.internalValues().disableGv1AutoMigrateNotification(), allowCensorshipSetting = SignalStore.internalValues().allowChangingCensorshipSetting(), callingServer = SignalStore.internalValues().groupCallingServer(), callingAudioProcessingMethod = SignalStore.internalValues().callingAudioProcessingMethod(), callingBandwidthMode = SignalStore.internalValues().callingBandwidthMode(), callingDisableTelecom = SignalStore.internalValues().callingDisableTelecom(), useBuiltInEmojiSet = SignalStore.internalValues().forceBuiltInEmoji(), emojiVersion = null, removeSenderKeyMinimium = SignalStore.internalValues().removeSenderKeyMinimum(), delayResends = SignalStore.internalValues().delayResends(), disableStorageService = SignalStore.internalValues().storageServiceDisabled(), disableStories = SignalStore.storyValues().isFeatureDisabled ) class Factory(private val repository: InternalSettingsRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return requireNotNull(modelClass.cast(InternalSettingsViewModel(repository))) } } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsViewModel.kt
251226042
package org.thoughtcrime.securesms.components.settings.conversation.sounds.custom import android.net.Uri import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.thoughtcrime.securesms.database.RecipientDatabase import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.notifications.NotificationChannels import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.FeatureFlags import org.thoughtcrime.securesms.util.livedata.Store class CustomNotificationsSettingsViewModel( private val recipientId: RecipientId, private val repository: CustomNotificationsSettingsRepository ) : ViewModel() { private val store = Store(CustomNotificationsSettingsState()) val state: LiveData<CustomNotificationsSettingsState> = store.stateLiveData init { store.update(Recipient.live(recipientId).liveData) { recipient, state -> val recipientHasCustomNotifications = NotificationChannels.supported() && recipient.notificationChannel != null state.copy( recipient = recipient, hasCustomNotifications = recipientHasCustomNotifications, controlsEnabled = (!NotificationChannels.supported() || recipientHasCustomNotifications) && state.isInitialLoadComplete, messageSound = recipient.messageRingtone, messageVibrateState = recipient.messageVibrate, messageVibrateEnabled = when (recipient.messageVibrate) { RecipientDatabase.VibrateState.DEFAULT -> SignalStore.settings().isMessageVibrateEnabled RecipientDatabase.VibrateState.ENABLED -> true RecipientDatabase.VibrateState.DISABLED -> false }, showCallingOptions = recipient.isRegistered && (!recipient.isGroup || FeatureFlags.groupCallRinging()), callSound = recipient.callRingtone, callVibrateState = recipient.callVibrate ) } } fun setHasCustomNotifications(hasCustomNotifications: Boolean) { repository.setHasCustomNotifications(recipientId, hasCustomNotifications) } fun setMessageVibrate(messageVibrateState: RecipientDatabase.VibrateState) { repository.setMessageVibrate(recipientId, messageVibrateState) } fun setMessageSound(uri: Uri?) { repository.setMessageSound(recipientId, uri) } fun setCallVibrate(callVibrateState: RecipientDatabase.VibrateState) { repository.setCallingVibrate(recipientId, callVibrateState) } fun setCallSound(uri: Uri?) { repository.setCallSound(recipientId, uri) } fun channelConsistencyCheck() { store.update { it.copy(isInitialLoadComplete = false) } repository.ensureCustomChannelConsistency(recipientId) { store.update { it.copy( isInitialLoadComplete = true, controlsEnabled = (!NotificationChannels.supported() || it.hasCustomNotifications) ) } } } class Factory( private val recipientId: RecipientId, private val repository: CustomNotificationsSettingsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return requireNotNull(modelClass.cast(CustomNotificationsSettingsViewModel(recipientId, repository))) } } }
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/sounds/custom/CustomNotificationsSettingsViewModel.kt
2543958488
package lt.markmerkk.timeselect.entities enum class TimeSelectType { UNKNOWN, FROM, TO, ; companion object { fun fromRaw(raw: String): TimeSelectType { return values() .firstOrNull { it.name.equals(raw, ignoreCase = true) } ?: UNKNOWN } } }
components/src/main/java/lt/markmerkk/timeselect/entities/TimeSelectType.kt
1472522843
package annotation /** * Desc: * Created by Chiclaim on 2018/10/15. */ @Target(AnnotationTarget.PROPERTY) annotation class PropertyOnly
language-kotlin/kotlin-sample/kotlin-in-action/src/annotation/PropertyOnly.kt
3101380325
package pfb.words.test import pfb.words.Dictionary import pfb.words.WordChecker import pfb.words.WordNode import org.junit.Assert import org.junit.Test import java.nio.file.Paths class WordNodeTest { }
src/test/kotlin/pfb/words/test/WordNodeTest.kt
4240923419
package com.rarnu.tophighlight.xposed import android.graphics.drawable.ColorDrawable import android.graphics.drawable.StateListDrawable import android.view.View import android.view.ViewGroup import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedHelpers /** * Created by rarnu on 1/11/17. */ object HookTopHighlight { /** * 此处是hook置顶的群和普通的群 */ fun hookTopHighlight(classLoader: ClassLoader?, ver: Versions) { XposedHelpers.findAndHookMethod(ver.conversationAdapter, classLoader, "getView", Integer.TYPE, View::class.java, ViewGroup::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(pmethod: MethodHookParam) { val ad = XposedHelpers.callMethod(pmethod.thisObject, ver.userInfoMethod, pmethod.args[0]) val j = XposedHelpers.callMethod(pmethod.thisObject, ver.topInfoMethod, ad) val oLH = XposedHelpers.getBooleanField(j, ver.topInfoField) (pmethod.result as View?)?.background = if (oLH) createTopHighlightSelectorDrawable(pmethod.args[0] as Int) else createNormalSelectorDrawable() } }) } fun hookTopReaderAndMac(classLoader: ClassLoader?, ver: Versions) { XposedHelpers.findAndHookMethod(ver.topMacActivity, classLoader, ver.topMacMethod, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(pmethod: MethodHookParam) { val v = XposedHelpers.getObjectField(pmethod.thisObject, ver.topMacField) as View? v?.background = createTopReaderAndMacSelectorDrawable() } }) XposedHelpers.findAndHookMethod(ver.topReaderActivity, classLoader, ver.topReaderMethod, Integer.TYPE, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(pmethod: MethodHookParam) { val view = XposedHelpers.getObjectField(pmethod.thisObject, ver.topReaderField) as View? view?.findViewById(ver.topReaderViewId)?.background = createTopReaderAndMacSelectorDrawable(1) } }) } private fun createTopHighlightSelectorDrawable(idx: Int): StateListDrawable? { return createSelectorDrawable(XpConfig.topColors[idx], XpConfig.topPressColors[idx]) } private fun createNormalSelectorDrawable(): StateListDrawable? { return createSelectorDrawable(XpConfig.normalColor, XpConfig.normalPressColor) } private fun createTopReaderAndMacSelectorDrawable(type: Int = 0): StateListDrawable? { return when (type) { 0 -> createSelectorDrawable(XpConfig.macColor, XpConfig.macPressColor) 1 -> createSelectorDrawable(XpConfig.readerColor, XpConfig.readerPressColor) else -> null } } private fun createSelectorDrawable(defaultColor: Int, pressColor: Int): StateListDrawable? { val stateList = StateListDrawable() stateList.addState(intArrayOf(android.R.attr.state_selected), ColorDrawable(pressColor)) stateList.addState(intArrayOf(android.R.attr.state_focused), ColorDrawable(pressColor)) stateList.addState(intArrayOf(android.R.attr.state_pressed), ColorDrawable(pressColor)) stateList.addState(intArrayOf(), ColorDrawable(defaultColor)) return stateList } }
src/main/kotlin/com/rarnu/tophighlight/xposed/HookTopHighlight.kt
125530402
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.taskdetail import android.arch.lifecycle.ViewModel import com.example.android.architecture.blueprints.todoapp.mvibase.MviAction import com.example.android.architecture.blueprints.todoapp.mvibase.MviIntent import com.example.android.architecture.blueprints.todoapp.mvibase.MviResult import com.example.android.architecture.blueprints.todoapp.mvibase.MviView import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewModel import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewState import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.ActivateTaskAction import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.CompleteTaskAction import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.DeleteTaskAction import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.PopulateTaskAction import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.ActivateTaskResult import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.CompleteTaskResult import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.DeleteTaskResult import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.PopulateTaskResult import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_ACTIVATED import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_COMPLETE import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_DELETED import com.example.android.architecture.blueprints.todoapp.util.notOfType import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.BiFunction import io.reactivex.subjects.PublishSubject /** * Listens to user actions from the UI ([TaskDetailFragment]), retrieves the data and updates * the UI as required. * * @property actionProcessorHolder Contains and executes the business logic of all emitted actions. */ class TaskDetailViewModel( private val actionProcessorHolder: TaskDetailActionProcessorHolder ) : ViewModel(), MviViewModel<TaskDetailIntent, TaskDetailViewState> { /** * Proxy subject used to keep the stream alive even after the UI gets recycled. * This is basically used to keep ongoing events and the last cached State alive * while the UI disconnects and reconnects on config changes. */ private val intentsSubject: PublishSubject<TaskDetailIntent> = PublishSubject.create() private val statesObservable: Observable<TaskDetailViewState> = compose() private val disposables = CompositeDisposable() /** * take only the first ever InitialIntent and all intents of other types * to avoid reloading data on config changes */ private val intentFilter: ObservableTransformer<TaskDetailIntent, TaskDetailIntent> get() = ObservableTransformer { intents -> intents.publish { shared -> Observable.merge<TaskDetailIntent>( shared.ofType(TaskDetailIntent.InitialIntent::class.java).take(1), shared.notOfType(TaskDetailIntent.InitialIntent::class.java) ) } } override fun processIntents(intents: Observable<TaskDetailIntent>) { disposables.add(intents.subscribe(intentsSubject::onNext)) } override fun states(): Observable<TaskDetailViewState> = statesObservable /** * Compose all components to create the stream logic */ private fun compose(): Observable<TaskDetailViewState> { return intentsSubject .compose<TaskDetailIntent>(intentFilter) .map(this::actionFromIntent) .compose(actionProcessorHolder.actionProcessor) // Cache each state and pass it to the reducer to create a new state from // the previous cached one and the latest Result emitted from the action processor. // The Scan operator is used here for the caching. .scan(TaskDetailViewState.idle(), reducer) // When a reducer just emits previousState, there's no reason to call render. In fact, // redrawing the UI in cases like this can cause jank (e.g. messing up snackbar animations // by showing the same snackbar twice in rapid succession). .distinctUntilChanged() // Emit the last one event of the stream on subscription // Useful when a View rebinds to the ViewModel after rotation. .replay(1) // Create the stream on creation without waiting for anyone to subscribe // This allows the stream to stay alive even when the UI disconnects and // match the stream's lifecycle to the ViewModel's one. .autoConnect(0) } /** * Translate an [MviIntent] to an [MviAction]. * Used to decouple the UI and the business logic to allow easy testings and reusability. */ private fun actionFromIntent(intent: TaskDetailIntent): TaskDetailAction { return when (intent) { is TaskDetailIntent.InitialIntent -> PopulateTaskAction(intent.taskId) is TaskDetailIntent.DeleteTask -> DeleteTaskAction(intent.taskId) is TaskDetailIntent.ActivateTaskIntent -> ActivateTaskAction(intent.taskId) is TaskDetailIntent.CompleteTaskIntent -> CompleteTaskAction(intent.taskId) } } override fun onCleared() { disposables.dispose() } companion object { /** * The Reducer is where [MviViewState], that the [MviView] will use to * render itself, are created. * It takes the last cached [MviViewState], the latest [MviResult] and * creates a new [MviViewState] by only updating the related fields. * This is basically like a big switch statement of all possible types for the [MviResult] */ private val reducer = BiFunction { previousState: TaskDetailViewState, result: TaskDetailResult -> when (result) { is PopulateTaskResult -> when (result) { is PopulateTaskResult.Success -> previousState.copy( loading = false, title = result.task.title!!, description = result.task.description!!, active = result.task.active ) is PopulateTaskResult.Failure -> previousState.copy( loading = false, error = result.error ) is PopulateTaskResult.InFlight -> previousState.copy(loading = true) } is ActivateTaskResult -> when (result) { is ActivateTaskResult.Success -> previousState.copy( uiNotification = TASK_ACTIVATED, active = true ) is ActivateTaskResult.Failure -> previousState.copy(error = result.error) is ActivateTaskResult.InFlight -> previousState is ActivateTaskResult.HideUiNotification -> if (previousState.uiNotification == TASK_ACTIVATED) { previousState.copy( uiNotification = null ) } else { previousState } } is CompleteTaskResult -> when (result) { is CompleteTaskResult.Success -> previousState.copy( uiNotification = TASK_COMPLETE, active = false ) is CompleteTaskResult.Failure -> previousState.copy(error = result.error) is CompleteTaskResult.InFlight -> previousState is CompleteTaskResult.HideUiNotification -> if (previousState.uiNotification == TASK_COMPLETE) { previousState.copy( uiNotification = null ) } else { previousState } } is DeleteTaskResult -> when (result) { is DeleteTaskResult.Success -> previousState.copy(uiNotification = TASK_DELETED) is DeleteTaskResult.Failure -> previousState.copy(error = result.error) is DeleteTaskResult.InFlight -> previousState } } } } }
app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailViewModel.kt
895424057
package sds.classfile.attribute import sds.classfile.ClassfileStream as Stream interface VerificationType { companion object VerificationTypeFactory { fun create(data: Stream): VerificationType = when(data.unsignedByte()) { 0 -> VerificationAdapter("top") 1 -> VerificationAdapter("int") 2 -> VerificationAdapter("float") 3 -> VerificationAdapter("double") 4 -> VerificationAdapter("long") 5 -> VerificationAdapter("null") 6 -> VerificationAdapter("") 7 -> ObjectVar(data.short()) else -> UninitializedVar(data.short()) } } class VerificationAdapter(val type: String): VerificationType { override fun toString(): String = type } class ObjectVar(val cpool: Int): VerificationType class UninitializedVar(val offset: Int): VerificationType }
src/main/kotlin/sds/classfile/attribute/VerificationType.kt
2362417016
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val EXT_memory_object_win32 = "EXTMemoryObjectWin32".nativeClassGLES("EXT_memory_object_win32", postfix = EXT) { documentation = """ Native bindings to the ${registryLink("EXT_external_objects_win32")} extension. Building upon the OpenGL memory object and semaphore framework defined in ${registryLinkTo("EXT", "external_objects")}, this extension enables an OpenGL application to import a memory object or semaphore from a Win32 NT handle or a KMT share handle. """ IntConstant( """ Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT(), #ImportMemoryWin32NameEXT(), #ImportSemaphoreWin32HandleEXT(), and #ImportSemaphoreWin32NameEXT(). """, "HANDLE_TYPE_OPAQUE_WIN32_EXT"..0x9587 ) IntConstant( "Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportSemaphoreWin32HandleEXT().", "HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT"..0x9588 ) IntConstant( """ Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, GetBooleani_v, GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v. """, "DEVICE_LUID_EXT"..0x9599, "DEVICE_NODE_MASK_EXT"..0x959A ) IntConstant( "Constant values.", "LUID_SIZE_EXT".."8" ) IntConstant( "Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportMemoryWin32NameEXT().", "HANDLE_TYPE_D3D12_TILEPOOL_EXT"..0x9589, "HANDLE_TYPE_D3D12_RESOURCE_EXT"..0x958A, "HANDLE_TYPE_D3D11_IMAGE_EXT"..0x958B ) IntConstant( "Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT().", "HANDLE_TYPE_D3D11_IMAGE_KMT_EXT"..0x958C ) void( "ImportMemoryWin32HandleEXT", "", GLuint("memory", ""), GLuint64("size", ""), GLenum("handleType", ""), opaque_p("handle", "") ) void( "ImportMemoryWin32NameEXT", "", GLuint("memory", ""), GLuint64("size", ""), GLenum("handleType", ""), opaque_const_p("name", "") ) } val EXT_semaphore_win32 = "EXTSemaphoreWin32".nativeClassGLES("EXT_semaphore_win32", postfix = EXT) { documentation = """ Native bindings to the ${registryLink("EXT_external_objects_win32")} extension. Building upon the OpenGL memory object and semaphore framework defined in ${registryLinkTo("EXT", "external_objects")}, this extension enables an OpenGL application to import a memory object or semaphore from a Win32 NT handle or a KMT share handle. """ IntConstant( """ Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT(), #ImportMemoryWin32NameEXT(), #ImportSemaphoreWin32HandleEXT(), and #ImportSemaphoreWin32NameEXT(). """, "HANDLE_TYPE_OPAQUE_WIN32_EXT"..0x9587 ) IntConstant( "Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportSemaphoreWin32HandleEXT().", "HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT"..0x9588 ) IntConstant( """ Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, GetBooleani_v, GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v. """, "DEVICE_LUID_EXT"..0x9599, "DEVICE_NODE_MASK_EXT"..0x959A ) IntConstant( "Constant values.", "LUID_SIZE_EXT".."8" ) IntConstant( "Accepted by the {@code handleType} parameter of #ImportSemaphoreWin32HandleEXT().", "HANDLE_TYPE_D3D12_FENCE_EXT"..0x9594 ) IntConstant( "Accepted by the {@code pname} parameter of #SemaphoreParameterui64vEXT() and #GetSemaphoreParameterui64vEXT().", "D3D12_FENCE_VALUE_EXT"..0x9595 ) void( "ImportSemaphoreWin32HandleEXT", "", GLuint("semaphore", ""), GLenum("handleType", ""), opaque_p("handle", "") ) void( "ImportSemaphoreWin32NameEXT", "", GLuint("semaphore", ""), GLenum("handleType", ""), opaque_const_p("name", "") ) }
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_external_objects_win32.kt
2836633406
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.ui.home.setting import android.os.Bundle import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.ayatk.biblio.BuildConfig import com.ayatk.biblio.R import com.ayatk.biblio.ui.license.LicenseActivity class SettingFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(bundle: Bundle?, s: String?) { addPreferencesFromResource(R.xml.pref) findPreference<Preference>("oss_license")?.setOnPreferenceClickListener { _ -> startActivity( LicenseActivity.createIntent( activity, getString(R.string.pref_oss_license), "file:///android_asset/licenses.html" ) ) true } findPreference<Preference>("app_version")?.apply { summary = "${BuildConfig.VERSION_NAME} #${BuildConfig.BUILD_NUM} (${BuildConfig.GIT_SHA})" } } companion object { fun newInstance(): SettingFragment = SettingFragment() } }
app/src/main/kotlin/com/ayatk/biblio/ui/home/setting/SettingFragment.kt
4023339655
@file:Suppress("unused") package com.ashish.movieguide.utils.extensions import android.app.Activity import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty // Required Views fun <V : View> View.bindView(id: Int): ReadOnlyProperty<View, V> = required(id, viewFinder) fun <V : View> Activity.bindView(id: Int): ReadOnlyProperty<Activity, V> = required(id, viewFinder) fun <V : View> Fragment.bindView(id: Int): ReadOnlyProperty<Fragment, V> = required(id, viewFinder) fun <V : View> ViewHolder.bindView(id: Int): ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder) // Optional Views fun <V : View> Activity.bindOptionalView(id: Int): ReadOnlyProperty<Activity, V?> = optional(id, viewFinder) fun <V : View> Fragment.bindOptionalView(id: Int): ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder) fun <V : View> ViewHolder.bindOptionalView(id: Int) : ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder) // Getters private val View.viewFinder: View.(Int) -> View? get() = { findViewById(it) } private val Activity.viewFinder: Activity.(Int) -> View? get() = { findViewById(it) } private val Fragment.viewFinder: Fragment.(Int) -> View? get() = { view?.findViewById(it) } private val ViewHolder.viewFinder: ViewHolder.(Int) -> View? get() = { itemView.findViewById(it) } @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) } private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing = throw IllegalStateException("View ID $id for '${desc.name}' not found.") @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, _ -> t.finder(id) as V? } // Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it private class Lazy<in T, out V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> { private object EMPTY private var value: Any? = EMPTY override fun getValue(thisRef: T, property: KProperty<*>): V { if (value == EMPTY) { value = initializer(thisRef, property) } @Suppress("UNCHECKED_CAST") return value as V } }
app/src/main/kotlin/com/ashish/movieguide/utils/extensions/ButterKnife.kt
1346011097
package com.example.demoaerisproject.service import android.app.job.JobParameters import android.app.job.JobService import com.example.demoaerisproject.data.preferenceStore.PrefStoreRepository import com.example.demoaerisproject.data.room.MyPlaceRepository import com.example.demoaerisproject.data.weather.WeatherRepository import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class NotificationService : JobService() { @Inject lateinit var myPlaceRepository: MyPlaceRepository @Inject lateinit var prefStoreRepository: PrefStoreRepository @Inject lateinit var weatherRepository: WeatherRepository @Inject lateinit var prefStore: PrefStoreRepository override fun onStartJob(jobParameters: JobParameters): Boolean { NotificationBuilder( context = applicationContext, myPlaceRepository, prefStoreRepository, weatherRepository, prefStore ).request() return true } override fun onStopJob(jobParameters: JobParameters): Boolean { return false } }
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/service/NotificationService.kt
2957126680
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.updates import com.intellij.openapi.updateSettings.impl.* import com.intellij.openapi.util.BuildNumber import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.util.loadElement import org.assertj.core.api.Assertions.assertThat import org.junit.Test // unless stated otherwise, the behavior described in cases is true for 162+ class UpdateStrategyTest : BareTestFixtureTestCase() { @Test fun `channel contains no builds`() { val result = check("IU-145.258", ChannelStatus.RELEASE, """<channel id="IDEA_Release" status="release" licensing="release"/>""") assertNull(result.newBuild) } @Test fun `already on the latest build`() { val result = check("IU-145.258", ChannelStatus.RELEASE, """ <channel id="IDEA15_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""") assertNull(result.newBuild) } @Test fun `patch exclusions`() { val channels = """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"> <patch from="145.596"/> <patch from="145.258" exclusions="win,mac,unix"/> </build> </channel>""" assertNotNull(check("IU-145.596", ChannelStatus.RELEASE, channels).patches) assertNull(check("IU-145.258", ChannelStatus.RELEASE, channels).patches) } @Test fun `order of builds does not matter`() { val resultDesc = check("IU-143.2332", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> <build number="145.258" version="2016.1"/> </channel>""") assertBuild("145.597", resultDesc.newBuild) val resultAsc = check("IU-143.2332", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", resultAsc.newBuild) } @Test fun `newer updates are preferred`() { val result = check("IU-145.258", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", result.newBuild) } @Test fun `newer updates are preferred over more stable ones`() { val result = check("IU-145.257", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Beta" status="beta" licensing="release"> <build number="145.257" version="2016.1 RC2"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""") assertBuild("145.596", result.newBuild) } @Test fun `newer updates from non-allowed channels are ignored`() { val channels = """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> </channel> <channel id="IDEA_Beta" status="beta" licensing="release"> <build number="145.257" version="2016.1 RC2"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.258" version="2016.1"/> </channel>""" assertBuild("145.258", check("IU-145.256", ChannelStatus.RELEASE, channels).newBuild) assertNull(check("IU-145.258", ChannelStatus.RELEASE, channels).newBuild) } @Test fun `ignored updates are excluded`() { val result = check("IU-145.258", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP"/> <build number="145.595" version="2016.1.1 EAP"/> </channel>""", listOf("145.596")) assertBuild("145.595", result.newBuild) } @Test fun `ignored same-baseline updates do not hide new major releases`() { val result = check("IU-145.971", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="145.1617" version="2016.1.3"/> <build number="145.2070" version="2016.1.4"/> <build number="171.4424" version="2017.1.3"/> </channel>""", listOf("145.1617", "145.2070")) assertBuild("171.4424", result.newBuild) } @Test fun `updates can be targeted for specific builds (different builds)`() { val channels = """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="145.596" version="2016.1.1 EAP" targetSince="145.595" targetUntil="145.*"/> <!-- this build is not for everyone --> <build number="145.595" version="2016.1.1 EAP"/> </channel>""" assertBuild("145.595", check("IU-145.258", ChannelStatus.EAP, channels).newBuild) assertBuild("145.596", check("IU-145.595", ChannelStatus.EAP, channels).newBuild) } @Test fun `updates can be targeted for specific builds (same build)`() { val channels = """ <channel id="IDEA_EAP" status="release" licensing="release"> <build number="163.101" version="2016.3.1" targetSince="163.0" targetUntil="163.*"><message>bug fix</message></build> <build number="163.101" version="2016.3.1"><message>new release</message></build> </channel>""" assertEquals("new release", check("IU-145.258", ChannelStatus.RELEASE, channels).newBuild?.message) assertEquals("bug fix", check("IU-163.50", ChannelStatus.RELEASE, channels).newBuild?.message) } @Test fun `updates from the same baseline are preferred (unified channels)`() { val result = check("IU-143.2287", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="143.2330" version="15.0.5 EAP"/> <build number="145.600" version="2016.1.2 EAP"/> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("143.2332", result.newBuild) } // since 163 @Test fun `updates from the same baseline are preferred (per-release channels)`() { val result = check("IU-143.2287", ChannelStatus.EAP, """ <channel id="IDEA_143_EAP" status="eap" licensing="eap"> <build number="143.2330" version="15.0.5 EAP"/> </channel> <channel id="IDEA_143_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> </channel> <channel id="IDEA_145_EAP" status="eap" licensing="eap"> <build number="145.600" version="2016.1.2 EAP"/> </channel> <channel id="IDEA_Release_145" status="release" licensing="release"> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("143.2332", result.newBuild) } @Test fun `cross-baseline updates are perfectly legal`() { val result = check("IU-143.2332", ChannelStatus.EAP, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="143.2332" version="15.0.5"/> <build number="145.597" version="2016.1.1"/> </channel>""") assertBuild("145.597", result.newBuild) } @Test fun `variable-length build numbers are supported`() { val channels = """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="162.11.10" version="2016.2"/> </channel>""" assertBuild("162.11.10", check("IU-145.597", ChannelStatus.RELEASE, channels).newBuild) assertBuild("162.11.10", check("IU-162.7.23", ChannelStatus.RELEASE, channels).newBuild) assertNull(check("IU-162.11.11", ChannelStatus.RELEASE, channels).newBuild) val result = check("IU-162.11.10", ChannelStatus.RELEASE, """ <channel id="IDEA_Release" status="release" licensing="release"> <build number="162.48" version="2016.2.1 EAP"/> </channel>""") assertBuild("162.48", result.newBuild) } @Test fun `for duplicate builds, first matching channel is preferred`() { val build = """<build number="163.9166" version="2016.3.1"/>""" val eap15 = """<channel id="IDEA15_EAP" status="eap" licensing="eap" majorVersion="15">$build</channel>""" val eap = """<channel id="IDEA_EAP" status="eap" licensing="eap" majorVersion="2016">$build</channel>""" val beta15 = """<channel id="IDEA15_Beta" status="beta" licensing="release" majorVersion="15">$build</channel>""" val beta = """<channel id="IDEA_Beta" status="beta" licensing="release" majorVersion="2016">$build</channel>""" val release15 = """<channel id="IDEA15_Release" status="release" licensing="release" majorVersion="15">$build</channel>""" val release = """<channel id="IDEA_Release" status="release" licensing="release" majorVersion="2016">$build</channel>""" // note: this is a test; in production, release builds should never be proposed via channels with EAP licensing assertEquals("IDEA15_EAP", check("IU-163.1", ChannelStatus.EAP, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel?.id) assertEquals("IDEA_EAP", check("IU-163.1", ChannelStatus.EAP, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel?.id) assertEquals("IDEA15_EAP", check("IU-163.1", ChannelStatus.EAP, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id) assertEquals("IDEA_EAP", check("IU-163.1", ChannelStatus.EAP, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id) assertEquals("IDEA15_Beta", check("IU-163.1", ChannelStatus.BETA, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id) assertEquals("IDEA_Beta", check("IU-163.1", ChannelStatus.BETA, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id) assertEquals("IDEA15_Release", check("IU-163.1", ChannelStatus.RELEASE, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel?.id) assertEquals("IDEA_Release", check("IU-163.1", ChannelStatus.RELEASE, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel?.id) assertEquals("IDEA15_Release", check("IU-163.1", ChannelStatus.RELEASE, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id) assertEquals("IDEA_Release", check("IU-163.1", ChannelStatus.RELEASE, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id) } @Test fun `building linear patch chain`() { val result = check("IU-182.3569.1", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="182.3684.40" version="2018.2 RC2"> <patch from="182.3684.2" size="from 1 to 8"/> </build> <build number="182.3684.2" version="2018.2 RC"> <patch from="182.3569.1" size="2"/> </build> </channel>""") assertBuild("182.3684.40", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("182.3569.1", "182.3684.2", "182.3684.40").map(BuildNumber::fromString)) assertThat(result.patches?.size).isEqualTo("10") } @Test fun `building patch chain across channels`() { val result = check("IU-182.3684.40", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="182.3684.40" version="2018.2 RC2"> <patch from="182.3684.2"/> </build> </channel> <channel id="IDEA_Release" status="release" licensing="release"> <build number="182.3684.41" version="2018.2"> <patch from="182.3684.40"/> </build> </channel> <channel id="IDEA_Stable_EAP" status="eap" licensing="release"> <build number="182.3911.2" version="2018.2.1 EAP"> <patch from="182.3684.41"/> </build> </channel>""") assertBuild("182.3911.2", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("182.3684.40", "182.3684.41", "182.3911.2").map(BuildNumber::fromString)) assertThat(result.patches?.size).isNull() } @Test fun `allow ignored builds in the middle of a chain`() { val result = check("IU-183.3795.13", ChannelStatus.EAP, """ <channel id="IDEA_EAP" status="eap" licensing="eap"> <build number="183.4139.22" version="2018.3 EAP"> <patch from="183.3975.18" size="1"/> </build> <build number="183.3975.18" version="2018.3 EAP"> <patch from="183.3795.13" size="1"/> </build> </channel>""", listOf("183.3975.18")) assertBuild("183.4139.22", result.newBuild) assertThat(result.patches?.chain).isEqualTo(listOf("183.3795.13", "183.3975.18", "183.4139.22").map(BuildNumber::fromString)) } private fun check(currentBuild: String, selectedChannel: ChannelStatus, testData: String, ignoredBuilds: List<String> = emptyList()): CheckForUpdateResult { val updates = UpdatesInfo(loadElement(""" <products> <product name="IntelliJ IDEA"> <code>IU</code> ${testData} </product> </products>""")) val settings = UpdateSettings() settings.selectedChannelStatus = selectedChannel settings.ignoredBuildNumbers += ignoredBuilds val result = UpdateStrategy(BuildNumber.fromString(currentBuild), updates, settings).checkForUpdates() assertEquals(UpdateStrategy.State.LOADED, result.state) return result } private fun assertBuild(expected: String, build: BuildInfo?) { assertEquals(expected, build?.number?.asStringWithoutProductCode()) } }
platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateStrategyTest.kt
231640070
package com.ashish.movieguide.utils.extensions import android.support.design.widget.TabLayout import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView operator fun ViewGroup?.get(position: Int): View? = this?.getChildAt(position) val ViewGroup.views: List<View> get() = (0 until childCount).map { getChildAt(it) } fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View? { return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot) } fun ViewGroup.changeViewGroupTextFont() { views.filterIsInstance<TextView>().forEach(TextView::changeTypeface) } fun TabLayout.changeTabFont() { val viewGroup = this[0] as ViewGroup (0 until viewGroup.childCount) .map { viewGroup[it] as ViewGroup } .forEach { it.changeViewGroupTextFont() } }
app/src/main/kotlin/com/ashish/movieguide/utils/extensions/ViewGroupExtensions.kt
748979064
package com.tungnui.dalatlaptop.ux.adapters import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.tungnui.dalatlaptop.models.Category import java.util.ArrayList import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.utils.inflate import kotlinx.android.synthetic.main.list_item_drawer_category.view.* class DrawerRecyclerAdapter(val listener: (Category) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val listCategory = ArrayList<Category>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = ViewHolderItemCategory(parent.inflate(R.layout.list_item_drawer_category)) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as ViewHolderItemCategory).blind(listCategory[position],listener) } override fun getItemCount(): Int { return listCategory.size } fun changeDrawerItems(categories: List<Category>) { listCategory.clear() listCategory.addAll(categories) notifyDataSetChanged() } class ViewHolderItemCategory(itemView: View) : RecyclerView.ViewHolder(itemView) { fun blind(item:Category,listener: (Category) -> Unit)=with(itemView){ drawer_list_item_text.text = item.name drawer_list_item_text.setTextColor(ContextCompat.getColor(context, R.color.textPrimary)) drawer_list_item_text.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null) drawer_list_item_divider.visibility = View.GONE if (item.display == "subcategories") { drawer_list_item_indicator.visibility = View.VISIBLE } else { drawer_list_item_indicator.visibility = View.INVISIBLE } setOnClickListener { listener(item) } } } }
app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/DrawerRecyclerAdapter.kt
2106255700
// IS_APPLICABLE: false fun <caret>foo(): Unit { }
plugins/kotlin/fir/testData/intentions/useExpressionBody/convertToExpressionBody/funWithEmptyBody2.kt
3152909297
// "Create enum 'A'" "true" // ERROR: Unresolved reference: A import J.A class X { }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/importDirective/enumWithJavaQualifier.after.kt
3362008422