repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
REDNBLACK/advent-of-code2016
src/main/kotlin/day15/Advent15.kt
1
4570
package day15 import parseInput import splitToLines /** --- Day 15: Timing is Everything --- The halls open into an interior plaza containing a large kinetic sculpture. The sculpture is in a sealed enclosure and seems to involve a set of identical spherical capsules that are carried to the top and allowed to bounce through the maze of spinning pieces. Part of the sculpture is even interactive! When a button is pressed, a capsule is dropped and tries to fall through slots in a set of rotating discs to finally go through a little hole at the bottom and come out of the sculpture. If any of the slots aren't aligned with the capsule as it passes, the capsule bounces off the disc and soars away. You feel compelled to get one of those capsules. The discs pause their motion each second and come in different sizes; they seem to each have a fixed number of positions at which they stop. You decide to call the position with the slot 0, and count up for each position it reaches next. Furthermore, the discs are spaced out so that after you push the button, one second elapses before the first disc is reached, and one second elapses as the capsule passes from one disc to the one below it. So, if you push the button at time=100, then the capsule reaches the top disc at time=101, the second disc at time=102, the third disc at time=103, and so on. The button will only drop a capsule at an integer time - no fractional seconds allowed. For example, at time=0, suppose you see the following arrangement: Disc #1 has 5 positions; at time=0, it is at position 4. Disc #2 has 2 positions; at time=0, it is at position 1. If you press the button exactly at time=0, the capsule would start to fall; it would reach the first disc at time=1. Since the first disc was at position 4 at time=0, by time=1 it has ticked one position forward. As a five-position disc, the next position is 0, and the capsule falls through the slot. Then, at time=2, the capsule reaches the second disc. The second disc has ticked forward two positions at this point: it started at position 1, then continued to position 0, and finally ended up at position 1 again. Because there's only a slot at position 0, the capsule bounces away. If, however, you wait until time=5 to push the button, then when the capsule reaches each disc, the first disc will have ticked forward 5+1 = 6 times (to position 0), and the second disc will have ticked forward 5+2 = 7 times (also to position 0). In this case, the capsule would fall through the discs and come out of the machine. However, your situation has more than two discs; you've noted their positions in your puzzle input. What is the first time you can press the button to get a capsule? --- Part Two --- After getting the first capsule (it contained a star! what great fortune!), the machine detects your success and begins to rearrange itself. When it's done, the discs are back in their original configuration as if it were time=0 again, but a new disc with 11 positions and starting at position 0 has appeared exactly one second below the previously-bottom disc. With this new disc, and counting again starting from time=0 with the configuration in your puzzle input, what is the first time you can press the button to get another capsule? */ fun main(args: Array<String>) { val test = """Disc #1 has 5 positions; at time=0, it is at position 4. |Disc #2 has 2 positions; at time=0, it is at position 1.""".trimMargin() val input = parseInput("day15-input.txt") val func1 = ::parseDiscs println(getTiming(test, func1) == 5) println(getTiming(input, func1)) val func2 = { input: String -> val discs = parseDiscs(input) discs.plus(Disc(discs.size + 1, 11, 0)) } println(getTiming(test, func2) == 85) println(getTiming(input, func2)) } data class Disc(val id: Int, val posCount: Int, val startPos: Int) fun getTiming(input: String, parseFunc: (String) -> List<Disc>): Int { tailrec fun loop(time: Int, discs: List<Disc>): Int { if (discs.none { d -> (d.startPos + d.id + time) % d.posCount != 0 }) return time return loop(time + 1, discs) } return loop(1, parseFunc(input)) } private fun parseDiscs(input: String) = input.splitToLines() .map { s -> val (id, posCount, _skip, startPos) = Regex("""(\d+)""") .findAll(s) .map { it.value } .toList() Disc(id = id.toInt(), posCount = posCount.toInt(), startPos = startPos.toInt()) }
mit
42f56bdcac0b05e5ec087a06b38bace9
57.589744
393
0.717724
3.882753
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/service/CollectionUploadService.kt
1
5244
package com.intfocus.template.service import android.app.IntentService import android.content.Context import android.content.Intent import com.google.gson.Gson import com.intfocus.template.SYPApplication.globalContext import com.intfocus.template.constant.Module.UPLOAD_IMAGES import com.intfocus.template.constant.Params.USER_BEAN import com.intfocus.template.constant.Params.USER_NUM import com.intfocus.template.general.net.RetrofitUtil import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.entity.Collection import com.intfocus.template.model.gen.CollectionDao import com.intfocus.template.model.gen.SourceDao import com.intfocus.template.subject.nine.entity.CollectionRequestBody import com.intfocus.template.util.K import com.intfocus.template.util.TempHost import com.intfocus.template.util.URLs import com.intfocus.template.util.Utils import okhttp3.* import org.json.JSONArray import org.json.JSONObject import java.io.File /** * @author liuruilin * @data 2017/11/7 * @describe 数据采集信息上传服务 */ class CollectionUploadService : IntentService("collection_upload") { private lateinit var collectionDao: CollectionDao private lateinit var sourceDao: SourceDao override fun onHandleIntent(p0: Intent?) { collectionDao = DaoUtil.getCollectionDao() val collectionList = collectionDao.loadAll() sourceDao = DaoUtil.getSourceDao() collectionList .filter { 0 == it.status } .forEach { if (1 != it.imageStatus) { uploadImage(it) } else { generateDJson(it) } } } /** * 上传图片 */ private fun uploadImage(collection: Collection) { val uuid = collection.uuid val reportId = collection.reportId val sourceQb = sourceDao.queryBuilder() val sourceList = sourceQb.where(sourceQb.and(SourceDao.Properties.Type.eq(UPLOAD_IMAGES), SourceDao.Properties.Uuid.eq(uuid))).list() // 如果采集数据中不包含图片, 直接生成 D_JSON if (sourceList.size < 1) { collection.imageStatus = 1 collectionDao.update(collection) generateDJson(collection) return } for (source in sourceList) { val fileList: MutableList<File> = arrayListOf() if (source.value.isEmpty()) { collection.imageStatus = 1 collectionDao.update(collection) generateDJson(collection) return } (Utils.stringToList(source.value)).mapTo(fileList) { File(it) } val mOkHttpClient = OkHttpClient() val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("api_token", URLs.MD5(K.ANDROID_API_KEY + K.API_IMAGE_UPLOAD + K.ANDROID_API_KEY)) .addFormDataPart("module_name", reportId) if (!fileList.isEmpty()) { fileList.forEachIndexed { index, itemFile -> if (itemFile.exists()) { requestBody.addFormDataPart("image" + index, itemFile.name, RequestBody.create(MediaType.parse("image/*"), itemFile)) } } } val request = Request.Builder() .url(TempHost.getHost() + K.API_IMAGE_UPLOAD) .post(requestBody.build()) .build() val result = mOkHttpClient.newCall(request).execute() if (!result.isSuccessful) { return } val responseData = result.body()!!.string() val valueArray = JSONObject(responseData)["data"] as JSONArray source.value = Gson().toJson(valueArray) sourceDao.update(source) } collection.imageStatus = 1 collectionDao.update(collection) generateDJson(collection) } /** * 生成需要上传给服务的 D_JSON (采集结果) */ private fun generateDJson(collection: Collection) { val moduleList = sourceDao.queryBuilder().where(SourceDao.Properties.Uuid.eq(collection.uuid)).list() val dJson = JSONObject() for (module in moduleList) { dJson.put(module.key, module.value) } uploadDJSon(Gson().toJson(dJson), collection) } /** * 上传 D_JSON 至服务器 */ private fun uploadDJSon(dJson: String, collection: Collection) { val collectionRequestBody = CollectionRequestBody() val data = CollectionRequestBody.Data() data.user_num = getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE).getString(USER_NUM, "") data.report_id = collection.reportId data.content = dJson collectionRequestBody.data = data val result = RetrofitUtil.getHttpService(globalContext).submitCollection(collectionRequestBody).execute() if (result.isSuccessful) { collection.status = 1 collection.dJson = dJson collectionDao.update(collection) } } }
gpl-3.0
059842a8289c6a37a74216ce67f6641f
31.974359
141
0.622473
4.601073
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/adapter/SimpleStickyListHeadersAdapter.kt
1
2773
package de.tum.`in`.tumcampusapp.component.other.generic.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import de.tum.`in`.tumcampusapp.R import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter /** * An abstract StickyListHeadersAdapter helps to reduce redundant work for using StickyListHeaders. * It implements some method required by StickyListHeadersAdapter, including getHeaderView getHeaderId, * getCount, getItem and getItemId. * By extending this class only getView needs to implemented. * On the other hand this class requires the data model implementing its interface to get header name and id. * * @param <T> the data model </T> */ abstract class SimpleStickyListHeadersAdapter<T : SimpleStickyListHeadersAdapter.SimpleStickyListItem>( var context: Context, var itemList: MutableList<T> ) : BaseAdapter(), StickyListHeadersAdapter { private val filters: MutableList<String> val inflater: LayoutInflater = LayoutInflater.from(context) init { filters = itemList.map { it.getHeaderId() }.distinct().toMutableList() } // needs to be implemented by subclass abstract override fun getView(position: Int, convertView: View?, parent: ViewGroup): View override fun getHeaderView(position: Int, convertView: View?, parent: ViewGroup): View { val holder: HeaderViewHolder val view: View if (convertView == null) { holder = HeaderViewHolder() view = inflater.inflate(R.layout.header, parent, false) holder.text = view.findViewById(R.id.lecture_header) view.tag = holder } else { view = convertView holder = view.tag as HeaderViewHolder } val headerText = generateHeaderName(itemList[position]) holder.text?.text = headerText return view } /** * Generate header for this item. * This method can be overridden if the header name needs to be modified. * * @param item the item * @return the header for this item */ open fun generateHeaderName(item: T): String = item.getHeadName() override fun getHeaderId(i: Int): Long = filters.indexOf(itemList[i].getHeaderId()).toLong() override fun getCount(): Int = itemList.size override fun getItem(position: Int) = itemList[position] override fun getItemId(position: Int): Long = position.toLong() // Header view private class HeaderViewHolder { internal var text: TextView? = null } interface SimpleStickyListItem { fun getHeadName(): String fun getHeaderId(): String } }
gpl-3.0
bc167a3cedea61dd37ccbb5ab228d5ba
32.829268
109
0.70321
4.684122
false
false
false
false
mike-neck/kuickcheck
example/src/test/kotlin/org/mikeneck/example/java/util/SetCheck.kt
1
964
/* * Copyright 2016 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.example.java.util import org.mikeneck.kuickcheck.Property import org.mikeneck.kuickcheck.forAll import org.mikeneck.kuickcheck.int import org.mikeneck.kuickcheck.set object SetCheck { @Property val elementIsUniqueInSet = forAll(set(int(0, 40)).size(15)) .satisfy { s -> s.map { i -> s.filter { it == i } }.all { it.size == 1 } } }
apache-2.0
163c1d0c07a2b84531a47f958ff1afcd
33.428571
86
0.728216
3.810277
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/TavernDetailFragment.kt
1
8290
package com.habitrpg.android.habitica.ui.fragments.social import android.content.Context import android.graphics.PorterDuff import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.FragmentTavernDetailBinding import com.habitrpg.android.habitica.extensions.setTintWith import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.social.Group import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.fragments.BaseFragment import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import com.habitrpg.android.habitica.ui.views.UsernameLabel import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import com.habitrpg.common.habitica.models.PlayerTier import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject class TavernDetailFragment : BaseFragment<FragmentTavernDetailBinding>() { @Inject lateinit var userRepository: UserRepository @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var userViewModel: MainUserViewModel @Inject lateinit var configManager: AppConfigManager private var shopSpriteSuffix = "" override var binding: FragmentTavernDetailBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentTavernDetailBinding { return FragmentTavernDetailBinding.inflate(inflater, container, false) } private var user: User? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) shopSpriteSuffix = configManager.shopSpriteSuffix() userViewModel.user.observe(viewLifecycleOwner) { user = it updatePausedState() } binding?.shopHeader?.descriptionView?.setText(R.string.tavern_description) binding?.shopHeader?.namePlate?.setText(R.string.tavern_owner) binding?.shopHeader?.npcBannerView?.shopSpriteSuffix = configManager.shopSpriteSuffix() binding?.shopHeader?.npcBannerView?.identifier = "tavern" addPlayerTiers() bindButtons() lifecycleScope.launch(ExceptionHandler.coroutine()) { socialRepository.getGroup(Group.TAVERN_ID) .onEach { if (it?.hasActiveQuest == false) binding?.worldBossSection?.visibility = View.GONE } .filter { it != null && it.hasActiveQuest } .onEach { binding?.questProgressView?.progress = it?.quest binding?.shopHeader?.descriptionView?.setText(R.string.tavern_description_world_boss) val filtered = it?.quest?.rageStrikes?.filter { strike -> strike.key == "tavern" } if ((filtered?.size ?: 0) > 0 && filtered?.get(0)?.wasHit == true) { val key = it.quest?.key if (key != null) { shopSpriteSuffix = key } } } .map { inventoryRepository.getQuestContent(it?.quest?.key ?: "").firstOrNull() } .collect { binding?.questProgressView?.quest = it binding?.worldBossSection?.visibility = View.VISIBLE } } lifecycleScope.launch(ExceptionHandler.coroutine()) { socialRepository.retrieveGroup(Group.TAVERN_ID) } user?.let { binding?.questProgressView?.configure(it) } } override fun onDestroy() { userRepository.close() socialRepository.close() inventoryRepository.close() super.onDestroy() } private fun bindButtons() { binding?.innButton?.setOnClickListener { lifecycleScope.launch(ExceptionHandler.coroutine()) { user?.let { user -> userRepository.sleep(user) } } } binding?.guidelinesButton?.setOnClickListener { MainNavigationController.navigate(R.id.guidelinesActivity) } binding?.faqButton?.setOnClickListener { MainNavigationController.navigate(R.id.FAQOverviewFragment) } binding?.reportButton?.setOnClickListener { MainNavigationController.navigate(R.id.aboutFragment) } binding?.worldBossSection?.infoIconView?.setOnClickListener { val context = this.context val quest = binding?.questProgressView?.quest if (context != null && quest != null) { showWorldBossInfoDialog(context, quest) } } } private fun updatePausedState() { if (binding?.innButton == null) { return } if (user?.preferences?.sleep == true) { binding?.innButton?.setText(R.string.tavern_inn_checkOut) } else { binding?.innButton?.setText(R.string.tavern_inn_rest) } } private fun addPlayerTiers() { for (tier in PlayerTier.getTiers()) { context?.let { val container = FrameLayout(it) container.background = ContextCompat.getDrawable(it, R.drawable.layout_rounded_bg_window) val label = UsernameLabel(it, null) label.tier = tier.id label.username = tier.title val params = FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER ) container.addView(label, params) binding?.playerTiersView?.addView(container) val padding = context?.resources?.getDimension(R.dimen.spacing_medium)?.toInt() ?: 0 container.setPadding(0, padding, 0, padding) } } (binding?.playerTiersView?.parent as? ViewGroup)?.invalidate() } override fun injectFragment(component: UserComponent) { component.inject(this) } companion object { fun showWorldBossInfoDialog(context: Context, quest: QuestContent) { val alert = HabiticaAlertDialog(context) val bossName = quest.boss?.name ?: "" alert.setTitle(R.string.world_boss_description_title) // alert.setSubtitle(context.getString(R.string.world_boss_description_subtitle, bossName)) alert.setAdditionalContentView(R.layout.world_boss_description_view) val descriptionView = alert.getContentView() val promptView: TextView? = descriptionView?.findViewById(R.id.worldBossActionPromptView) promptView?.text = context.getString(R.string.world_boss_action_prompt, bossName) promptView?.setTextColor(quest.colors?.lightColor ?: 0) val background = ContextCompat.getDrawable(context, R.drawable.rounded_border) background?.setTintWith(quest.colors?.extraLightColor ?: 0, PorterDuff.Mode.MULTIPLY) promptView?.background = background alert.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.close)) { dialog, _ -> dialog.dismiss() } alert.show() } } }
gpl-3.0
a8f77d37777a73df2f0490c3a77d1f58
40.243781
111
0.668154
4.914049
false
false
false
false
caot/intellij-community
plugins/settings-repository/src/autoSync.kt
2
5903
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.configurationStore.ComponentStoreImpl import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.notification.NotificationsAdapter import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationAdapter import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.ShutDownTracker import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import java.util.concurrent.Future class AutoSyncManager(private val icsManager: IcsManager) { private volatile var autoSyncFuture: Future<*>? = null fun waitAutoSync(indicator: ProgressIndicator) { val autoFuture = autoSyncFuture if (autoFuture != null) { if (autoFuture.isDone()) { autoSyncFuture = null } else if (autoSyncFuture != null) { LOG.info("Wait for auto sync future") indicator.setText("Wait for auto sync completion") while (!autoFuture.isDone()) { if (indicator.isCanceled()) { return } Thread.sleep(5) } } } } fun registerListeners(application: Application) { application.addApplicationListener(object : ApplicationAdapter() { override fun applicationExiting() { autoSync(true) } }) } fun registerListeners(project: Project) { project.getMessageBus().connect().subscribe(Notifications.TOPIC, object : NotificationsAdapter() { override fun notify(notification: Notification) { if (!icsManager.repositoryActive || project.isDisposed()) { return } if (when { notification.getGroupId() == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.getDisplayId() -> { val message = notification.getContent() message.startsWith("VCS Update Finished") || message == VcsBundle.message("message.text.file.is.up.to.date") || message == VcsBundle.message("message.text.all.files.are.up.to.date") } notification.getGroupId() == VcsNotifier.NOTIFICATION_GROUP_ID.getDisplayId() && notification.getTitle() == "Push successful" -> true else -> false }) { autoSync() } } }) } fun autoSync(onAppExit: Boolean = false) { if (!icsManager.repositoryActive) { return } var future = autoSyncFuture if (future != null && !future.isDone()) { return } val app = ApplicationManagerEx.getApplicationEx() as ApplicationImpl if (onAppExit) { sync(app, onAppExit) return } else if (app.isDisposeInProgress()) { // will be handled by applicationExiting listener return } future = app.executeOnPooledThread { if (autoSyncFuture == future) { // to ensure that repository will not be in uncompleted state and changes will be pushed ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread()) try { sync(app, onAppExit) } finally { autoSyncFuture = null ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread()) } } } autoSyncFuture = future } private fun sync(app: ApplicationImpl, onAppExit: Boolean) { catchAndLog { icsManager.runInAutoCommitDisabledMode { val repositoryManager = icsManager.repositoryManager if (!repositoryManager.canCommit()) { LOG.warn("Auto sync skipped: repository is not committable") return@runInAutoCommitDisabledMode } // on app exit fetch and push only if there are commits to push if (onAppExit && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0) { return@runInAutoCommitDisabledMode } val updater = repositoryManager.fetch() // we merge in EDT non-modal to ensure that new settings will be properly applied app.invokeAndWait({ catchAndLog { val updateResult = updater.merge() if (!onAppExit && !app.isDisposeInProgress() && updateResult != null && updateStoragesFromStreamProvider(app.stateStore as ComponentStoreImpl, updateResult, app.getMessageBus())) { // force to avoid saveAll & confirmation app.exit(true, true, true, true) } } }, ModalityState.NON_MODAL) if (!updater.definitelySkipPush) { repositoryManager.push() } } } } } inline fun catchAndLog(runnable: () -> Unit) { try { runnable() } catch (e: ProcessCanceledException) { } catch (e: Throwable) { if (e is AuthenticationException || e is NoRemoteRepositoryException) { LOG.warn(e) } else { LOG.error(e) } } }
apache-2.0
f7725a106a698d17bd8ef31696cb5742
32.355932
192
0.67525
4.818776
false
false
false
false
docker-client/docker-compose-v3
src/test/kotlin/de/gesellix/docker/compose/interpolation/TemplateTest.kt
1
2700
package de.gesellix.docker.compose.interpolation import io.kotest.core.spec.style.DescribeSpec import kotlin.test.assertEquals import kotlin.test.assertFailsWith class TemplateTest : DescribeSpec({ describe("Template") { val defaults = hashMapOf<String, String>().apply { put("FOO", "first") put("BAR", "") } context("an escaped template") { val t = "\$\${foo}" val rendered = Template().substitute(t, defaults) it("should return the un-escaped input '\${foo}'") { assertEquals("\${foo}", rendered) } } context("an invalid template") { listOf( "\${", "\$}", "\${}", "\${ }", "\${ foo}", "\${foo }", "\${foo!}" ).forEach { t -> it("should fail for $t") { assertFailsWith(Exception::class) { Template().substitute(t, defaults) } } } } context("a template without value and without default") { listOf( "This \${missing} var", "This \${BAR} var" ).forEach { t -> val rendered = Template().substitute(t, defaults) it("should render $t as 'This var'") { assertEquals("This var", rendered) } } } context("a template with value and without default") { listOf( "This \$FOO var", "This \${FOO} var" ).forEach { t -> val rendered = Template().substitute(t, defaults) it("should render $t as 'This first var'") { assertEquals("This first var", rendered) } } } context("a template without value but with default") { listOf( "ok \${missing:-def}", "ok \${missing-def}" ).forEach { t -> val rendered = Template().substitute(t, defaults) it("should render $t as 'ok def'") { assertEquals("ok def", rendered) } } } context("a template with empty value but with soft default") { val t = "ok \${BAR:-def}" val rendered = Template().substitute(t, defaults) it("should render $t as 'ok def'") { assertEquals("ok def", rendered) } } context("a template with empty value but with hard default") { val t = "ok \${BAR-def}" val rendered = Template().substitute(t, defaults) it("should render $t as 'ok def'") { assertEquals("ok ", rendered) } } context("a non alphanumeric default") { val t = "ok \${BAR:-/non:-alphanumeric}" val rendered = Template().substitute(t, defaults) it("should render $t as 'ok /non:-alphanumeric'") { assertEquals("ok /non:-alphanumeric", rendered) } } } })
mit
65a443e6644fba7bcd8622cb40fdf106
24.471698
82
0.535926
4.231975
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/coroutines/controlFlow_inline2.kt
1
766
import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> { companion object : EmptyContinuation() override fun resume(value: Any?) {} override fun resumeWithException(exception: Throwable) { throw exception } } suspend fun s1(): Int = suspendCoroutineOrReturn { x -> println("s1") x.resume(42) COROUTINE_SUSPENDED } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } inline suspend fun inline_s2(): Int { var x = s1() return x } fun main(args: Array<String>) { var result = 0 builder { result = inline_s2() } println(result) }
apache-2.0
702489ee067bd630a96ff8c5fcf262f6
22.212121
115
0.690601
4.163043
false
false
false
false
anrelic/Anci-OSS
event/src/main/kotlin/su/jfdev/anci/event/DummyBus.kt
1
564
package su.jfdev.anci.event /** * Jamefrus and his team on 14.06.2016. */ object DummyBus: EventBus<Any> { override fun unregister(subscriber: (Any) -> Unit) = Unit override fun handle(event: Any) = Unit override fun sync(event: Any) = Unit override val loop: EventLoop = object: EventLoop { override fun <E: Any> handle(subscribers: Collection<(E) -> Unit>, event: E) = Unit override fun <E: Any> sync(subscribers: Collection<(E) -> Unit>, event: E) = Unit } override fun register(subscriber: (Any) -> Unit) = Unit }
mit
8bfe5cc0d094206f3bbbde4aab4a362f
28.736842
91
0.647163
3.615385
false
false
false
false
apollostack/apollo-android
composite/integration-tests/src/testShared/kotlin/com/apollographql/apollo3/CacheHeadersTest.kt
1
5674
package com.apollographql.apollo3 import com.apollographql.apollo3.Utils.immediateExecutor import com.apollographql.apollo3.Utils.immediateExecutorService import com.apollographql.apollo3.Utils.readFileToString import com.apollographql.apollo3.api.Optional import com.apollographql.apollo3.cache.ApolloCacheHeaders import com.apollographql.apollo3.cache.CacheHeaders import com.apollographql.apollo3.cache.CacheHeaders.Companion.builder import com.apollographql.apollo3.cache.normalized.* import com.apollographql.apollo3.coroutines.await import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.integration.normalizer.HeroAndFriendsNamesQuery import com.apollographql.apollo3.integration.normalizer.type.Episode import com.apollographql.apollo3.rx2.Rx2Apollo import com.google.common.truth.Truth import kotlinx.coroutines.runBlocking import okhttp3.Dispatcher import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.Test import java.io.IOException import java.util.concurrent.atomic.AtomicBoolean import kotlin.reflect.KClass class CacheHeadersTest { val server = MockWebServer() @Test @Throws(ApolloException::class, IOException::class) fun testHeadersReceived() { val hasHeader = AtomicBoolean() val normalizedCache: NormalizedCache = object : NormalizedCache() { override fun loadRecord(key: String, cacheHeaders: CacheHeaders): Record? { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return null } override fun merge(record: Record, cacheHeaders: CacheHeaders): Set<String> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptySet<String>() } override fun clearAll() {} override fun remove(cacheKey: CacheKey, cascade: Boolean): Boolean { return false } override fun loadRecords(keys: Collection<String>, cacheHeaders: CacheHeaders): Collection<Record> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptyList() } override fun merge(records: Collection<Record>, cacheHeaders: CacheHeaders): Set<String> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptySet() } override fun dump(): Map<@JvmSuppressWildcards KClass<*>, Map<String, Record>> { return emptyMap() } } val cacheFactory: NormalizedCacheFactory = object : NormalizedCacheFactory() { override fun create(): NormalizedCache { return normalizedCache } } val apolloClient = ApolloClient.builder() .normalizedCache(cacheFactory, IdFieldCacheKeyResolver()) .serverUrl(server.url("/")) .okHttpClient(OkHttpClient.Builder().dispatcher(Dispatcher(immediateExecutorService())).build()) .dispatcher(immediateExecutor()) .build() server.enqueue(mockResponse("HeroAndFriendsNameResponse.json")) val cacheHeaders = builder().addHeader(ApolloCacheHeaders.DO_NOT_STORE, "true").build() Rx2Apollo.from(apolloClient.query(HeroAndFriendsNamesQuery(Episode.NEWHOPE)) .cacheHeaders(cacheHeaders)) .test() Truth.assertThat(hasHeader.get()).isTrue() } @Test @Throws(Exception::class) fun testDefaultHeadersReceived() { val hasHeader = AtomicBoolean() val normalizedCache: NormalizedCache = object : NormalizedCache() { override fun loadRecord(key: String, cacheHeaders: CacheHeaders): Record? { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return null } override fun merge(record: Record, cacheHeaders: CacheHeaders): Set<String> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptySet<String>() } override fun clearAll() {} override fun remove(cacheKey: CacheKey, cascade: Boolean): Boolean { return false } override fun loadRecords(keys: Collection<String>, cacheHeaders: CacheHeaders): Collection<Record> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptyList() } override fun merge(records: Collection<Record>, cacheHeaders: CacheHeaders): Set<String> { hasHeader.set(cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) return emptySet() } override fun dump(): Map<@JvmSuppressWildcards KClass<*>, Map<String, Record>> { return emptyMap() } } val cacheFactory: NormalizedCacheFactory = object : NormalizedCacheFactory() { override fun create(): NormalizedCache { return normalizedCache } } val cacheHeaders = builder().addHeader(ApolloCacheHeaders.DO_NOT_STORE, "true").build() val apolloClient = ApolloClient.builder() .normalizedCache(cacheFactory, IdFieldCacheKeyResolver()) .serverUrl(server.url("/")) .okHttpClient(OkHttpClient.Builder().dispatcher(Dispatcher(immediateExecutorService())).build()) .dispatcher(immediateExecutor()) .defaultCacheHeaders(cacheHeaders) .build() server.enqueue(mockResponse("HeroAndFriendsNameResponse.json")) runBlocking { apolloClient.query(HeroAndFriendsNamesQuery(Episode.NEWHOPE)) .cacheHeaders(cacheHeaders) .await() } Truth.assertThat(hasHeader.get()).isTrue() } @Throws(IOException::class) private fun mockResponse(fileName: String): MockResponse { return MockResponse().setChunkedBody(readFileToString(javaClass, "/$fileName"), 32) } }
mit
63f67586740378ecb874cbffadb5fab8
37.863014
106
0.728234
4.689256
false
false
false
false
sdoward/AwarenessApiPlayGround
app/src/main/java/com/sdoward/awareness/android/MainActivity.kt
1
3425
package com.sdoward.awareness.android import android.Manifest import android.content.Intent import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import com.google.android.gms.awareness.Awareness import com.google.android.gms.common.api.GoogleApiClient import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Function3 import kotlinx.android.synthetic.main.main_activity.* import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { val repository: Repository by lazy { Repository(UserManager(PreferenceManager.getDefaultSharedPreferences(this)).getIdentifier()) } val client: GoogleApiClient by lazy { GoogleApiClient.Builder(this) .addApi(Awareness.API) .build() } val dateFormat = SimpleDateFormat("dd-MM-yyyy HH:mm:ss") val disposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) setSupportActionBar(toolbar) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 0) client.connect() activitiesButton.setOnClickListener { Awareness.SnapshotApi.getActivityObservable(client) .map { AwarenessModel(it) } .doOnSuccess { repository.setData(getDateTime(), it) } .subscribe { activities -> infoTextView.text = activities.toString() } .addTo(disposable) } locationButton.setOnClickListener { Awareness.SnapshotApi.getLocationObservable(client) .map { AwarenessModel(location = it) } .doOnSuccess { repository.setData(getDateTime(), it) } .subscribe { location -> infoTextView.text = location.toString() } .addTo(disposable) } placesButton.setOnClickListener { Awareness.SnapshotApi.getPlacesObservable(client) .map { AwarenessModel(places = it) } .doOnSuccess { repository.setData(getDateTime(), it) } .subscribe { places -> infoTextView.text = places.toString() } .addTo(disposable) } getAllButton.setOnClickListener { Single.zip( Awareness.SnapshotApi.getActivityObservable(client), Awareness.SnapshotApi.getLocationObservable(client), Awareness.SnapshotApi.getPlacesObservable(client), Function3<List<Activity>, Location, List<Place>, AwarenessModel> { activities, location, places -> AwarenessModel(activities, location, places) }) .doOnSuccess { repository.setData(getDateTime(), it) } .subscribe { awarenessModel -> infoTextView.text = awarenessModel.toString() } .addTo(disposable) } geoFenceButton.setOnClickListener { startActivity(Intent(this, GeoFenceActivity::class.java)) } } fun getDateTime() = dateFormat.format(Date()) override fun onDestroy() { client.disconnect() disposable.clear() super.onDestroy() } }
apache-2.0
a2ab15104073d7408994030ba625fc0e
40.768293
166
0.654599
5.074074
false
false
false
false
PolymerLabs/arcs
javatests/arcs/showcase/instant/Calendar.kt
1
1036
@file:Suppress("EXPERIMENTAL_FEATURE_WARNING", "EXPERIMENTAL_API_USAGE") package arcs.showcase.instant import arcs.jvm.host.TargetHost import arcs.sdk.ArcsDuration import arcs.sdk.ArcsInstant typealias Event = AbstractCalendar.Event @TargetHost(arcs.android.integration.IntegrationHost::class) class Calendar : AbstractCalendar() { override fun onFirstStart() { handles.events.storeAll( setOf( Event( name = "Launch", start = ArcsInstant.ofEpochMilli(819007320000), // 1995-12-15 i.e. not today end = ArcsInstant.ofEpochMilli(819093720000) ), Event( name = "Celebration", start = ArcsInstant.ofEpochMilli(1552266000000), // 2019-03-11 i.e. not today end = ArcsInstant.ofEpochMilli(1552269600000) ), Event( name = "Team Meeting", start = ArcsInstant.now().plus(ArcsDuration.ofHours(1)), // today, in 1 hour end = ArcsInstant.now().plus(ArcsDuration.ofHours(2)) ) ) ) } }
bsd-3-clause
897c44f05edbcb44ee7bd438f38f39b0
29.470588
87
0.646718
3.894737
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSelectionSpinner.kt
2
3236
package com.fsck.k9.ui.settings.account import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import androidx.appcompat.widget.AppCompatSpinner import androidx.core.view.isVisible import com.fsck.k9.Account import com.fsck.k9.ui.R class AccountSelectionSpinner : AppCompatSpinner { var selection: Account get() = selectedItem as Account set(account) { selectedAccount = account val adapter = adapter as AccountsAdapter val adapterPosition = adapter.getPosition(account) setSelection(adapterPosition, false) } private val cachedBackground: Drawable private var selectedAccount: Account? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) init { adapter = AccountsAdapter(context) cachedBackground = background } fun setTitle(title: CharSequence) { val adapter = adapter as AccountsAdapter adapter.title = title adapter.notifyDataSetChanged() } fun setAccounts(accounts: List<Account>) { val adapter = adapter as AccountsAdapter adapter.clear() adapter.addAll(accounts) selectedAccount?.let { selection = it } val showAccountSwitcher = accounts.size > 1 isEnabled = showAccountSwitcher background = if (showAccountSwitcher) cachedBackground else null } internal class AccountsAdapter(context: Context) : ArrayAdapter<Account>(context, 0) { var title: CharSequence = "" override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val account = getItem(position) ?: error("No item at position $position") val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.account_spinner_item, parent, false) val name: TextView = view.findViewById(R.id.name) val email: TextView = view.findViewById(R.id.email) return view.apply { name.text = title email.text = account.displayName } } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val account = getItem(position) ?: error("No item at position $position") val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.account_spinner_dropdown_item, parent, false) val name: TextView = view.findViewById(R.id.name) val email: TextView = view.findViewById(R.id.email) return view.apply { val accountName = account.name if (accountName != null) { name.text = accountName email.text = account.email email.isVisible = true } else { name.text = account.email email.isVisible = false } } } } }
apache-2.0
1a982ae64ec2d965d7fb8af0fbf49e96
33.425532
120
0.637824
4.91047
false
false
false
false
livefront/bridge
bridgesample/src/main/java/com/livefront/bridgesample/scenario/activity/LargeDataActivity.kt
1
2368
package com.livefront.bridgesample.scenario.activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.os.Parcelable import android.view.MenuItem import com.evernote.android.state.State import com.livefront.bridgesample.R import com.livefront.bridgesample.base.BridgeBaseActivity import com.livefront.bridgesample.util.handleHomeAsBack import com.livefront.bridgesample.util.setHomeAsUpToolbar import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.activity_large_data.bitmapGeneratorView import kotlinx.android.synthetic.main.basic_toolbar.toolbar class LargeDataActivity : BridgeBaseActivity() { @State var savedBitmap: Bitmap? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_large_data) setHomeAsUpToolbar(toolbar, R.string.large_data_screen_title) bitmapGeneratorView.apply { setHeaderText(R.string.large_data_header) generatedBitmap = savedBitmap onBitmapGeneratedListener = { savedBitmap = it } if (getArguments(this@LargeDataActivity).infiniteBackstack) { onNavigateButtonClickListener = { startActivity( getNavigationIntent( this@LargeDataActivity, getArguments(this@LargeDataActivity) ) ) } } } } override fun onOptionsItemSelected(item: MenuItem) = handleHomeAsBack(item) { super.onOptionsItemSelected(item) } companion object { private const val ARGUMENTS_KEY = "arguments" fun getArguments( activity: LargeDataActivity ): LargeDataActivityArguments = activity .intent .getParcelableExtra(ARGUMENTS_KEY)!! fun getNavigationIntent( context: Context, arguments: LargeDataActivityArguments ) = Intent(context, LargeDataActivity::class.java).apply { putExtra(ARGUMENTS_KEY, arguments) } } } @Parcelize data class LargeDataActivityArguments( val infiniteBackstack: Boolean = false ) : Parcelable
apache-2.0
d5a9830bf330170de1a4e2e844ac9595
33.318841
81
0.667652
5.238938
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt
3
3579
// 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.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.psi.KtObjectLiteralExpression import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUObjectLiteralExpression( override val sourcePsi: KtObjectLiteralExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UObjectLiteralExpression, UCallExpression, DelegatedMultiResolve, KotlinUElementWithType { override val declaration: UClass by lz { sourcePsi.objectDeclaration.toLightClass() ?.let { languagePlugin?.convertOpt(it, this) } ?: KotlinInvalidUClass("<invalid object code>", sourcePsi, this) } override fun getExpressionType() = sourcePsi.objectDeclaration.toPsiType() private val superClassConstructorCall by lz { sourcePsi.objectDeclaration.superTypeListEntries.firstOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } override val classReference: UReferenceExpression? by lz { superClassConstructorCall?.let { ObjectLiteralClassReference(it, this) } } override val valueArgumentCount: Int get() = superClassConstructorCall?.valueArguments?.size ?: 0 override val valueArguments by lz { val psi = superClassConstructorCall ?: return@lz emptyList<UExpression>() psi.valueArguments.map { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) } } override val typeArgumentCount: Int get() = superClassConstructorCall?.typeArguments?.size ?: 0 override val typeArguments by lz { val psi = superClassConstructorCall ?: return@lz emptyList<PsiType>() psi.typeArguments.map { typeArgument -> typeArgument.typeReference?.let { baseResolveProviderService.resolveToType(it, this, boxed = true) } ?: UastErrorType } } override fun resolve() = superClassConstructorCall?.let { baseResolveProviderService.resolveCall(it) } override fun getArgumentForParameter(i: Int): UExpression? = superClassConstructorCall?.let { baseResolveProviderService.getArgumentForParameter(it, i, this) } private class ObjectLiteralClassReference( override val sourcePsi: KtSuperTypeCallEntry, givenParent: UElement? ) : KotlinAbstractUElement(givenParent), USimpleNameReferenceExpression { override val javaPsi: PsiElement? get() = null override val psi: KtSuperTypeCallEntry get() = sourcePsi override fun resolve() = baseResolveProviderService.resolveToClassIfConstructorCall(sourcePsi, this) ?: baseResolveProviderService.resolveCall(sourcePsi)?.containingClass override val uAnnotations: List<UAnnotation> get() = emptyList() override val resolvedName: String get() = identifier override val identifier: String get() = psi.name ?: referenceNameElement.sourcePsi?.text ?: "<error>" override val referenceNameElement: UElement get() = KotlinUIdentifier(psi.typeReference?.nameElement, this) } }
apache-2.0
a1109e6ed664c9cf145ed2e85e786c95
38.32967
158
0.724504
5.717252
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/expectActualUtil.kt
3
7465
// 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.util import com.intellij.openapi.module.Module import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.allImplementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.multiplatform.* fun MemberDescriptor.expectedDescriptors(): List<DeclarationDescriptor> { val expectedCompatibilityMap = ExpectedActualResolver.findExpectedForActual(this) ?: return emptyList() return expectedCompatibilityMap[ExpectActualCompatibility.Compatible] ?: expectedCompatibilityMap.values.flatten() } // TODO: Sort out the cases with multiple expected descriptors fun MemberDescriptor.expectedDescriptor(): DeclarationDescriptor? { return expectedDescriptors().firstOrNull() } fun KtDeclaration.expectedDeclarationIfAny(): KtDeclaration? { val expectedDescriptor = (resolveToDescriptorIfAny() as? MemberDescriptor)?.expectedDescriptor() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtDeclaration } fun DeclarationDescriptor.liftToExpected(): DeclarationDescriptor? { if (this is MemberDescriptor) { return when { isExpect -> this isActual -> expectedDescriptor() else -> null } } if (this is ValueParameterDescriptor) { val containingExpectedDescriptor = containingDeclaration.liftToExpected() as? CallableDescriptor ?: return null return containingExpectedDescriptor.valueParameters.getOrNull(index) } return null } fun KtDeclaration.liftToExpected(): KtDeclaration? { val descriptor = resolveToDescriptorIfAny() val expectedDescriptor = descriptor?.liftToExpected() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtDeclaration } fun KtParameter.liftToExpected(): KtParameter? { val parameterDescriptor = resolveToParameterDescriptorIfAny() val expectedDescriptor = parameterDescriptor?.liftToExpected() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtParameter } fun ModuleDescriptor.hasActualsFor(descriptor: MemberDescriptor) = descriptor.findActualInModule(this).isNotEmpty() private fun MemberDescriptor.findActualInModule( module: ModuleDescriptor, checkCompatible: Boolean = false ): List<DeclarationDescriptor> = if (checkCompatible) { findCompatibleActualsForExpected(module, onlyFromThisModule(module)) } else { findAnyActualsForExpected(module, onlyFromThisModule(module)) }.filter { (it as? MemberDescriptor)?.isEffectivelyActual() == true } private fun MemberDescriptor.isEffectivelyActual(checkConstructor: Boolean = true): Boolean = isActual || isEnumEntryInActual() || isConstructorInActual(checkConstructor) private fun MemberDescriptor.isConstructorInActual(checkConstructor: Boolean) = checkConstructor && this is ClassConstructorDescriptor && containingDeclaration.isEffectivelyActual(checkConstructor) private fun MemberDescriptor.isEnumEntryInActual() = (DescriptorUtils.isEnumEntry(this) && (containingDeclaration as? MemberDescriptor)?.isActual == true) fun DeclarationDescriptor.actualsForExpected(): Collection<DeclarationDescriptor> { if (this is MemberDescriptor) { if (!this.isExpect) return emptyList() return (module.allImplementingDescriptors + module).flatMap { module -> this.findActualInModule(module) } } if (this is ValueParameterDescriptor) { return containingDeclaration.actualsForExpected().mapNotNull { (it as? CallableDescriptor)?.valueParameters?.getOrNull(index) } } return emptyList() } fun KtDeclaration.hasAtLeastOneActual() = actualsForExpected().isNotEmpty() // null means "any platform" here fun KtDeclaration.actualsForExpected(module: Module? = null): Set<KtDeclaration> = resolveToDescriptorIfAny(BodyResolveMode.FULL) ?.actualsForExpected() ?.filter { module == null || (it.module.getCapability(ModuleInfo.Capability) as? ModuleSourceInfo)?.module == module } ?.mapNotNullTo(LinkedHashSet()) { DescriptorToSourceUtils.descriptorToDeclaration(it) as? KtDeclaration } ?: emptySet() fun KtDeclaration.isExpectDeclaration(): Boolean { return when { hasExpectModifier() -> true else -> containingClassOrObject?.isExpectDeclaration() == true } } fun KtDeclaration.hasMatchingExpected() = (resolveToDescriptorIfAny() as? MemberDescriptor)?.expectedDescriptor() != null fun KtDeclaration.isEffectivelyActual(checkConstructor: Boolean = true): Boolean = when { hasActualModifier() -> true this is KtEnumEntry || checkConstructor && this is KtConstructor<*> -> containingClass()?.hasActualModifier() == true else -> false } fun KtDeclaration.runOnExpectAndAllActuals(checkExpect: Boolean = true, useOnSelf: Boolean = false, f: (KtDeclaration) -> Unit) { if (hasActualModifier()) { val expectElement = liftToExpected() expectElement?.actualsForExpected()?.forEach { if (it !== this) { f(it) } } expectElement?.let { f(it) } } else if (!checkExpect || isExpectDeclaration()) { actualsForExpected().forEach { f(it) } } if (useOnSelf) f(this) } fun KtDeclaration.collectAllExpectAndActualDeclaration(withSelf: Boolean = true): Set<KtDeclaration> = when { isExpectDeclaration() -> actualsForExpected() hasActualModifier() -> liftToExpected()?.let { it.actualsForExpected() + it - this }.orEmpty() else -> emptySet() }.let { if (withSelf) it + this else it } fun KtDeclaration.runCommandOnAllExpectAndActualDeclaration( @NlsContexts.Command command: String = "", writeAction: Boolean = false, withSelf: Boolean = true, f: (KtDeclaration) -> Unit ) { val (pointers, project) = runReadAction { collectAllExpectAndActualDeclaration(withSelf).map { it.createSmartPointer() } to project } fun process() { for (pointer in pointers) { val declaration = pointer.element ?: continue f(declaration) } } if (writeAction) { project.executeWriteCommand(command, ::process) } else { project.executeCommand(command, command = ::process) } }
apache-2.0
432463af6993434281a24bd7bfed8825
40.703911
158
0.751507
5.081688
false
false
false
false
PolymerLabs/arcs
java/arcs/core/entity/testutil/DummyVariableEntity.kt
1
1739
package arcs.core.entity.testutil import arcs.core.data.FieldType import arcs.core.data.RawEntity import arcs.core.data.Schema import arcs.core.data.SchemaFields import arcs.core.data.SchemaName import arcs.core.entity.CollectionProperty import arcs.core.entity.EntitySpec import arcs.core.entity.Reference import arcs.core.entity.SingletonProperty import arcs.core.entity.Storable import arcs.core.entity.VariableEntityBase /** * An [Entity] similar to [DummyEntity], except with only a subset of its properties. */ class DummyVariableEntity : VariableEntityBase(ENTITY_CLASS_NAME, SCHEMA), Storable { var text: String? by SingletonProperty(this) var ref: Reference<DummyEntity>? by SingletonProperty(this) var bools: Set<Boolean> by CollectionProperty(this) var nums: Set<Double> by CollectionProperty(this) private val nestedEntitySpecs = mapOf( DummyEntity.SCHEMA_HASH to DummyEntity ) fun deserializeForTest(rawEntity: RawEntity) = super.deserialize(rawEntity, nestedEntitySpecs) companion object : EntitySpec<DummyVariableEntity> { override fun deserialize(data: RawEntity) = DummyVariableEntity().apply { deserialize(data, mapOf(SCHEMA_HASH to DummyVariableEntity)) } const val ENTITY_CLASS_NAME = "DummyVariableEntity" const val SCHEMA_HASH = "hijklmn" override val SCHEMA = Schema( names = setOf(SchemaName(ENTITY_CLASS_NAME)), fields = SchemaFields( singletons = mapOf( "text" to FieldType.Text, "ref" to FieldType.EntityRef(DummyEntity.SCHEMA_HASH) ), collections = mapOf( "bools" to FieldType.Boolean, "nums" to FieldType.Number ) ), hash = SCHEMA_HASH ) } }
bsd-3-clause
df2bb95e3a496fe5297112c6e731006f
30.618182
96
0.726279
4.091765
false
false
false
false
Tiofx/semester_6
TRPSV/src/main/kotlin/task2/graph/bellmanFord/parallel/util.kt
1
619
package task2.graph.bellmanFord.parallel import mpi.Datatype import mpi.MPI data class EdgeSegment(val startEdge: Int, val endEdge: Int) fun Work.EdgeSegment(edgeNumber: Int = this.edgeNumber): EdgeSegment { val edgePerProc = edgeNumber / procNum val startEdge = edgePerProc * rank val endEdge = if (rank != procNum - 1) startEdge + edgePerProc - 1 else edgeNumber - 1 return EdgeSegment(startEdge, endEdge) } fun mpiBcastOneValue(value: Int, datatype: Datatype?, root: Int): Int { val wrapper = intArrayOf(value) MPI.COMM_WORLD.Bcast(wrapper, 0, 1, datatype, root) return wrapper[0] }
gpl-3.0
08bae0d55bea37e33a224d6b83b3e4b5
29.95
90
0.726979
3.275132
false
false
false
false
google/identity-credential
appholder/src/main/java/com/android/mdl/app/document/DocumentRepository.kt
1
1411
/* * Copyright (C) 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mdl.app.document /** * Repository module for handling data operations. */ class DocumentRepository private constructor(private val documentDao: DocumentDao) { suspend fun getAll() = documentDao.getAll() suspend fun insert(document: Document) = documentDao.insert(document) suspend fun delete(document: Document) = documentDao.delete(document) suspend fun findById(credentialName: String) = documentDao.findById(credentialName) companion object { // For Singleton instantiation @Volatile private var instance: DocumentRepository? = null fun getInstance(documentDao: DocumentDao) = instance ?: synchronized(this) { instance ?: DocumentRepository(documentDao).also { instance = it } } } }
apache-2.0
04d2e47543b94185add30c69e0e2b48f
31.813953
87
0.709426
4.522436
false
false
false
false
KotlinNLP/SimpleDNN
examples/traininghelpers/validation/SequenceWithFinalOutputEvaluator.kt
1
3105
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package traininghelpers.validation import com.kotlinnlp.simplednn.core.neuralprocessor.recurrent.RecurrentNeuralProcessor import utils.SequenceExampleWithFinalOutput import com.kotlinnlp.simplednn.core.functionalities.outputevaluation.OutputEvaluationFunction import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters import com.kotlinnlp.simplednn.helpers.Statistics import com.kotlinnlp.simplednn.helpers.Evaluator import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * A helper which evaluates a dataset of [SequenceExampleWithFinalOutput]s. * * @param model the model to validate * @param examples a list of examples to validate * @param outputEvaluationFunction the output evaluation function * @param saveContributions whether to save the contributions of each input to its output (needed to calculate the * relevance, default false) * @param afterEachEvaluation a callback called after each example evaluation * @param verbose whether to print info about the validation progress (default = true) */ class SequenceWithFinalOutputEvaluator<NDArrayType: NDArray<NDArrayType>>( model: StackedLayersParameters, examples: List<SequenceExampleWithFinalOutput<NDArrayType>>, private val outputEvaluationFunction: OutputEvaluationFunction, private val saveContributions: Boolean = false, private val afterEachEvaluation: (example: SequenceExampleWithFinalOutput<NDArrayType>, isCorrect: Boolean, processor: RecurrentNeuralProcessor<NDArrayType>) -> Unit = { _, _, _ -> }, verbose: Boolean = true ) : Evaluator<SequenceExampleWithFinalOutput<NDArrayType>, Statistics.Simple>( examples = examples, verbose = verbose ) { /** * The validation statistics. */ override val stats = Statistics.Simple() /** * A recurrent neural processor. */ private val neuralProcessor = RecurrentNeuralProcessor<NDArrayType>(model = model, propagateToInput = false) /** * Evaluate the model with a single example. * * @param example the example to validate the model with */ override fun evaluate(example: SequenceExampleWithFinalOutput<NDArrayType>) { val output: DenseNDArray = this.neuralProcessor.forward(example.sequenceFeatures, saveContributions = this.saveContributions) val isCorrect: Boolean = this.outputEvaluationFunction(output = output, outputGold = example.outputGold) if (isCorrect) this.stats.metric.truePos++ else this.stats.metric.falsePos++ this.stats.accuracy = this.stats.metric.precision this.afterEachEvaluation(example, isCorrect, this.neuralProcessor) } }
mpl-2.0
b0445006c1c90aa7ea7519a6097f451b
40.4
114
0.739452
4.718845
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/lstm/LSTMBackwardHelper.kt
1
7622
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.lstm import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the backward on a [layer]. * * @property layer the [LSTMLayer] in which the backward is executed */ internal class LSTMBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: LSTMLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { val prevStateLayer = this.layer.layersWindow.getPrevState() as? LSTMLayer val nextStateLayer = this.layer.layersWindow.getNextState() as? LSTMLayer if (nextStateLayer != null) { this.addOutputRecurrentGradients(nextStateLayer) } this.assignGatesGradients(prevStateLayer = prevStateLayer, nextStateLayer = nextStateLayer) this.assignParamsGradients(prevStateOutput = prevStateLayer?.outputArray) if (propagateToInput) { this.assignLayerGradients() } } /** * * @param nextStateLayer the layer structure in the next state */ fun getLayerRecurrentContribution(nextStateLayer: LSTMLayer<*>): DenseNDArray { val gInGNext: DenseNDArray = nextStateLayer.inputGate.errors val gOutGNext: DenseNDArray = nextStateLayer.outputGate.errors val gForGNext: DenseNDArray = nextStateLayer.forgetGate.errors val gCandNext: DenseNDArray = nextStateLayer.candidate.errors val wInGRec: DenseNDArray = this.layer.params.inputGate.recurrentWeights.values val wOutGRec: DenseNDArray = this.layer.params.outputGate.recurrentWeights.values val wForGRec: DenseNDArray = this.layer.params.forgetGate.recurrentWeights.values val wCandRec: DenseNDArray = this.layer.params.candidate.recurrentWeights.values val gRec1: DenseNDArray = gInGNext.t.dot(wInGRec) val gRec2: DenseNDArray = gOutGNext.t.dot(wOutGRec) val gRec3: DenseNDArray = gForGNext.t.dot(wForGRec) val gRec4: DenseNDArray = gCandNext.t.dot(wCandRec) return gRec1.assignSum(gRec2).assignSum(gRec3).assignSum(gRec4) } /** * * @param prevStateLayer the layer in the previous state * @param nextStateLayer the layer in the next state */ private fun assignGatesGradients(prevStateLayer: LSTMLayer<*>?, nextStateLayer: LSTMLayer<*>?) { val gy: DenseNDArray = this.layer.outputArray.errors val inG: DenseNDArray = this.layer.inputGate.values val outG: DenseNDArray = this.layer.outputGate.values val cand: DenseNDArray = this.layer.candidate.values val cell: DenseNDArray = this.layer.cell.values val inGDeriv: DenseNDArray = this.layer.inputGate.calculateActivationDeriv() val outGDeriv: DenseNDArray = this.layer.outputGate.calculateActivationDeriv() // WARNING: gCell must be calculated before others val gCell: DenseNDArray = this.layer.cell.assignErrorsByProd(outG, gy) if (this.layer.cell.hasActivation) { val cellDeriv: DenseNDArray = this.layer.cell.calculateActivationDeriv() this.layer.cell.errors.assignProd(cellDeriv) } if (nextStateLayer != null) { // add recurrent contribution gCell.assignSum(this.getCellRecurrentContribution(nextStateLayer)) } this.layer.outputGate.assignErrorsByProd(cell, outGDeriv).assignProd(gy) this.layer.inputGate.assignErrorsByProd(gCell, cand).assignProd(inGDeriv) if (prevStateLayer != null) { val cellPrev: DenseNDArray = prevStateLayer.cell.valuesNotActivated val forGDeriv: DenseNDArray = this.layer.forgetGate.calculateActivationDeriv() this.layer.forgetGate.assignErrorsByProd(gCell, cellPrev).assignProd(forGDeriv) } else { this.layer.forgetGate.assignZeroErrors() } this.layer.candidate.assignErrorsByProd(gCell, inG) if (this.layer.candidate.hasActivation) { val candDeriv: DenseNDArray = this.layer.candidate.calculateActivationDeriv() this.layer.candidate.errors.assignProd(candDeriv) } } /** * @param prevStateOutput the outputArray in the previous state */ private fun assignParamsGradients(prevStateOutput: AugmentedArray<DenseNDArray>?) { val x: InputNDArrayType = this.layer.inputArray.values val yPrev: DenseNDArray? = prevStateOutput?.values this.layer.inputGate.assignParamsGradients( gw = this.layer.params.inputGate.weights.errors.values, gb = this.layer.params.inputGate.biases.errors.values, gwRec = this.layer.params.inputGate.recurrentWeights.errors.values, x = x, yPrev = yPrev) this.layer.outputGate.assignParamsGradients( gw = this.layer.params.outputGate.weights.errors.values, gb = this.layer.params.outputGate.biases.errors.values, gwRec = this.layer.params.outputGate.recurrentWeights.errors.values, x = x, yPrev = yPrev) this.layer.forgetGate.assignParamsGradients( gw = this.layer.params.forgetGate.weights.errors.values, gb = this.layer.params.forgetGate.biases.errors.values, gwRec = this.layer.params.forgetGate.recurrentWeights.errors.values, x = x, yPrev = yPrev) this.layer.candidate.assignParamsGradients( gw = this.layer.params.candidate.weights.errors.values, gb = this.layer.params.candidate.biases.errors.values, gwRec = this.layer.params.candidate.recurrentWeights.errors.values, x = x, yPrev = yPrev) } /** * */ private fun assignLayerGradients() { val wInG: DenseNDArray = this.layer.params.inputGate.weights.values val wOutG: DenseNDArray = this.layer.params.outputGate.weights.values val wForG: DenseNDArray = this.layer.params.forgetGate.weights.values val wCand: DenseNDArray = this.layer.params.candidate.weights.values val gInG: DenseNDArray = this.layer.inputGate.errors val gOutG: DenseNDArray = this.layer.outputGate.errors val gForG: DenseNDArray = this.layer.forgetGate.errors val gCand: DenseNDArray = this.layer.candidate.errors this.layer.inputArray .assignErrorsByDotT(gInG.t, wInG) .assignSum(gOutG.t.dot(wOutG)) .assignSum(gForG.t.dot(wForG)) .assignSum(gCand.t.dot(wCand)) } /** * * @param nextStateLayer the layer structure in the next state */ private fun addOutputRecurrentGradients(nextStateLayer: LSTMLayer<*>) { val gy: DenseNDArray = this.layer.outputArray.errors val gyRec: DenseNDArray = this.getLayerRecurrentContribution(nextStateLayer) gy.assignSum(gyRec) } /** * * @param nextStateLayer the layer structure in the next state */ private fun getCellRecurrentContribution(nextStateLayer: LSTMLayer<*>): DenseNDArray { val gCellNext: DenseNDArray = nextStateLayer.cell.errors val forGNext: DenseNDArray = nextStateLayer.forgetGate.values return gCellNext.prod(forGNext) } }
mpl-2.0
57f6ca5539f61735c9b5e4983d96429f
36.546798
111
0.735634
4.144644
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/internal/components/ListPersistentStateComponentsAction.kt
7
4997
// 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.internal.components import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.ui.DialogWrapper import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.ui.layout.* import com.intellij.ui.table.JBTable import com.intellij.util.ui.JBUI import javax.swing.JComponent import javax.swing.table.AbstractTableModel internal class ListPersistentStateComponentsAction : AnAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { ComponentListDialog().show() } class ComponentListDialog : DialogWrapper(false) { init { init() title = "Application-Level Persistent State Components" setSize(JBUI.scale(1000), JBUI.scale(600)) } override fun createCenterPanel(): JComponent { val componentTable = JBTable() componentTable.model = ComponentTableModel() ComponentTableModel.columnWidths.forEachIndexed { i, width -> if (width > 0) { val column = componentTable.columnModel.getColumn(i) column.minWidth = JBUI.scale(width) column.maxWidth = JBUI.scale(width) } } return panel { row { scrollPane(componentTable) } } } class ComponentTableModel : AbstractTableModel() { companion object { val columnNames = arrayOf("Plugin", "Class Name", "Roaming Type", "Category") val columnWidths = arrayOf(250, -1, 100, 100) } private val descriptors = ArrayList<ComponentDescriptor>() init { val componentManager = ApplicationManager.getApplication() as ComponentManagerImpl componentManager.processAllImplementationClasses { aClass, descriptor -> if (PersistentStateComponent::class.java.isAssignableFrom(aClass)) { val state = aClass.getAnnotation(State::class.java) val roamingType = getRoamingType(state) @Suppress("UNCHECKED_CAST") descriptors.add( ComponentDescriptor( descriptor?.name?.toString() ?: "", aClass.name, roamingType, getCategory(aClass as Class<PersistentStateComponent<*>>, state, descriptor, roamingType) ) ) } } descriptors.sortWith( compareBy<ComponentDescriptor> { it.name }.thenBy { it.className } ) } private fun getCategory(aClass : Class<PersistentStateComponent<*>>, state: State?, descriptor: PluginDescriptor?, roamingType: String): String { if (roamingType != RoamingType.DISABLED.toString() && descriptor != null) { if (descriptor.name == PluginManagerCore.SPECIAL_IDEA_PLUGIN_ID.idString) { return state?.category?.name ?: "" } else { return ComponentCategorizer.getPluginCategory(aClass, descriptor).toString() } } else { return "" } } private fun getRoamingType(state: State?): String { if (state != null) { var roamingType: String? = null state.storages.forEach { if (!it.deprecated) { val storageRoamingType = if (it.value == StoragePathMacros.NON_ROAMABLE_FILE || it.value == StoragePathMacros.CACHE_FILE || it.value == StoragePathMacros.WORKSPACE_FILE) "DISABLED" else it.roamingType.toString() if (roamingType == null) { roamingType = storageRoamingType } else { if (roamingType != storageRoamingType) { roamingType = "MIXED" } } } } return roamingType ?: "" } return "" } override fun getRowCount() = descriptors.size override fun getColumnCount() = 4 override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { return when (columnIndex) { 0 -> descriptors[rowIndex].name 1 -> descriptors[rowIndex].className 2 -> descriptors[rowIndex].roamingType 3 -> descriptors[rowIndex].category else -> "" } } override fun getColumnName(column: Int): String { return columnNames[column] } } } data class ComponentDescriptor( val name: String, val className: String, val roamingType: String, val category: String ) }
apache-2.0
ff855357df1b7577fecd4a84613b842c
33
151
0.626976
5.221526
false
false
false
false
mdaniel/intellij-community
platform/platform-api/src/com/intellij/openapi/wm/BannerStartPagePromoter.kt
1
3840
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm import com.intellij.openapi.util.SystemInfo import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.CurrentTheme.Button.buttonOutlineColorStart import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import java.awt.Component import java.awt.Dimension import java.awt.Font import java.awt.Rectangle import java.awt.event.ActionEvent import javax.swing.* import javax.swing.border.MatteBorder abstract class BannerStartPagePromoter : StartPagePromoter { override fun getPromotionForInitialState(): JPanel? { val rPanel: JPanel = NonOpaquePanel() rPanel.layout = BoxLayout(rPanel, BoxLayout.PAGE_AXIS) rPanel.border = JBUI.Borders.empty(JBUI.scale(10), JBUI.scale(32)) val vPanel: JPanel = NonOpaquePanel() vPanel.layout = BoxLayout(vPanel, BoxLayout.PAGE_AXIS) vPanel.alignmentY = Component.TOP_ALIGNMENT val header = JLabel(getHeaderLabel()) header.font = StartupUiUtil.getLabelFont().deriveFont(Font.BOLD).deriveFont(StartupUiUtil.getLabelFont().size2D + JBUI.scale(4)) vPanel.add(header) vPanel.add(rigid(0, 4)) val description = JLabel( "<html>${getDescription()}</html>").also { it.font = JBUI.Fonts.label().deriveFont(JBUI.Fonts.label().size2D + (when { SystemInfo.isLinux -> JBUIScale.scale(-2) SystemInfo.isMac -> JBUIScale.scale(-1) else -> 0 })) it.foreground = UIUtil.getContextHelpForeground() } vPanel.add(description) val jButton = JButton() jButton.isOpaque = false jButton.action = object : AbstractAction(getActionLabel()) { override fun actionPerformed(e: ActionEvent?) { runAction() } } vPanel.add(rigid(0, 18)) vPanel.add(buttonPixelHunting(jButton)) val hPanel: JPanel = NonOpaquePanel() hPanel.layout = BoxLayout(hPanel, BoxLayout.X_AXIS) hPanel.add(vPanel) hPanel.add(Box.createHorizontalGlue()) hPanel.add(rigid(20, 0)) val picture = JLabel(promoImage()) picture.alignmentY = Component.TOP_ALIGNMENT hPanel.add(picture) rPanel.add(NonOpaquePanel().apply { border = MatteBorder(JBUI.scale(1), 0, 0, 0, outLineColor()) }) rPanel.add(rigid(0, 20)) rPanel.add(hPanel) return rPanel } private fun buttonPixelHunting(button: JButton): JPanel { val buttonSizeWithoutInsets = Dimension(button.preferredSize.width - button.insets.left - button.insets.right, button.preferredSize.height - button.insets.top - button.insets.bottom) val buttonPlace = JPanel().apply { layout = null maximumSize = buttonSizeWithoutInsets preferredSize = buttonSizeWithoutInsets minimumSize = buttonSizeWithoutInsets isOpaque = false alignmentX = JPanel.LEFT_ALIGNMENT } buttonPlace.add(button) button.bounds = Rectangle(-button.insets.left, -button.insets.top, button.preferredSize.width, button.preferredSize.height) return buttonPlace } fun rigid(width: Int, height: Int): Component { return scaledRigid(JBUI.scale(width), JBUI.scale(height)) } fun scaledRigid(width: Int, height: Int): Component { return (Box.createRigidArea(Dimension(width, height)) as JComponent).apply { alignmentX = Component.LEFT_ALIGNMENT alignmentY = Component.TOP_ALIGNMENT } } abstract fun getHeaderLabel(): String abstract fun getActionLabel(): String abstract fun runAction() abstract fun getDescription(): String abstract fun promoImage(): Icon protected open fun outLineColor() = buttonOutlineColorStart(false) }
apache-2.0
c112b85eed81ac924e9ce5652ae78b6e
34.897196
132
0.715625
4.076433
false
false
false
false
Carighan/kotlin-koans
test/v_builders/N40BuildersHowItWorksKtTest.kt
10
667
package v_builders import org.junit.Assert.fail import org.junit.Test import util.questions.Answer.b import util.questions.Answer.c import v_builders.builders.task40 class N40BuildersHowItWorksKtTest { @Test fun testBuildersQuiz() { val answers = task40() if (answers.values.toSet() == setOf(null)) { fail("Please specify your answers!") } val correctAnswers = mapOf(22 - 20 to b, 1 + 3 to c, 11 - 8 to b, 79 - 78 to c) if (correctAnswers != answers) { val incorrect = (1..4).filter { answers[it] != correctAnswers[it] } fail("Your answers are incorrect! $incorrect") } } }
mit
b4e1d6b3add0120937eb008d13a284b2
30.809524
87
0.626687
3.705556
false
true
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/usecase/BuyColorPackUseCase.kt
1
1285
package io.ipoli.android.player.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository import io.ipoli.android.quest.ColorPack /** * Created by Venelin Valkov <[email protected]> * on 16.12.17. */ class BuyColorPackUseCase(private val playerRepository: PlayerRepository) : UseCase<BuyColorPackUseCase.Params, BuyColorPackUseCase.Result> { override fun execute(parameters: BuyColorPackUseCase.Params): BuyColorPackUseCase.Result { val colorPack = parameters.colorPack val player = playerRepository.find() requireNotNull(player) require(!player!!.hasColorPack(colorPack)) if (player.gems < colorPack.gemPrice) { return BuyColorPackUseCase.Result.TooExpensive } val newPlayer = player.copy( gems = player.gems - colorPack.gemPrice, inventory = player.inventory.addColorPack(colorPack) ) return BuyColorPackUseCase.Result.ColorPackBought(playerRepository.save(newPlayer)) } data class Params(val colorPack: ColorPack) sealed class Result { data class ColorPackBought(val player: Player) : Result() object TooExpensive : Result() } }
gpl-3.0
160f0f9128aec1c3322700ec9123267f
31.125
94
0.714397
4.172078
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/postfix-templates/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KotlinTryPostfixTemplate.kt
3
6687
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.postfix import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.annotations.KtAnnotationValue import org.jetbrains.kotlin.analysis.api.annotations.KtArrayAnnotationValue import org.jetbrains.kotlin.analysis.api.annotations.KtKClassAnnotationValue import org.jetbrains.kotlin.analysis.api.annotations.annotationsByClassId import org.jetbrains.kotlin.analysis.api.calls.* import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.idea.base.psi.classIdIfNonLocal import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType internal class KotlinTryPostfixTemplate : StringBasedPostfixTemplate { @Suppress("ConvertSecondaryConstructorToPrimary") constructor(provider: KotlinPostfixTemplateProvider) : super( /* name = */ "try", /* example = */ "try { expr } catch (e: Exception) {}", /* selector = */ allExpressions(StatementFilter), /* provider = */ provider ) override fun getTemplateString(element: PsiElement): String { val exceptionClasses = collectPossibleExceptions(element) return buildString { append("try {\n\$expr$\$END\$\n} ") for (exceptionClass in exceptionClasses) { append("catch (e: ${exceptionClass.asFqNameString()} ) {\nthrow e\n}") } } } private fun collectPossibleExceptions(element: PsiElement): List<ClassId> { val ktElement = element.getParentOfType<KtElement>(strict = false) if (ktElement != null) { val exceptionClasses = ExceptionClassCollector().also { ktElement.accept(it, null) }.exceptionClasses if (exceptionClasses.isNotEmpty()) { return exceptionClasses } } return listOf(ClassId.fromString("kotlin/Exception")) } override fun getElementToRemove(expr: PsiElement) = expr } @OptIn(KtAllowAnalysisOnEdt::class) private class ExceptionClassCollector : KtTreeVisitor<Unit?>() { private companion object { val THROWS_ANNOTATION_FQ_NAMES = listOf( ClassId.fromString("kotlin/Throws"), ClassId.fromString("kotlin/jvm/Throws") ) } private val mutableExceptionClasses = LinkedHashSet<ClassId>() private var hasLocalClasses = false val exceptionClasses: List<ClassId> get() = if (!hasLocalClasses) mutableExceptionClasses.toList() else emptyList() override fun visitCallExpression(expression: KtCallExpression, data: Unit?): Void? { processElement(expression) return super.visitCallExpression(expression, data) } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, data: Unit?): Void? { val shouldProcess = when (val parent = expression.parent) { is KtCallExpression -> expression != parent.calleeExpression is KtBinaryExpression -> expression != parent.operationReference is KtUnaryExpression -> expression != parent.operationReference else -> true } if (shouldProcess) { processElement(expression) } return super.visitSimpleNameExpression(expression, data) } override fun visitBinaryExpression(expression: KtBinaryExpression, data: Unit?): Void? { processElement(expression) return super.visitBinaryExpression(expression, data) } override fun visitUnaryExpression(expression: KtUnaryExpression, data: Unit?): Void? { processElement(expression) return super.visitUnaryExpression(expression, data) } private fun <T: KtElement> processElement(element: T) { if (hasLocalClasses) { return } allowAnalysisOnEdt { analyze(element) { processCall(element.resolveCall()) } } } private fun processCall(callInfo: KtCallInfo?) { val call = (callInfo as? KtSuccessCallInfo)?.call ?: return when (call) { is KtSimpleFunctionCall -> processCallable(call.symbol) is KtSimpleVariableAccessCall -> { val symbol = call.symbol if (symbol is KtPropertySymbol) { when (call.simpleAccess) { KtSimpleVariableAccess.Read -> symbol.getter?.let { processCallable(it) } is KtSimpleVariableAccess.Write -> symbol.setter?.let { processCallable(it) } else -> {} } } } is KtCompoundVariableAccessCall -> processCallable(call.compoundAccess.operationPartiallyAppliedSymbol.symbol) is KtCompoundArrayAccessCall -> { processCallable(call.getPartiallyAppliedSymbol.symbol) processCallable(call.setPartiallyAppliedSymbol.symbol) } else -> {} } } private fun processCallable(symbol: KtCallableSymbol) { if (symbol.origin == KtSymbolOrigin.JAVA) { val javaMethod = symbol.psiSafe<PsiMethod>() ?: return for (type in javaMethod.throwsList.referencedTypes) { val classId = type.resolve()?.classIdIfNonLocal if (classId != null) { mutableExceptionClasses.add(classId) } else { hasLocalClasses = true } } return } for (classId in THROWS_ANNOTATION_FQ_NAMES) { for (annotation in symbol.annotationsByClassId(classId)) { for (argument in annotation.arguments) { processAnnotationValue(argument.expression) } } } } private fun processAnnotationValue(value: KtAnnotationValue) { when (value) { is KtArrayAnnotationValue -> value.values.forEach(::processAnnotationValue) is KtKClassAnnotationValue.KtNonLocalKClassAnnotationValue -> mutableExceptionClasses.add(value.classId) is KtKClassAnnotationValue.KtLocalKClassAnnotationValue -> hasLocalClasses = true else -> {} } } }
apache-2.0
3fc5e39ed759b4a863ecbab50978c0c3
38.341176
122
0.654853
5.244706
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/impl/TrustedPathsSettings.kt
5
1483
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.impl import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.util.io.isAncestor import com.intellij.util.xmlb.annotations.OptionTag import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.* @ApiStatus.Internal fun isPathTrustedInSettings(path: Path): Boolean = service<TrustedPathsSettings>().isPathTrusted(path) @State(name = "Trusted.Paths.Settings", storages = [Storage(value = "trusted-paths.xml", roamingType = RoamingType.DISABLED)]) @Service(Service.Level.APP) internal class TrustedPathsSettings : SimplePersistentStateComponent<TrustedPathsSettings.State>(State()) { class State : BaseState() { @get:OptionTag("TRUSTED_PATHS") var trustedPaths by list<String>() } fun isPathTrusted(path: Path): Boolean { return state.trustedPaths.asSequence() .mapNotNull { try { Path.of(it) } catch (e: Exception) { logger<TrustedPathsSettings>().warn(e) null } } .any { it.isAncestor(path) } } fun getTrustedPaths(): List<String> = Collections.unmodifiableList(state.trustedPaths) fun setTrustedPaths(paths: List<String>) { state.trustedPaths = paths.toMutableList() } fun addTrustedPath(path: String) { state.trustedPaths.add(path) } }
apache-2.0
210ac0b1e17d42495dc08fbe82ea9d37
31.26087
126
0.720836
3.965241
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/KotlinTypeHierarchyProviderBySuperTypeCallEntry.kt
4
2061
// 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.hierarchy import com.intellij.ide.hierarchy.type.JavaTypeHierarchyProvider import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.psi.PsiClass import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch class KotlinTypeHierarchyProviderBySuperTypeCallEntry : JavaTypeHierarchyProvider() { override fun getTarget(dataContext: DataContext): PsiClass? { val project = PlatformDataKeys.PROJECT.getData(dataContext) ?: return null val editor = PlatformDataKeys.EDITOR.getData(dataContext) ?: return null val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return null val offset = editor.caretModel.offset val elementAtCaret = file.findElementAt(offset) ?: return null if (elementAtCaret.getParentOfTypeAndBranch<KtSuperTypeCallEntry> { calleeExpression } == null) return null val targetElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext)?.unwrapped return when { targetElement is KtConstructor<*> -> targetElement.containingClassOrObject?.toLightClass() targetElement is PsiMethod && targetElement.isConstructor -> targetElement.containingClass targetElement is KtClassOrObject -> targetElement.toLightClass() targetElement is PsiClass -> targetElement else -> null } } }
apache-2.0
c7c5e676f246b3a1fff37e8d83f1a68c
50.525
158
0.78263
5.257653
false
false
false
false
walleth/kethereum
uri_common/src/main/kotlin/org/kethereum/uri/common/CommonEthereumURIData.kt
1
382
package org.kethereum.uri.common import org.kethereum.model.ChainId data class CommonEthereumURIData( var valid: Boolean = true, var scheme: String? = null, var prefix: String? = null, var chainId: ChainId? = null, var address: String? = null, var function: String? = null, var query: List<Pair<String, String>> = listOf() )
mit
286c417c92d4eeded6a9044b5b8d3651
28.461538
56
0.63089
3.82
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/feature/history/HistoryScreen.kt
1
11667
/* * HistoryScreen.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[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/>. */ @file:Suppress("UNNECESSARY_NOT_NULL_ASSERTION") package com.codebutler.farebot.app.feature.history import android.Manifest import android.app.Activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Environment import android.view.Menu import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.codebutler.farebot.R import com.codebutler.farebot.app.core.activity.ActivityOperations import com.codebutler.farebot.app.core.inject.ScreenScope import com.codebutler.farebot.app.core.kotlin.Optional import com.codebutler.farebot.app.core.kotlin.filterAndGetOptional import com.codebutler.farebot.app.core.transit.TransitFactoryRegistry import com.codebutler.farebot.app.core.ui.ActionBarOptions import com.codebutler.farebot.app.core.ui.FareBotScreen import com.codebutler.farebot.app.core.util.ErrorUtils import com.codebutler.farebot.app.core.util.ExportHelper import com.codebutler.farebot.app.feature.card.CardScreen import com.codebutler.farebot.app.feature.main.MainActivity import com.codebutler.farebot.card.serialize.CardSerializer import com.codebutler.farebot.persist.CardPersister import com.codebutler.farebot.persist.db.model.SavedCard import com.codebutler.farebot.transit.TransitIdentity import com.uber.autodispose.kotlin.autoDisposable import dagger.Component import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.io.File import javax.inject.Inject class HistoryScreen : FareBotScreen<HistoryScreen.HistoryComponent, HistoryScreenView>(), HistoryScreenView.Listener { companion object { private const val REQUEST_SELECT_FILE = 1 private const val REQUEST_PERMISSION_STORAGE = 2 private const val FILENAME = "farebot-export.json" } @Inject lateinit var activityOperations: ActivityOperations @Inject lateinit var cardPersister: CardPersister @Inject lateinit var cardSerializer: CardSerializer @Inject lateinit var exportHelper: ExportHelper @Inject lateinit var transitFactoryRegistry: TransitFactoryRegistry override fun getTitle(context: Context): String = context.getString(R.string.history) override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions( backgroundColorRes = R.color.accent, textColorRes = R.color.white ) override fun onCreateView(context: Context): HistoryScreenView = HistoryScreenView(context, activityOperations, this) override fun onUpdateMenu(menu: Menu) { activity.menuInflater.inflate(R.menu.screen_history, menu) } override fun onShow(context: Context) { super.onShow(context) activityOperations.menuItemClick .autoDisposable(this) .subscribe { menuItem -> val clipboardManager = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager when (menuItem.itemId) { R.id.import_file -> { val storageUri = Uri.fromFile(Environment.getExternalStorageDirectory()) val target = Intent(Intent.ACTION_GET_CONTENT) target.putExtra(Intent.EXTRA_STREAM, storageUri) target.type = "*/*" activity.startActivityForResult( Intent.createChooser(target, activity.getString(R.string.select_file)), REQUEST_SELECT_FILE) } R.id.import_clipboard -> { val importClip = clipboardManager.primaryClip if (importClip != null && importClip.itemCount > 0) { val text = importClip.getItemAt(0).coerceToText(activity).toString() Single.fromCallable { exportHelper.importCards(text) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe { cards -> onCardsImported(cards) } } } R.id.copy -> { val exportClip = ClipData.newPlainText(null, exportHelper.exportCards()) clipboardManager.primaryClip = exportClip Toast.makeText(activity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show() } R.id.share -> { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, exportHelper.exportCards()) activity.startActivity(intent) } R.id.save -> exportToFile() } } activityOperations.permissionResult .autoDisposable(this) .subscribe { (requestCode, _, grantResults) -> when (requestCode) { REQUEST_PERMISSION_STORAGE -> { if (grantResults.getOrNull(0) == PackageManager.PERMISSION_GRANTED) { exportToFileWithPermission() } } } } activityOperations.activityResult .autoDisposable(this) .subscribe { (requestCode, resultCode, data) -> when (requestCode) { REQUEST_SELECT_FILE -> { if (resultCode == Activity.RESULT_OK) { data?.data?.let { importFromFile(it) } } } } } loadCards() view.observeItemClicks() .autoDisposable(this) .subscribe { viewModel -> navigator.goTo(CardScreen(viewModel.rawCard)) } } override fun onDeleteSelectedItems(items: List<HistoryViewModel>) { for ((savedCard) in items) { cardPersister.deleteCard(savedCard) } loadCards() } override fun createComponent(parentComponent: MainActivity.MainActivityComponent): HistoryComponent = DaggerHistoryScreen_HistoryComponent.builder() .mainActivityComponent(parentComponent) .build() override fun inject(component: HistoryComponent) { component.inject(this) } private fun loadCards() { observeCards() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe( { viewModels -> view.setViewModels(viewModels) }, { e -> ErrorUtils.showErrorToast(activity, e) }) } private fun observeCards(): Single<List<HistoryViewModel>> { return Single.create<List<SavedCard>> { e -> try { e.onSuccess(cardPersister.cards) } catch (error: Throwable) { e.onError(error) } }.map { savedCards -> savedCards.map { savedCard -> val rawCard = cardSerializer.deserialize(savedCard.data) var transitIdentity: TransitIdentity? = null var parseException: Exception? = null try { transitIdentity = transitFactoryRegistry.parseTransitIdentity(rawCard.parse()) } catch (ex: Exception) { parseException = ex } HistoryViewModel(savedCard, rawCard, transitIdentity, parseException) } } } private fun onCardsImported(cardIds: List<Long>) { loadCards() val text = activity.resources.getQuantityString(R.plurals.cards_imported, cardIds.size, cardIds.size) Toast.makeText(activity, text, Toast.LENGTH_SHORT).show() if (cardIds.size == 1) { Single.create<Optional<SavedCard>> { e -> e.onSuccess(Optional(cardPersister.getCard(cardIds[0]))) } .filterAndGetOptional() .map { savedCard -> cardSerializer.deserialize(savedCard.data) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe { rawCard -> navigator.goTo(CardScreen(rawCard)) } } } private fun exportToFile() { val permission = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION_STORAGE) } else { exportToFileWithPermission() } } private fun exportToFileWithPermission() { Single.fromCallable { val file = File(Environment.getExternalStorageDirectory(), FILENAME) file.writeText(exportHelper.exportCards()) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe({ Toast.makeText(activity, activity.getString(R.string.saved_to_x, FILENAME), Toast.LENGTH_SHORT) .show() }, { ex -> ErrorUtils.showErrorAlert(activity, ex) }) } private fun importFromFile(uri: Uri) { Single.fromCallable { val json = activity.contentResolver.openInputStream(uri) .bufferedReader() .use { it.readText() } exportHelper.importCards(json) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe { cards -> onCardsImported(cards) } } @ScreenScope @Component(dependencies = [MainActivity.MainActivityComponent::class]) interface HistoryComponent { fun inject(historyScreen: HistoryScreen) } }
gpl-3.0
9aebba3c3bcebe9ff1d4bf970a4bf48a
41.271739
118
0.59904
5.236535
false
false
false
false
roylanceMichael/yaclib
core/src/test/java/org/roylance/yaclib/services/java/JavaServerProcessLanguageServiceTest.kt
1
1704
package org.roylance.yaclib.services.java import org.junit.Assert import org.junit.Test import org.naru.park.ParkController import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.services.ProcessFileDescriptorService import org.roylance.yaclib.core.services.java.server.JavaServerProcessLanguageService import org.roylance.yaclib.core.utilities.TypeScriptUtilities class JavaServerProcessLanguageServiceTest { @Test fun simplePassThroughTest() { // arrange val service = ProcessFileDescriptorService() val controllers = service.processFile(ParkController.getDescriptor()) val javaServiceLanguageProcess = JavaServerProcessLanguageService() val dependency = YaclibModel.Dependency.newBuilder() .setGroup("org.naru.park") .setName("api") .setMinorVersion("14") .setTypescriptModelFile("NaruPark") .build() val controllerDependencies = YaclibModel.ControllerDependency.newBuilder().setDependency(dependency) .setControllers(controllers) .build() val all = YaclibModel.AllControllerDependencies.newBuilder().addControllerDependencies(controllerDependencies).build() // act val projectInformation = YaclibModel.ProjectInformation.newBuilder() .setControllers(all) .setMainDependency(dependency).build() val item = javaServiceLanguageProcess.buildInterface(projectInformation) // assert item.filesList.forEach { System.out.println(it.fileToWrite) System.out.println("----------------") } Assert.assertTrue(true) } }
mit
b48faf3a83949625472fea26b34416a0
36.888889
126
0.694836
5.026549
false
true
false
false
ktorio/ktor
ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyCertificatePinner.kt
1
17435
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.darwin.certificates import io.ktor.client.engine.darwin.* import kotlinx.cinterop.* import platform.CoreCrypto.* import platform.CoreFoundation.* import platform.Foundation.* import platform.Security.* /** * Constrains which certificates are trusted. Pinning certificates defends against attacks on * certificate authorities. It also prevents connections through man-in-the-middle certificate * authorities either known or unknown to the application's user. * This class currently pins a certificate's Subject Public Key Info as described on * [Adam Langley's Weblog](http://goo.gl/AIx3e5). Pins are either base64 SHA-256 hashes as in * [HTTP Public Key Pinning (HPKP)](http://tools.ietf.org/html/rfc7469) or SHA-1 base64 hashes as * in Chromium's [static certificates](http://goo.gl/XDh6je). * * ## Setting up Certificate Pinning * * The easiest way to pin a host is to turn on pinning with a broken configuration and read the * expected configuration when the connection fails. Be sure to do this on a trusted network, and * without man-in-the-middle tools like [Charles](http://charlesproxy.com) or * [Fiddler](http://fiddlertool.com). * * For example, to pin `https://publicobject.com`, start with a broken configuration: * * ``` * HttpClient(Darwin) { * * // ... * * engine { * val builder = CertificatePinner.Builder() * .add("publicobject.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") * handleChallenge(builder.build()) * } * } * ``` * * As expected, this fails with an exception, see the logs: * * ``` * HttpClient: Certificate pinning failure! * Peer certificate chain: * sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: publicobject.com * sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: COMODO RSA Secure Server CA * sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: COMODO RSA Certification Authority * sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: AddTrust External CA Root * Pinned certificates for publicobject.com: * sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= * ``` * * Follow up by pasting the public key hashes from the logs into the * certificate pinner's configuration: * * ``` * val builder = CertificatePinner.Builder() * .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") * .add("publicobject.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=") * .add("publicobject.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=") * .add("publicobject.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=") * handleChallenge(builder.build()) * ``` * * ## Domain Patterns * * Pinning is per-hostname and/or per-wildcard pattern. To pin both `publicobject.com` and * `www.publicobject.com` you must configure both hostnames. Or you may use patterns to match * sets of related domain names. The following forms are permitted: * * * **Full domain name**: you may pin an exact domain name like `www.publicobject.com`. It won't * match additional prefixes (`us-west.www.publicobject.com`) or suffixes (`publicobject.com`). * * * **Any number of subdomains**: Use two asterisks to like `**.publicobject.com` to match any * number of prefixes (`us-west.www.publicobject.com`, `www.publicobject.com`) including no * prefix at all (`publicobject.com`). For most applications this is the best way to configure * certificate pinning. * * * **Exactly one subdomain**: Use a single asterisk like `*.publicobject.com` to match exactly * one prefix (`www.publicobject.com`, `api.publicobject.com`). Be careful with this approach as * no pinning will be enforced if additional prefixes are present, or if no prefixes are present. * * Note that any other form is unsupported. You may not use asterisks in any position other than * the leftmost label. * * If multiple patterns match a hostname, any match is sufficient. For example, suppose pin A * applies to `*.publicobject.com` and pin B applies to `api.publicobject.com`. Handshakes for * `api.publicobject.com` are valid if either A's or B's certificate is in the chain. * * ## Warning: Certificate Pinning is Dangerous! * * Pinning certificates limits your server team's abilities to update their TLS certificates. By * pinning certificates, you take on additional operational complexity and limit your ability to * migrate between certificate authorities. Do not use certificate pinning without the blessing of * your server's TLS administrator! * * See also [OWASP: Certificate and Public Key Pinning](https://www.owasp.org/index * .php/Certificate_and_Public_Key_Pinning). * * This class was heavily inspired by OkHttp, which is a great Http library for Android * https://square.github.io/okhttp/4.x/okhttp/okhttp3/-certificate-pinner/ * https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/CertificatePinner.kt */ @OptIn(UnsafeNumber::class) public data class LegacyCertificatePinner internal constructor( private val pinnedCertificates: Set<LegacyPinnedCertificate>, private val validateTrust: Boolean ) : ChallengeHandler { override fun invoke( session: NSURLSession, task: NSURLSessionTask, challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Unit ) { val hostname = challenge.protectionSpace.host val matchingPins = findMatchingPins(hostname) if (matchingPins.isEmpty()) { println("CertificatePinner: No pins found for host") completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, null) return } if (challenge.protectionSpace.authenticationMethod != NSURLAuthenticationMethodServerTrust ) { println("CertificatePinner: Authentication method not suitable for pinning") completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, null) return } val trust = challenge.protectionSpace.serverTrust if (trust == null) { println("CertificatePinner: Server trust is not available") completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null) return } if (validateTrust) { val hostCFString = CFStringCreateWithCString(null, hostname, kCFStringEncodingUTF8) hostCFString?.use { SecPolicyCreateSSL(true, hostCFString)?.use { policy -> SecTrustSetPolicies(trust, policy) } } if (!trust.trustIsValid()) { println("CertificatePinner: Server trust is invalid") completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null) return } } val certCount = SecTrustGetCertificateCount(trust) val certificates = (0 until certCount).mapNotNull { index -> SecTrustGetCertificateAtIndex(trust, index) } if (certificates.size != certCount.toInt()) { println("CertificatePinner: Unknown certificates") completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null) return } val result = hasOnePinnedCertificate(certificates) if (result) { completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential) } else { val message = buildErrorMessage(certificates, hostname) println(message) completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null) } } /** * Confirms that at least one of the certificates is pinned */ private fun hasOnePinnedCertificate( certificates: List<SecCertificateRef> ): Boolean = certificates.any { certificate -> val publicKey = certificate.getPublicKeyBytes() ?: return@any false // Lazily compute the hashes for each public key. var sha1: String? = null var sha256: String? = null pinnedCertificates.any { pin -> when (pin.hashAlgorithm) { LegacyCertificatesInfo.HASH_ALGORITHM_SHA_256 -> { if (sha256 == null) { sha256 = publicKey.toSha256String() } pin.hash == sha256 } LegacyCertificatesInfo.HASH_ALGORITHM_SHA_1 -> { if (sha1 == null) { sha1 = publicKey.toSha1String() } pin.hash == sha1 } else -> { println("CertificatePinner: Unsupported hashAlgorithm: ${pin.hashAlgorithm}") false } } } } /** * Build an error string to display */ private fun buildErrorMessage( certificates: List<SecCertificateRef>, hostname: String ): String = buildString { append("Certificate pinning failure!") append("\n Peer certificate chain:") for (certificate in certificates) { append("\n ") val publicKeyStr = certificate.getPublicKeyBytes()?.toSha256String() append("${LegacyCertificatesInfo.HASH_ALGORITHM_SHA_256}$publicKeyStr") append(": ") val summaryRef = SecCertificateCopySubjectSummary(certificate) val summary = CFBridgingRelease(summaryRef) as NSString append("$summary") } append("\n Pinned certificates for ") append(hostname) append(":") for (pin in pinnedCertificates) { append("\n ") append(pin) } } /** * Returns list of matching certificates' pins for the hostname. Returns an empty list if the * hostname does not have pinned certificates. */ internal fun findMatchingPins(hostname: String): List<LegacyPinnedCertificate> { var result: List<LegacyPinnedCertificate> = emptyList() for (pin in pinnedCertificates) { if (pin.matches(hostname)) { if (result.isEmpty()) result = mutableListOf() (result as MutableList<LegacyPinnedCertificate>).add(pin) } } return result } /** * Evaluates trust for the specified certificate and policies. */ private fun SecTrustRef.trustIsValid(): Boolean { var isValid = false val version = cValue<NSOperatingSystemVersion> { majorVersion = 12 minorVersion = 0 patchVersion = 0 } if (NSProcessInfo().isOperatingSystemAtLeastVersion(version)) { // https://developer.apple.com/documentation/security/2980705-sectrustevaluatewitherror isValid = SecTrustEvaluateWithError(this, null) } else { // https://developer.apple.com/documentation/security/1394363-sectrustevaluate memScoped { val result = alloc<SecTrustResultTypeVar>() result.value = kSecTrustResultInvalid val status = SecTrustEvaluate(this@trustIsValid, result.ptr) if (status == errSecSuccess) { isValid = result.value == kSecTrustResultUnspecified || result.value == kSecTrustResultProceed } } } return isValid } /** * Gets the public key from the SecCertificate */ private fun SecCertificateRef.getPublicKeyBytes(): ByteArray? { val publicKeyRef = SecCertificateCopyKey(this) ?: return null return publicKeyRef.use { val publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) val publicKeyTypePointer = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeyType) val publicKeyType = CFBridgingRelease(publicKeyTypePointer) as NSString val publicKeySizePointer = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeySizeInBits) val publicKeySize = CFBridgingRelease(publicKeySizePointer) as NSNumber CFBridgingRelease(publicKeyAttributes) if (!checkValidKeyType(publicKeyType, publicKeySize)) { println("CertificatePinner: Public Key not supported type or size") return null } val publicKeyDataRef = SecKeyCopyExternalRepresentation(publicKeyRef, null) val publicKeyData = CFBridgingRelease(publicKeyDataRef) as NSData val publicKeyBytes = publicKeyData.toByteArray() val headerInts = getAsn1HeaderBytes(publicKeyType, publicKeySize) val header = headerInts.foldIndexed(ByteArray(headerInts.size)) { i, a, v -> a[i] = v.toByte() a } header + publicKeyBytes } } /** * Checks that we support the key type and size */ private fun checkValidKeyType(publicKeyType: NSString, publicKeySize: NSNumber): Boolean { val keyTypeRSA = CFBridgingRelease(kSecAttrKeyTypeRSA) as NSString val keyTypeECSECPrimeRandom = CFBridgingRelease(kSecAttrKeyTypeECSECPrimeRandom) as NSString val size: Int = publicKeySize.intValue.toInt() val keys = when (publicKeyType) { keyTypeRSA -> LegacyCertificatesInfo.rsa keyTypeECSECPrimeRandom -> LegacyCertificatesInfo.ecdsa else -> return false } return keys.containsKey(size) } /** * Get the [IntArray] of Asn1 headers needed to prepend to the public key to create the * encoding [ASN1Header](https://docs.oracle.com/middleware/11119/opss/SCRPJ/oracle/security/crypto/asn1/ASN1Header.html) */ private fun getAsn1HeaderBytes(publicKeyType: NSString, publicKeySize: NSNumber): IntArray { val keyTypeRSA = CFBridgingRelease(kSecAttrKeyTypeRSA) as NSString val keyTypeECSECPrimeRandom = CFBridgingRelease(kSecAttrKeyTypeECSECPrimeRandom) as NSString val size: Int = publicKeySize.intValue.toInt() val keys = when (publicKeyType) { keyTypeRSA -> LegacyCertificatesInfo.rsa keyTypeECSECPrimeRandom -> LegacyCertificatesInfo.ecdsa else -> return intArrayOf() } return keys[size] ?: intArrayOf() } /** * Converts a [ByteArray] into sha256 base 64 encoded string */ @OptIn(ExperimentalUnsignedTypes::class) private fun ByteArray.toSha256String(): String { val digest = UByteArray(CC_SHA256_DIGEST_LENGTH) usePinned { inputPinned -> digest.usePinned { digestPinned -> CC_SHA256(inputPinned.addressOf(0), this.size.convert(), digestPinned.addressOf(0)) } } return digest.toByteArray().toNSData().base64EncodedStringWithOptions(0u) } /** * Converts a [ByteArray] into sha1 base 64 encoded string */ @OptIn(ExperimentalUnsignedTypes::class) private fun ByteArray.toSha1String(): String { val digest = UByteArray(CC_SHA1_DIGEST_LENGTH) usePinned { inputPinned -> digest.usePinned { digestPinned -> CC_SHA1(inputPinned.addressOf(0), this.size.convert(), digestPinned.addressOf(0)) } } return digest.toByteArray().toNSData().base64EncodedStringWithOptions(0u) } /** * Builds a configured [LegacyCertificatePinner]. */ public data class Builder( private val pinnedCertificates: MutableList<LegacyPinnedCertificate> = mutableListOf(), private var validateTrust: Boolean = true ) { /** * Pins certificates for `pattern`. * * @param pattern lower-case host name or wildcard pattern such as `*.example.com`. * @param pins SHA-256 or SHA-1 hashes. Each pin is a hash of a certificate's * Subject Public Key Info, base64-encoded and prefixed with either `sha256/` or `sha1/`. * @return The [Builder] so calls can be chained */ public fun add(pattern: String, vararg pins: String): Builder = apply { pins.forEach { pin -> this.pinnedCertificates.add( LegacyPinnedCertificate.new( pattern, pin ) ) } } /** * Whether to valid the trust of the server * https://developer.apple.com/documentation/security/2980705-sectrustevaluatewitherror * @param validateTrust * @return The [Builder] so calls can be chained */ public fun validateTrust(validateTrust: Boolean): Builder = apply { this.validateTrust = validateTrust } /** * Build into a [LegacyCertificatePinner] * @return [LegacyCertificatePinner] */ public fun build(): LegacyCertificatePinner = LegacyCertificatePinner( pinnedCertificates.toSet(), validateTrust ) } }
apache-2.0
1821863249edf5401a06a634a2602739
39.452436
125
0.651391
4.484311
false
false
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteTaskHandlerTest.kt
1
9124
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.TaskComplete import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.Task import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher object CompleteTaskHandlerTest : SubjectSpek<CompleteTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() subject(GROUP) { CompleteTaskHandler(queue, repository, ContextParameterProcessor(), publisher, clock, NoopRegistry()) } fun resetMocks() = reset(queue, repository, publisher) setOf(SUCCEEDED).forEach { successfulStatus -> describe("when a task completes with $successfulStatus status") { given("the stage contains further tasks") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", successfulStatus, successfulStatus ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage(check { it.tasks.first().apply { assertThat(status).isEqualTo(successfulStatus) assertThat(endTime).isEqualTo(clock.millis()) } }) } it("runs the next task") { verify(queue) .push(StartTask( message.executionType, message.executionId, message.application, message.stageId, "2" )) } it("publishes an event") { verify(publisher).publishEvent(check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.taskId).isEqualTo(message.taskId) assertThat(it.status).isEqualTo(successfulStatus) }) } } given("the stage is complete") { val pipeline = pipeline { stage { type = singleTaskStage.type singleTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", SUCCEEDED, SUCCEEDED ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage(check { it.tasks.last().apply { assertThat(status).isEqualTo(SUCCEEDED) assertThat(endTime).isEqualTo(clock.millis()) } }) } it("emits an event to signal the stage is complete") { verify(queue) .push(CompleteStage( message.executionType, message.executionId, message.application, message.stageId )) } } given("the task is the end of a rolling push loop") { val pipeline = pipeline { stage { refId = "1" type = rollingPushStage.type rollingPushStage.buildTasks(this) } } and("when the task returns REDIRECT") { val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stageByRef("1").id, "4", REDIRECT, REDIRECT ) beforeGroup { pipeline.stageByRef("1").apply { tasks[0].status = SUCCEEDED tasks[1].status = SUCCEEDED tasks[2].status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("repeats the loop") { verify(queue).push(check<StartTask> { assertThat(it.taskId).isEqualTo("2") }) } it("resets the status of the loop tasks") { verify(repository).storeStage(check { assertThat(it.tasks[1..3].map(Task::getStatus)).allMatch { it == NOT_STARTED } }) } it("does not publish an event") { verifyZeroInteractions(publisher) } } } } } setOf(TERMINAL, CANCELED).forEach { status -> describe("when a task completes with $status status") { val pipeline = pipeline { stage { type = multiTaskStage.type multiTaskStage.buildTasks(this) } } val message = CompleteTask( pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", status, status ) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the task state in the stage") { verify(repository).storeStage(check { it.tasks.first().apply { assertThat(status).isEqualTo(status) assertThat(endTime).isEqualTo(clock.millis()) } }) } it("fails the stage") { verify(queue).push(CompleteStage( message.executionType, message.executionId, message.application, message.stageId )) } it("does not run the next task") { verify(queue, never()).push(any<RunTask>()) } it("publishes an event") { verify(publisher).publishEvent(check<TaskComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.taskId).isEqualTo(message.taskId) assertThat(it.status).isEqualTo(status) }) } } } describe("when a task should complete parent stage") { val task = fun(isStageEnd: Boolean) : Task { val task = Task() task.isStageEnd = isStageEnd return task } it("is last task in stage") { subject.shouldCompleteStage(task(true), SUCCEEDED, SUCCEEDED) == true subject.shouldCompleteStage(task(false), SUCCEEDED, SUCCEEDED) == false } it("did not originally complete with FAILED_CONTINUE") { subject.shouldCompleteStage(task(false), TERMINAL, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, TERMINAL) == true subject.shouldCompleteStage(task(false), FAILED_CONTINUE, FAILED_CONTINUE) == false } } })
apache-2.0
4d2147ae95b27777884493fbbd63d12d
29.61745
105
0.610368
4.812236
false
false
false
false
beyondeye/graphkool
graphkool-core/src/test/kotlin/com/beyondeye/graphkool/StarWarsSchema.kt
1
3496
package com.beyondeye.graphkool import graphql.schema.* import graphql.Scalars.GraphQLString import graphql.schema.GraphQLArgument.newArgument import graphql.schema.GraphQLFieldDefinition.newFieldDefinition import graphql.schema.GraphQLObjectType.newObject object StarWarsSchema { var episodeEnum = newEnum("Episode") .description("One of the films in the Star Wars Trilogy") .value("NEWHOPE", 4, "Released in 1977.") .value("EMPIRE", 5, "Released in 1980.") .value("JEDI", 6, "Released in 1983.") .build() var characterInterface:GraphQLInterfaceType = newInterface("Character") .description("A character in the Star Wars Trilogy") .field("id"..!GraphQLString description "The id of the character." ) .field("name"..GraphQLString description "The name of the character." ) .field("friends"..listOfRefs("Character") description "The friends of the character, or an empty list if they have none." ) .field("appearsIn"..listOfObjs(episodeEnum) description "Which movies they appear in." ) .typeResolver(StarWarsData.characterTypeResolver) .build() var humanType = newObject("Human") .description("A humanoid creature in the Star Wars universe.") .withInterface(characterInterface) .field("id"..!GraphQLString description "The id of the human." ) .field("name"..GraphQLString description "The name of the human.") .field("friends"..GraphQLList(characterInterface) description "The friends of the human, or an empty list if they have none." dataFetcher(StarWarsData.friendsDataFetcher)) .field("appearsIn"..GraphQLList(episodeEnum) description "Which movies they appear in.") .field("homePlanet"..GraphQLString description "The home planet of the human, or null if unknown.") .build() var droidType = newObject("Droid") .description("A mechanical creature in the Star Wars universe.") .withInterface(characterInterface) .field("id"..!GraphQLString description "The id of the droid.") .field("name"..GraphQLString description "The name of the droid.") .field("friends"..GraphQLList(characterInterface) description "The friends of the droid, or an empty list if they have none." dataFetcher(StarWarsData.friendsDataFetcher)) .field("appearsIn"..GraphQLList(episodeEnum) description "Which movies they appear in.") .field("primaryFunction"..GraphQLString description "The primary function of the droid.") .build() var queryType = newObject("QueryType") .field("hero"..characterInterface argument (+"episode"..episodeEnum description "If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode.") dataFetcher (StaticDataFetcher(StarWarsData.artoo))) .field("human"..humanType argument (+"id"..!GraphQLString description "id of the human" ) dataFetcher (StarWarsData.humanDataFetcher)) .field("droid"..droidType argument (+"id"..!GraphQLString description "id of the droid") dataFetcher (StarWarsData.droidDataFetcher)) var starWarsSchema = newGraphQLSchema(query = queryType).build() }
apache-2.0
80f05123e2c14a88fe11e1f124defb2e
49.666667
174
0.655034
4.882682
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/unit/RibbonDiagramTests.kt
1
7544
package graphics.scenery.tests.unit import graphics.scenery.geometry.DummySpline import graphics.scenery.proteins.Protein import graphics.scenery.proteins.RibbonDiagram import graphics.scenery.utils.LazyLogger import org.biojava.nbio.structure.Group import org.biojava.nbio.structure.secstruc.SecStrucElement import org.joml.Vector3f import org.junit.Test import kotlin.reflect.full.declaredMemberFunctions import kotlin.reflect.jvm.isAccessible import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertTrue /** * This is the test for the RibbonCalculation, i.e. the pdb-support. * * @author Justin Buerger, [email protected] */ class RibbonDiagramTests { private val logger by LazyLogger() /** * Tests coherence of curve size and number of residues. */ @Test fun residueCountTest() { logger.info("Tests coherence of curve size and number of residues.") val plantProtein = Protein.fromID("3nir") val plantRibbon = RibbonDiagram(plantProtein) val dsspPlant = plantRibbon.callPrivateFunc("dssp") val plantChains = plantProtein.getResidues() var allPlantPoints = 0 plantChains.forEach { if (dsspPlant is List<*>) { @Suppress("UNCHECKED_CAST") val guides = RibbonDiagram.GuidePointCalculation.calculateGuidePoints(it, dsspPlant as List<SecStrucElement>) val spline = plantRibbon.callPrivateFunc("ribbonSpline", guides) as DummySpline allPlantPoints += spline.splinePoints().size } } assertEquals(allPlantPoints, (46) * (10 + 1)) val saccharomycesCerevisiae = Protein.fromID("6zqd") val scRibbon = RibbonDiagram(saccharomycesCerevisiae) val dsspSC = scRibbon.callPrivateFunc("dssp") val scChains = saccharomycesCerevisiae.getResidues() var allSCPoints = 0 scChains.forEach { if (dsspSC is List<*>) { @Suppress("UNCHECKED_CAST") val guides = RibbonDiagram.GuidePointCalculation.calculateGuidePoints(it, dsspSC as List<SecStrucElement>) val spline = scRibbon.callPrivateFunc("ribbonSpline", guides) as DummySpline allSCPoints += spline.splinePoints().size } } assertEquals(allSCPoints, (23448) * (10 + 1)) } /** * Tests number of subProteins. */ @Test fun numberSubProteinsTest() { logger.info("Tests number of subProteins.") val plantProtein = Protein.fromID("3nir") val plantRibbon = RibbonDiagram(plantProtein) assertEquals(plantRibbon.children.size, 1) val insectWing = Protein.fromID("2w49") val insectWingRibbon = RibbonDiagram(insectWing) assertEquals(insectWingRibbon.children.size, 36) /* val saccharomycesCerevisiae = Protein.fromID("6zqd") val scRibbon = RibbonDiagram(saccharomycesCerevisiae) assertEquals(scRibbon.children.size, 63) */ /* val covid19 = Protein.fromID("6zcz") val covidRibbon = RibbonDiagram(covid19) assertEquals(covidRibbon.children.size, 4) */ val aspirin = Protein.fromID("6mqf") val aspirinRibbon = RibbonDiagram(aspirin) assertEquals(aspirinRibbon.children.size, 2) val nucleosome = Protein.fromID("6y5e") val nucRibbon = RibbonDiagram(nucleosome) assertEquals(nucRibbon.children.size, 9) } /** * Tests a lot of pdb structures and check that everyone of them yields a valid output. * The comments refer to the chosen filter in the "SCIENTIFIC NAME OF SOURCE ORGANISM" category * in the RCSB data base. These organisms as well as the pdb files have been chosen arbitrary. * The null checks are there to satisfy the test structure- the test verifies in fact that no * exception is thrown. */ @Test fun testLotsOfProteins() { val proteins = listOf( "6l69", "3mbw", "4u1a", "5m9m", "6mzl", "6mp5", "2qd4", "6pe9", "1ydk", "2rma", "3mdc", "2kne", "4tn7", "3mao", "5m8s", "6v2e", "4giz", "3l2j", "4odq", "6slm", "2qho", "1zr0", "2ake", "2wx1", "2mue", "2m0j", "1q5w", "3gj8", "3sui", "6pby", "2m0k", "1r4a", "3fub", "6uku", "6v92", "2l2i", "1pyo", "4lcd", "6p9x", "6uun", "6v80", "6v7z", "4grw", "3mc5", "3mbw", "4tkw", "4u0i", "3mas", "6znn", "1ctp", "3j92", "3jak", "1nb5", "3lk3", "1mdu", "3eks", "2ebv", "4gbj", "6v4e", "6v4h", "4m8n", "4ia1", "3ei2", "2rh1", "6ps3", "3v2y", "4pla", "3eml", "2seb", "2qej", "1d5m", "2wy8", "4idj", "2vr3", "2win", "6urh", "3ua7", "3mrn", "4z0x", "2rhk", "6pdx", "6urm", "2x4q", "1r0n", "2ff6", "4i7b", "3bs5", "5chl", "5f84", "4uuz", "4v98", "4wsi", "4u68", "4aa1", "5jvs", "6hom", "4xib", "4u0q", "6phf" ) proteins.shuffled().drop(80).forEach { pdbId -> val protein = Protein.fromID(pdbId) logger.info("Testing ${protein.structure.name} ...") RibbonDiagram(protein) } } /** * Verifies that the boundingbox min and max vector don't become the null vector. */ @Test fun testMaxBoundingBoxNoNullVector() { //test min max don't become the null vector val protein = Protein.fromID("2zzw") val ribbon = RibbonDiagram(protein) val bb = ribbon.getMaximumBoundingBox() assertEquals(bb.n, ribbon) assertNotEquals(bb.min, Vector3f(0f, 0f, 0f)) assertNotEquals(bb.max, Vector3f(0f, 0f, 0f)) } /** * Verifies that a BoundingBox for a ribbon can be created. */ @Test fun testMaxBoundingBox() { // check if the right BoundingBoc is created val protein = Protein.fromID("5m9m") val ribbon = RibbonDiagram(protein) val bb = ribbon.getMaximumBoundingBox() print(bb.max) //We use ranges because the first and last guidePoint are created nondeterministically- but in the guaranteed range assertTrue { 22.2 < bb.max.x && bb.max.x < 22.6 } assertTrue { 33.6 < bb.max.y && 34 > bb.max.y } assertTrue { 37.5 < bb.max.z && 37.9 > bb.max.z } assertTrue { -31.3 < bb.min.x && -29.9 > bb.min.x } assertTrue { -28.3 < bb.min.y && -27.9 > bb.min.y } assertTrue { -36.8 < bb.min.z && -36.4 > bb.min.z } } //Inline function for the protein to access residues private fun Protein.getResidues(): ArrayList<ArrayList<Group>> { val proteins = ArrayList<ArrayList<Group>>(this.structure.chains.size) this.structure.chains.forEach { chain -> if (chain.isProtein) { val aminoList = ArrayList<Group>(chain.atomGroups.size) chain.atomGroups.forEach { group -> if (group.hasAminoAtoms()) { aminoList.add(group) } } proteins.add(aminoList) } } return proteins } //Inline function to access private function in the RibbonDiagram private inline fun <reified T> T.callPrivateFunc(name: String, vararg args: Any?): Any? = T::class .declaredMemberFunctions .firstOrNull { it.name == name } ?.apply { isAccessible = true } ?.call(this, *args) }
lgpl-3.0
b8609f6f2a27c0fce19dc664a087185a
38.497382
123
0.603659
3.538462
false
true
false
false
bozaro/git-lfs-java
gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/internal/LfsRequest.kt
1
1446
package ru.bozaro.gitlfs.client.internal import org.apache.http.client.methods.HttpUriRequest import org.apache.http.entity.AbstractHttpEntity import org.apache.http.protocol.HTTP class LfsRequest internal constructor(private val request: HttpUriRequest, private val entity: AbstractHttpEntity?) { fun addHeaders(headers: Map<String, String>): HttpUriRequest { for ((key, value) in headers) { if (HTTP.TRANSFER_ENCODING == key) { /* See https://github.com/bozaro/git-as-svn/issues/365 LFS-server can ask us to respond with chunked body via setting "Transfer-Encoding: chunked" HTTP header in LFS link Unfortunately, we cannot pass it as-is to response HTTP headers, see RequestContent#process. If it sees that Transfer-Encoding header was set, it throws exception immediately. So instead, we suppress addition of Transfer-Encoding header and set entity to be chunked here. RequestContent#process will see that HttpEntity#isChunked returns true and will set correct Transfer-Encoding header. */ if (entity != null) { val chunked = HTTP.CHUNK_CODING == value entity.isChunked = chunked } } else { request.addHeader(key, value) } } return request } }
lgpl-3.0
9532674b186e39754986dd3a956dfe89
48.862069
135
0.628631
4.852349
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opencl/src/templates/kotlin/opencl/templates/CL30.kt
4
31735
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl.templates import org.lwjgl.generator.* import opencl.* val CL30 = "CL30".nativeClassCL("CL30") { extends = CL22 documentation = "The core OpenCL 3.0 functionality." IntConstant( "OpenCL Version.", "VERSION_3_0".."1" ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetPlatformInfo(), returns a {@code cl_version} value. Returns the detailed (major, minor, patch) version supported by the platform. The major and minor version numbers returned must match those returned via #PLATFORM_VERSION. """, "PLATFORM_NUMERIC_VERSION"..0x0906 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetPlatformInfo(), returns a {@code cl_name_version[]} value. Returns an array of description (name and version) structures that lists all the extensions supported by the platform. The same extension name must not be reported more than once. The list of extensions reported must match the list reported via #PLATFORM_EXTENSIONS. """, "PLATFORM_EXTENSIONS_WITH_VERSION"..0x0907 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_version} value. Returns the detailed (major, minor, patch) version supported by the device. The major and minor version numbers returned must match those returned via #DEVICE_VERSION. """, "DEVICE_NUMERIC_VERSION"..0x105E ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_name_version[]} value. Returns an array of description (name and version) structures. The same extension name must not be reported more than once. The list of extensions reported must match the list reported via #DEVICE_EXTENSIONS. See {@code CL_DEVICE_EXTENSIONS} for a list of extensions that are required to be reported for a given OpenCL version. """, "DEVICE_EXTENSIONS_WITH_VERSION"..0x1060 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_name_version[]} value. Returns an array of descriptions (name and version) for all supported intermediate languages. Intermediate languages with the same name may be reported more than once but each name and major/minor version combination may only be reported once. The list of intermediate languages reported must match the list reported via #DEVICE_IL_VERSION. For an OpenCL 2.1 or 2.2 device, at least one version of SPIR-V must be reported. """, "DEVICE_ILS_WITH_VERSION"..0x1061 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_name_version[]} value. Returns an array of descriptions for the built-in kernels supported by the device. Each built-in kernel may only be reported once. The list of reported kernels must match the list returned via #DEVICE_BUILT_IN_KERNELS. """, "DEVICE_BUILT_IN_KERNELS_WITH_VERSION"..0x1062 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_device_atomic_capabilities} value. Describes the various memory orders and scopes that the device supports for atomic memory operations. This is a bit-field that describes a combination of the following values: ${ul( "#DEVICE_ATOMIC_ORDER_RELAXED - Support for the relaxed memory order.", "#DEVICE_ATOMIC_ORDER_ACQ_REL - Support for the acquire, release, and acquire-release memory orders.", "#DEVICE_ATOMIC_ORDER_SEQ_CST - Support for the sequentially consistent memory order." )} Because atomic memory orders are hierarchical, a device that supports a strong memory order must also support all weaker memory orders. ${ul( "#DEVICE_ATOMIC_SCOPE_WORK_ITEM - Support for memory ordering constraints that apply to a single work item.", "#DEVICE_ATOMIC_SCOPE_WORK_GROUP - Support for memory ordering constraints that apply to all work-items in a work-group.", "#DEVICE_ATOMIC_SCOPE_DEVICE - Support for memory ordering constraints that apply to all work-items executing on the device.", """ #DEVICE_ATOMIC_SCOPE_ALL_DEVICES - Support for memory ordering constraints that apply to all work-items executing across all devices that can share SVM memory with each other and the host process. """ )} Because atomic scopes are hierarchical, a device that supports a wide scope must also support all narrower scopes, except for the work-item scope, which is a special case. The mandated minimum capability is: ${codeBlock(""" CL_DEVICE_ATOMIC_ORDER_RELAXED | CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP """)} """, "DEVICE_ATOMIC_MEMORY_CAPABILITIES"..0x1063 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_device_atomic_capabilities} value. Describes the various memory orders and scopes that the device supports for atomic fence operations. This is a bit-field that has the same set of possible values as described for #DEVICE_ATOMIC_MEMORY_CAPABILITIES. The mandated minimum capability is: ${codeBlock(""" CL_DEVICE_ATOMIC_ORDER_RELAXED | CL_DEVICE_ATOMIC_ORDER_ACQ_REL | CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP """)} """, "DEVICE_ATOMIC_FENCE_CAPABILITIES"..0x1064 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_bool} value. Is #TRUE if the device supports non-uniform work groups, and #FALSE otherwise. """, "DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT"..0x1065 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_name_version[]} value. Returns an array of name, version descriptions listing all the versions of OpenCL C supported by the compiler for the device. In each returned description structure, the name field is required to be "OpenCL C". The list may include both newer non-backwards compatible OpenCL C versions, such as OpenCL C 3.0, and older OpenCL C versions with mandatory backwards compatibility. The version returned by #DEVICE_OPENCL_C_VERSION is required to be present in the list. For devices that support compilation from OpenCL C source: Because OpenCL 3.0 is backwards compatible with OpenCL C 1.2, and OpenCL C 1.2 is backwards compatible with OpenCL C 1.1 and OpenCL C 1.0, support for at least OpenCL C 3.0, OpenCL C 1.2, OpenCL C 1.1, and OpenCL C 1.0 is required for an OpenCL 3.0 device. Support for OpenCL C 2.0, OpenCL C 1.2, OpenCL C 1.1, and OpenCL C 1.0 is required for an OpenCL 2.0, OpenCL 2.1, or OpenCL 2.2 device. Support for OpenCL C 1.2, OpenCL C 1.1, and OpenCL C 1.0 is required for an OpenCL 1.2 device. Support for OpenCL C 1.1 and OpenCL C 1.0 is required for an OpenCL 1.1 device. Support for at least OpenCL C 1.0 is required for an OpenCL 1.0 device. For devices that do not support compilation from OpenCL C source, this query may return an empty array. """, "DEVICE_OPENCL_C_ALL_VERSIONS"..0x1066 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code size_t} value. Returns the preferred multiple of work-group size for the given device. This is a performance hint intended as a guide when specifying the local work size argument to #EnqueueNDRangeKernel(). (Refer also to #GetKernelWorkGroupInfo() where #KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE can return a different value to {@code CL_DEVICE_PREFERRED_WORK_GROUP_SIZE_MULTIPLE} which may be more optimal.) """, "DEVICE_PREFERRED_WORK_GROUP_SIZE_MULTIPLE"..0x1067 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_bool} value. Is #TRUE if the device supports work group collective functions e.g. {@code work_group_broadcast}, {@code work_group_reduce}, and {@code work_group_scan}, and #FALSE otherwise. """, "DEVICE_WORK_GROUP_COLLECTIVE_FUNCTIONS_SUPPORT"..0x1068 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_bool} value. Is #TRUE if the device supports the generic address space and its associated built-in functions, and #FALSE otherwise. """, "DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT"..0x1069 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_name_version[]} value. Returns an array of optional OpenCL C features supported by the compiler for the device alongside the OpenCL C version that introduced the feature macro. For example, if a compiler supports an OpenCL C 3.0 feature, the returned name will be the full name of the OpenCL C feature macro, and the returned version will be 3.0.0. For devices that do not support compilation from OpenCL C source, this query may return an empty array. """, "DEVICE_OPENCL_C_FEATURES"..0x106F ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_device_device_enqueue_capabilities} value. Describes device-side enqueue capabilities of the device. This is a bit-field that describes one or more of the following values: ${ul( "#DEVICE_QUEUE_SUPPORTED - Device supports device-side enqueue and on-device queues.", "#DEVICE_QUEUE_REPLACEABLE_DEFAULT - Device supports a replaceable default on-device queue." )} If {@code CL_DEVICE_QUEUE_REPLACEABLE_DEFAULT} is set, {@code CL_DEVICE_QUEUE_SUPPORTED} must also be set. Devices that set {@code CL_DEVICE_QUEUE_SUPPORTED} for {@code CL_DEVICE_DEVICE_ENQUEUE_CAPABILITIES} must also return #TRUE for #DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT. """, "DEVICE_DEVICE_ENQUEUE_CAPABILITIES"..0x1070 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code cl_bool} value. Is #TRUE if the device supports pipes, and CL_FALSE otherwise. Devices that return #TRUE for {@code CL_DEVICE_PIPE_SUPPORT} must also return {@code CL_TRUE} for #DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT. """, "DEVICE_PIPE_SUPPORT"..0x1071 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetDeviceInfo(), returns a {@code char[]} value. Returns the latest version of the conformance test suite that this device has fully passed in accordance with the official conformance process. """, "DEVICE_LATEST_CONFORMANCE_VERSION_PASSED"..0x1072 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetCommandQueueInfo(), returns a {@code cl_queue_properties[]} value. Return the properties argument specified in #CreateCommandQueueWithProperties(). If the properties argument specified in {@code clCreateCommandQueueWithProperties} used to create {@code command_queue} was not #NULL, the implementation must return the values specified in the properties argument in the same order and without including additional properties. If {@code command_queue} was created using #CreateCommandQueue(), or if the properties argument specified in {@code clCreateCommandQueueWithProperties} was #NULL, the implementation must return {@code param_value_size_ret} equal to 0, indicating that there are no properties to be returned. """, "QUEUE_PROPERTIES_ARRAY"..0x1098 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetMemObjectInfo(), returns a {@code cl_mem_properties[]} value. Return the {@code properties} argument specified in #CreateBufferWithProperties() or #CreateImageWithProperties(). If the {@code properties} argument specified in {@code clCreateBufferWithProperties} or {@code clCreateImageWithProperties} used to create {@code memobj} was not #NULL, the implementation must return the values specified in the {@code properties} argument in the same order and without including additional properties. If {@code memobj} was created using #CreateBuffer(), #CreateSubBuffer(), #CreateImage(), #CreateImage2D(), or #CreateImage3D(), or if the {@code properties} argument specified in {@code clCreateBufferWithProperties} or {@code clCreateImageWithProperties} was #NULL, the implementation must return {@code param_value_size_ret} equal to 0, indicating that there are no properties to be returned. """, "MEM_PROPERTIES"..0x110A ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetPipeInfo(), returns a {@code cl_pipe_properties[]} value. Return the {@code properties} argument specified in #CreatePipe(). If the {@code properties} argument specified in {@code clCreatePipe} used to create pipe was not #NULL, the implementation must return the values specified in the {@code properties} argument in the same order and without including additional properties. If the {@code properties} argument specified in {@code clCreatePipe} used to create pipe was #NULL, the implementation must return {@code param_value_size_ret} equal to 0, indicating that there are no properties to be returned. """, "PIPE_PROPERTIES"..0x1122 ) IntConstant( """ Accepted as the {@code param_name} parameter of #GetSamplerInfo(), returns a {@code cl_sampler_properties[]} value. Return the {@code properties} argument specified in #CreateSamplerWithProperties(). If the {@code properties} argument specified in {@code clCreateSamplerWithProperties} used to create sampler was not #NULL, the implementation must return the values specified in the {@code properties} argument in the same order and without including additional properties. If {@code sampler} was created using #CreateSampler(), or if the {@code properties} argument specified in {@code clCreateSamplerWithProperties} was #NULL, the implementation must return {@code param_value_size_ret} equal to 0, indicating that there are no properties to be returned. """, "SAMPLER_PROPERTIES"..0x1158 ) IntConstant( "{@code cl_command_type}", "COMMAND_SVM_MIGRATE_MEM"..0x120E ) IntConstant( "{@code cl_device_atomic_capabilities} - bitfield", "DEVICE_ATOMIC_ORDER_RELAXED".."(1 << 0)", "DEVICE_ATOMIC_ORDER_ACQ_REL".."(1 << 1)", "DEVICE_ATOMIC_ORDER_SEQ_CST".."(1 << 2)", "DEVICE_ATOMIC_SCOPE_WORK_ITEM".."(1 << 3)", "DEVICE_ATOMIC_SCOPE_WORK_GROUP".."(1 << 4)", "DEVICE_ATOMIC_SCOPE_DEVICE".."(1 << 5)", "DEVICE_ATOMIC_SCOPE_ALL_DEVICES".."(1 << 6)" ) IntConstant( "{@code cl_device_device_enqueue_capabilities} - bitfield", "DEVICE_QUEUE_SUPPORTED".."(1 << 0)", "DEVICE_QUEUE_REPLACEABLE_DEFAULT".."(1 << 1)" ) IntConstant( "{@code cl_version} constants", "VERSION_MAJOR_BITS".."10", "VERSION_MINOR_BITS".."10", "VERSION_PATCH_BITS".."12", "VERSION_MAJOR_MASK".."((1 << CL_VERSION_MAJOR_BITS) - 1)", "VERSION_MINOR_MASK".."((1 << CL_VERSION_MINOR_BITS) - 1)", "VERSION_PATCH_MASK".."((1 << CL_VERSION_PATCH_BITS) - 1)", ) macro(expression = "version >>> (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS)")..uint32_t( "CL_VERSION_MAJOR", "Extracts the {@code major} version from a packed {@code cl_version}.", uint32_t("version", "a packed {@code cl_version}"), noPrefix = true ) macro(expression = "(version >>> CL_VERSION_PATCH_BITS) & CL_VERSION_MINOR_MASK")..uint32_t( "CL_VERSION_MINOR", "Extracts the {@code minor} version from a packed {@code cl_version}.", uint32_t("version", "a packed {@code cl_version}"), noPrefix = true ) macro(expression = "version & CL_VERSION_PATCH_MASK")..uint32_t( "CL_VERSION_PATCH", "Extracts the {@code patch} version from a packed {@code cl_version}.", uint32_t("version", "a packed {@code cl_version}"), noPrefix = true ) macro(expression = """((major & CL_VERSION_MAJOR_MASK) << (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS)) | ((minor & CL_VERSION_MINOR_MASK) << CL_VERSION_PATCH_BITS) | (patch & CL_VERSION_PATCH_MASK)""")..uint32_t( "CL_MAKE_VERSION", "Returns a packed {@code cl_version} from a major, minor and patch version.", uint32_t("major", "the major version"), uint32_t("minor", "the minor version"), uint32_t("patch", "the patch version"), noPrefix = true ) cl_int( "SetContextDestructorCallback", """ Registers a callback function with a context that is called when the context is destroyed. Each call to {@code clSetContextDestructorCallback} registers the specified callback function on a destructor callback stack associated with context. The registered callback functions are called in the reverse order in which they were registered. If a context callback function was specified when context was created, it will not be called after any context destructor callback is called. Therefore, the context destructor callback provides a mechanism for an application to safely re-use or free any {@code user_data} specified for the context callback function when context was created. """, cl_context("context", "specifies the OpenCL context to register the callback to"), cl_context_destructor_callback( "pfn_notify", """ the callback function to register. This callback function may be called asynchronously by the OpenCL implementation. It is the application’s responsibility to ensure that the callback function is thread-safe. """ ), nullable..opaque_p("user_data", "will be passed as the {@code user_data} argument when {@code pfn_notify} is called. {@code user_data} can be #NULL."), returnDoc = """ #SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors: ${ul( ICE, "$INVALID_VALUE if {@code pfn_notify} is #NULL.", OORE, OOHME )} """ ) cl_mem( "CreateBufferWithProperties", """ Creates a buffer object with additional properties. If {@code clCreateBufferWithProperties} is called with #MEM_USE_HOST_PTR set in its {@code flags} argument, the contents of the memory pointed to by {@code host_ptr} at the time of the {@code clCreateBufferWithProperties} call define the initial contents of the buffer object. If {@code clCreateBufferWithProperties} is called with a pointer returned by #SVMAlloc() as its {@code host_ptr} argument, and {@code CL_MEM_USE_HOST_PTR} is set in its {@code flags} argument, {@code clCreateBufferWithProperties} will succeed and return a valid non-zero buffer object as long as the {@code size} argument is no larger than the size argument passed in the original {@code clSVMAlloc} call. The new buffer object returned has the shared memory as the underlying storage. Locations in the buffers underlying shared memory can be operated on using atomic operations to the devices level of support as defined in the memory model. """, cl_context("context", "a valid OpenCL context used to create the buffer object"), nullable..NullTerminated..cl_mem_properties.const.p( "properties", """ an optional list of properties for the buffer object and their corresponding values. The list is terminated with the special property 0. If no properties are required, {@code properties} may be #NULL. """ ), cl_mem_flags( "flags", "a bit-field that is used to specify allocation and usage information about the image memory object being created", """ #MEM_READ_WRITE #MEM_WRITE_ONLY #MEM_READ_ONLY #MEM_USE_HOST_PTR #MEM_ALLOC_HOST_PTR #MEM_COPY_HOST_PTR #MEM_HOST_WRITE_ONLY #MEM_HOST_READ_ONLY #MEM_HOST_NO_ACCESS" """ ), AutoSize("host_ptr")..size_t("size", "the size in bytes of the buffer memory object to be allocated"), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE )..optional..void.p( "host_ptr", """ a pointer to the buffer data that may already be allocated by the application. The size of the buffer that {@code host_ptr} points to must be greater than or equal to {@code size} bytes. """ ), ERROR_RET, returnDoc = """ a valid non-zero buffer object and $errcode_ret is set to $SUCCESS if the buffer object is created successfully. Otherwise, it returns a #NULL value with one of the following error values returned in $errcode_ret: ${ul( ICE, """ $INVALID_PROPERTY if a property name in {@code properties} is not a supported property name, if the value specified for a supported property name is not valid, or if the same property name is specified more than once. """, "$INVALID_VALUE if values specified in {@code flags} are not valid.", "$INVALID_BUFFER_SIZE if {@code size} is 0 or if {@code size} is greater than #DEVICE_MAX_MEM_ALLOC_SIZE for all devices in context.", """ $INVALID_HOST_PTR if {@code host_ptr} is #NULL and #MEM_USE_HOST_PTR or #MEM_COPY_HOST_PTR are set in {@code flags} or if {@code host_ptr} is not #NULL but #MEM_COPY_HOST_PTR or #MEM_USE_HOST_PTR are not set in {@code flags}. """, "#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for buffer object.", OORE, OOHME )} """ ) cl_mem( "CreateImageWithProperties", """ Creates an image object with additional properties. For a 3D image or 2D image array, the image data specified by {@code host_ptr} is stored as a linear sequence of adjacent 2D image slices or 2D images respectively. Each 2D image is a linear sequence of adjacent scanlines. Each scanline is a linear sequence of image elements. For a 2D image, the image data specified by {@code host_ptr} is stored as a linear sequence of adjacent scanlines. Each scanline is a linear sequence of image elements. For a 1D image array, the image data specified by {@code host_ptr} is stored as a linear sequence of adjacent 1D images. Each 1D image is stored as a single scanline which is a linear sequence of adjacent elements. For 1D image or 1D image buffer, the image data specified by {@code host_ptr} is stored as a single scanline which is a linear sequence of adjacent elements. """, cl_context("context", "a valid OpenCL context used to create the image object"), nullable..NullTerminated..cl_mem_properties.const.p( "properties", """ an optional list of properties for the image object and their corresponding values. The list is terminated with the special property 0. If no properties are required, properties may be #NULL. """ ), cl_mem_flags( "flags", """ a bit-field that is used to specify allocation and usage information about the image memory object being created. For all image types except #MEM_OBJECT_IMAGE1D_BUFFER, if the value specified for {@code flags} is 0, the default is used which is #MEM_READ_WRITE. For {@code CL_MEM_OBJECT_IMAGE1D_BUFFER} image type, or an image created from another memory object (image or buffer), if the {@code CL_MEM_READ_WRITE}, #MEM_READ_ONLY or #MEM_WRITE_ONLY values are not specified in {@code flags}, they are inherited from the corresponding memory access qualifiers associated with {@code mem_object}. The #MEM_USE_HOST_PTR, #MEM_ALLOC_HOST_PTR and #MEM_COPY_HOST_PTR values cannot be specified in {@code flags} but are inherited from the corresponding memory access qualifiers associated with {@code mem_object}. If {@code CL_MEM_COPY_HOST_PTR} is specified in the memory access qualifier values associated with {@code mem_object} it does not imply any additional copies when the image is created from {@code mem_object}. If the #MEM_HOST_WRITE_ONLY, #MEM_HOST_READ_ONLY or #MEM_HOST_NO_ACCESS values are not specified in {@code flags}, they are inherited from the corresponding memory access qualifiers associated with {@code mem_object}. """, """ #MEM_READ_WRITE #MEM_WRITE_ONLY #MEM_READ_ONLY #MEM_USE_HOST_PTR #MEM_ALLOC_HOST_PTR #MEM_COPY_HOST_PTR #MEM_HOST_WRITE_ONLY #MEM_HOST_READ_ONLY #MEM_HOST_NO_ACCESS """ ), cl_image_format.const.p( "image_format", """ a pointer to a structure that describes format properties of the image to be allocated. A 1D image buffer or 2D image can be created from a buffer by specifying a buffer object in the {@code image_desc→mem_object}. A 2D image can be created from another 2D image object by specifying an image object in the {@code image_desc→mem_object}. """ ), cl_image_desc.const.p("image_desc", "a pointer to a structure that describes type and dimensions of the image to be allocated"), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..Unsafe..nullable..void.p( "host_ptr", """ a pointer to the image data that may already be allocated by the application. Refer to table below for a description of how large the buffer that {@code host_ptr} points to must be. ${table( tr(th("ImageType"), th("Size of buffer that {@code host_ptr} points to")), tr(td("#MEM_OBJECT_IMAGE1D"), td("&ge; {@code image_row_pitch}")), tr(td("#MEM_OBJECT_IMAGE1D_BUFFER"), td("&ge; {@code image_row_pitch}")), tr(td("#MEM_OBJECT_IMAGE2D"), td("&ge; {@code image_row_pitch * image_height}")), tr(td("#MEM_OBJECT_IMAGE3D"), td("&ge; {@code image_slice_pitch * image_depth}")), tr(td("#MEM_OBJECT_IMAGE1D_ARRAY"), td("&ge; {@code image_slice_pitch * image_array_size}")), tr(td("#MEM_OBJECT_IMAGE2D_ARRAY"), td("&ge; {@code image_slice_pitch * image_array_size}")) )} """ ), ERROR_RET, returnDoc = """ a valid non-zero image object and the $errcode_ret is set to $SUCCESS if the image object is created successfully. Otherwise, it returns a #NULL value with one of the following error values returned in $errcode_ret: ${ul( ICE, """ $INVALID_PROPERTY if a property name in {@code properties} is not a supported property name, if the value specified for a supported property name is not valid, or if the same property name is specified more than once. """, "$INVALID_VALUE if values specified in {@code flags} are not valid.", "#INVALID_IMAGE_FORMAT_DESCRIPTOR if values specified in {@code image_format} are not valid or if {@code image_format} is #NULL.", """ #INVALID_IMAGE_FORMAT_DESCRIPTOR if a 2D image is created from a buffer and the row pitch and base address alignment does not follow the rules described for creating a 2D image from a buffer. """, "#INVALID_IMAGE_FORMAT_DESCRIPTOR if a 2D image is created from a 2D image object and the rules described above are not followed.", "#INVALID_IMAGE_DESCRIPTOR if values specified in {@code image_desc} are not valid or if {@code image_desc} is #NULL.", "#INVALID_IMAGE_SIZE if image dimensions specified in {@code image_desc} exceed the maximum image dimensions for all devices in context.", """ $INVALID_HOST_PTR if {@code host_ptr} is #NULL and #MEM_USE_HOST_PTR or #MEM_COPY_HOST_PTR are set in flags or if {@code host_ptr} is not #NULL but #MEM_COPY_HOST_PTR or #MEM_USE_HOST_PTR are not set in flags. """, """ #INVALID_VALUE if an image is being created from another memory object (buffer or image) under one of the following circumstances: ${ol( """ {@code mem_object} was created with {@code CL_MEM_WRITE_ONLY} and {@code flags} specifies {@code CL_MEM_READ_WRITE} or {@code CL_MEM_READ_ONLY}, """, "{@code mem_object} was created with {@code CL_MEM_READ_ONLY} and flags specifies {@code CL_MEM_READ_WRITE} or {@code CL_MEM_WRITE_ONLY},", "{@code flags} specifies {@code CL_MEM_USE_HOST_PTR} or {@code CL_MEM_ALLOC_HOST_PTR} or {@code CL_MEM_COPY_HOST_PTR}." )} """, """ #INVALID_VALUE if an image is being created from another memory object (buffer or image) and {@code mem_object} was created with {@code CL_MEM_HOST_WRITE_ONLY} and {@code flags} specifies {@code CL_MEM_HOST_READ_ONLY}, or if {@code mem_object} was created with {@code CL_MEM_HOST_READ_ONLY} and {@code flags} specifies {@code CL_MEM_HOST_WRITE_ONLY}, or if {@code mem_object} was created with {@code CL_MEM_HOST_NO_ACCESS} and {@code flags} specifies {@code CL_MEM_HOST_READ_ONLY} or {@code CL_MEM_HOST_WRITE_ONLY}. """, "#IMAGE_FORMAT_NOT_SUPPORTED if there are no devices in context that support {@code image_format}.", "#MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for image object.", "#INVALID_OPERATION if there are no devices in context that support images.", OORE, OOHME )} """ ) }
bsd-3-clause
f83db6d56d8cd3576d4350e9f1c5e6af
47.88906
179
0.647011
4.432663
false
false
false
false
paslavsky/spek
spek-tests/src/test/kotlin/org/jetbrains/spek/console/PlainTextListenerTest.kt
1
2077
package org.jetbrains.spek.console import org.mockito.Mockito import org.junit.Test as test class TextListenerTest { val device = Mockito.mock(OutputDevice::class.java)!! val textListener = OutputDeviceWorkflowReporter(device) @test fun given() { //given a text listener and a step listener that is bound to it. val listener = textListener.given("Spek", "A Given") //when execution started listener.started() //then a log message is written to output device Mockito.verify(device)!!.output(" A Given") //when execution completed listener.completed() //then a log message is written to output device Mockito.verify(device)!!.output("") //when execution failed listener.failed(RuntimeException()) //then a log message is written to output device Mockito.verify(device)!!.output(" Failed: java.lang.RuntimeException") } @test fun on() { //given a text listener and a step listener that is bound to it. val listener = textListener.on("Spek", "A Given", "An On") //when execution started listener.started() //then a log message is written to output device Mockito.verify(device)!!.output(" An On") //when execution failed listener.failed(RuntimeException()) //then a log message is written to output device Mockito.verify(device)!!.output(" Failed: java.lang.RuntimeException") } @test fun it() { //given a text listener and a step listener that is bound to it. val listener = textListener.it("Spek", "A Given", "An On", "An It") //when execution started listener.started() //then a log message is written to output device Mockito.verify(device)!!.output(" An It") //when execution failed listener.failed(RuntimeException()) //then a log message is written to output device Mockito.verify(device)!!.output(" Failed: java.lang.RuntimeException") } }
bsd-3-clause
772fde9ae94a78d0a1def7f336bd09a4
34.220339
83
0.636013
4.646532
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/LambdaImpicitHints.kt
3
2624
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.parameterInfo import com.intellij.codeInsight.hints.InlayInfo import com.intellij.lang.ASTNode import com.intellij.psi.PsiComment import com.intellij.psi.TokenType import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetails import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isUnit fun provideLambdaImplicitHints(lambda: KtLambdaExpression): List<InlayInfoDetails>? { val lbrace = lambda.leftCurlyBrace if (!lbrace.isFollowedByNewLine()) { return null } val bindingContext = lambda.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val functionDescriptor = bindingContext[BindingContext.FUNCTION, lambda.functionLiteral] ?: return null val implicitReceiverHint = functionDescriptor.extensionReceiverParameter?.let { implicitReceiver -> val type = implicitReceiver.type val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(bindingContext, lambda).renderTypeIntoInlayInfo(type) InlayInfoDetails(InlayInfo("", lbrace.psi.textRange.endOffset), listOf(TextInlayInfoDetail("this: ")) + renderedType) } val singleParameter = functionDescriptor.valueParameters.singleOrNull() val singleParameterHint = if (singleParameter != null && bindingContext[BindingContext.AUTO_CREATED_IT, singleParameter] == true) { val type = singleParameter.type if (type.isUnit()) null else { val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(bindingContext, lambda).renderTypeIntoInlayInfo(type) InlayInfoDetails(InlayInfo("", lbrace.textRange.endOffset), listOf(TextInlayInfoDetail("it: ")) + renderedType) } } else null return listOfNotNull(implicitReceiverHint, singleParameterHint) } internal fun ASTNode.isFollowedByNewLine(): Boolean { for (sibling in siblings()) { if (sibling.elementType != TokenType.WHITE_SPACE && sibling.psi !is PsiComment) { continue } if (sibling.elementType == TokenType.WHITE_SPACE && sibling.textContains('\n')) { return true } } return false }
apache-2.0
30364e9e3e5506f9ec03c5885bc6d48a
47.592593
158
0.76372
4.814679
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/ButtonsGroupImpl.kt
2
3297
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.ButtonsGroup import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.MutableProperty import com.intellij.ui.layout.* import org.jetbrains.annotations.ApiStatus import javax.swing.AbstractButton import javax.swing.ButtonGroup @ApiStatus.Internal internal class ButtonsGroupImpl(panel: PanelImpl, startIndex: Int) : RowsRangeImpl(panel, startIndex), ButtonsGroup { private val unboundRadioButtons = mutableSetOf<Cell<AbstractButton>>() private val boundRadioButtons = mutableMapOf<Cell<AbstractButton>, Any>() private var groupBinding: GroupBinding<*>? = null override fun visible(isVisible: Boolean): ButtonsGroup { super.visible(isVisible) return this } override fun visibleIf(predicate: ComponentPredicate): ButtonsGroup { super.visibleIf(predicate) return this } override fun enabled(isEnabled: Boolean): ButtonsGroup { super.enabled(isEnabled) return this } override fun enabledIf(predicate: ComponentPredicate): ButtonsGroup { super.enabledIf(predicate) return this } override fun <T> bind(prop: MutableProperty<T>, type: Class<T>): ButtonsGroup { if (groupBinding != null) { throw UiDslException("The group is bound already") } groupBinding = GroupBinding(prop, type) return this } fun <T : AbstractButton> add(cell: Cell<T>, value: Any? = null) { if (value == null) { unboundRadioButtons += cell } else { boundRadioButtons[cell] = value } } fun postInit() { if (groupBinding == null) { postInitUnbound() } else { postInitBound(groupBinding!!) } } private fun postInitBound(groupBinding: GroupBinding<*>) { if (unboundRadioButtons.isNotEmpty()) { throw UiDslException("Radio button '${unboundRadioButtons.first().component.text}' is used without value for binding") } val buttonGroup = ButtonGroup() for ((cell, value) in boundRadioButtons) { groupBinding.validate(value) buttonGroup.add(cell.component) cell.component.isSelected = groupBinding.prop.get() == value cell.onApply { if (cell.component.isSelected) groupBinding.set(value) } cell.onReset { cell.component.isSelected = groupBinding.prop.get() == value } cell.onIsModified { cell.component.isSelected != (groupBinding.prop.get() == value) } } } private fun postInitUnbound() { if (boundRadioButtons.isNotEmpty()) { throw UiDslException("Radio button '${boundRadioButtons.keys.first().component.text}' is used without ButtonsGroup.bind") } val buttonGroup = ButtonGroup() for (cell in unboundRadioButtons) { buttonGroup.add(cell.component) } } } private class GroupBinding<T>(val prop: MutableProperty<T>, val type: Class<T>) { fun set(value: Any) { prop.set(type.cast(value)) } fun validate(value: Any) { if (!type.isInstance(value)) { throw UiDslException("Value $value is incompatible with button group binding class ${type.simpleName}") } } }
apache-2.0
fa427a4ac892fa82c21397eab18c10de
30.103774
158
0.707613
4.157629
false
false
false
false
openium/auvergne-webcams-droid
app/src/main/java/fr/openium/auvergnewebcams/ui/sectionDetail/FragmentSectionDetail.kt
1
3719
package fr.openium.auvergnewebcams.ui.sectionDetail import android.os.Bundle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import fr.openium.auvergnewebcams.Constants import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.base.AbstractFragment import fr.openium.auvergnewebcams.model.entity.Section import fr.openium.auvergnewebcams.model.entity.Webcam import fr.openium.auvergnewebcams.ui.webcamDetail.ActivityWebcamDetail import fr.openium.auvergnewebcams.utils.AnalyticsUtils import fr.openium.auvergnewebcams.utils.Optional import fr.openium.rxtools.ext.fromIOToMain import io.reactivex.Single import io.reactivex.functions.BiFunction import io.reactivex.rxkotlin.addTo import kotlinx.android.synthetic.main.fragment_section_detail.* import timber.log.Timber /** * Created by Openium on 19/02/2019. */ class FragmentSectionDetail : AbstractFragment() { override val layoutId: Int = R.layout.fragment_section_detail protected lateinit var viewModelSectionDetail: ViewModelSectionDetail protected lateinit var section: Section private var adapterSectionDetail: AdapterSectionDetail? = null // --- Life cycle // --------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModelSectionDetail = ViewModelProvider(this).get(ViewModelSectionDetail::class.java) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val sectionId = arguments?.getLong(Constants.KEY_SECTION_ID, -1L) ?: -1L if (sectionId != -1L) { setListener(sectionId) } else requireActivity().finish() } // --- Methods // --------------------------------------------------- private fun setListener(sectionId: Long) { Single.zip( viewModelSectionDetail.getSectionSingle(sectionId), viewModelSectionDetail.getWebcamsSingle(sectionId), BiFunction { section: Optional<Section>, webcams: List<Webcam> -> section to webcams }) .fromIOToMain() .subscribe({ sectionAndWebcams -> sectionAndWebcams.first.value?.let { section = it section.webcams = sectionAndWebcams.second initAdapter() } }, { Timber.e(it, "Error when getting sections and webcams") }).addTo(disposables) } private fun initAdapter() { if (adapterSectionDetail == null) { adapterSectionDetail = AdapterSectionDetail(prefUtils, dateUtils, Glide.with(requireContext()), getData()) { AnalyticsUtils.webcamDetailsClicked(requireContext(), it.title ?: "") requireContext().startActivity(ActivityWebcamDetail.getIntent(requireContext(), it)) } recyclerViewSectionDetail.apply { layoutManager = LinearLayoutManager(context) adapter = adapterSectionDetail // Optimize setHasFixedSize(true) } } else { adapterSectionDetail?.refreshData(getData()) } } private fun getData(): List<AdapterSectionDetail.Data> = mutableListOf<AdapterSectionDetail.Data>().apply { // First add section add(AdapterSectionDetail.Data(section)) // Then add all webcams section.webcams.forEach { add(AdapterSectionDetail.Data(webcam = it)) } } }
mit
066d3e3c75380ff2c23a9293a30cd164
34.428571
120
0.650444
5.129655
false
false
false
false
phylame/qaf
kotlin-swing/src/main/kotlin/qaf/swing/Menus.kt
1
1105
package qaf.swing import javax.swing.* fun <T : JMenuBar> T.menu(adding: Boolean = true, init: JMenu.() -> Unit): JMenu { val menu = JMenu() if (adding) { add(menu) } menu.init() return menu } fun <T : JMenu> T.menu(adding: Boolean = true, init: JMenu.() -> Unit): JMenu { val menu = JMenu() if (adding) { add(menu) } menu.init() return menu } fun <T : JMenu> T.separator() { add(JPopupMenu.Separator()) } fun <T : JMenu> T.item(adding: Boolean = true, init: JMenuItem.() -> Unit): JMenuItem { val item = JMenuItem() if (adding) { add(item) } item.init() return item } fun <T : JMenu> T.check(adding: Boolean = true, init: JCheckBoxMenuItem.() -> Unit): JCheckBoxMenuItem { val item = JCheckBoxMenuItem() if (adding) { add(item) } item.init() return item } fun <T : JMenu> T.radio(adding: Boolean = true, init: JRadioButtonMenuItem.() -> Unit): JRadioButtonMenuItem { val item = JRadioButtonMenuItem() if (adding) { add(item) } item.init() return item }
apache-2.0
20d051adf4e8d1eb77785e8a9f3c3fd1
20.25
110
0.579186
3.431677
false
false
false
false
audit4j/audit4j-demo
audit4j-kotlin-demo-springboot/src/main/kotlin/org/springframework/samples/petclinic/owner/PetValidator.kt
1
1058
package org.springframework.samples.petclinic.owner import org.springframework.util.StringUtils import org.springframework.validation.Errors import org.springframework.validation.Validator class PetValidator : Validator { companion object { const val REQUIRED = "required" } override fun validate(obj: Any?, errors: Errors) { if (obj == null) { return } val pet = obj as Pet val name = pet.name; // name validation if (!StringUtils.hasLength(name)) { errors.rejectValue("name", REQUIRED, REQUIRED); } // type validation if (pet.isNew && pet.type == null) { errors.rejectValue("type", REQUIRED, REQUIRED); } // birth date validation if (pet.birthDate == null) { errors.rejectValue("birthDate", REQUIRED, REQUIRED); } } /** * This Validator validates *just* Pet instances */ override fun supports(clazz: Class<*>) = Pet::class.java.isAssignableFrom(clazz) }
apache-2.0
a80af2bc14d007b4b68c1e7c4935bae6
23.627907
84
0.60586
4.620087
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/model/PaymentMethod.kt
2
1945
package co.smartreceipts.android.model import android.content.res.Resources import android.os.Parcelable import co.smartreceipts.android.model.factory.PaymentMethodBuilderFactory import co.smartreceipts.core.sync.model.SyncState import co.smartreceipts.core.sync.model.Syncable import co.smartreceipts.core.sync.model.impl.DefaultSyncState import kotlinx.android.parcel.Parcelize import java.util.* /** * An immutable implementation of [PaymentMethod]. * * @author Will Baumann */ @Parcelize class PaymentMethod @JvmOverloads constructor ( override val id: Int, override val uuid: UUID, val method: String, // The actual payment method that the user specified val isReimbursable: Boolean, override val syncState: SyncState = DefaultSyncState(), override val customOrderId: Long = 0 ) : Keyed, Parcelable, Syncable, Draggable<PaymentMethod> { override fun toString() = method override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PaymentMethod) return false val that = other as PaymentMethod? if (id != that!!.id) return false if (uuid != that.uuid) return false if (isReimbursable != that.isReimbursable) return false return if (customOrderId != that.customOrderId) false else method == that.method } override fun hashCode(): Int { var result = id result = 31 * result + uuid.hashCode() result = 31 * result + method.hashCode() result = 31 * result + isReimbursable.hashCode() result = 31 * result + (customOrderId xor customOrderId.ushr(32)).toInt() return result } override fun compareTo(other: PaymentMethod): Int { return customOrderId.compareTo(other.customOrderId) } companion object { val NONE = PaymentMethodBuilderFactory().setMethod(Resources.getSystem().getString(android.R.string.untitled)).build() } }
agpl-3.0
1aa031db31f9bac80ccbfb66d9e3fa17
32.534483
126
0.703342
4.502315
false
false
false
false
paplorinc/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorageTest.kt
1
2407
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.project.manage import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.util.Alarm import kotlinx.coroutines.runBlocking import org.assertj.core.api.BDDAssertions.then import org.junit.After import org.junit.Before import org.junit.Test import java.util.concurrent.TimeUnit.SECONDS import kotlin.reflect.jvm.jvmName class ExternalProjectsDataStorageTest: UsefulTestCase() { lateinit var myFixture: IdeaProjectTestFixture @Before override fun setUp() { super.setUp() myFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name).fixture myFixture.setUp() } @After override fun tearDown() { myFixture.tearDown() super.tearDown() } @Test fun `test external project data is saved and loaded`() = runBlocking<Unit> { val dataStorage = ExternalProjectsDataStorage(myFixture.project) val testId = ProjectSystemId("Test") val externalName = "external_name" val externalProjectPath = FileUtil.toSystemIndependentName(createTempDir(suffix = "externalProject").canonicalPath) val projectData = ProjectData(testId, externalName, "external_project_path", externalProjectPath) val node = DataNode<ProjectData>(Key(ProjectData::class.jvmName, 0), projectData, null) val externalProjectInfo = InternalExternalProjectInfo(testId, externalProjectPath, node) dataStorage.update(externalProjectInfo) dataStorage.save() dataStorage.load() val list = dataStorage.list(testId) then(list).hasSize(1) then(list .iterator() .next() .externalProjectStructure?.data?.externalName) .isEqualTo(externalName) } }
apache-2.0
0c0e334f99349bb9ef1ce2f3dc6b67de
36.625
140
0.768592
4.814
false
true
false
false
Zeyad-37/RxRedux
core/src/test/java/com/zeyad/rxredux/core/UserListVM.kt
1
5943
package com.zeyad.rxredux.core import android.util.Log import androidx.recyclerview.widget.DiffUtil import com.zeyad.gadapter.ItemInfo import com.zeyad.rxredux.core.viewmodel.BaseViewModel import com.zeyad.rxredux.core.viewmodel.SuccessEffectResult import com.zeyad.rxredux.core.viewmodel.throwIllegalStateException import com.zeyad.usecases.api.IDataService import com.zeyad.usecases.db.RealmQueryProvider import com.zeyad.usecases.requests.GetRequest import com.zeyad.usecases.requests.PostRequest import io.reactivex.Flowable import io.reactivex.functions.BiFunction import io.realm.Realm import io.realm.RealmQuery class UserListVM(private val dataUseCase: IDataService) : BaseViewModel<UserListIntents<*>, UserListResult, UserListState, UserListEffect>() { override fun reduceIntentsToResults(intent: UserListIntents<*>, currentState: Any): Flowable<*> { Log.d("UserListVM", "currentStateBundle: $currentState") return when (intent) { is GetPaginatedUsersIntent -> when (currentState) { is EmptyState, is GetState -> getUsers(intent.getPayLoad()) else -> throwIllegalStateException(intent) } is DeleteUsersIntent -> when (currentState) { is GetState -> deleteCollection(intent.getPayLoad()) else -> throwIllegalStateException(intent) } is SearchUsersIntent -> when (currentState) { is GetState -> search(intent.getPayLoad()) else -> throwIllegalStateException(intent) } is UserClickedIntent -> when (currentState) { is GetState -> Flowable.just(SuccessEffectResult(NavigateTo(intent.getPayLoad()), intent)) else -> throwIllegalStateException(intent) } } } override fun stateReducer(newResult: UserListResult, currentState: UserListState): UserListState { val currentItemInfo = currentState.list.toMutableList() return when (currentState) { is EmptyState -> when (newResult) { is EmptyResult -> EmptyState() is UsersResult -> { val pair = Flowable.fromIterable(newResult.list) .map { ItemInfo(it, R.layout.abc_action_menu_item_layout, it.id) } .toList().toFlowable() .calculateDiff(currentItemInfo) GetState(pair.first, pair.first[pair.first.size - 1].id, pair.second) } } is GetState -> when (newResult) { is EmptyResult -> EmptyState() is UsersResult -> { val pair = Flowable.fromIterable(newResult.list) .map { ItemInfo(it, R.layout.abc_action_menu_item_layout, it.id) } .toList() .map { val list = currentState.list.toMutableList() list.addAll(it) list.toSet().toMutableList() }.toFlowable() .calculateDiff(currentItemInfo) GetState(pair.first, pair.first[pair.first.size - 1].id, pair.second) } } } } private fun Flowable<MutableList<ItemInfo>>.calculateDiff(initialList: MutableList<ItemInfo>) : Pair<MutableList<ItemInfo>, DiffUtil.DiffResult> = scan<Pair<MutableList<ItemInfo>, DiffUtil.DiffResult>>(Pair(initialList, DiffUtil.calculateDiff(UserDiffCallBack(mutableListOf(), mutableListOf())))) { pair1, next -> Pair(next, DiffUtil.calculateDiff(UserDiffCallBack(pair1.first, next))) }.skip(1) .blockingFirst() private fun getUsers(lastId: Long): Flowable<*> { // return if (lastId == 0L) // dataUseCase.getListOffLineFirst(GetRequest.Builder(User::class.java, true) // .url(String.format(USERS, lastId)) // .build()) // else return dataUseCase.getList<User>(GetRequest.Builder(User::class.java, true) .url(String.format(USERS, lastId)).build()) .map { when (it.isEmpty()) { true -> EmptyResult false -> UsersResult(it) } } } private fun search(query: String): Flowable<UsersResult> { return dataUseCase .queryDisk(object : RealmQueryProvider<User> { override fun create(realm: Realm): RealmQuery<User> = realm.where(User::class.java).beginsWith(User.LOGIN, query) }) .zipWith(dataUseCase.getObject<User>(GetRequest.Builder(User::class.java, false) .url(String.format(USER, query)).build()) .onErrorReturnItem(User()) .filter { user -> user.id != 0L } .map { mutableListOf(it) }, BiFunction<List<User>, MutableList<User>, List<User>> { singleton, users -> users.addAll(singleton) users.asSequence().toSet().toList() }).map { UsersResult(it) } } private fun deleteCollection(selectedItemsIds: List<String>): Flowable<List<String>> { return dataUseCase.deleteCollectionByIds<Any>(PostRequest.Builder(User::class.java, true) .payLoad(selectedItemsIds) .idColumnName(User.LOGIN, String::class.java).cache() .build()) .map { selectedItemsIds } } companion object { const val USERS = "users?since=%s" const val USER = "users/%s" } }
apache-2.0
bafe2f23f7981978eef0fc3edbe459c7
45.429688
142
0.565034
5.00674
false
false
false
false
paplorinc/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseLineStatusTrackerManagerTest.kt
2
5124
// 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.openapi.vcs import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.impl.UndoManagerImpl import com.intellij.openapi.command.undo.DocumentReferenceManager import com.intellij.openapi.command.undo.DocumentReferenceProvider import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.vcs.BaseLineStatusTrackerTestCase.Companion.parseInput import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.ex.* import com.intellij.openapi.vcs.impl.LineStatusTrackerManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.RunAll import com.intellij.util.ThrowableRunnable import com.intellij.util.ui.UIUtil import org.mockito.Mockito abstract class BaseLineStatusTrackerManagerTest : BaseChangeListsTest() { protected lateinit var shelveManager: ShelveChangesManager protected lateinit var lstm: LineStatusTrackerManager protected lateinit var undoManager: UndoManagerImpl override fun setUp() { super.setUp() lstm = LineStatusTrackerManager.getInstanceImpl(getProject()) undoManager = UndoManager.getInstance(getProject()) as UndoManagerImpl shelveManager = ShelveChangesManager.getInstance(getProject()) } override fun tearDown() { RunAll() .append(ThrowableRunnable { clm.waitUntilRefreshed() }) .append(ThrowableRunnable { UIUtil.dispatchAllInvocationEvents() }) .append(ThrowableRunnable { lstm.resetExcludedFromCommitMarkers() }) .append(ThrowableRunnable { lstm.releaseAllTrackers() }) .append(ThrowableRunnable { super.tearDown() }) .run() } override fun resetSettings() { super.resetSettings() VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS = true VcsApplicationSettings.getInstance().SHOW_LST_GUTTER_MARKERS = true VcsApplicationSettings.getInstance().SHOW_WHITESPACES_IN_LST = true arePartialChangelistsSupported = true } protected fun releaseUnneededTrackers() { runWriteAction { } // LineStatusTrackerManager.MyApplicationListener.afterWriteActionFinished } protected val VirtualFile.tracker: LineStatusTracker<*>? get() = lstm.getLineStatusTracker(this) protected fun VirtualFile.withOpenedEditor(task: () -> Unit) { lstm.requestTrackerFor(document, this) try { task() } finally { lstm.releaseTrackerFor(document, this) } } protected open fun runCommand(groupId: String? = null, task: () -> Unit) { CommandProcessor.getInstance().executeCommand(getProject(), { ApplicationManager.getApplication().runWriteAction(task) }, "", groupId) } protected fun undo(document: Document) { val editor = createMockFileEditor(document) undoManager.undo(editor) } protected fun redo(document: Document) { val editor = createMockFileEditor(document) undoManager.redo(editor) } private fun createMockFileEditor(document: Document): FileEditor { val editor = Mockito.mock(FileEditor::class.java, Mockito.withSettings().extraInterfaces(DocumentReferenceProvider::class.java)) val references = listOf(DocumentReferenceManager.getInstance().create(document)) Mockito.`when`((editor as DocumentReferenceProvider).documentReferences).thenReturn(references) return editor } protected fun PartialLocalLineStatusTracker.assertAffectedChangeLists(vararg expectedNames: String) { assertSameElements(this.getAffectedChangeListsIds().asListIdsToNames(), *expectedNames) } protected fun LineStatusTracker<*>.assertTextContentIs(expected: String) { assertEquals(parseInput(expected), document.text) } protected fun LineStatusTracker<*>.assertBaseTextContentIs(expected: String) { assertEquals(parseInput(expected), vcsDocument.text) } protected fun Range.assertChangeList(listName: String) { val localRange = this as LocalRange assertEquals(listName, localRange.changelistId.asListIdToName()) } protected fun VirtualFile.assertNullTracker() { val tracker = this.tracker if (tracker != null) { var message = "$tracker" + ": operational - ${tracker.isOperational()}" + ", valid - ${tracker.isValid()}, " + ", file - ${tracker.virtualFile}" if (tracker is PartialLocalLineStatusTracker) { message += ", hasPartialChanges - ${tracker.hasPartialChangesToCommit()}" + ", lists - ${tracker.getAffectedChangeListsIds().asListIdsToNames()}" } assertNull(message, tracker) } } protected fun PartialLocalLineStatusTracker.assertExcludedState(expected: ExclusionState, listName: String) { assertEquals(expected, getExcludedFromCommitState(listName.asListNameToId())) } }
apache-2.0
0574f96a6e730f2702f0140b12e5b506
38.423077
140
0.758392
5.048276
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/DateHelper.kt
2
1819
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.utils import kotlin.js.Date object DateHelper { fun toDate(content: Any?): Date { val result = when (content) { is String -> { var s = content if (!s.contains("-")) { s = convertJavaOffsetDateTimeToISO(content) } val millis = Date.parse(s) Date(millis) } is Long -> { Date(content as Number) } else -> { Date() } } return result } fun convertJavaOffsetDateTimeToISO(input: String): String { val year = input.substring(0, 4) val month = input.substring(4, 6) val dayEtc = input.substring(6, 11) val minutes = input.substring(11, 13) val rest = input.substring(13, input.length) val output = "$year-$month-$dayEtc:$minutes:$rest" return output } }
apache-2.0
7ff5cd593404fdab5ee5968649c9951f
32.072727
64
0.604178
4.310427
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.kt
2
28027
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.actions.* import com.intellij.ide.impl.ContentManagerWatcher import com.intellij.idea.ActionsBundle import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.notification.EventLog import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.FusAwareAction import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.Divider import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.util.* import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import com.intellij.toolWindow.FocusTask import com.intellij.toolWindow.InternalDecoratorImpl import com.intellij.toolWindow.ToolWindowEventSource import com.intellij.toolWindow.ToolWindowProperty import com.intellij.ui.ClientProperty import com.intellij.ui.LayeredIcon import com.intellij.ui.UIBundle import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener import com.intellij.ui.content.impl.ContentImpl import com.intellij.ui.content.impl.ContentManagerImpl import com.intellij.ui.scale.JBUIScale import com.intellij.util.Consumer import com.intellij.util.ModalityUiUtil import com.intellij.util.SingleAlarm import com.intellij.util.ui.* import com.intellij.util.ui.update.Activatable import com.intellij.util.ui.update.UiNotifyConnector import org.jetbrains.annotations.ApiStatus import java.awt.AWTEvent import java.awt.Color import java.awt.Component import java.awt.Rectangle import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.event.InputEvent import java.util.* import javax.swing.* import kotlin.math.abs internal class ToolWindowImpl(val toolWindowManager: ToolWindowManagerImpl, private val id: String, private val canCloseContent: Boolean, private val dumbAware: Boolean, component: JComponent?, private val parentDisposable: Disposable, windowInfo: WindowInfo, private var contentFactory: ToolWindowFactory?, private var isAvailable: Boolean = true, @NlsContexts.TabTitle private var stripeTitle: String) : ToolWindowEx { var windowInfoDuringInit: WindowInfoImpl? = null private val focusTask by lazy { FocusTask(this) } val focusAlarm by lazy { SingleAlarm(focusTask, 0, disposable) } override fun getId() = id override fun getProject() = toolWindowManager.project override fun getDecoration(): ToolWindowEx.ToolWindowDecoration { return ToolWindowEx.ToolWindowDecoration(icon, additionalGearActions) } var windowInfo: WindowInfo = windowInfo private set private var contentUi: ToolWindowContentUi? = null internal var decorator: InternalDecoratorImpl? = null private set private var hideOnEmptyContent = false var isPlaceholderMode = false private var pendingContentManagerListeners: MutableList<ContentManagerListener>? = null private val showing = object : BusyObject.Impl() { override fun isReady(): Boolean { return getComponentIfInitialized()?.isShowing ?: false } } private var toolWindowFocusWatcher: ToolWindowFocusWatcher? = null private var additionalGearActions: ActionGroup? = null private var helpId: String? = null internal var icon: ToolWindowIcon? = null private val contentManager = lazy { val result = createContentManager() if (toolWindowManager.isNewUi) { result.addContentManagerListener(UpdateBackgroundContentManager(decorator)) } result } init { if (component != null) { val content = ContentImpl(component, "", false) val contentManager = contentManager.value contentManager.addContent(content) contentManager.setSelectedContent(content, false) } } private class UpdateBackgroundContentManager(private val decorator: InternalDecoratorImpl?) : ContentManagerListener { override fun contentAdded(event: ContentManagerEvent) { setBackgroundRecursively(event.content.component, JBUI.CurrentTheme.ToolWindow.background()) addAdjustListener(decorator, event.content.component) } } internal fun getOrCreateDecoratorComponent(): InternalDecoratorImpl { ensureContentManagerInitialized() return decorator!! } fun createCellDecorator() : InternalDecoratorImpl { val cellContentManager = ContentManagerImpl(canCloseContent, toolWindowManager.project, parentDisposable, ContentManagerImpl.ContentUiProducer { contentManager, componentGetter -> ToolWindowContentUi(this, contentManager, componentGetter.get()) }) return InternalDecoratorImpl(this, cellContentManager.ui as ToolWindowContentUi, cellContentManager.component) } private fun createContentManager(): ContentManagerImpl { val contentManager = ContentManagerImpl(canCloseContent, toolWindowManager.project, parentDisposable, ContentManagerImpl.ContentUiProducer { contentManager, componentGetter -> val result = ToolWindowContentUi(this, contentManager, componentGetter.get()) contentUi = result result }) addContentNotInHierarchyComponents(contentUi!!) val contentComponent = contentManager.component InternalDecoratorImpl.installFocusTraversalPolicy(contentComponent, LayoutFocusTraversalPolicy()) Disposer.register(parentDisposable, UiNotifyConnector(contentComponent, object : Activatable { override fun showNotify() { showing.onReady() } })) var decoratorChild = contentManager.component if (!dumbAware) { decoratorChild = DumbService.getInstance(toolWindowManager.project).wrapGently(decoratorChild, parentDisposable) } val decorator = InternalDecoratorImpl(this, contentUi!!, decoratorChild) this.decorator = decorator decorator.applyWindowInfo(windowInfo) decorator.addComponentListener(object : ComponentAdapter() { private val alarm = SingleAlarm(Runnable { toolWindowManager.resized(decorator) windowInfo = toolWindowManager.getLayout().getInfo(getId()) as WindowInfo }, 100, disposable) override fun componentResized(e: ComponentEvent) { alarm.cancelAndRequest() } }) toolWindowFocusWatcher = ToolWindowFocusWatcher(toolWindow = this, component = decorator) contentManager.addContentManagerListener(object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { [email protected]?.headerToolbar?.updateActionsImmediately() } }) // after init, as it was before contentManager creation was changed to be lazy pendingContentManagerListeners?.let { list -> pendingContentManagerListeners = null for (listener in list) { contentManager.addContentManagerListener(listener) } } return contentManager } internal fun setWindowInfoSilently(info: WindowInfo) { windowInfo = info } internal fun applyWindowInfo(info: WindowInfo) { windowInfo = info contentUi?.setType(info.contentUiType) val decorator = decorator if (decorator != null) { decorator.applyWindowInfo(info) decorator.validate() decorator.repaint() } } val decoratorComponent: JComponent? get() = decorator val hasFocus: Boolean get() = decorator?.hasFocus() ?: false fun setFocusedComponent(component: Component) { toolWindowFocusWatcher?.setFocusedComponentImpl(component) } fun getLastFocusedContent() : Content? { val lastFocusedComponent = toolWindowFocusWatcher?.focusedComponent if (lastFocusedComponent is JComponent) { if (!lastFocusedComponent.isShowing) return null val nearestDecorator = InternalDecoratorImpl.findNearestDecorator(lastFocusedComponent) val content = nearestDecorator?.contentManager?.getContent(lastFocusedComponent) if (content != null && content.isSelected) return content } return null } override fun getDisposable() = parentDisposable override fun remove() { @Suppress("DEPRECATION") toolWindowManager.unregisterToolWindow(id) } override fun activate(runnable: Runnable?, autoFocusContents: Boolean, forced: Boolean) { toolWindowManager.activateToolWindow(id, runnable, autoFocusContents) } override fun isActive(): Boolean { toolWindowManager.assertIsEdt() return windowInfo.isVisible && decorator != null && toolWindowManager.activeToolWindowId == id } override fun getReady(requestor: Any): ActionCallback { val result = ActionCallback() showing.getReady(this) .doWhenDone { toolWindowManager.focusManager.doWhenFocusSettlesDown { if (contentManager.isInitialized() && contentManager.value.isDisposed) { return@doWhenFocusSettlesDown } contentManager.value.getReady(requestor).notify(result) } } return result } override fun show(runnable: Runnable?) { EDT.assertIsEdt() toolWindowManager.showToolWindow(id) callLater(runnable) } override fun hide(runnable: Runnable?) { toolWindowManager.hideToolWindow(id) callLater(runnable) } override fun isVisible() = windowInfo.isVisible override fun getAnchor() = windowInfo.anchor override fun setAnchor(anchor: ToolWindowAnchor, runnable: Runnable?) { EDT.assertIsEdt() toolWindowManager.setToolWindowAnchor(id, anchor) callLater(runnable) } override fun isSplitMode() = windowInfo.isSplit override fun setContentUiType(type: ToolWindowContentUiType, runnable: Runnable?) { EDT.assertIsEdt() toolWindowManager.setContentUiType(id, type) callLater(runnable) } override fun setDefaultContentUiType(type: ToolWindowContentUiType) { toolWindowManager.setDefaultContentUiType(this, type) } override fun getContentUiType() = windowInfo.contentUiType override fun setSplitMode(isSideTool: Boolean, runnable: Runnable?) { EDT.assertIsEdt() toolWindowManager.setSideTool(id, isSideTool) callLater(runnable) } override fun setAutoHide(value: Boolean) { toolWindowManager.setToolWindowAutoHide(id, value) } override fun isAutoHide() = windowInfo.isAutoHide override fun getType() = windowInfo.type override fun setType(type: ToolWindowType, runnable: Runnable?) { EDT.assertIsEdt() toolWindowManager.setToolWindowType(id, type) callLater(runnable) } override fun getInternalType() = windowInfo.internalType override fun stretchWidth(value: Int) { toolWindowManager.stretchWidth(this, value) } override fun stretchHeight(value: Int) { toolWindowManager.stretchHeight(this, value) } override fun getDecorator(): InternalDecoratorImpl = decorator!! override fun setAdditionalGearActions(value: ActionGroup?) { additionalGearActions = value } override fun setTitleActions(actions: List<AnAction>) { ensureContentManagerInitialized() decorator!!.setTitleActions(actions) } override fun setTabActions(vararg actions: AnAction) { createContentIfNeeded() decorator!!.setTabActions(actions.toList()) } override fun setTabDoubleClickActions(actions: List<AnAction>) { contentUi?.setTabDoubleClickActions(actions) } override fun setAvailable(value: Boolean) { if (isAvailable == value) { return } if (windowInfoDuringInit != null) { throw IllegalStateException("Do not use toolWindow.setAvailable() as part of ToolWindowFactory.init().\n" + "Use ToolWindowFactory.shouldBeAvailable() instead.") } toolWindowManager.assertIsEdt() isAvailable = value if (value) { toolWindowManager.toolWindowAvailable(this) } else { toolWindowManager.toolWindowUnavailable(this) contentUi?.dropCaches() } } override fun setAvailable(value: Boolean, runnable: Runnable?) { setAvailable(value) callLater(runnable) } private fun callLater(runnable: Runnable?) { if (runnable != null) { toolWindowManager.invokeLater(runnable) } } override fun installWatcher(contentManager: ContentManager) { ContentManagerWatcher.watchContentManager(this, contentManager) } override fun isAvailable() = isAvailable override fun getComponent(): JComponent { if (toolWindowManager.project.isDisposed) { // nullable because of TeamCity plugin @Suppress("HardCodedStringLiteral") return JLabel("Do not call getComponent() on dispose") } return contentManager.value.component } fun getComponentIfInitialized(): JComponent? { return if (contentManager.isInitialized()) contentManager.value.component else null } override fun getContentManagerIfCreated(): ContentManager? { return if (contentManager.isInitialized()) contentManager.value else null } override fun getContentManager(): ContentManager { createContentIfNeeded() return contentManager.value } override fun addContentManagerListener(listener: ContentManagerListener) { if (contentManager.isInitialized()) { contentManager.value.addContentManagerListener(listener) } else { if (pendingContentManagerListeners == null) { pendingContentManagerListeners = mutableListOf() } pendingContentManagerListeners!!.add(listener) } } override fun canCloseContents() = canCloseContent override fun getIcon() = icon override fun getTitle(): String? = contentManager.value.selectedContent?.displayName override fun getStripeTitle() = stripeTitle override fun setIcon(newIcon: Icon) { EDT.assertIsEdt() if (newIcon !== icon?.retrieveIcon()) { doSetIcon(newIcon) toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.ICON) } } internal fun doSetIcon(newIcon: Icon) { val oldIcon = icon if (EventLog.LOG_TOOL_WINDOW_ID != id && oldIcon !== newIcon && newIcon !is LayeredIcon && !toolWindowManager.isNewUi && (abs(newIcon.iconHeight - JBUIScale.scale(13f)) >= 1 || abs(newIcon.iconWidth - JBUIScale.scale(13f)) >= 1)) { logger<ToolWindowImpl>().warn("ToolWindow icons should be 13x13. Please fix ToolWindow (ID: $id) or icon $newIcon") } icon = ToolWindowIcon(newIcon, id) } override fun setTitle(title: String) { EDT.assertIsEdt() contentManager.value.selectedContent?.displayName = title toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.TITLE) } override fun setStripeTitle(value: String) { if (value == stripeTitle) { return } stripeTitle = value contentUi?.update() if (windowInfoDuringInit == null) { EDT.assertIsEdt() toolWindowManager.toolWindowPropertyChanged(toolWindow = this, property = ToolWindowProperty.STRIPE_TITLE) } } fun fireActivated(source: ToolWindowEventSource) { toolWindowManager.activated(this, source) } fun fireHidden(source: ToolWindowEventSource?) { toolWindowManager.hideToolWindow(id = id, source = source) } fun fireHiddenSide(source: ToolWindowEventSource?) { toolWindowManager.hideToolWindow(id = id, hideSide = true, source = source) } override fun setDefaultState(anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) { toolWindowManager.setDefaultState(this, anchor, type, floatingBounds) } override fun setToHideOnEmptyContent(value: Boolean) { hideOnEmptyContent = value } fun isToHideOnEmptyContent() = hideOnEmptyContent override fun setShowStripeButton(value: Boolean) { val windowInfoDuringInit = windowInfoDuringInit if (windowInfoDuringInit == null) { toolWindowManager.setShowStripeButton(id, value) } else { windowInfoDuringInit.isShowStripeButton = value } } override fun isShowStripeButton() = windowInfo.isShowStripeButton override fun isDisposed() = contentManager.isInitialized() && contentManager.value.isDisposed private fun ensureContentManagerInitialized() { contentManager.value } internal fun scheduleContentInitializationIfNeeded() { if (contentFactory != null) { // todo use lazy loading (e.g. JBLoadingPanel) createContentIfNeeded() } } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Do not use. Tool window content will be initialized automatically.", level = DeprecationLevel.ERROR) @ApiStatus.ScheduledForRemoval fun ensureContentInitialized() { createContentIfNeeded() } internal fun createContentIfNeeded() { val currentContentFactory = contentFactory ?: return // clear it first to avoid SOE this.contentFactory = null if (contentManager.isInitialized()) { contentManager.value.removeAllContents(false) } else { ensureContentManagerInitialized() } currentContentFactory.createToolWindowContent(toolWindowManager.project, this) if (toolWindowManager.isNewUi) { setBackgroundRecursively(contentManager.value.component, JBUI.CurrentTheme.ToolWindow.background()) addAdjustListener(decorator, contentManager.value.component) } } override fun getHelpId() = helpId override fun setHelpId(value: String) { helpId = value } override fun showContentPopup(inputEvent: InputEvent) { // called only when tool window is already opened, so, content should be already created ToolWindowContentUi.toggleContentPopup(contentUi!!, contentManager.value) } @JvmOverloads fun createPopupGroup(skipHideAction: Boolean = false): ActionGroup { val group = GearActionGroup(this) if (!skipHideAction) { group.addSeparator() group.add(HideAction()) } group.addSeparator() group.add(object : ContextHelpAction() { override fun getHelpId(dataContext: DataContext): String? { val content = contentManagerIfCreated?.selectedContent if (content != null) { val helpId = content.helpId if (helpId != null) { return helpId } } val id = getHelpId() if (id != null) { return id } val context = if (content == null) dataContext else DataManager.getInstance().getDataContext(content.component) return super.getHelpId(context) } override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = getHelpId(e.dataContext) != null } }) return group } override fun getEmptyText(): StatusText = (contentManager.value.component as ComponentWithEmptyText).emptyText fun setEmptyStateBackground(color: Color) { decorator?.background = color } private inner class GearActionGroup(toolWindow: ToolWindowImpl) : DefaultActionGroup(), DumbAware { init { templatePresentation.icon = AllIcons.General.GearPlain if (toolWindowManager.isNewUi) { templatePresentation.icon = AllIcons.Actions.More } templatePresentation.text = IdeBundle.message("show.options.menu") val additionalGearActions = additionalGearActions if (additionalGearActions != null) { if (additionalGearActions.isPopup && !additionalGearActions.templatePresentation.text.isNullOrEmpty()) { add(additionalGearActions) } else { addSorted(this, additionalGearActions) } addSeparator() } val toggleToolbarGroup = ToggleToolbarAction.createToggleToolbarGroup(toolWindowManager.project, this@ToolWindowImpl) if (ToolWindowId.PREVIEW != id) { toggleToolbarGroup.addAction(ToggleContentUiTypeAction()) } addAction(toggleToolbarGroup).setAsSecondary(true) add(ActionManager.getInstance().getAction("TW.ViewModeGroup")) if (toolWindowManager.isNewUi) { add(SquareStripeButton.createMoveGroup(toolWindow)) } else { add(ToolWindowMoveAction.Group()) } add(ResizeActionGroup()) addSeparator() add(RemoveStripeButtonAction()) } } private inner class HideAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { toolWindowManager.hideToolWindow(id, false) } override fun update(event: AnActionEvent) { val presentation = event.presentation presentation.isEnabled = isVisible } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } init { ActionUtil.copyFrom(this, InternalDecoratorImpl.HIDE_ACTIVE_WINDOW_ACTION_ID) templatePresentation.text = UIBundle.message("tool.window.hide.action.name") } } private inner class ResizeActionGroup : ActionGroup(ActionsBundle.groupText("ResizeToolWindowGroup"), true), DumbAware { private val children by lazy<Array<AnAction>> { // force creation createContentIfNeeded() val component = decorator val toolWindow = this@ToolWindowImpl arrayOf( ResizeToolWindowAction.Left(toolWindow, component), ResizeToolWindowAction.Right(toolWindow, component), ResizeToolWindowAction.Up(toolWindow, component), ResizeToolWindowAction.Down(toolWindow, component), ActionManager.getInstance().getAction("MaximizeToolWindow") ) } override fun getChildren(e: AnActionEvent?) = children override fun isDumbAware() = true } private inner class RemoveStripeButtonAction : AnAction(ActionsBundle.messagePointer("action.RemoveStripeButton.text"), ActionsBundle.messagePointer("action.RemoveStripeButton.description"), null), DumbAware, FusAwareAction { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isShowStripeButton } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(e: AnActionEvent) { toolWindowManager.hideToolWindow(id, removeFromStripe = true, source = ToolWindowEventSource.RemoveStripeButtonAction) } override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> { return listOf(ToolwindowFusEventFields.TOOLWINDOW with id) } } private inner class ToggleContentUiTypeAction : ToggleAction(), DumbAware, FusAwareAction { private var hadSeveralContents = false init { ActionUtil.copyFrom(this, "ToggleContentUiTypeMode") } override fun update(e: AnActionEvent) { hadSeveralContents = hadSeveralContents || (contentManager.isInitialized() && contentManager.value.contentCount > 1) super.update(e) e.presentation.isVisible = hadSeveralContents } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun isSelected(e: AnActionEvent): Boolean { return windowInfo.contentUiType === ToolWindowContentUiType.COMBO } override fun setSelected(e: AnActionEvent, state: Boolean) { toolWindowManager.setContentUiType(id, if (state) ToolWindowContentUiType.COMBO else ToolWindowContentUiType.TABBED) } override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> { return listOf(ToolwindowFusEventFields.TOOLWINDOW with id) } } fun requestFocusInToolWindow() { focusTask.resetStartTime() val alarm = focusAlarm alarm.cancelAllRequests() alarm.request(delay = 0) } } private fun addSorted(main: DefaultActionGroup, group: ActionGroup) { val children = group.getChildren(null) var hadSecondary = false for (action in children) { if (group.isPrimary(action)) { main.add(action) } else { hadSecondary = true } } if (hadSecondary) { main.addSeparator() for (action in children) { if (!group.isPrimary(action)) { main.addAction(action).setAsSecondary(true) } } } val separatorText = group.templatePresentation.text if (children.isNotEmpty() && !separatorText.isNullOrEmpty()) { main.addAction(Separator(separatorText), Constraints.FIRST) } } private fun addContentNotInHierarchyComponents(contentUi: ToolWindowContentUi) { contentUi.component.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, object : Iterable<JComponent> { override fun iterator(): Iterator<JComponent> { val contentManager = contentUi.contentManager if (contentManager.contentCount == 0) { return Collections.emptyIterator() } return contentManager.contents .asSequence() .mapNotNull { content: Content -> var last: JComponent? = null var parent: Component? = content.component while (parent != null) { if (parent === contentUi.component || parent !is JComponent) { return@mapNotNull null } last = parent parent = parent.getParent() } last } .iterator() } }) } /** * Notifies window manager about focus traversal in a tool window */ private class ToolWindowFocusWatcher(private val toolWindow: ToolWindowImpl, component: JComponent) : FocusWatcher() { private val id = toolWindow.id init { install(component) Disposer.register(toolWindow.disposable, Disposable { deinstall(component) }) } override fun isFocusedComponentChangeValid(component: Component?, cause: AWTEvent?) = component != null override fun focusedComponentChanged(component: Component?, cause: AWTEvent?) { if (component == null || !toolWindow.isActive) { return } val toolWindowManager = toolWindow.toolWindowManager toolWindowManager.focusManager .doWhenFocusSettlesDown(ExpirableRunnable.forProject(toolWindowManager.project) { ModalityUiUtil.invokeLaterIfNeeded(ModalityState.defaultModalityState(), toolWindowManager.project.disposed) { val entry = toolWindowManager.getEntry(id) ?: return@invokeLaterIfNeeded val windowInfo = entry.readOnlyWindowInfo if (!windowInfo.isVisible) { return@invokeLaterIfNeeded } toolWindowManager.activateToolWindow(entry = entry, info = toolWindowManager.getRegisteredMutableInfoOrLogError(entry.id), autoFocusContents = false) } }) } } private fun setBackgroundRecursively(component: Component, bg: Color) { UIUtil.forEachComponentInHierarchy(component, Consumer { c -> if (c !is ActionButton && c !is Divider) { c.background = bg } }) } private fun addAdjustListener(decorator: InternalDecoratorImpl?, component: JComponent) { UIUtil.findComponentOfType(component, JScrollPane::class.java)?.verticalScrollBar?.addAdjustmentListener { event -> decorator?.let { ClientProperty.put(it, SimpleToolWindowPanel.SCROLLED_STATE, event.adjustable?.value != 0) it.header.repaint() } } }
apache-2.0
1c2a3568d96f7424519fb2b680219702
32.526316
183
0.717201
5.13409
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinBuildScriptManipulator.kt
1
28529
// 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.gradleJava.configuration import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.buildArgumentString import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.replaceLanguageFeature import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.* import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.utils.addToStdlib.cast class KotlinBuildScriptManipulator( override val scriptFile: KtFile, override val preferNewSyntax: Boolean ) : GradleBuildScriptManipulator<KtFile> { override fun isApplicable(file: PsiFile): Boolean = file is KtFile private val gradleVersion = GradleVersionProvider.fetchGradleVersion(scriptFile) override fun isConfiguredWithOldSyntax(kotlinPluginName: String) = runReadAction { scriptFile.containsApplyKotlinPlugin(kotlinPluginName) && scriptFile.containsCompileStdLib() } override fun isConfigured(kotlinPluginExpression: String): Boolean = runReadAction { scriptFile.containsKotlinPluginInPluginsGroup(kotlinPluginExpression) && scriptFile.containsCompileStdLib() } override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean { if (useNewSyntax(kotlinPluginName, gradleVersion)) return false val originalText = scriptFile.text scriptFile.getBuildScriptBlock()?.apply { addDeclarationIfMissing("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true).also { addExpressionAfterIfMissing("$GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$version\"", it) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } getDependenciesBlock()?.addPluginToClassPathIfMissing() } return originalText != scriptFile.text } override fun configureModuleBuildScript( kotlinPluginName: String, kotlinPluginExpression: String, stdlibArtifactName: String, version: IdeKotlinVersion, jvmTarget: String? ): Boolean { val originalText = scriptFile.text val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion) scriptFile.apply { if (useNewSyntax) { createPluginInPluginsGroupIfMissing(kotlinPluginExpression, version) getDependenciesBlock()?.addNoVersionCompileStdlibIfMissing(stdlibArtifactName) getRepositoriesBlock()?.apply { val repository = getRepositoryForVersion(version) if (repository != null) { scriptFile.module?.getBuildScriptSettingsPsiFile()?.let { with(GradleBuildScriptSupport.getManipulator(it)) { addPluginRepository(repository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } } } } else { script?.blockExpression?.addDeclarationIfMissing("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true) getApplyBlock()?.createPluginIfMissing(kotlinPluginName) getDependenciesBlock()?.addCompileStdlibIfMissing(stdlibArtifactName) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } jvmTarget?.let { changeKotlinTaskParameter("jvmTarget", it, forTests = false) changeKotlinTaskParameter("jvmTarget", it, forTests = true) } } return originalText != scriptFile.text } override fun changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? = scriptFile.changeLanguageFeatureConfiguration(feature, state, forTests) override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("languageVersion", version, forTests) override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("apiVersion", version, forTests) override fun addKotlinLibraryToModuleBuildScript( targetModule: Module?, scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor ) { val dependencyText = getCompileDependencySnippet( libraryDescriptor.libraryGroupId, libraryDescriptor.libraryArtifactId, libraryDescriptor.maxVersion, scope.toGradleCompileScope(scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle) ) if (targetModule != null && usesNewMultiplatform()) { val findOrCreateTargetSourceSet = scriptFile .getKotlinBlock() ?.getSourceSetsBlock() ?.findOrCreateTargetSourceSet(targetModule.name.takeLastWhile { it != '.' }) val dependenciesBlock = findOrCreateTargetSourceSet?.getDependenciesBlock() dependenciesBlock?.addExpressionIfMissing(dependencyText) } else { scriptFile.getDependenciesBlock()?.addExpressionIfMissing(dependencyText) } } private fun KtBlockExpression.findOrCreateTargetSourceSet(moduleName: String) = findTargetSourceSet(moduleName) ?: createTargetSourceSet(moduleName) private fun KtBlockExpression.findTargetSourceSet(moduleName: String): KtBlockExpression? = statements.find { it.isTargetSourceSetDeclaration(moduleName) }?.getOrCreateBlock() private fun KtExpression.getOrCreateBlock(): KtBlockExpression? = when (this) { is KtCallExpression -> getBlock() ?: addBlock() is KtReferenceExpression -> replace(KtPsiFactory(project).createExpression("$text {\n}")).cast<KtCallExpression>().getBlock() is KtProperty -> delegateExpressionOrInitializer?.getOrCreateBlock() else -> error("Impossible create block for $this") } private fun KtCallExpression.addBlock(): KtBlockExpression? = parent.addAfter( KtPsiFactory(project).createEmptyBody(), this ) as? KtBlockExpression private fun KtBlockExpression.createTargetSourceSet(moduleName: String) = addExpressionIfMissing("getByName(\"$moduleName\") {\n}") .cast<KtCallExpression>() .getBlock() override fun getKotlinStdlibVersion(): String? = scriptFile.getKotlinStdlibVersion() private fun KtBlockExpression.addCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( getCompileDependencySnippet( KOTLIN_GROUP_ID, stdlibArtifactName, version = "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" ) ) as? KtCallExpression private fun addPluginRepositoryExpression(expression: String) { scriptFile.getPluginManagementBlock()?.findOrCreateBlock("repositories")?.addExpressionIfMissing(expression) } override fun addMavenCentralPluginRepository() { addPluginRepositoryExpression("mavenCentral()") } override fun addPluginRepository(repository: RepositoryDescription) { addPluginRepositoryExpression(repository.toKotlinRepositorySnippet()) } override fun addResolutionStrategy(pluginId: String) { scriptFile .getPluginManagementBlock() ?.findOrCreateBlock("resolutionStrategy") ?.findOrCreateBlock("eachPlugin") ?.addExpressionIfMissing( """ if (requested.id.id == "$pluginId") { useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") } """.trimIndent() ) } private fun KtBlockExpression.addNoVersionCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( "implementation(${getKotlinModuleDependencySnippet( stdlibArtifactName, null )})" ) as? KtCallExpression private fun KtFile.containsCompileStdLib(): Boolean = findScriptInitializer("dependencies")?.getBlock()?.findStdLibDependency() != null private fun KtFile.containsApplyKotlinPlugin(pluginName: String): Boolean = findScriptInitializer("apply")?.getBlock()?.findPlugin(pluginName) != null private fun KtFile.containsKotlinPluginInPluginsGroup(pluginName: String): Boolean = findScriptInitializer("plugins")?.getBlock()?.findPluginInPluginsGroup(pluginName) != null private fun KtBlockExpression.findPlugin(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { it.calleeExpression?.text == "plugin" && it.valueArguments.firstOrNull()?.text == "\"$pluginName\"" } } private fun KtBlockExpression.findClassPathDependencyVersion(pluginName: String): String? { return PsiTreeUtil.getChildrenOfAnyType(this, KtCallExpression::class.java).mapNotNull { if (it?.calleeExpression?.text == "classpath") { val dependencyName = it.valueArguments.firstOrNull()?.text?.removeSurrounding("\"") if (dependencyName?.startsWith(pluginName) == true) dependencyName.substringAfter("$pluginName:") else null } else null }.singleOrNull() } private fun getPluginInfoFromBuildScript( operatorName: String?, pluginVersion: KtExpression?, receiverCalleeExpression: KtCallExpression? ): Pair<String, String>? { val receiverCalleeExpressionText = receiverCalleeExpression?.calleeExpression?.text?.trim() val receivedPluginName = when { receiverCalleeExpressionText == "id" -> receiverCalleeExpression.valueArguments.firstOrNull()?.text?.trim()?.removeSurrounding("\"") operatorName == "version" -> receiverCalleeExpressionText else -> null } val pluginVersionText = pluginVersion?.text?.trim()?.removeSurrounding("\"") ?: return null return receivedPluginName?.to(pluginVersionText) } private fun KtBlockExpression.findPluginVersionInPluginGroup(pluginName: String): String? { val versionsToPluginNames = PsiTreeUtil.getChildrenOfAnyType(this, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java).mapNotNull { when (it) { is KtBinaryExpression -> getPluginInfoFromBuildScript( it.operationReference.text, it.right, it.left as? KtCallExpression ) is KtDotQualifiedExpression -> (it.selectorExpression as? KtCallExpression)?.run { getPluginInfoFromBuildScript( calleeExpression?.text, valueArguments.firstOrNull()?.getArgumentExpression(), it.receiverExpression as? KtCallExpression ) } else -> null } }.toMap() return versionsToPluginNames.getOrDefault(pluginName, null) } private fun KtBlockExpression.findPluginInPluginsGroup(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfAnyType( this, KtCallExpression::class.java, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java ).mapNotNull { when (it) { is KtCallExpression -> it is KtBinaryExpression -> { if (it.operationReference.text == "version") it.left as? KtCallExpression else null } is KtDotQualifiedExpression -> { if ((it.selectorExpression as? KtCallExpression)?.calleeExpression?.text == "version") { it.receiverExpression as? KtCallExpression } else null } else -> null } }.find { "${it.calleeExpression?.text?.trim() ?: ""}(${it.valueArguments.firstOrNull()?.text ?: ""})" == pluginName } } private fun KtFile.findScriptInitializer(startsWith: String): KtScriptInitializer? = PsiTreeUtil.findChildrenOfType(this, KtScriptInitializer::class.java).find { it.text.startsWith(startsWith) } private fun KtBlockExpression.findBlock(name: String): KtBlockExpression? { return getChildrenOfType<KtCallExpression>().find { it.calleeExpression?.text == name && it.valueArguments.singleOrNull()?.getArgumentExpression() is KtLambdaExpression }?.getBlock() } private fun KtScriptInitializer.getBlock(): KtBlockExpression? = PsiTreeUtil.findChildOfType(this, KtCallExpression::class.java)?.getBlock() private fun KtCallExpression.getBlock(): KtBlockExpression? = (valueArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression)?.bodyExpression ?: lambdaArguments.lastOrNull()?.getLambdaExpression()?.bodyExpression private fun KtFile.getKotlinStdlibVersion(): String? { return findScriptInitializer("dependencies")?.getBlock()?.let { when (val expression = it.findStdLibDependency()?.valueArguments?.firstOrNull()?.getArgumentExpression()) { is KtCallExpression -> expression.valueArguments.getOrNull(1)?.text?.trim('\"') is KtStringTemplateExpression -> expression.text?.trim('\"')?.substringAfterLast(":")?.removePrefix("$") else -> null } } } private fun KtBlockExpression.findStdLibDependency(): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { val calleeText = it.calleeExpression?.text calleeText in SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS && (it.valueArguments.firstOrNull()?.getArgumentExpression()?.isKotlinStdLib() ?: false) } } private fun KtExpression.isKotlinStdLib(): Boolean = when (this) { is KtCallExpression -> { val calleeText = calleeExpression?.text (calleeText == "kotlinModule" || calleeText == "kotlin") && valueArguments.firstOrNull()?.getArgumentExpression()?.text?.startsWith("\"stdlib") ?: false } is KtStringTemplateExpression -> text.startsWith("\"$STDLIB_ARTIFACT_PREFIX") else -> false } private fun KtFile.getPluginManagementBlock(): KtBlockExpression? = findOrCreateScriptInitializer("pluginManagement", true) private fun KtFile.getKotlinBlock(): KtBlockExpression? = findOrCreateScriptInitializer("kotlin") private fun KtBlockExpression.getSourceSetsBlock(): KtBlockExpression? = findOrCreateBlock("sourceSets") private fun KtFile.getRepositoriesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("repositories") private fun KtFile.getDependenciesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("dependencies") private fun KtFile.getPluginsBlock(): KtBlockExpression? = findOrCreateScriptInitializer("plugins", true) private fun KtFile.createPluginInPluginsGroupIfMissing(pluginName: String, version: IdeKotlinVersion): KtCallExpression? = getPluginsBlock()?.let { it.findPluginInPluginsGroup(pluginName) ?: it.addExpressionIfMissing("$pluginName version \"${version.artifactVersion}\"") as? KtCallExpression } private fun KtFile.createApplyBlock(): KtBlockExpression? { val apply = psiFactory.createScriptInitializer("apply {\n}") val plugins = findScriptInitializer("plugins") val addedElement = plugins?.addSibling(apply) ?: addToScriptBlock(apply) addedElement?.addNewLinesIfNeeded() return (addedElement as? KtScriptInitializer)?.getBlock() } private fun KtFile.getApplyBlock(): KtBlockExpression? = findScriptInitializer("apply")?.getBlock() ?: createApplyBlock() private fun KtBlockExpression.createPluginIfMissing(pluginName: String): KtCallExpression? = findPlugin(pluginName) ?: addExpressionIfMissing("plugin(\"$pluginName\")") as? KtCallExpression private fun KtFile.changeCoroutineConfiguration(coroutineOption: String): PsiElement? { val snippet = "experimental.coroutines = Coroutines.${coroutineOption.toUpperCase()}" val kotlinBlock = getKotlinBlock() ?: return null addImportIfMissing("org.jetbrains.kotlin.gradle.dsl.Coroutines") val statement = kotlinBlock.statements.find { it.text.startsWith("experimental.coroutines") } return if (statement != null) { statement.replace(psiFactory.createExpression(snippet)) } else { kotlinBlock.add(psiFactory.createExpression(snippet)).apply { addNewLinesIfNeeded() } } } private fun KtFile.changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? { if (usesNewMultiplatform()) { state.assertApplicableInMultiplatform() return getKotlinBlock() ?.findOrCreateBlock("sourceSets") ?.findOrCreateBlock("all") ?.addExpressionIfMissing("languageSettings.enableLanguageFeature(\"${feature.name}\")") } val pluginsBlock = findScriptInitializer("plugins")?.getBlock() val rawKotlinVersion = pluginsBlock?.findPluginVersionInPluginGroup("kotlin") ?: pluginsBlock?.findPluginVersionInPluginGroup("org.jetbrains.kotlin.jvm") ?: findScriptInitializer("buildscript")?.getBlock()?.findBlock("dependencies")?.findClassPathDependencyVersion("org.jetbrains.kotlin:kotlin-gradle-plugin") val kotlinVersion = rawKotlinVersion?.let(IdeKotlinVersion::opt) val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val parameterName = "freeCompilerArgs" return addOrReplaceKotlinTaskParameter( parameterName, "listOf(\"$featureArgumentString\")", forTests ) { val newText = text.replaceLanguageFeature( feature, state, kotlinVersion, prefix = "$parameterName = listOf(", postfix = ")" ) replace(psiFactory.createExpression(newText)) } } private fun KtFile.addOrReplaceKotlinTaskParameter( parameterName: String, defaultValue: String, forTests: Boolean, replaceIt: KtExpression.() -> PsiElement ): PsiElement? { val taskName = if (forTests) "compileTestKotlin" else "compileKotlin" val optionsBlock = findScriptInitializer("$taskName.kotlinOptions")?.getBlock() return if (optionsBlock != null) { val assignment = optionsBlock.statements.find { (it as? KtBinaryExpression)?.left?.text == parameterName } assignment?.replaceIt() ?: optionsBlock.addExpressionIfMissing("$parameterName = $defaultValue") } else { addImportIfMissing("org.jetbrains.kotlin.gradle.tasks.KotlinCompile") script?.blockExpression?.addDeclarationIfMissing("val $taskName: KotlinCompile by tasks") addTopLevelBlock("$taskName.kotlinOptions")?.addExpressionIfMissing("$parameterName = $defaultValue") } } private fun KtFile.changeKotlinTaskParameter(parameterName: String, parameterValue: String, forTests: Boolean): PsiElement? { return addOrReplaceKotlinTaskParameter(parameterName, "\"$parameterValue\"", forTests) { replace(psiFactory.createExpression("$parameterName = \"$parameterValue\"")) } } private fun KtBlockExpression.getRepositorySnippet(version: IdeKotlinVersion): String? { val repository = getRepositoryForVersion(version) return when { repository != null -> repository.toKotlinRepositorySnippet() !isRepositoryConfigured(text) -> MAVEN_CENTRAL else -> null } } private fun KtFile.getBuildScriptBlock(): KtBlockExpression? = findOrCreateScriptInitializer("buildscript", true) private fun KtFile.findOrCreateScriptInitializer(name: String, first: Boolean = false): KtBlockExpression? = findScriptInitializer(name)?.getBlock() ?: addTopLevelBlock(name, first) private fun KtBlockExpression.getRepositoriesBlock(): KtBlockExpression? = findOrCreateBlock("repositories") private fun KtBlockExpression.getDependenciesBlock(): KtBlockExpression? = findOrCreateBlock("dependencies") private fun KtBlockExpression.addRepositoryIfMissing(version: IdeKotlinVersion): KtCallExpression? { val snippet = getRepositorySnippet(version) ?: return null return addExpressionIfMissing(snippet) as? KtCallExpression } private fun KtBlockExpression.addMavenCentralIfMissing(): KtCallExpression? = if (!isRepositoryConfigured(text)) addExpressionIfMissing(MAVEN_CENTRAL) as? KtCallExpression else null private fun KtBlockExpression.findOrCreateBlock(name: String, first: Boolean = false) = findBlock(name) ?: addBlock(name, first) private fun KtBlockExpression.addPluginToClassPathIfMissing(): KtCallExpression? = addExpressionIfMissing(getKotlinGradlePluginClassPathSnippet()) as? KtCallExpression private fun KtBlockExpression.addBlock(name: String, first: Boolean = false): KtBlockExpression? { return psiFactory.createExpression("$name {\n}") .let { if (first) addAfter(it, null) else add(it) } ?.apply { addNewLinesIfNeeded() } ?.cast<KtCallExpression>() ?.getBlock() } private fun KtFile.addTopLevelBlock(name: String, first: Boolean = false): KtBlockExpression? { val scriptInitializer = psiFactory.createScriptInitializer("$name {\n}") val addedElement = addToScriptBlock(scriptInitializer, first) as? KtScriptInitializer addedElement?.addNewLinesIfNeeded() return addedElement?.getBlock() } private fun PsiElement.addSibling(element: PsiElement): PsiElement = parent.addAfter(element, this) private fun PsiElement.addNewLineBefore(lineBreaks: Int = 1) { parent.addBefore(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLineAfter(lineBreaks: Int = 1) { parent.addAfter(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLinesIfNeeded(lineBreaks: Int = 1) { if (prevSibling != null && prevSibling.text.isNotBlank()) { addNewLineBefore(lineBreaks) } if (nextSibling != null && nextSibling.text.isNotBlank()) { addNewLineAfter(lineBreaks) } } private fun KtFile.addToScriptBlock(element: PsiElement, first: Boolean = false): PsiElement? = if (first) script?.blockExpression?.addAfter(element, null) else script?.blockExpression?.add(element) private fun KtFile.addImportIfMissing(path: String): KtImportDirective = importDirectives.find { it.importPath?.pathStr == path } ?: importList?.add( psiFactory.createImportDirective( ImportPath.fromString( path ) ) ) as KtImportDirective private fun KtBlockExpression.addExpressionAfterIfMissing(text: String, after: PsiElement): KtExpression = addStatementIfMissing(text) { addAfter(psiFactory.createExpression(it), after) } private fun KtBlockExpression.addExpressionIfMissing(text: String, first: Boolean = false): KtExpression = addStatementIfMissing(text) { psiFactory.createExpression(it).let { created -> if (first) addAfter(created, null) else add(created) } } private fun KtBlockExpression.addDeclarationIfMissing(text: String, first: Boolean = false): KtDeclaration = addStatementIfMissing(text) { psiFactory.createDeclaration<KtDeclaration>(it).let { created -> if (first) addAfter(created, null) else add(created) } } private inline fun <reified T : PsiElement> KtBlockExpression.addStatementIfMissing( text: String, crossinline factory: (String) -> PsiElement ): T { statements.find { StringUtil.equalsIgnoreWhitespaces(it.text, text) }?.let { return it as T } return factory(text).apply { addNewLinesIfNeeded() } as T } private fun KtPsiFactory.createScriptInitializer(text: String): KtScriptInitializer = createFile("dummy.kts", text).script?.blockExpression?.firstChild as KtScriptInitializer private val PsiElement.psiFactory: KtPsiFactory get() = KtPsiFactory(project) private fun getCompileDependencySnippet( groupId: String, artifactId: String, version: String?, compileScope: String = "implementation" ): String { if (groupId != KOTLIN_GROUP_ID) { return "$compileScope(\"$groupId:$artifactId:$version\")" } val kotlinPluginName = if (scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle) { "kotlin-android" } else { KotlinGradleModuleConfigurator.KOTLIN } if (useNewSyntax(kotlinPluginName, gradleVersion)) { return "$compileScope(${getKotlinModuleDependencySnippet(artifactId)})" } val libraryVersion = if (version == GSK_KOTLIN_VERSION_PROPERTY_NAME) "\$$version" else version return "$compileScope(${getKotlinModuleDependencySnippet(artifactId, libraryVersion)})" } companion object { private const val STDLIB_ARTIFACT_PREFIX = "org.jetbrains.kotlin:kotlin-stdlib" const val GSK_KOTLIN_VERSION_PROPERTY_NAME = "kotlin_version" fun getKotlinGradlePluginClassPathSnippet(): String = "classpath(${getKotlinModuleDependencySnippet("gradle-plugin", "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})" fun getKotlinModuleDependencySnippet(artifactId: String, version: String? = null): String { val moduleName = artifactId.removePrefix("kotlin-") return when (version) { null -> "kotlin(\"$moduleName\")" "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" -> "kotlinModule(\"$moduleName\", $GSK_KOTLIN_VERSION_PROPERTY_NAME)" else -> "kotlinModule(\"$moduleName\", ${"\"$version\""})" } } } } private fun KtExpression.isTargetSourceSetDeclaration(moduleName: String): Boolean = with(text) { when (this@isTargetSourceSetDeclaration) { is KtProperty -> startsWith("val $moduleName by") || initializer?.isTargetSourceSetDeclaration(moduleName) == true is KtCallExpression -> startsWith("getByName(\"$moduleName\")") else -> false } }
apache-2.0
bb17da92a0429595312a4eece59256c0
45.768852
167
0.670791
5.842515
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt
1
5352
// 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.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightField import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.codeUsageScope import org.jetbrains.kotlin.idea.base.util.restrictByFileType import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject class AddJvmStaticIntention : SelfTargetingRangeIntention<KtNamedDeclaration>( KtNamedDeclaration::class.java, KotlinBundle.lazyMessage("add.jvmstatic.annotation") ), LowPriorityAction { private val JvmStaticFqName = FqName("kotlin.jvm.JvmStatic") private val JvmFieldFqName = FqName("kotlin.jvm.JvmField") override fun startInWriteAction() = false override fun applicabilityRange(element: KtNamedDeclaration): TextRange? { if (element !is KtNamedFunction && element !is KtProperty) return null if (element.hasModifier(KtTokens.ABSTRACT_KEYWORD)) return null if (element.hasModifier(KtTokens.OPEN_KEYWORD)) return null if (element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return null if (containingObject.isObjectLiteral()) return null if (element is KtProperty) { if (element.hasModifier(KtTokens.CONST_KEYWORD)) return null if (element.findAnnotation(JvmFieldFqName) != null) return null } if (element.findAnnotation(JvmStaticFqName) != null) return null return element.nameIdentifier?.textRange } override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { val target = getTarget(editor, file) ?: return IntentionPreviewInfo.EMPTY target.addAnnotation(JvmStaticFqName) return IntentionPreviewInfo.DIFF } override fun applyTo(element: KtNamedDeclaration, editor: Editor?) { val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return val isCompanionMember = containingObject.isCompanion() val instanceFieldName = if (isCompanionMember) containingObject.name else JvmAbi.INSTANCE_FIELD val instanceFieldContainingClass = if (isCompanionMember) (containingObject.containingClassOrObject ?: return) else containingObject val project = element.project val expressionsToReplaceWithQualifier = project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.in.java.files"), true) { runReadAction { val searchScope = element.codeUsageScope().restrictByFileType(JavaFileType.INSTANCE) ReferencesSearch .search(element, searchScope) .mapNotNull { val refExpr = it.element as? PsiReferenceExpression ?: return@mapNotNull null if ((refExpr.resolve() as? KtLightElement<*, *>)?.kotlinOrigin != element) return@mapNotNull null val qualifierExpr = refExpr.qualifierExpression as? PsiReferenceExpression ?: return@mapNotNull null if (qualifierExpr.qualifierExpression == null) return@mapNotNull null val instanceField = qualifierExpr.resolve() as? KtLightField ?: return@mapNotNull null if (instanceField.name != instanceFieldName) return@mapNotNull null if ((instanceField.containingClass as? KtLightClass)?.kotlinOrigin != instanceFieldContainingClass) return@mapNotNull null qualifierExpr } } } ?: return runWriteAction { element.addAnnotation(JvmStaticFqName) expressionsToReplaceWithQualifier.forEach { it.replace(it.qualifierExpression!!) } } } }
apache-2.0
62cff2b41694f3fb0ba7fd0d3e3f156e
53.612245
158
0.735987
5.357357
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialogUI.kt
1
7490
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.progress.util import com.intellij.CommonBundle import com.intellij.openapi.Disposable import com.intellij.openapi.progress.TaskCancellation import com.intellij.openapi.progress.impl.CancellableTaskCancellation import com.intellij.openapi.progress.impl.NonCancellableTaskCancellation import com.intellij.openapi.progress.impl.ProgressState import com.intellij.openapi.ui.DialogWrapperDialog import com.intellij.openapi.util.NlsContexts.ProgressTitle import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.ExperimentalUI import com.intellij.ui.TitlePanel import com.intellij.ui.WindowMoveListener import com.intellij.ui.components.JBLabel import com.intellij.ui.scale.JBUIScale import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridConstraints.* import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.util.ui.* import org.jetbrains.annotations.Contract import java.awt.Component import java.awt.Dimension import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.io.File import javax.swing.* internal class ProgressDialogUI : Disposable { val panel: JPanel = JPanel() private val myTitlePanel = TitlePanel() private val textLabel = JLabel(" ") private val detailsLabel = JBLabel("") val progressBar: JProgressBar = JProgressBar() val cancelButton: JButton = JButton() val backgroundButton: JButton = JButton() init { myTitlePanel.setActive(true) detailsLabel.componentStyle = UIUtil.ComponentStyle.REGULAR if (SystemInfoRt.isMac) { UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, detailsLabel) } detailsLabel.foreground = UIUtil.getContextHelpForeground() progressBar.putClientProperty("html.disable", java.lang.Boolean.FALSE) progressBar.maximum = 100 cancelButton.text = CommonBundle.getCancelButtonText() DialogUtil.registerMnemonic(cancelButton, '&') backgroundButton.text = CommonBundle.message("button.background") DialogUtil.registerMnemonic(backgroundButton, '&') val progressPanel = JPanel() progressPanel.layout = GridLayoutManager(3, 2, JBInsets.emptyInsets(), -1, -1, false, false) progressPanel.preferredSize = Dimension(if (SystemInfoRt.isMac) 350 else JBUIScale.scale(450), -1) progressPanel.add(textLabel, gridConstraints(row = 0, minimumSize = Dimension(0, -1))) progressPanel.add(JLabel(" "), gridConstraints( row = 0, column = 1, anchor = ANCHOR_WEST, fill = FILL_NONE, HSizePolicy = SIZEPOLICY_FIXED, )) progressPanel.add(progressBar, gridConstraints(row = 1, colSpan = 2)) progressPanel.add(detailsLabel, gridConstraints( row = 2, anchor = ANCHOR_NORTHWEST, minimumSize = Dimension(0, -1), )) progressPanel.add(JLabel(" "), gridConstraints( row = 2, column = 1, anchor = ANCHOR_WEST, fill = FILL_NONE, HSizePolicy = SIZEPOLICY_FIXED, )) val buttonPanel = JPanel() buttonPanel.layout = GridLayoutManager(2, 1, JBInsets.emptyInsets(), -1, -1, false, false) buttonPanel.add(cancelButton, gridConstraints(row = 0, HSizePolicy = SIZE_POLICY_DEFAULT)) buttonPanel.add(backgroundButton, gridConstraints(row = 1, HSizePolicy = SIZE_POLICY_DEFAULT)) val progressAndButtonPanel = JPanel() progressAndButtonPanel.layout = GridLayoutManager(1, 2, JBInsets(6, 10, 10, 10), -1, -1, false, false) progressAndButtonPanel.isOpaque = false progressAndButtonPanel.add(progressPanel, gridConstraints(row = 0, VSizePolicy = SIZEPOLICY_CAN_GROW)) progressAndButtonPanel.add(buttonPanel, gridConstraints( row = 0, column = 1, HSizePolicy = SIZEPOLICY_CAN_SHRINK, VSizePolicy = SIZEPOLICY_CAN_GROW )) panel.layout = GridLayoutManager(2, 1, JBInsets.emptyInsets(), -1, -1, false, false) panel.add(myTitlePanel, gridConstraints(row = 0)) panel.add(progressAndButtonPanel, gridConstraints( row = 1, fill = FILL_BOTH, HSizePolicy = SIZE_POLICY_DEFAULT, VSizePolicy = SIZE_POLICY_DEFAULT )) if (ExperimentalUI.isNewUI()) { panel.background = JBUI.CurrentTheme.Popup.BACKGROUND progressPanel.isOpaque = false progressBar.isOpaque = false buttonPanel.isOpaque = false cancelButton.isOpaque = false backgroundButton.isOpaque = false } val moveListener = object : WindowMoveListener(myTitlePanel) { override fun getView(component: Component): Component { return SwingUtilities.getAncestorOfClass(DialogWrapperDialog::class.java, component) } } myTitlePanel.addMouseListener(moveListener) myTitlePanel.addMouseMotionListener(moveListener) } override fun dispose() { UIUtil.disposeProgress(progressBar) UIUtil.dispose(myTitlePanel) UIUtil.dispose(backgroundButton) UIUtil.dispose(cancelButton) } fun initCancellation(cancellation: TaskCancellation, cancelAction: () -> Unit) { when (cancellation) { is NonCancellableTaskCancellation -> { cancelButton.isVisible = false } is CancellableTaskCancellation -> { cancellation.buttonText?.let { cancelButton.text = it } cancellation.tooltipText?.let { cancelButton.toolTipText = it } val buttonListener = ActionListener { cancelAction() } cancelButton.addActionListener(buttonListener) cancelButton.registerKeyboardAction( buttonListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ) } } } fun updateTitle(title: @ProgressTitle String?) { EDT.assertIsEdt() myTitlePanel.setText(title?.takeIf(String::isNotEmpty) ?: " ") } fun updateProgress(state: ProgressState) { EDT.assertIsEdt() textLabel.text = fitTextToLabel(state.text, textLabel) detailsLabel.text = fitTextToLabel(state.details, detailsLabel) if (progressBar.isShowing) { val fraction = state.fraction if (fraction < 0.0) { progressBar.isIndeterminate = true } else { progressBar.isIndeterminate = false progressBar.value = (fraction * 100).toInt() } } } } @Contract(pure = true) private fun fitTextToLabel(fullText: String?, label: JLabel): String { if (fullText.isNullOrEmpty()) return " " if (fullText.startsWith("<html>") && fullText.endsWith("</html>")) { return fullText // Don't truncate if the text is HTML } var newFullText = StringUtil.last(fullText, 500, true).toString() // avoid super long strings while (label.getFontMetrics(label.font).stringWidth(newFullText) > label.width) { val sep = newFullText.indexOf(File.separatorChar, 4) if (sep < 0) return newFullText newFullText = "..." + newFullText.substring(sep) } return newFullText } private const val SIZE_POLICY_DEFAULT = SIZEPOLICY_CAN_GROW or SIZEPOLICY_CAN_SHRINK private fun gridConstraints( row: Int, column: Int = 0, colSpan: Int = 1, anchor: Int = ANCHOR_CENTER, fill: Int = FILL_HORIZONTAL, HSizePolicy: Int = SIZE_POLICY_DEFAULT or SIZEPOLICY_WANT_GROW, VSizePolicy: Int = SIZEPOLICY_FIXED, minimumSize: Dimension? = null, ): GridConstraints { return GridConstraints(row, column, 1, colSpan, anchor, fill, HSizePolicy, VSizePolicy, minimumSize, null, null) }
apache-2.0
4f1e8dcd7acd6b24793e79e0fb6cf58c
39.053476
120
0.729239
4.231638
false
false
false
false
youdonghai/intellij-community
platform/vcs-log/impl/test/com/intellij/vcs/log/data/VisiblePackBuilderTest.kt
1
9094
/* * 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 com.intellij.vcs.log.data import com.intellij.mock.MockVirtualFile import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.Condition import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.Function import com.intellij.vcs.log.* import com.intellij.vcs.log.graph.GraphCommit import com.intellij.vcs.log.graph.GraphCommitImpl import com.intellij.vcs.log.graph.PermanentGraph import com.intellij.vcs.log.graph.VisibleGraph import com.intellij.vcs.log.impl.* import com.intellij.vcs.log.impl.TestVcsLogProvider.BRANCH_TYPE import com.intellij.vcs.log.impl.TestVcsLogProvider.DEFAULT_USER import com.intellij.vcs.log.impl.VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder import org.junit.Test import java.util.* import kotlin.test.assertEquals import kotlin.test.assertTrue class VisiblePackBuilderTest { @Test fun `no filters`() { val graph = graph { 1(2) *"master" 2(3) 3(4) 4() } val visiblePack = graph.build(noFilters()) assertEquals(4, visiblePack.visibleGraph.visibleCommitCount) } @Test fun `branch filter`() { val graph = graph { 1(3) *"master" 2(3) *"feature" 3(4) 4() } val visiblePack = graph.build(filters(branch = listOf("master"))) val visibleGraph = visiblePack.visibleGraph assertEquals(3, visibleGraph.visibleCommitCount) assertDoesNotContain(visibleGraph, 2) } @Test fun `filter by user in memory`() { val graph = graph { 1(2) *"master" 2(3) 3(4) +"bob.doe" 4(5) 5(6) 6(7) 7() } val visiblePack = graph.build(filters(user = DEFAULT_USER)) val visibleGraph = visiblePack.visibleGraph assertEquals(6, visibleGraph.visibleCommitCount) assertDoesNotContain(visibleGraph, 3) } @Test fun `filter by branch deny`() { val graph = graph { 1(3) *"master" 2(3) *"feature" 3(4) 4() } val visiblePack = graph.build(filters(VcsLogBranchFilterImpl.fromTextPresentation(setOf("-master"), setOf("master")))) val visibleGraph = visiblePack.visibleGraph assertEquals(3, visibleGraph.visibleCommitCount) assertDoesNotContain(visibleGraph, 1) } @Test fun `filter by branch deny works with extra results from vcs provider`() { val graph = graph { 1(3) *"master" +null 2(3) *"feature" +null 3(4) +null 4() +null } val func = Function<VcsLogFilterCollection, MutableList<TimedVcsCommit>> { ArrayList(listOf(2, 3, 4).map { val id = it val commit = graph.commits.firstOrNull { it.id == id } commit!!.toVcsCommit(graph.hashMap) }) } graph.providers.entries.iterator().next().value.setFilteredCommitsProvider(func) val visiblePack = graph.build(filters(VcsLogBranchFilterImpl.fromTextPresentation(setOf("-master"), setOf("master")), userFilter(DEFAULT_USER))) val visibleGraph = visiblePack.visibleGraph assertEquals(3, visibleGraph.visibleCommitCount) assertDoesNotContain(visibleGraph, 1) } private fun GraphCommit<Int>.toVcsCommit(map: VcsLogStorage) = TimedVcsCommitImpl(map.getCommitId(this.id)!!.hash, map.getHashes(this.parents), 1) fun assertDoesNotContain(graph: VisibleGraph<Int>, id: Int) { assertTrue(null == (1..graph.visibleCommitCount).firstOrNull { graph.getRowInfo(it - 1).commit == id }) } data class Ref(val name: String, val commit: Int) data class Data(val user: VcsUser? = DEFAULT_USER, val subject: String = "default commit message") inner class Graph(val commits: List<GraphCommit<Int>>, val refs: Set<VisiblePackBuilderTest.Ref>, val data: HashMap<GraphCommit<Int>, Data>) { val root: VirtualFile = MockVirtualFile("root") val providers: Map<VirtualFile, TestVcsLogProvider> = mapOf(root to TestVcsLogProvider(root)) val hashMap = generateHashMap(commits.maxBy { it.id }!!.id, refs, root) fun build(filters: VcsLogFilterCollection): VisiblePack { val dataPack = DataPack.build(commits, mapOf(root to hashMap.refsReversed.keys).mapValues { CompressedRefs(it.value, hashMap) }, providers, hashMap, true) val detailsCache = TopCommitsCache(hashMap) detailsCache.storeDetails(ArrayList(data.entries.mapNotNull { val hash = hashMap.getCommitId(it.key.id).hash if (it.value.user == null) null else VcsCommitMetadataImpl(hash, hashMap.getHashes(it.key.parents), 1L, root, it.value.subject, it.value.user!!, it.value.subject, it.value.user!!, 1L) })) val commitDetailsGetter = object : DataGetter<VcsFullCommitDetails> { override fun getCommitData(row: Int, neighbourHashes: MutableIterable<Int>): VcsFullCommitDetails { throw UnsupportedOperationException() } override fun loadCommitsData(hashes: MutableList<Int>, consumer: Consumer<MutableList<VcsFullCommitDetails>>, indicator: ProgressIndicator?) { } override fun getCommitDataIfAvailable(hash: Int): VcsFullCommitDetails? { return null } } val builder = VisiblePackBuilder(providers, hashMap, detailsCache, commitDetailsGetter, EmptyIndex()) return builder.build(dataPack, PermanentGraph.SortType.Normal, filters, CommitCountStage.INITIAL).first } fun generateHashMap(num: Int, refs: Set<VisiblePackBuilderTest.Ref>, root: VirtualFile): ConstantVcsLogStorage { val hashes = HashMap<Int, Hash>() for (i in 1..num) { hashes.put(i, HashImpl.build(i.toString())) } val vcsRefs = refs.mapTo(ArrayList<VcsRef>(), { VcsRefImpl(hashes[it.commit]!!, it.name, BRANCH_TYPE, root) }) return ConstantVcsLogStorage(hashes, vcsRefs.indices.map { Pair(it, vcsRefs[it]) }.toMap(), root) } } fun VcsLogStorage.getHashes(ids: List<Int>) = ids.map { getCommitId(it)!!.hash } fun noFilters(): VcsLogFilterCollection = VcsLogFilterCollectionBuilder().build() fun filters(branch: VcsLogBranchFilter? = null, user: VcsLogUserFilter? = null) = VcsLogFilterCollectionBuilder().with(branch).with(user).build() fun filters(branch: List<String>? = null, user: VcsUser? = null) = VcsLogFilterCollectionBuilder().with(branchFilter(branch)).with(userFilter(user)).build() fun branchFilter(branch: List<String>?): VcsLogBranchFilterImpl? { return if (branch != null) VcsLogBranchFilterImpl.fromTextPresentation(branch, branch.toHashSet()) else null } fun userFilter(user: VcsUser?): VcsLogUserFilter? { return if (user != null) VcsLogUserFilterImpl(listOf(user.name), emptyMap(), emptySet()) else null } fun graph(f: GraphBuilder.() -> Unit): Graph { val builder = GraphBuilder() builder.f() return builder.done() } inner class GraphBuilder { val commits = ArrayList<GraphCommit<Int>>() val refs = HashSet<Ref>() val data = HashMap<GraphCommit<Int>, Data>() operator fun Int.invoke(vararg id: Int): GraphCommit<Int> { val commit = GraphCommitImpl(this, id.toList(), this.toLong()) commits.add(commit) data[commit] = Data() return commit } operator fun GraphCommit<Int>.times(name: String): GraphCommit<Int> { refs.add(Ref(name, this.id)) return this } operator fun GraphCommit<Int>.plus(name: String): GraphCommit<Int> { data[this] = Data(VcsUserImpl(name, name + "@example.com")) return this; } operator fun GraphCommit<Int>.plus(user: VcsUser?): GraphCommit<Int> { data[this] = Data(user) return this; } fun done() = Graph(commits, refs, data) } class ConstantVcsLogStorage(val hashes: Map<Int, Hash>, val refs: Map<Int, VcsRef>, val root: VirtualFile) : VcsLogStorage { val hashesReversed = hashes.entries.map { Pair(it.value, it.key) }.toMap() val refsReversed = refs.entries.map { Pair(it.value, it.key) }.toMap() override fun getCommitIndex(hash: Hash, root: VirtualFile) = hashesReversed[hash]!! override fun getCommitId(commitIndex: Int) = CommitId(hashes[commitIndex]!!, root) override fun getVcsRef(refIndex: Int): VcsRef = refs[refIndex]!! override fun getRefIndex(ref: VcsRef): Int = refsReversed[ref]!! override fun findCommitId(condition: Condition<CommitId>): CommitId? = throw UnsupportedOperationException() override fun flush() { } } }
apache-2.0
ea3498822f4229d307a1a7b55296a83e
35.669355
160
0.690455
4.177308
false
true
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/components/ConfirmDialog.kt
1
1523
package com.nononsenseapps.feeder.ui.compose.components import android.R import androidx.annotation.StringRes import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun ConfirmDialog( onDismiss: () -> Unit, onOk: () -> Unit, @StringRes title: Int, @StringRes body: Int, ) { AlertDialog( onDismissRequest = onDismiss, confirmButton = { Button(onClick = onOk) { Text(text = stringResource(id = R.string.ok)) } }, dismissButton = { Button(onClick = onDismiss) { Text(text = stringResource(id = R.string.cancel)) } }, title = { Text( text = stringResource(id = title), style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, modifier = Modifier .padding(vertical = 8.dp) ) }, text = { Text( text = stringResource(id = body), style = MaterialTheme.typography.bodyLarge ) }, ) }
gpl-3.0
ae9ba4a0ac12bfc2dac33a8af3c7a592
28.862745
65
0.606041
4.744548
false
false
false
false
domdomegg/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/explore/recentsearches/RecentSearchesDaoTest.kt
3
9784
package fr.free.nrw.commons.explore.recentsearches import android.content.ContentProviderClient import android.content.ContentValues import android.database.Cursor import android.database.MatrixCursor import android.database.sqlite.SQLiteDatabase import android.os.RemoteException import com.nhaarman.mockitokotlin2.* import fr.free.nrw.commons.BuildConfig import fr.free.nrw.commons.TestCommonsApplication import fr.free.nrw.commons.explore.recentsearches.RecentSearchesContentProvider.BASE_URI import fr.free.nrw.commons.explore.recentsearches.RecentSearchesContentProvider.uriForId import fr.free.nrw.commons.explore.recentsearches.RecentSearchesDao.Table.* import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.util.* @RunWith(RobolectricTestRunner::class) @Config(sdk = [21], application = TestCommonsApplication::class) class RecentSearchesDaoTest { private val columns = arrayOf(COLUMN_ID, COLUMN_NAME, COLUMN_LAST_USED) private val client: ContentProviderClient = mock() private val database: SQLiteDatabase = mock() private val captor = argumentCaptor<ContentValues>() private val queryCaptor = argumentCaptor<Array<String>>() private lateinit var testObject: RecentSearchesDao @Before fun setUp() { testObject = RecentSearchesDao { client } } /** * Unit Test for creating a table for recent Searches */ @Test fun createTable() { onCreate(database) verify(database).execSQL(CREATE_TABLE_STATEMENT) } /** * Unit Test for deleting table for recent Searches */ @Test fun deleteTable() { onDelete(database) inOrder(database) { verify(database).execSQL(DROP_TABLE_STATEMENT) verify(database).execSQL(CREATE_TABLE_STATEMENT) } } /** * Unit Test for migrating from database version 1 to 2 for recent Searches Table */ @Test fun migrateTableVersionFrom_v1_to_v2() { onUpdate(database, 1, 2) // Table didnt exist before v7 verifyZeroInteractions(database) } /** * Unit Test for migrating from database version 2 to 3 for recent Searches Table */ @Test fun migrateTableVersionFrom_v2_to_v3() { onUpdate(database, 2, 3) // Table didnt exist before v7 verifyZeroInteractions(database) } /** * Unit Test for migrating from database version 3 to 4 for recent Searches Table */ @Test fun migrateTableVersionFrom_v3_to_v4() { onUpdate(database, 3, 4) // Table didnt exist before v7 verifyZeroInteractions(database) } /** * Unit Test for migrating from database version 4 to 5 for recent Searches Table */ @Test fun migrateTableVersionFrom_v4_to_v5() { onUpdate(database, 4, 5) // Table didnt exist before v7 verifyZeroInteractions(database) } /** * Unit Test for migrating from database version 5 to 6 for recent Searches Table */ @Test fun migrateTableVersionFrom_v5_to_v6() { onUpdate(database, 5, 6) // Table didnt exist before v7 verifyZeroInteractions(database) } /** * Unit Test for migrating from database version 6 to 7 for recent Searches Table */ @Test fun migrateTableVersionFrom_v6_to_v7() { onUpdate(database, 6, 7) verify(database).execSQL(CREATE_TABLE_STATEMENT) } /** * Unit Test for migrating from database version 7 to 8 for recent Searches Table */ @Test fun migrateTableVersionFrom_v7_to_v8() { onUpdate(database, 7, 8) // Table didnt change in version 8 verifyZeroInteractions(database) } /** * Unit Test for migrating from creating a row without using ID in recent Searches Table */ @Test fun createFromCursor() { createCursor(1).let { cursor -> cursor.moveToFirst() testObject.fromCursor(cursor).let { assertEquals(uriForId(1), it.contentUri) assertEquals("butterfly", it.query) assertEquals(123, it.lastSearched.time) } } } /** * Unit Test for migrating from updating a row using contentUri in recent Searches Table */ @Test fun saveExistingQuery() { createCursor(1).let { val recentSearch = testObject.fromCursor(it.apply { moveToFirst() }) testObject.save(recentSearch) verify(client).update(eq(recentSearch.contentUri!!), captor.capture(), isNull(), isNull()) captor.firstValue.let { cv -> assertEquals(2, cv.size()) assertEquals(recentSearch.query, cv.getAsString(COLUMN_NAME)) assertEquals(recentSearch.lastSearched.time, cv.getAsLong(COLUMN_LAST_USED)) } } } /** * Unit Test for migrating from creating a row using ID in recent Searches Table */ @Test fun saveNewQuery() { val contentUri = RecentSearchesContentProvider.uriForId(111) whenever(client.insert(isA(), isA())).thenReturn(contentUri) val recentSearch = RecentSearch(null, "butterfly", Date(234L)) testObject.save(recentSearch) verify(client).insert(eq(BASE_URI), captor.capture()) captor.firstValue.let { cv -> assertEquals(2, cv.size()) assertEquals(recentSearch.query, cv.getAsString(COLUMN_NAME)) assertEquals(recentSearch.lastSearched.time, cv.getAsLong(COLUMN_LAST_USED)) assertEquals(contentUri, recentSearch.contentUri) } } /** * Unit Test for checking translation exceptions in searching a row from DB using recent search query */ @Test(expected = RuntimeException::class) fun findRecentSearchTranslatesExceptions() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenThrow(RemoteException("")) testObject.find("butterfly") } /** * Unit Test for checking data if it's not present in searching a row from DB using recent search query */ @Test fun whenTheresNoDataFindReturnsNull_nullCursor() { whenever(client.query(any(), any(), any(), any(), any())).thenReturn(null) assertNull(testObject.find("butterfly")) } /** * Unit Test for checking data if it's not present in searching a row from DB using recent search query */ @Test fun whenTheresNoDataFindReturnsNull_emptyCursor() { whenever(client.query(any(), any(), any(), any(), any())).thenReturn(createCursor(0)) assertNull(testObject.find("butterfly")) } /** * Unit Test for checking if cursor's are closed after use or not */ @Test fun cursorsAreClosedAfterUse() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.find("butterfly") verify(mockCursor).close() } /** * Unit Test for checking search results after searching a row from DB using recent search query */ @Test fun findRecentSearchQuery() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(createCursor(1)) val recentSearch = testObject.find("butterfly") assertNotNull(recentSearch) assertEquals(uriForId(1), recentSearch?.contentUri) assertEquals("butterfly", recentSearch?.query) assertEquals(123L, recentSearch?.lastSearched?.time) verify(client).query( eq(BASE_URI), eq(ALL_FIELDS), eq("$COLUMN_NAME=?"), queryCaptor.capture(), isNull() ) assertEquals("butterfly", queryCaptor.firstValue[0]) } /** * Unit Test for checking if cursor's are closed after recent search query or not */ @Test fun cursorsAreClosedAfterRecentSearchQuery() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.recentSearches(1) verify(mockCursor).close() } /** * Unit Test for checking when recent searches returns less than the limit */ @Test fun recentSearchesReturnsLessThanLimit() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(createCursor(1)) val result = testObject.recentSearches(10) assertEquals(1, result.size) assertEquals("butterfly", result[0]) verify(client).query( eq(BASE_URI), eq(ALL_FIELDS), isNull(), queryCaptor.capture(), eq("$COLUMN_LAST_USED DESC") ) assertEquals(0, queryCaptor.firstValue.size) } /** * Unit Test for checking size or list recieved from recent searches */ @Test fun recentSearchesHonorsLimit() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(createCursor(10)) val result = testObject.recentSearches(5) assertEquals(5, result.size) } /** * Unit Test for creating entries in recent searches database. * @param rowCount No of rows */ private fun createCursor(rowCount: Int) = MatrixCursor(columns, rowCount).apply { for (i in 0 until rowCount) { addRow(listOf("1", "butterfly", "123")) } } }
apache-2.0
bfb5985a0f57a5dff098b2ad522d3758
30.872964
107
0.640433
4.550698
false
true
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_String.kt
1
1645
@file:Suppress("unused") /* * Copyright (C) 2017 Customerly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.customerly.utils.ggkext import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * Created by Gianni on 05/01/18. */ internal fun String.hash(sha1 : Boolean = false, sha256 : Boolean = false, sha512 : Boolean = false) : String { assert(sha1.as1or0 + sha256.as1or0 + sha512.as1or0 == 1)//Solo uno deve essere valorizzato return this.hash( when { sha512 -> "SHA-512" sha512 -> "SHA-256" sha512 -> "SHA-1" else -> throw NoSuchAlgorithmException() }) } internal fun String.hash(algorithm : String) : String { return MessageDigest.getInstance(algorithm) .digest(this.toByteArray()).joinToString(separator = "") { String.format("%02x", it) } } internal fun String.toBooleanOrNull() : Boolean? { return when { "true".equals(this, ignoreCase = true) -> true "false".equals(this, ignoreCase = true) -> false else -> null } }
apache-2.0
1dfc201e86924edc84e676df2425e798
32.591837
111
0.656535
3.898104
false
false
false
false
budioktaviyan/kotlin-android
app/src/main/kotlin/com/baculsoft/kotlin/android/views/main/MainActivity.kt
1
5416
package com.baculsoft.kotlin.android.views.main import android.app.ProgressDialog import android.os.Build import android.os.Bundle import android.text.Editable import android.text.TextWatcher import com.baculsoft.kotlin.android.App import com.baculsoft.kotlin.android.R import com.baculsoft.kotlin.android.internal.data.local.TwitterSearch import com.baculsoft.kotlin.android.internal.injectors.component.ActivityComponent import com.baculsoft.kotlin.android.internal.injectors.component.DaggerActivityComponent import com.baculsoft.kotlin.android.internal.injectors.module.ActivityModule import com.baculsoft.kotlin.android.utils.Commons import com.baculsoft.kotlin.android.utils.Keyboards import com.baculsoft.kotlin.android.utils.Navigators import com.baculsoft.kotlin.android.views.base.BaseActivity import kotlinx.android.synthetic.main.activity_main.* import javax.inject.Inject /** * @author Budi Oktaviyan Suryanto ([email protected]) */ class MainActivity : BaseActivity(), MainView { companion object { lateinit var component: ActivityComponent lateinit var progressDialog: ProgressDialog } @Inject lateinit var presenter: MainPresenter @Inject lateinit var commonUtils: Commons @Inject lateinit var keyboards: Keyboards @Inject lateinit var navigators: Navigators override fun getContentView(): Int = R.layout.activity_main override fun initComponents(savedInstanceState: Bundle?) { inject() onAttach() setToolbar() addEditTextListener() addButtonListener() } override fun inject() { component = DaggerActivityComponent.builder().applicationComponent(App.component) .activityModule(ActivityModule(this)) .build() component.inject(this) } override fun onAttach() { presenter.onAttach(this) } override fun onDetach() { presenter.onDetach() } override fun onShowProgressDialog() { progressDialog = commonUtils.getProgressDialog(this) if (!progressDialog.isShowing) { progressDialog.setMessage(resources.getString(R.string.message_search)) progressDialog.show() } } override fun onDismissProgressDialog() { if (this.isFinishing) { return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (this.isDestroyed) { return } } if (progressDialog.isShowing) { progressDialog.dismiss() reset() } } override fun onShowError() { commonUtils.showGeneralError(cl_main, resources.getString(R.string.error_failed)).show() } override fun onConnectionError() { commonUtils.showGeneralError(cl_main, resources.getString(R.string.error_unknown)).show() } override fun onNavigateView(twitterSearch: TwitterSearch) { navigators.openResultActivity(this, twitterSearch) } override fun onDestroy() { onDetach() super.onDestroy() } private fun addEditTextListener() { tiet_main_query.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val query: String = tiet_main_query.text.toString() val page: String = tiet_main_page.text.toString() presenter.validateSearch(query, page, btn_main) } }) tiet_main_page.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val query: String = tiet_main_query.text.toString() val page: String = tiet_main_page.text.toString() presenter.validateSearch(query, page, btn_main) } }) } private fun addButtonListener() { btn_main.setOnClickListener { view -> val query: String = tiet_main_query.text.toString() val page: String = tiet_main_page.text.toString() val searchType: String = sp_main_type.selectedItem.toString().toLowerCase() val resultType: String = sp_main_result.selectedItem.toString().toLowerCase() presenter.getTwitterSearch(query, page, searchType, resultType) } } private fun setToolbar() { toolbar_main.setPadding(0, getStatusBarHeight() as Int, 0, 0) toolbar_main.setTitle(R.string.app_name) toolbar_main.setSubtitle(R.string.app_desc) setSupportActionBar(toolbar_main) } private fun reset() { tiet_main_query.text.clear() tiet_main_page.text.clear() sp_main_type.setSelection(0) sp_main_result.setSelection(0) btn_main.isEnabled = false keyboards.hide(cl_main, this) cl_main.requestFocus() } }
apache-2.0
817a9cf66ac7a1f50a05344301d31d65
31.053254
98
0.645126
4.582064
false
false
false
false
scenerygraphics/scenery
src/main/kotlin/graphics/scenery/proteins/Protein.kt
1
2696
package graphics.scenery.proteins import graphics.scenery.Mesh import graphics.scenery.proteins.Protein.MyProtein.fromFile import graphics.scenery.proteins.Protein.MyProtein.fromID import graphics.scenery.utils.LazyLogger import org.biojava.nbio.structure.Structure import org.biojava.nbio.structure.StructureException import org.biojava.nbio.structure.StructureIO import org.biojava.nbio.structure.io.PDBFileReader import java.io.FileNotFoundException import java.io.IOException import java.nio.file.InvalidPathException /** * Constructs a protein from a pdb-file. * @author Justin Buerger <[email protected]> * [fromID] loads a pbd-file with an ID. See also: https://www.rcsb.org/pages/help/advancedsearch/pdbIDs * [fromFile] loads a pdb-file from memory. */ class Protein(val structure: Structure): Mesh("Protein") { companion object MyProtein { private val proteinLogger by LazyLogger() fun fromID(id: String): Protein { try { StructureIO.getStructure(id) } catch (ioe: IOException) { proteinLogger.error("Something went wrong during the loading process of the pdb file, " + "maybe a typo in the pdb entry or you chose a deprecated one?" + "Here is the trace: \n" + ioe.printStackTrace()) throw ioe } catch(se: StructureException) { proteinLogger.error("Something went wrong during the loading of the pdb file."+ "Here is the trace: \n" + se.printStackTrace()) throw se } catch(npe: NullPointerException) { proteinLogger.error("Something is broken in BioJava. You can try to update the version.") throw npe } val structure = StructureIO.getStructure(id) val protein = Protein(structure) return protein } fun fromFile(path: String): Protein { val reader = PDBFileReader() //print("Please enter the path of your PDB-File: ") //val readPath = readLine() try { reader.getStructure(path) } catch (ipe: InvalidPathException) { proteinLogger.info("Path was invalid, maybe this helps: ${ipe.reason} " + "or the index: ${ipe.index}") throw ipe } catch(fnfe: FileNotFoundException) { proteinLogger.error("The pdb file is not in the directory") throw fnfe } val structure = reader.getStructure(path) return Protein(structure) } } }
lgpl-3.0
93da4dbbba3cdd3c4898db8b22289554
36.971831
105
0.613131
4.705061
false
false
false
false
leafclick/intellij-community
platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/typedModel/library/LibraryViaTypedEntity.kt
1
6686
package com.intellij.workspace.legacyBridge.typedModel.library import com.intellij.configurationStore.ComponentSerializationUtil import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.openapi.roots.RootProvider import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.impl.libraries.UnknownLibraryKind import com.intellij.openapi.roots.libraries.* import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.workspace.api.* import com.intellij.workspace.legacyBridge.intellij.* import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeLibrary import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeLibraryImpl import org.jdom.Element import java.io.StringReader internal class LibraryViaTypedEntity(val libraryImpl: LegacyBridgeLibraryImpl, val libraryEntity: LibraryEntity, internal val filePointerProvider: LegacyBridgeFilePointerProvider, val storage: TypedEntityStorage, val libraryTable: LibraryTable, private val modifiableModelFactory: (LibraryViaTypedEntity, TypedEntityStorageBuilder) -> LibraryEx.ModifiableModelEx) : LegacyBridgeLibrary, RootProvider { override fun getModule(): Module? = (libraryTable as? LegacyBridgeModuleLibraryTable)?.module private val roots = libraryEntity.roots.groupBy { it.type }.mapValues {(_, roots) -> val urls = roots.filter { it.inclusionOptions == LibraryRoot.InclusionOptions.ROOT_ITSELF }.map { it.url } val jarDirs = roots .filter { it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF } .map { LegacyBridgeJarDirectory(it.url, it.inclusionOptions == LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY) } LegacyBridgeFileContainer(urls, jarDirs) } private val excludedRoots = if (libraryEntity.excludedRoots.isNotEmpty()) LegacyBridgeFileContainer(libraryEntity.excludedRoots, emptyList()) else null private val libraryKind = libraryEntity.getCustomProperties()?.libraryType?.let { LibraryKind.findById(it) ?: UnknownLibraryKind.getOrCreate(it) } as? PersistentLibraryKind<*> private val properties = loadProperties() private fun loadProperties(): LibraryProperties<*>? { if (libraryKind == null) return null val properties = libraryKind.createDefaultProperties() val propertiesElement = libraryEntity.getCustomProperties()?.propertiesXmlTag if (propertiesElement == null) return properties ComponentSerializationUtil.loadComponentState<Any>(properties, JDOMUtil.load(StringReader(propertiesElement))) return properties } private var disposed = false override val libraryId: LibraryId get() = libraryEntity.persistentId() override fun getName(): String? = LegacyBridgeLibraryImpl.getLegacyLibraryName(libraryId) override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = roots[LibraryRootTypeId(rootType.name())] ?.getAndCacheVirtualFilePointerContainer(filePointerProvider) ?.files ?: VirtualFile.EMPTY_ARRAY override fun getUrls(rootType: OrderRootType): Array<String> = roots[LibraryRootTypeId(rootType.name())] ?.run { urls + jarDirectories.map { it.directoryUrl } } ?.map { it.url }?.toTypedArray() ?: ArrayUtil.EMPTY_STRING_ARRAY override fun getKind(): PersistentLibraryKind<*>? = libraryKind override fun getProperties(): LibraryProperties<*>? = properties override fun getTable() = if (libraryTable is LegacyBridgeModuleLibraryTable) null else libraryTable override fun getExcludedRootUrls(): Array<String> = excludedRoots?.getAndCacheVirtualFilePointerContainer(filePointerProvider)?.urls ?: ArrayUtil.EMPTY_STRING_ARRAY override fun getExcludedRoots(): Array<VirtualFile> = excludedRoots?.getAndCacheVirtualFilePointerContainer(filePointerProvider)?.files ?: VirtualFile.EMPTY_ARRAY override fun getRootProvider() = this override fun isValid(url: String, rootType: OrderRootType) = roots[LibraryRootTypeId(rootType.name())] ?.getAndCacheVirtualFilePointerContainer(filePointerProvider) ?.findByUrl(url)?.isValid ?: false override fun getInvalidRootUrls(type: OrderRootType): List<String> = roots[LibraryRootTypeId(type.name())] ?.getAndCacheVirtualFilePointerContainer(filePointerProvider) ?.list?.filterNot { it.isValid }?.map { it.url } ?: emptyList() override fun isJarDirectory(url: String) = isJarDirectory(url, OrderRootType.CLASSES) override fun isJarDirectory(url: String, rootType: OrderRootType) = roots[LibraryRootTypeId(rootType.name())] ?.getAndCacheVirtualFilePointerContainer(filePointerProvider) ?.jarDirectories?.any { it.first == url } ?: false override fun dispose() { disposed = true } override fun isDisposed() = disposed // TODO Implement override fun getExternalSource(): ProjectModelExternalSource? = null override fun getModifiableModel(): LibraryEx.ModifiableModelEx = modifiableModelFactory(this, TypedEntityStorageBuilder.from(storage)) override fun getModifiableModel(builder: TypedEntityStorageBuilder): LibraryEx.ModifiableModelEx = modifiableModelFactory(this, builder) override fun getSource(): Library = libraryImpl override fun readExternal(element: Element) = throw NotImplementedError() override fun writeExternal(rootElement: Element) = throw NotImplementedError() override fun addRootSetChangedListener(listener: RootProvider.RootSetChangedListener) = throw NotImplementedError() override fun addRootSetChangedListener(listener: RootProvider.RootSetChangedListener, parentDisposable: Disposable) = throw NotImplementedError() override fun removeRootSetChangedListener(listener: RootProvider.RootSetChangedListener) = throw NotImplementedError() }
apache-2.0
4a1312fff3db0bf3768374e55cc3785f
58.696429
184
0.707299
5.991039
false
false
false
false
moko256/twicalico
component_client_twitter/src/main/java/com/github/moko256/latte/client/twitter/TwitterAuthApiClient.kt
1
3452
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.latte.client.twitter import com.github.moko256.latte.client.base.AuthApiClient import com.github.moko256.latte.client.base.entity.AccessToken import com.github.moko256.latte.client.base.entity.RequestToken import twitter4j.auth.OAuthAuthorization import twitter4j.conf.ConfigurationBuilder /** * Created by moko256 on 2018/12/06. * * @author moko256 */ class TwitterAuthApiClient(consumerKey: String, consumerSecret: String) : AuthApiClient { private val oauth = generateOAuth(consumerKey, consumerSecret) override fun getOAuthRequestToken( optionalConsumerKey: String?, optionalConsumerSecret: String?, serverUrl: String, callbackUrl: String? ): RequestToken { val redirectUrl = callbackUrl ?: "oob" return getCustomOAuthOrDefault(optionalConsumerKey, optionalConsumerSecret) .getOAuthRequestToken(redirectUrl).let { RequestToken( serverUrl, it.authorizationURL, redirectUrl, optionalConsumerKey, optionalConsumerSecret, it.token, it.tokenSecret ) } } override fun initializeToken(requestToken: RequestToken, key: String): AccessToken { return getCustomOAuthOrDefault(requestToken.consumerKey, requestToken.consumerSecret) .getOAuthAccessToken( twitter4j.auth.RequestToken( requestToken.token, requestToken.tokenSecret ), key ).let { AccessToken( CLIENT_TYPE_TWITTER, requestToken.serverUrl, it.userId, it.screenName, requestToken.consumerKey, requestToken.consumerSecret, it.token, it.tokenSecret ) } } private fun generateOAuth(consumerKey: String, consumerSecret: String) = OAuthAuthorization( ConfigurationBuilder() .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret) .build() ) private fun getCustomOAuthOrDefault( optionalConsumerKey: String?, optionalConsumerSecret: String? ) = if (optionalConsumerKey != null && optionalConsumerSecret != null) { generateOAuth(optionalConsumerKey, optionalConsumerSecret) } else { oauth } }
apache-2.0
47341cc905edbd4a9862128b099050c2
36.532609
96
0.582561
5.62215
false
false
false
false
leafclick/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/worktree/LegacyBridgeMavenRootModelAdapter.kt
1
11536
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing.worktree import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.pom.java.LanguageLevel import com.intellij.workspace.api.* import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeCompilerModuleExtension import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModule import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModuleManagerComponent import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModuleRootComponent import org.jetbrains.idea.maven.importing.MavenModelUtil import org.jetbrains.idea.maven.importing.MavenRootModelAdapterInterface import org.jetbrains.idea.maven.model.MavenArtifact import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.utils.Path import org.jetbrains.idea.maven.utils.Url import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer import java.io.File @Retention(AnnotationRetention.SOURCE) private annotation class NotRequiredToImplement; class LegacyBridgeMavenRootModelAdapter(private val myMavenProject: MavenProject, private val module: LegacyBridgeModule, private val project: Project, initialModuleEntity: ModuleEntity, private val legacyBridgeModifiableModelsProvider: LegacyBrigdeIdeModifiableModelsProvider, private val builder: TypedEntityStorageBuilder) : MavenRootModelAdapterInterface { private var moduleEntity: ModuleEntity = initialModuleEntity private val legacyBridge = LegacyBridgeModuleRootComponent.getInstance(module) private val modifiableModel = legacyBridge.getModifiableModel(builder, RootConfigurationAccessor()) private val entitySource = MavenExternalSource.INSTANCE override fun init(isNewlyCreatedModule: Boolean) {} override fun getRootModel(): ModifiableRootModel { return modifiableModel } override fun getSourceRootUrls(includingTests: Boolean): Array<String> { return legacyBridge.sourceRootUrls } override fun getModule(): Module { return module } @NotRequiredToImplement override fun clearSourceFolders() { } override fun <P : JpsElement?> addSourceFolder(path: String, rootType: JpsModuleSourceRootType<P>) { createSourceRoot(rootType, path, false) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType, ifNotEmpty: Boolean) { createSourceRoot(rootType, path, true) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType) { createSourceRoot(rootType, path, true) } private fun <P : JpsElement?> createSourceRoot(rootType: JpsModuleSourceRootType<P>, path: String, generated: Boolean) { val typeId = getTypeId(rootType) val sourceRootEntity = builder.addSourceRootEntity(moduleEntity, VirtualFileUrlManager.fromUrl(VfsUtilCore.pathToUrl(path)), rootType.isForTests, typeId, entitySource) when (rootType) { is JavaSourceRootType -> builder.addJavaSourceRootEntity(sourceRootEntity, generated, "", entitySource) is JavaResourceRootType -> builder.addJavaResourceRootEntity(sourceRootEntity, generated, "", entitySource) else -> TODO() } } private fun <P : JpsElement?> getTypeId(rootType: JpsModuleSourceRootType<P>): String { return if (rootType.isForTests()) return JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID else JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID } override fun hasRegisteredSourceSubfolder(f: File): Boolean { val url: String = toUrl(f.path).url return builder.entities(SourceRootEntity::class.java).filter { VfsUtilCore.isEqualOrAncestor(url, it.url.url) }.any() } private fun toUrl(path: String): Url { return toPath(path).toUrl() } override fun toPath(path: String): Path { if (!FileUtil.isAbsolute(path)) { return Path(File(myMavenProject.directory, path).path) } return Path(path) } override fun getSourceFolder(folder: File): SourceFolder? { return legacyBridge.contentEntries.flatMap { it.sourceFolders.asList() }.find { it.url == VfsUtilCore.fileToUrl(folder) } } override fun isAlreadyExcluded(f: File): Boolean { val url = toUrl(f.path).url return moduleEntity.contentRoots.filter { cre -> VfsUtilCore.isUnder(url, cre.excludedUrls.map { it.url }) }.any() } override fun addExcludedFolder(path: String) { getContentRootFor(toUrl(path))?.let { builder.modifyEntity(ModifiableContentRootEntity::class.java, it) { this.excludedUrls = this.excludedUrls + VirtualFileUrlManager.fromUrl(VfsUtilCore.pathToUrl(path)) } } } private fun getContentRootFor(url: Url): ContentRootEntity? { return moduleEntity.contentRoots.firstOrNull { VfsUtilCore.isEqualOrAncestor(it.url.url, url.url) } } @NotRequiredToImplement override fun unregisterAll(path: String, under: Boolean, unregisterSources: Boolean) { } @NotRequiredToImplement override fun hasCollision(sourceRootPath: String): Boolean { return false } override fun useModuleOutput(production: String, test: String) { LegacyBridgeCompilerModuleExtension(module, module.entityStore, builder).apply { inheritCompilerOutputPath(false); setCompilerOutputPath(toUrl(production).getUrl()); setCompilerOutputPathForTests(toUrl(test).getUrl()); } } override fun addModuleDependency(moduleName: String, scope: DependencyScope, testJar: Boolean) { val dependency = ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(moduleName), false, toEntityScope(scope), testJar) moduleEntity = builder.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = this.dependencies + dependency } } private fun toEntityScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope { return when (scope) { DependencyScope.COMPILE -> ModuleDependencyItem.DependencyScope.COMPILE DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST } } override fun findModuleByName(moduleName: String): Module? { return LegacyBridgeModuleManagerComponent(project).modules.firstOrNull { it.name == moduleName } } private fun MavenArtifact.ideaLibraryName(): String = "${this.libraryName}"; override fun addSystemDependency(artifact: MavenArtifact, scope: DependencyScope) { assert(MavenConstants.SCOPE_SYSTEM == artifact.scope) { "Artifact scope should be \"system\"" } val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(VirtualFileUrlManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId("CLASSES"), LibraryRoot.InclusionOptions.ROOT_ITSELF)) val libraryTableId = LibraryTableId.ModuleLibraryTableId(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />", MavenExternalSource.INSTANCE) } override fun addLibraryDependency(artifact: MavenArtifact, scope: DependencyScope, provider: IdeModifiableModelsProvider, project: MavenProject): LibraryOrderEntry { val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(VirtualFileUrlManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId("CLASSES"), LibraryRoot.InclusionOptions.ROOT_ITSELF)) roots.add( LibraryRoot(VirtualFileUrlManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")), LibraryRootTypeId("JAVADOC"), LibraryRoot.InclusionOptions.ROOT_ITSELF)) roots.add( LibraryRoot(VirtualFileUrlManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")), LibraryRootTypeId("SOURCES"), LibraryRoot.InclusionOptions.ROOT_ITSELF)) val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />", MavenExternalSource.INSTANCE) val libDependency = ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(libraryEntity.name, libraryTableId), false, toEntityScope(scope)) moduleEntity = builder.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity, { this.dependencies += this.dependencies + libDependency }) val last = legacyBridge.orderEntries.last() assert(last is LibraryOrderEntry && last.libraryName == artifact.ideaLibraryName()) return last as LibraryOrderEntry } override fun findLibrary(artifact: MavenArtifact): Library? { return legacyBridge.legacyBridgeModuleLibraryTable().libraries.firstOrNull { it.name == artifact.ideaLibraryName() } } override fun setLanguageLevel(level: LanguageLevel) { try { modifiableModel.getModuleExtension(LanguageLevelModuleExtension::class.java)?.apply { languageLevel = level } } catch (e: IllegalArgumentException) { //bad value was stored } } }
apache-2.0
e4e556fb08c675a4dc5d5ed0c4d040ee
44.243137
155
0.692874
5.671583
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/secondaryConstructors/innerClasses.kt
4
2320
class Outer { val outerProp: String constructor(x: String) { outerProp = x } var sideEffects = "" inner class A1() { var prop: String = "" init { sideEffects += outerProp + "#" + prop + "first" } constructor(x: String): this() { prop = x + "#${outerProp}" sideEffects += "#third" } init { sideEffects += prop + "#second" } constructor(x: Int): this(x.toString() + "#" + outerProp) { prop += "#int" sideEffects += "#fourth" } } inner class A2 { var prop: String = "" init { sideEffects += outerProp + "#" + prop + "first" } constructor(x: String) { prop = x + "#$outerProp" sideEffects += "#third" } init { sideEffects += prop + "#second" } constructor(x: Int) { prop += "$x#$outerProp#int" sideEffects += "#fourth" } } } fun box(): String { val outer1 = Outer("propValue1") val a1 = outer1.A1("abc") if (a1.prop != "abc#propValue1") return "fail1: ${a1.prop}" if (outer1.sideEffects != "propValue1#first#second#third") return "fail1-sideEffects: ${outer1.sideEffects}" val outer2 = Outer("propValue2") val a2 = outer2.A1(123) if (a2.prop != "123#propValue2#propValue2#int") return "fail2: ${a2.prop}" if (outer2.sideEffects != "propValue2#first#second#third#fourth") return "fail2-sideEffects: ${outer2.sideEffects}" val outer3 = Outer("propValue3") val a3 = outer3.A1() if (a3.prop != "") return "fail2: ${a3.prop}" if (outer3.sideEffects != "propValue3#first#second") return "fail3-sideEffects: ${outer3.sideEffects}" val outer4 = Outer("propValue4") val a4 = outer4.A2("abc") if (a4.prop != "abc#propValue4") return "fail4: ${a4.prop}" if (outer4.sideEffects != "propValue4#first#second#third") return "fail4-sideEffects: ${outer4.sideEffects}" val outer5 = Outer("propValue5") val a5 = outer5.A2(123) if (a5.prop != "123#propValue5#int") return "fail5: ${a5.prop}" if (outer5.sideEffects != "propValue5#first#second#fourth") return "fail5-sideEffects: ${outer5.sideEffects}" return "OK" }
apache-2.0
6764b08bb5a267823e4b01a5cd2d01c5
28.367089
119
0.550862
3.504532
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/learn/OpenLessonActivities.kt
1
22133
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.ide.startup.StartupManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.fileEditor.TextEditorWithPreview import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Computable import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ToolWindowType import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresEdt import training.dsl.LessonUtil import training.dsl.impl.LessonContextImpl import training.dsl.impl.LessonExecutor import training.lang.LangManager import training.lang.LangSupport import training.learn.course.KLesson import training.learn.course.Lesson import training.learn.course.LessonType import training.learn.exceptons.LessonPreparationException import training.learn.lesson.LessonManager import training.project.ProjectUtils import training.statistic.LessonStartingWay import training.statistic.StatisticBase import training.statistic.StatisticLessonListener import training.ui.LearnToolWindowFactory import training.ui.LearningUiManager import training.util.findLanguageByID import training.util.getLearnToolWindowForProject import training.util.isLearningProject import training.util.learningToolWindow import java.io.IOException internal class OpenLessonParameters(val projectWhereToStartLesson: Project, val lesson: Lesson, val forceStartLesson: Boolean, val startingWay: LessonStartingWay) internal object OpenLessonActivities { private val LOG = logger<OpenLessonActivities>() @RequiresEdt fun openLesson(params: OpenLessonParameters) { val projectWhereToStartLesson = params.projectWhereToStartLesson LOG.debug("${projectWhereToStartLesson.name}: start openLesson method") // Stop the current lesson (if any) LessonManager.instance.stopLesson() val activeToolWindow = LearningUiManager.activeToolWindow ?: getLearnToolWindowForProject(projectWhereToStartLesson).also { LearningUiManager.activeToolWindow = it } if (activeToolWindow != null && activeToolWindow.project != projectWhereToStartLesson) { // maybe we need to add some confirmation dialog? activeToolWindow.setModulesPanel() } if (!params.forceStartLesson && LessonManager.instance.lessonShouldBeOpenedCompleted(params.lesson)) { // TODO: Do not stop lesson in another toolwindow IFT-110 LearningUiManager.activeToolWindow?.setLearnPanel() ?: error("No active toolwindow in $projectWhereToStartLesson") LessonManager.instance.openLessonPassed(params.lesson as KLesson, projectWhereToStartLesson) return } try { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined") var learnProject = LearningUiManager.learnProject if (learnProject != null && !isLearningProject(learnProject, langSupport)) { learnProject = null // We are in the project from another course } LOG.debug("${projectWhereToStartLesson.name}: trying to get cached LearnProject ${learnProject != null}") if (learnProject == null) learnProject = findLearnProjectInOpenedProjects(langSupport) LOG.debug("${projectWhereToStartLesson.name}: trying to find LearnProject in opened projects ${learnProject != null}") if (learnProject != null) LearningUiManager.learnProject = learnProject val lessonType = params.lesson.lessonType when { lessonType == LessonType.SCRATCH -> { LOG.debug("${projectWhereToStartLesson.name}: scratch based lesson") } lessonType == LessonType.USER_PROJECT -> { LOG.debug("The lesson opened in user project ${projectWhereToStartLesson.name}") } learnProject == null || learnProject.isDisposed -> { if (!isLearningProject(projectWhereToStartLesson, langSupport)) { //1. learnProject == null and current project has different name then initLearnProject and register post startup open lesson LOG.debug("${projectWhereToStartLesson.name}: 1. learnProject is null or disposed") initLearnProject(projectWhereToStartLesson, null) { LOG.debug("${projectWhereToStartLesson.name}: 1. ... LearnProject has been started") openLessonWhenLearnProjectStart(OpenLessonParameters(it, params.lesson, params.forceStartLesson, params.startingWay)) LOG.debug("${projectWhereToStartLesson.name}: 1. ... open lesson when learn project has been started") } return } else { LOG.debug( "${projectWhereToStartLesson.name}: 0. learnProject is null but the current project (${projectWhereToStartLesson.name})" + "is LearnProject then just getFileInLearnProject") LearningUiManager.learnProject = projectWhereToStartLesson learnProject = projectWhereToStartLesson } } learnProject.isOpen && projectWhereToStartLesson != learnProject -> { LOG.debug("${projectWhereToStartLesson.name}: 3. LearnProject is opened but not focused. Ask user to focus to LearnProject") askSwitchToLearnProjectBack(learnProject, projectWhereToStartLesson) return } learnProject.isOpen && projectWhereToStartLesson == learnProject -> { LOG.debug("${projectWhereToStartLesson.name}: 4. LearnProject is the current project") } else -> { throw Exception("Unable to start Learn project") } } if (lessonType.isProject) { if (lessonType == LessonType.USER_PROJECT) { prepareAndOpenLesson(params, withCleanup = false) } else { if (projectWhereToStartLesson != learnProject) { LOG.error(Exception("Invalid learning project initialization: " + "projectWhereToStartLesson = $projectWhereToStartLesson, learnProject = $learnProject")) return } prepareAndOpenLesson(params) } } else { openLessonForPreparedProject(params) } } catch (e: Exception) { LOG.error(e) } } private fun prepareAndOpenLesson(params: OpenLessonParameters, withCleanup: Boolean = true) { runBackgroundableTask(LearnBundle.message("learn.project.initializing.process"), project = params.projectWhereToStartLesson) l@{ val project = params.projectWhereToStartLesson val lessonToOpen = params.lesson try { if (withCleanup) { LangManager.getInstance().getLangSupport()?.cleanupBeforeLessons(project) } lessonToOpen.prepare(project) } catch (e: LessonPreparationException) { thisLogger().warn("Error occurred when preparing the lesson ${lessonToOpen.id}", e) return@l } catch (t: Throwable) { thisLogger().error("Error occurred when preparing the lesson ${lessonToOpen.id}", t) return@l } invokeLater { openLessonForPreparedProject(params) } } } private fun openLessonForPreparedProject(params: OpenLessonParameters) { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language should be defined by now") val project = params.projectWhereToStartLesson val lesson = params.lesson val vf: VirtualFile? = if (lesson.lessonType == LessonType.SCRATCH) { LOG.debug("${project.name}: scratch based lesson") getScratchFile(project, lesson, langSupport.filename) } else { LOG.debug("${project.name}: 4. LearnProject is the current project") getFileInLearnProject(lesson) } if (lesson.lessonType != LessonType.SCRATCH) { ProjectUtils.closeAllEditorsInProject(project) } if (lesson.lessonType != LessonType.SCRATCH || LearningUiManager.learnProject == project) { // do not change view environment for scratch lessons in user project hideOtherViews(project) } // We need to ensure that the learning panel is initialized if (showLearnPanel(project, lesson.preferredLearnWindowAnchor(project))) { openLessonWhenLearnPanelIsReady(params, vf) } else waitLearningToolwindow(params, vf) } private fun openLessonWhenLearnPanelIsReady(params: OpenLessonParameters, vf: VirtualFile?) { val project = params.projectWhereToStartLesson LOG.debug("${project.name}: Add listeners to lesson") addStatisticLessonListenerIfNeeded(project, params.lesson) //open next lesson if current is passed LOG.debug("${project.name}: Set lesson view") LearningUiManager.activeToolWindow = getLearnToolWindowForProject(project)?.also { it.setLearnPanel() } LOG.debug("${project.name}: XmlLesson onStart()") params.lesson.onStart(params.startingWay) //to start any lesson we need to do 4 steps: //1. open editor or find editor LOG.debug("${project.name}: PREPARING TO START LESSON:") LOG.debug("${project.name}: 1. Open or find editor") var textEditor: TextEditor? = null if (vf != null && FileEditorManager.getInstance(project).isFileOpen(vf)) { val editors = FileEditorManager.getInstance(project).getEditors(vf) for (fileEditor in editors) { if (fileEditor is TextEditor) { textEditor = fileEditor } } } if (vf != null && textEditor == null) { val editors = FileEditorManager.getInstance(project).openFile(vf, true, true) for (fileEditor in editors) { if (fileEditor is TextEditor) { textEditor = fileEditor } } if (textEditor == null) { LOG.error("Cannot open editor for $vf") if (params.lesson.lessonType == LessonType.SCRATCH) { invokeLater { runWriteAction { vf.delete(this) } } } } } //2. set the focus on this editor //FileEditorManager.getInstance(project).setSelectedEditor(vf, TextEditorProvider.getInstance().getEditorTypeId()); LOG.debug("${project.name}: 2. Set the focus on this editor") if (vf != null) FileEditorManager.getInstance(project).openEditor(OpenFileDescriptor(project, vf), true) //4. Process lesson LOG.debug("${project.name}: 4. Process lesson") if (params.lesson is KLesson) processDslLesson(params.lesson, textEditor, project, vf) else error("Unknown lesson format") } private fun waitLearningToolwindow(params: OpenLessonParameters, vf: VirtualFile?) { val project = params.projectWhereToStartLesson val connect = project.messageBus.connect() connect.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { override fun toolWindowsRegistered(ids: MutableList<String>, toolWindowManager: ToolWindowManager) { if (ids.contains(LearnToolWindowFactory.LEARN_TOOL_WINDOW)) { val toolWindow = toolWindowManager.getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW) if (toolWindow != null) { connect.disconnect() invokeLater { showLearnPanel(project, params.lesson.preferredLearnWindowAnchor(project)) openLessonWhenLearnPanelIsReady(params, vf) } } } } }) } private fun processDslLesson(lesson: KLesson, textEditor: TextEditor?, projectWhereToStartLesson: Project, vf: VirtualFile?) { val executor = LessonExecutor(lesson, projectWhereToStartLesson, textEditor?.editor, vf) val lessonContext = LessonContextImpl(executor) LessonManager.instance.initDslLesson(textEditor?.editor, lesson, executor) lesson.lessonContent(lessonContext) executor.startLesson() } private fun hideOtherViews(project: Project) { ApplicationManager.getApplication().invokeLater { LessonUtil.hideStandardToolwindows(project) } } private fun addStatisticLessonListenerIfNeeded(currentProject: Project, lesson: Lesson) { val statLessonListener = StatisticLessonListener(currentProject) if (!lesson.lessonListeners.any { it is StatisticLessonListener }) lesson.addLessonListener(statLessonListener) } private fun openReadme(project: Project) { val root = ProjectUtils.getProjectRoot(project) val readme = root.findFileByRelativePath("README.md") ?: return TextEditorWithPreview.openPreviewForFile(project, readme) } fun openOnboardingFromWelcomeScreen(onboarding: Lesson, selectedSdk: Sdk?) { StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.ONBOARDING_PROMOTER) initLearnProject(null, selectedSdk) { project -> StartupManager.getInstance(project).runAfterOpened { invokeLater { if (onboarding.properties.canStartInDumbMode) { CourseManager.instance.openLesson(project, onboarding, LessonStartingWay.ONBOARDING_PROMOTER, true) } else { DumbService.getInstance(project).runWhenSmart { CourseManager.instance.openLesson(project, onboarding, LessonStartingWay.ONBOARDING_PROMOTER, true) } } } } } } fun openLearnProjectFromWelcomeScreen(selectedSdk: Sdk?) { StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.LEARN_IDE) initLearnProject(null, selectedSdk) { project -> StartupManager.getInstance(project).runAfterOpened { invokeLater { openReadme(project) hideOtherViews(project) val anchor = LangManager.getInstance().getLangSupport()?.getToolWindowAnchor() ?: ToolWindowAnchor.LEFT showLearnPanel(project, anchor) CourseManager.instance.unfoldModuleOnInit = null // Try to fix PyCharm double startup indexing :( val openWhenSmart = { showLearnPanel(project, anchor) DumbService.getInstance(project).runWhenSmart { showLearnPanel(project, anchor) } } Alarm().addRequest(openWhenSmart, 500) } } } } private fun showLearnPanel(project: Project, preferredAnchor: ToolWindowAnchor): Boolean { val learn = learningToolWindow(project) ?: return false if (learn.anchor != preferredAnchor && learn.type == ToolWindowType.DOCKED) { learn.setAnchor(preferredAnchor, null) } learn.show() return true } @RequiresEdt private fun openLessonWhenLearnProjectStart(params: OpenLessonParameters) { if (params.lesson.properties.canStartInDumbMode) { prepareAndOpenLesson(params, withCleanup = false) return } val myLearnProject = params.projectWhereToStartLesson fun openLesson() { val toolWindowManager = ToolWindowManager.getInstance(myLearnProject) val learnToolWindow = toolWindowManager.getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW) if (learnToolWindow != null) { DumbService.getInstance(myLearnProject).runWhenSmart { // Try to fix PyCharm double startup indexing :( val openWhenSmart = { DumbService.getInstance(myLearnProject).runWhenSmart { prepareAndOpenLesson(params, withCleanup = false) } } Alarm().addRequest(openWhenSmart, 500) } } } val startupManager = StartupManager.getInstance(myLearnProject) if (startupManager is StartupManagerEx && startupManager.postStartupActivityPassed()) { openLesson() } else { startupManager.registerPostStartupActivity { openLesson() } } } @Throws(IOException::class) private fun getScratchFile(project: Project, lesson: Lesson, filename: String): VirtualFile { val languageId = lesson.languageId ?: error("Scratch lesson ${lesson.id} should define language") var vf: VirtualFile? = null val languageByID = findLanguageByID(languageId) if (CourseManager.instance.mapModuleVirtualFile.containsKey(lesson.module)) { vf = CourseManager.instance.mapModuleVirtualFile[lesson.module] ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID) } if (vf == null || !vf.isValid) { //while module info is not stored //find file if it is existed vf = ScratchFileService.getInstance().findFile(ScratchRootType.getInstance(), filename, ScratchFileService.Option.existing_only) if (vf != null) { FileEditorManager.getInstance(project).closeFile(vf) ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID) } if (vf == null || !vf.isValid) { vf = ScratchRootType.getInstance().createScratchFile(project, filename, languageByID, "") assert(vf != null) } CourseManager.instance.registerVirtualFile(lesson.module, vf!!) } return vf } private fun askSwitchToLearnProjectBack(learnProject: Project, currentProject: Project) { Messages.showInfoMessage(currentProject, LearnBundle.message("dialog.askToSwitchToLearnProject.message", learnProject.name), LearnBundle.message("dialog.askToSwitchToLearnProject.title")) } @Throws(IOException::class) private fun getFileInLearnProject(lesson: Lesson): VirtualFile? { if (!lesson.properties.openFileAtStart) { LOG.debug("${lesson.name} does not open any file at the start") return null } val function = object : Computable<VirtualFile> { override fun compute(): VirtualFile { val learnProject = LearningUiManager.learnProject!! val existedFile = lesson.existedFile ?: lesson.module.primaryLanguage?.projectSandboxRelativePath val manager = ProjectRootManager.getInstance(learnProject) if (existedFile != null) { val root = ProjectUtils.getProjectRoot(learnProject) val findFileByRelativePath = root.findFileByRelativePath(existedFile) if (findFileByRelativePath != null) return findFileByRelativePath } val fileName = existedFile ?: lesson.fileName var lessonVirtualFile: VirtualFile? = null var roots = manager.contentSourceRoots if (roots.isEmpty()) { roots = manager.contentRoots } for (file in roots) { if (file.name == fileName) { lessonVirtualFile = file break } else { lessonVirtualFile = file.findChild(fileName) if (lessonVirtualFile != null) { break } } } if (lessonVirtualFile == null) { lessonVirtualFile = roots[0].createChildData(this, fileName) } CourseManager.instance.registerVirtualFile(lesson.module, lessonVirtualFile) return lessonVirtualFile } } val vf = ApplicationManager.getApplication().runWriteAction(function) assert(vf is VirtualFile) return vf } private fun initLearnProject(projectToClose: Project?, selectedSdk: Sdk?, postInitCallback: (learnProject: Project) -> Unit) { val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined") //if projectToClose is open findLearnProjectInOpenedProjects(langSupport)?.let { postInitCallback(it) return } if (!ApplicationManager.getApplication().isUnitTestMode && projectToClose != null) if (!NewLearnProjectUtil.showDialogOpenLearnProject(projectToClose)) return //if user abort to open lesson in a new Project try { NewLearnProjectUtil.createLearnProject(projectToClose, langSupport, selectedSdk) { learnProject -> try { langSupport.applyToProjectAfterConfigure().invoke(learnProject) } catch (e: Throwable) { LOG.error(e) LOG.error("The configuration will be retried after 2 seconds") Alarm().addRequest({ langSupport.applyToProjectAfterConfigure().invoke(learnProject) finishProjectInitialization(learnProject, postInitCallback) }, 2000) return@createLearnProject } finishProjectInitialization(learnProject, postInitCallback) } } catch (e: IOException) { LOG.error(e) } } private fun finishProjectInitialization(learnProject: Project, postInitCallback: (learnProject: Project) -> Unit) { LearningUiManager.learnProject = learnProject runInEdt { postInitCallback(learnProject) } } private fun findLearnProjectInOpenedProjects(langSupport: LangSupport): Project? { val openProjects = ProjectManager.getInstance().openProjects return openProjects.firstOrNull { isLearningProject(it, langSupport) } } }
apache-2.0
a8ef0afae5bdd8680131038e78a93311
40.762264
140
0.701532
4.901019
false
false
false
false
smmribeiro/intellij-community
java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.kt
2
7740
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.projectImport import com.intellij.CommonBundle import com.intellij.ide.IdeBundle import com.intellij.ide.JavaUiBundle import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.CompilerProjectExtension import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.nio.file.Files import javax.swing.Icon abstract class ProjectOpenProcessorBase<T : ProjectImportBuilder<*>> : ProjectOpenProcessor { companion object { @JvmStatic protected fun canOpenFile(file: VirtualFile, supported: Array<String>): Boolean { return supported.contains(file.name) } @JvmStatic fun getUrl(path: String): String { var resolvedPath: String try { resolvedPath = FileUtil.resolveShortWindowsName(path) } catch (ignored: IOException) { resolvedPath = path } return VfsUtilCore.pathToUrl(resolvedPath) } } private val myBuilder: T? @Deprecated("Override {@link #doGetBuilder()} and use {@code ProjectImportBuilder.EXTENSIONS_POINT_NAME.findExtensionOrFail(yourClass.class)}.") @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") protected constructor(builder: T) { myBuilder = builder } protected constructor() { myBuilder = null } open val builder: T get() = doGetBuilder() protected open fun doGetBuilder(): T = myBuilder!! override fun getName(): String = builder.name override fun getIcon(): Icon? = builder.icon override fun canOpenProject(file: VirtualFile): Boolean { val supported = supportedExtensions if (file.isDirectory) { return getFileChildren(file).any { canOpenFile(it, supported) } } else { return canOpenFile(file, supported) } } protected open fun doQuickImport(file: VirtualFile, wizardContext: WizardContext): Boolean = false abstract val supportedExtensions: Array<String> override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? { try { val wizardContext = WizardContext(null, null) builder.isUpdate = false var resolvedVirtualFile = virtualFile if (virtualFile.isDirectory) { val supported = supportedExtensions for (file in getFileChildren(virtualFile)) { if (canOpenFile(file, supported)) { resolvedVirtualFile = file break } } } wizardContext.setProjectFileDirectory(resolvedVirtualFile.parent.toNioPath(), false) if (!doQuickImport(resolvedVirtualFile, wizardContext)) { return null } if (wizardContext.projectName == null) { if (wizardContext.projectStorageFormat == StorageScheme.DEFAULT) { wizardContext.projectName = JavaUiBundle.message("project.import.default.name", name) + ProjectFileType.DOT_DEFAULT_EXTENSION } else { wizardContext.projectName = JavaUiBundle.message("project.import.default.name.dotIdea", name) } } wizardContext.projectJdk = ProjectRootManager.getInstance(ProjectManager.getInstance().defaultProject).projectSdk ?: ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance()) val dotIdeaFile = wizardContext.projectDirectory.resolve(Project.DIRECTORY_STORE_FOLDER) val projectFile = wizardContext.projectDirectory.resolve(wizardContext.projectName + ProjectFileType.DOT_DEFAULT_EXTENSION).normalize() var pathToOpen = if (wizardContext.projectStorageFormat == StorageScheme.DEFAULT) projectFile.toAbsolutePath() else dotIdeaFile.parent var shouldOpenExisting = false var importToProject = true if (Files.exists(projectFile) || Files.exists(dotIdeaFile)) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { shouldOpenExisting = true importToProject = true } else { val existingName: String if (Files.exists(dotIdeaFile)) { existingName = "an existing project" pathToOpen = dotIdeaFile.parent } else { existingName = "'${projectFile.fileName}'" pathToOpen = projectFile } val result = Messages.showYesNoCancelDialog( projectToClose, JavaUiBundle.message("project.import.open.existing", existingName, projectFile.parent, virtualFile.name), IdeBundle.message("title.open.project"), JavaUiBundle.message("project.import.open.existing.openExisting"), JavaUiBundle.message("project.import.open.existing.reimport"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon()) if (result == Messages.CANCEL) { return null } shouldOpenExisting = result == Messages.YES importToProject = !shouldOpenExisting } } var options = OpenProjectTask(projectToClose = projectToClose, forceOpenInNewFrame = forceOpenInNewFrame, projectName = wizardContext.projectName) if (!shouldOpenExisting) { options = options.copy(isNewProject = true) } if (importToProject) { options = options.copy(beforeOpen = { project -> importToProject(project, projectToClose, wizardContext) }) } try { val project = ProjectManagerEx.getInstanceEx().openProject(pathToOpen, options) ProjectUtil.updateLastProjectLocation(pathToOpen) return project } catch (e: Exception) { logger<ProjectOpenProcessorBase<*>>().warn(e) } } finally { builder.cleanup() } return null } private fun importToProject(projectToOpen: Project, projectToClose: Project?, wizardContext: WizardContext): Boolean { return invokeAndWaitIfNeeded { if (!builder.validate(projectToClose, projectToOpen)) { return@invokeAndWaitIfNeeded false } ApplicationManager.getApplication().runWriteAction { wizardContext.projectJdk?.let { JavaSdkUtil.applyJdkToProject(projectToOpen, it) } val projectDirPath = wizardContext.projectFileDirectory val path = projectDirPath + if (projectDirPath.endsWith('/')) "classes" else "/classes" CompilerProjectExtension.getInstance(projectToOpen)?.let { it.compilerOutputUrl = getUrl(path) } } builder.commit(projectToOpen, null, ModulesProvider.EMPTY_MODULES_PROVIDER) true } } } private fun getFileChildren(file: VirtualFile) = file.children ?: VirtualFile.EMPTY_ARRAY
apache-2.0
e38413e015623f522a791ba766cbd782
36.391304
152
0.710336
4.990329
false
false
false
false
smmribeiro/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/lesson/navigation/JavaOccurrencesLesson.kt
1
3788
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.ift.lesson.navigation import com.intellij.find.SearchTextArea import com.intellij.java.ift.JavaLessonsBundle import com.intellij.usageView.UsageViewBundle import training.dsl.LessonContext import training.dsl.LessonUtil import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.parseLessonSample import training.learn.course.KLesson import training.learn.course.LessonType class JavaOccurrencesLesson : KLesson("java.occurrences.lesson", JavaLessonsBundle.message("java.find.occurrences.lesson.name")) { override val lessonType = LessonType.SINGLE_EDITOR val sample = parseLessonSample(""" class OccurrencesDemo { final private String DATABASE = "MyDataBase"; DataEntry myPerson; OccurrencesDemo(String name, int age, String <select>cellphone</select>) { myPerson = new Person(name, age, "Cellphone: " + cellphone); } interface DataEntry { String getCellphone(); String getName(); } class Person implements DataEntry { public Person(String name, int age, String cellphone) { this.name = name; this.age = age; this.cellphone = cellphone; } private String name; private int age; private String cellphone; public String getCellphone() { return cellphone; } public String getName() { return name; } } } """.trimIndent()) override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) task("Find") { text(JavaLessonsBundle.message("java.find.occurrences.invoke.find", code("cellphone"), action(it))) triggerByUiComponentAndHighlight(false, false) { _: SearchTextArea -> true } restoreIfModifiedOrMoved() test { actions(it) } } task("FindNext") { trigger("com.intellij.find.editorHeaderActions.NextOccurrenceAction") text(JavaLessonsBundle.message("java.find.occurrences.find.next", LessonUtil.rawEnter(), action(it))) restoreByUi() test { ideFrame { actionButton(UsageViewBundle.message("action.next.occurrence")).click() } } } task("FindPrevious") { trigger("com.intellij.find.editorHeaderActions.PrevOccurrenceAction") text(JavaLessonsBundle.message("java.find.occurrences.find.previous", action("FindPrevious"))) showWarning(JavaLessonsBundle.message("java.find.occurrences.search.closed.warning", action("Find"))) { editor.headerComponent == null } test { ideFrame { actionButton(UsageViewBundle.message("action.previous.occurrence")).click() } } } task("EditorEscape") { text(JavaLessonsBundle.message("java.find.occurrences.close.search.tool", action(it))) stateCheck { editor.headerComponent == null } test { invokeActionViaShortcut("ESCAPE") } } actionTask("FindNext") { JavaLessonsBundle.message("java.find.occurrences.find.next.in.editor", action(it)) } actionTask("FindPrevious") { JavaLessonsBundle.message("java.find.occurrences.find.previous.in.editor", action(it)) } text(JavaLessonsBundle.message("java.find.occurrences.note.about.cyclic", action("FindNext"), action("FindPrevious"))) } override val helpLinks: Map<String, String> get() = mapOf( Pair(JavaLessonsBundle.message("java.find.help.link"), LessonUtil.getHelpLink("finding-and-replacing-text-in-file.html")), ) }
apache-2.0
9e3718f198134e992f11a1c373915e04
33.445455
140
0.660771
4.735
false
false
false
false
Werb/MoreType
app/src/main/java/com/werb/moretype/me/MeThanksViewHolder.kt
1
791
package com.werb.moretype.me import android.content.Intent import android.net.Uri import android.view.View import com.werb.library.MoreViewHolder import kotlinx.android.synthetic.main.item_view_about_me_thx.* /** * Created by wanbo on 2017/7/15. */ class MeThanksViewHolder(values: MutableMap<String, Any>, containerView: View) : MoreViewHolder<MeThanks>(values, containerView) { override fun bindData(data: MeThanks, payloads: List<Any>) { name.text = data.name desc.text = data.desc icon.setImageURI(data.url) itemView.setOnClickListener { val intent = Intent() intent.action = "android.intent.action.VIEW" intent.data = Uri.parse(data.gitHub) itemView.context.startActivity(intent) } } }
apache-2.0
5aac7f47919ddbd01c87fed50416fca8
30.68
130
0.685209
3.896552
false
false
false
false
vanniktech/lint-rules
lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/ImplicitStringPlaceholderDetector.kt
1
1428
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE import com.android.tools.lint.detector.api.Severity.WARNING import com.android.tools.lint.detector.api.XmlContext import org.w3c.dom.Node val ISSUE_IMPLICIT_STRING_PLACEHOLDER = Issue.create( "ImplicitStringPlaceholder", "Marks implicit placeholders in strings without an index.", "It's better and more explicit to use numbered placeholders.", CORRECTNESS, PRIORITY, WARNING, Implementation(ImplicitStringPlaceholderDetector::class.java, RESOURCE_FILE_SCOPE), ) class ImplicitStringPlaceholderDetector : StringXmlDetector() { override fun checkText(context: XmlContext, node: Node, textNode: Node) { var index = 0 Regex("%s|%d").findAll(textNode.nodeValue).forEach { match -> val old = match.value val new = "%${++index}$" + match.value.last() val fix = fix().replace().name("Fix $old with $new").text(old).with(new).autoFix().build() context.report(ISSUE_IMPLICIT_STRING_PLACEHOLDER, node, context.getLocation(textNode, match.range.first, match.range.last + 1), "Implicit placeholder", fix) } } }
apache-2.0
d5a29de8a389bba02a8883f476be4f4f
45.064516
162
0.759104
3.787798
false
false
false
false
ex3ndr/telegram-tl
Builder/src/org/telegram/tl/builder/TLBuilder.kt
1
5196
package org.telegram.tl.builder import java.util.HashSet import java.util.ArrayList import java.util.HashMap /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 23.10.13 * Time: 8:28 */ /** * Support only for Vector generics */ fun checkType(t: TLType) { if (t is TLTypeGeneric) { if ((t as TLTypeGeneric).name != "Vector") throw RuntimeException("Only `Vector` generics are supported"); } } fun checkType(t: TLType, availableTypes: HashSet<String>) { if (t is TLTypeGeneric) { if (!availableTypes.contains(t.name)) { throw RuntimeException("Unknown `" + t.name + "` generic type"); } for (g in t.generics) { checkType(g, availableTypes) } } else if (t is TLTypeRaw) { if (!availableTypes.contains(t.name)) { throw RuntimeException("Unknown `" + t.name + "` type"); } } } fun checkDefinition(definition: TLDefinition) { // Checking supported types for (constr in definition.contructors) { if (constr.tlType is TLTypeGeneric) { throw RuntimeException("Generic types are not supported as custom types") } checkType(constr.tlType); for (p in constr.parameters) { checkType(p.tlType); } } // Type system constraints var availableTypes = HashSet<String>() for (builtIn in BuiltInTypes) { availableTypes.add(builtIn) } for (constr in definition.contructors) { if (constr.tlType is TLTypeRaw) { availableTypes.add((constr.tlType as TLTypeRaw).name); } } for (constr in definition.contructors) { for (p in constr.parameters) { checkType(p.tlType) } } for (constr in definition.methods) { for (p in constr.parameters) { checkType(p.tlType) } checkType(constr.tlType) } } fun getTypeReference(sourceType: TLType, types: HashMap<String, TLTypeDef>): TLTypeDef { return if (sourceType is TLTypeRaw) { var rawType = sourceType as TLTypeRaw if (BuiltInTypes.any {(x) -> rawType.name == x } ) { TLBuiltInTypeDef(rawType.name) } else { types.get(rawType.name)!! } } else if (sourceType is TLTypeAny) { TLAnyTypeDef() } else if (sourceType is TLTypeGeneric) { var generic = sourceType as TLTypeGeneric TLBuiltInGenericTypeDef(generic.name, getTypeReference(generic.generics.get(0), types)) } else if (sourceType is TLTypeFunctional) { TLFunctionalTypeDef() } else { throw RuntimeException("Unknown type") } } fun buildParameterDef(sourceType: TLParameter, types: HashMap<String, TLTypeDef>): TLParameterDef { return TLParameterDef(sourceType.name, getTypeReference(sourceType.tlType, types)) } fun buildModel(definition: TLDefinition): TLModel { var typeMap = HashMap<String, TLTypeDef>() // Prepopulate all types without constructors in combined types // to avoid issueses with references for (constr in definition.contructors) { if (constr.tlType is TLTypeGeneric) { throw RuntimeException("Generics are not supported as custom types"); } else if (constr.tlType is TLTypeRaw) { if (BuiltInTypes.any {(x) -> (constr.tlType as TLTypeRaw).name == x } ) { throw RuntimeException("Founed " + constr.toString() + " for built-in type"); } else { var rawType = constr.tlType as TLTypeRaw; if (!typeMap.containsKey(rawType.name)) { typeMap.put(rawType.name, TLCombinedTypeDef(rawType.name, ArrayList<TLConstructorDef>())) } } } else if (constr.tlType is TLTypeAny) { // When we create constructor without particular type typeMap.put(constr.name, TLAnonymousTypeDef(constr)) } else { throw RuntimeException("Functional arguments in constructors are not supported") } } // Fill all constructors for (constr in definition.contructors) { if (constr.tlType is TLTypeRaw) { var rawType = constr.tlType as TLTypeRaw; var typedef = typeMap.get(rawType.name) as TLCombinedTypeDef var paramDefs = ArrayList<TLParameterDef>() for (p in constr.parameters) { paramDefs.add(buildParameterDef(p, typeMap)) } var constrDef = TLConstructorDef(constr.name, constr.id, paramDefs) typedef.constructors.add(constrDef); } } var methods = ArrayList<TLMethodDef>() for (method in definition.methods) { var returnType = getTypeReference(method.tlType, typeMap) var paramDefs = ArrayList<TLParameterDef>() for (p in method.parameters) { paramDefs.add(buildParameterDef(p, typeMap)) } methods.add(TLMethodDef(method.name, method.id, paramDefs, returnType)) } return TLModel(typeMap.values().toList(), methods) }
mit
396c908bb8c544f88f482581cbb825a0
27.872222
109
0.606236
4.283594
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/ibl/SkyCubePass.kt
1
7639
package de.fabmax.kool.pipeline.ibl import de.fabmax.kool.math.Vec3f import de.fabmax.kool.math.clamp import de.fabmax.kool.math.toRad import de.fabmax.kool.modules.atmosphere.AtmosphereNode import de.fabmax.kool.modules.atmosphere.OpticalDepthLutPass import de.fabmax.kool.modules.atmosphere.RaySphereIntersectionNode import de.fabmax.kool.pipeline.* import de.fabmax.kool.pipeline.shadermodel.* import de.fabmax.kool.pipeline.shading.ModeledShader import de.fabmax.kool.pipeline.shading.PbrShader import de.fabmax.kool.pipeline.shading.pbrShader import de.fabmax.kool.scene.* import de.fabmax.kool.util.Color import de.fabmax.kool.util.ColorGradient import de.fabmax.kool.util.MdColor import de.fabmax.kool.util.MutableColor import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt class SkyCubePass(opticalDepthLut: Texture2d, size: Int = 256) : OffscreenRenderPassCube(Group(), renderPassConfig { name = "SkyCubePass" setSize(size, size) addColorTexture(TexFormat.RGBA_F16) clearDepthTexture() }) { val syncLights = mutableListOf<Light>() var azimuth = 0f set(value) { field = value isEnabled = true } var elevation = 60f set(value) { field = value.clamp(-90f, 90f) isEnabled = true } private val lightGradient = ColorGradient( -90f to Color.BLACK, -2f to Color.BLACK, 0f to MdColor.ORANGE.mix(Color.WHITE, 0.6f).toLinear().scale(0.7f), 5f to MdColor.AMBER.mix(Color.WHITE, 0.6f).toLinear(), 10f to Color.WHITE, 90f to Color.WHITE, ) private val sunLight = Light() .setDirectional(Vec3f(-1f, -1f, -1f)) .setColor(Color.WHITE, 3f) val groundShader: PbrShader private val skyShader = SkyShader(opticalDepthLut) init { lighting = Lighting().apply { lights.clear() lights += sunLight } groundShader = pbrShader { isHdrOutput = true useStaticAlbedo(MdColor.BROWN toneLin 500) roughness = 0.8f }.apply { ambient(nightSkyColor) } (drawNode as Group).apply { // sky +textureMesh { generate { icoSphere { steps = 2 } } shader = skyShader } // ground +colorMesh { generate { translate(0f, -0.011f, 0f) rotate(-90f, Vec3f.X_AXIS) circle { radius = 9f steps = 100 } } shader = groundShader } } onBeforeCollectDrawCommands += { updateSunLight() skyShader.atmoNode?.let { it.uDirToSun.value.set(sunLight.direction).scale(-1f) it.uSunColor.value.set(sunLight.color) it.uSunColor.value.a /= 3f } } onAfterDraw += { isEnabled = false } } private fun updateSunLight() { val phi = -azimuth.toRad() val theta = (PI.toFloat() / 2f) - elevation.toRad() sunLight.direction.z = -sin(theta) * cos(phi) sunLight.direction.x = -sin(theta) * sin(phi) sunLight.direction.y = -cos(theta) val syncColor = lightGradient.getColorInterpolated(elevation, MutableColor(), -90f, 90f) val strength = sqrt(syncColor.r * syncColor.r + syncColor.g * syncColor.g + syncColor.b * syncColor.b) for (light in syncLights) { light.setDirectional(sunLight.direction) light.setColor(syncColor, strength * sunLight.color.a) } } companion object { private val nightSkyColor = Color(0.02f, 0.07f, 0.15f).scaleRgb(1.5f, MutableColor()).toLinear() } private class SkyShader(opticalDepthLut: Texture2d) : ModeledShader(model()) { var atmoNode: AtmosphereNode? = null init { onPipelineSetup += { builder, _, _ -> builder.depthTest = DepthCompareOp.DISABLED builder.cullMethod = CullMethod.NO_CULLING } onPipelineCreated += { _, _, _ -> model.findNode<Texture2dNode>("tOpticalDepthLut")!!.sampler.texture = opticalDepthLut atmoNode = model.findNodeByType<AtmosphereNode>()!!.apply { uPlanetCenter.value.set(0f, -60f, 0f) uSurfaceRadius.value = 60f uAtmosphereRadius.value = 65f uScatteringCoeffs.value.set(0.274f, 1.536f, 3.859f) uRayleighColor.value.set(0.5f, 0.5f, 1.0f, 1.0f) uMieColor.value.set(1f, 0.35f, 0.35f, 0.5f) uMieG.value = 0.8f } } } companion object { fun model() = ShaderModel("sky-cube-shader").apply { val mvp: UniformBufferMvp val ifWorldPos: StageInterfaceNode vertexStage { mvp = mvpNode() val localPos = attrPositions().output val worldPos = vec3TransformNode(localPos, mvp.outModelMat, 1f).outVec3 ifWorldPos = stageInterfaceNode("ifFragPos", worldPos) positionOutput = vec4TransformNode(localPos, mvp.outMvpMat).outVec4 } fragmentStage { addNode(RaySphereIntersectionNode(stage)) val fragMvp = mvp.addToStage(stage) val opticalDepthLut = texture2dNode("tOpticalDepthLut") val viewDir = viewDirNode(fragMvp.outCamPos, ifWorldPos.output).output val atmoNd = addNode(AtmosphereNode(opticalDepthLut, stage)).apply { inSceneColor = constVec4f(nightSkyColor) inSkyColor = constVec4f(nightSkyColor) inScenePos = ifWorldPos.output inCamPos = fragMvp.outCamPos inLookDir = viewDir randomizeStartOffsets = false } colorOutput(atmoNd.outColor) } } } } } class SkyCubeIblSystem(val parentScene: Scene) { val opticalDepthLutPass = OpticalDepthLutPass() val skyPass = SkyCubePass(opticalDepthLutPass.colorTexture!!) val irradianceMapPass = IrradianceMapPass.irradianceMap(parentScene, skyPass.colorTexture!!, 8) val reflectionMapPass = ReflectionMapPass.reflectionMap(parentScene, skyPass.colorTexture!!, 128) val envMaps = EnvironmentMaps(irradianceMapPass.colorTexture!!, reflectionMapPass.colorTexture!!) var isAutoUpdateIblMaps = true init { irradianceMapPass.isAutoRemove = false reflectionMapPass.isAutoRemove = false skyPass.onAfterDraw += { if (isAutoUpdateIblMaps) { updateIblMaps() } } } fun updateIblMaps() { irradianceMapPass.isEnabled = true reflectionMapPass.isEnabled = true } fun setupOffscreenPasses() { parentScene.addOffscreenPass(opticalDepthLutPass) parentScene.addOffscreenPass(skyPass) parentScene.addOffscreenPass(irradianceMapPass) parentScene.addOffscreenPass(reflectionMapPass) } }
apache-2.0
d0bfde3fb8c5dfdbfcec05624fed165f
32.800885
110
0.573373
4.183461
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt
1
2694
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject import kotlin.math.ceil class DanaRS_Packet_Basal_Get_Temporary_Basal_State( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE aapsLogger.debug(LTag.PUMPCOMM, "Requesting temporary basal status") } override fun handleMessage(data: ByteArray) { val error = byteArrayToInt(getBytes(data, DATA_START, 1)) danaPump.isTempBasalInProgress = byteArrayToInt(getBytes(data, DATA_START + 1, 1)) == 0x01 val isAPSTempBasalInProgress = byteArrayToInt(getBytes(data, DATA_START + 1, 1)) == 0x02 danaPump.tempBasalPercent = byteArrayToInt(getBytes(data, DATA_START + 2, 1)) if (danaPump.tempBasalPercent > 200) danaPump.tempBasalPercent = (danaPump.tempBasalPercent - 200) * 10 val durationHour = byteArrayToInt(getBytes(data, DATA_START + 3, 1)) if (durationHour == 150) danaPump.tempBasalTotalSec = 15 * 60 else if (durationHour == 160) danaPump.tempBasalTotalSec = 30 * 60 else danaPump.tempBasalTotalSec = durationHour * 60 * 60 val runningMin = byteArrayToInt(getBytes(data, DATA_START + 4, 2)) if (error != 0) failed = true val tempBasalRemainingMin = (danaPump.tempBasalTotalSec - runningMin * 60) / 60 val tempBasalStart = if (danaPump.isTempBasalInProgress) getDateFromTempBasalSecAgo(runningMin * 60) else 0 aapsLogger.debug(LTag.PUMPCOMM, "Error code: $error") aapsLogger.debug(LTag.PUMPCOMM, "Is temp basal running: " + danaPump.isTempBasalInProgress) aapsLogger.debug(LTag.PUMPCOMM, "Is APS temp basal running: $isAPSTempBasalInProgress") aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal percent: " + danaPump.tempBasalPercent) aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal remaining min: $tempBasalRemainingMin") aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal total sec: " + danaPump.tempBasalTotalSec) aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + dateUtil.dateAndTimeString(tempBasalStart)) } override fun getFriendlyName(): String { return "BASAL__TEMPORARY_BASAL_STATE" } private fun getDateFromTempBasalSecAgo(tempBasalAgoSecs: Int): Long { return (ceil(System.currentTimeMillis() / 1000.0) - tempBasalAgoSecs).toLong() * 1000 } }
agpl-3.0
49e4b01f1fafcf03d54b9ba3bbd49d0b
54
193
0.730883
4.24252
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ExtensionFieldEntityToParent.kt
1
2753
package com.intellij.workspaceModel.storage.entities.test.api import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface MainEntityToParent : WorkspaceEntity { val child: @Child AttachedEntityToParent? val x: String //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: MainEntityToParent, ModifiableWorkspaceEntity<MainEntityToParent>, ObjBuilder<MainEntityToParent> { override var child: AttachedEntityToParent? override var entitySource: EntitySource override var x: String } companion object: Type<MainEntityToParent, Builder>() { operator fun invoke(x: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): MainEntityToParent { val builder = builder() builder.entitySource = entitySource builder.x = x init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: MainEntityToParent, modification: MainEntityToParent.Builder.() -> Unit) = modifyEntity(MainEntityToParent.Builder::class.java, entity, modification) //endregion interface AttachedEntityToParent : WorkspaceEntity { val data: String //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: AttachedEntityToParent, ModifiableWorkspaceEntity<AttachedEntityToParent>, ObjBuilder<AttachedEntityToParent> { override var data: String override var entitySource: EntitySource } companion object: Type<AttachedEntityToParent, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): AttachedEntityToParent { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: AttachedEntityToParent, modification: AttachedEntityToParent.Builder.() -> Unit) = modifyEntity(AttachedEntityToParent.Builder::class.java, entity, modification) var AttachedEntityToParent.Builder.ref: MainEntityToParent by WorkspaceEntity.extension() //endregion val AttachedEntityToParent.ref: MainEntityToParent by WorkspaceEntity.extension()
apache-2.0
c2bfe77301b71f5ee33d7a846a2315bc
34.294872
207
0.761351
5.356031
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/Farmer.kt
1
2178
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import org.joda.time.DateTime /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ class Farmer(foodStorage: IResourceStorage, flows: MutableList<ResourceFlow>, val maxDaysWithoutFood: Int, dailyPotatoConsumption: Double) : IAgent, IHuman { override fun init() { } override fun id(): String = "Farmer" val actions = listOf<IAction>( EatingAction( this, foodStorage, flows, dailyPotatoConsumption ) ) var daysWithoutFood : Int = 0 var alive: Boolean = true get private set override fun eat() { this.daysWithoutFood = 0 } override fun hungerOneDay() { this.daysWithoutFood++ if (this.daysWithoutFood > maxDaysWithoutFood) { die() } } override fun die() { alive = false } override fun act(time: DateTime) { actions .filter { x -> x.timeToRun(time) } .forEach { x -> x.run(time) } } }
gpl-3.0
cd847865dd553e64a7f968c946bbbffb
25.225
72
0.598255
4.172414
false
false
false
false
idea4bsd/idea4bsd
platform/configuration-store-impl/src/FileBasedStorage.kt
3
10436
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.StorageUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.LineSeparator import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.readChars import com.intellij.util.io.systemIndependentPath import com.intellij.util.loadElement import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import java.io.IOException import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.attribute.BasicFileAttributes open class FileBasedStorage(file: Path, fileSpec: String, rootElementName: String?, pathMacroManager: TrackingPathMacroSubstitutor? = null, roamingType: RoamingType? = null, provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) { private @Volatile var cachedVirtualFile: VirtualFile? = null private var lineSeparator: LineSeparator? = null private var blockSavingTheContent = false @Volatile var file = file private set init { if (ApplicationManager.getApplication().isUnitTestMode && file.toString().startsWith('$')) { throw AssertionError("It seems like some macros were not expanded for path: $file") } } protected open val isUseXmlProlog: Boolean = false // we never set io file to null fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) { cachedVirtualFile = virtualFile if (ioFileIfChanged != null) { file = ioFileIfChanged } } override fun createSaveSession(states: StateMap) = FileSaveSession(states, this) protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) { override fun save() { if (!storage.blockSavingTheContent) { super.save() } } override fun saveLocally(element: Element?) { if (storage.lineSeparator == null) { storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator() } val virtualFile = storage.virtualFile if (element == null) { deleteFile(storage.file, this, virtualFile) storage.cachedVirtualFile = null } else { storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog) } } } val virtualFile: VirtualFile? get() { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(file.systemIndependentPath) cachedVirtualFile = result } return cachedVirtualFile } override fun loadLocalData(): Element? { blockSavingTheContent = false val attributes: BasicFileAttributes? try { attributes = Files.readAttributes(file, BasicFileAttributes::class.java) } catch (e: NoSuchFileException) { return null } catch (e: IOException) { processReadException(e) return null } try { if (!attributes.isRegularFile) { LOG.debug { "Document was not loaded for $fileSpec, not a file" } } else if (attributes.size() == 0L) { processReadException(null) } else { val data = file.readChars() lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF) return loadElement(data) } } catch (e: JDOMException) { processReadException(e) } catch (e: IOException) { processReadException(e) } return null } private fun processReadException(e: Exception?) { val contentTruncated = e == null blockSavingTheContent = !contentTruncated && (PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE) if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) { if (e != null) { LOG.info(e) } Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.message}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING) .notify(null) } } override fun toString() = file.systemIndependentPath } fun writeFile(file: Path?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile { val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) { StorageUtil.getOrCreateVirtualFile(requestor, file) } else { virtualFile!! } if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) { val content = element.toBufferExposingByteArray(lineSeparator.separatorString) if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) { throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}") } else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) { StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------" } } doWrite(requestor, result, element, lineSeparator, prependXmlProlog) return result } private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray() private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean { val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size if (result.length.toInt() != (headerLength + content.size())) { return false } val oldContent = result.contentsToByteArray() if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) { return false } for (i in headerLength..oldContent.size - 1) { if (oldContent[i] != content.internalBuffer[i - headerLength]) { return false } } return true } private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) { LOG.debug { "Save ${file.presentableUrl}" } if (!file.isWritable) { // may be element is not long-lived, so, we must write it to byte array val byteArray = if (content is Element) content.toBufferExposingByteArray(lineSeparator.separatorString) else (content as BufferExposingByteArrayOutputStream) throw ReadOnlyModificationException(file, StateStorage.SaveSession { doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog) }) } runWriteAction { file.getOutputStream(requestor).use { out -> if (prependXmlProlog) { out.write(XML_PROLOG) out.write(lineSeparator.separatorBytes) } if (content is Element) { JDOMUtil.writeParent(content, out, lineSeparator.separatorString) } else { (content as BufferExposingByteArrayOutputStream).writeTo(out) } } } } internal fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.writeParent(this, out, lineSeparator) return out } internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator { for (c in chars) { if (c == '\r') { return LineSeparator.CRLF } else if (c == '\n') { // if we are here, there was no \r before return LineSeparator.LF } } return defaultSeparator ?: LineSeparator.getSystemLineSeparator() } private fun deleteFile(file: Path, requestor: Any, virtualFile: VirtualFile?) { if (virtualFile == null) { LOG.warn("Cannot find virtual file $file") } if (virtualFile == null) { if (file.exists()) { file.delete() } } else if (virtualFile.exists()) { if (virtualFile.isWritable) { deleteFile(requestor, virtualFile) } else { throw ReadOnlyModificationException(virtualFile, StateStorage.SaveSession { deleteFile(requestor, virtualFile) }) } } } fun deleteFile(requestor: Any, virtualFile: VirtualFile) { runWriteAction { virtualFile.delete(requestor) } } internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException("File is read-only: "+file)
apache-2.0
5d46123d1a7f3783859ca6e76c15aa19
36.142349
215
0.719049
4.802577
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/log/GitCommitSignature.kt
1
3032
// 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 git4idea.log import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.runUnderIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsLogObjectsFactory import git4idea.GitVcs import git4idea.commands.Git import git4idea.history.GitLogUtil import git4idea.history.GitLogUtil.createGitHandler import git4idea.history.GitLogUtil.sendHashesToStdin import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext internal sealed class GitCommitSignature { object NoSignature : GitCommitSignature() class Verified(val user: @NlsSafe String, val fingerprint: @NlsSafe String) : GitCommitSignature() object NotVerified : GitCommitSignature() } private const val NEW_LINE = "%n" private const val HASH = "%H" private const val SIGNATURE_STATUS = "%G?" private const val SIGNER = "%GS" private const val FINGERPRINT = "%GF" private val COMMIT_SIGNATURES_FORMAT = listOf(HASH, SIGNATURE_STATUS, SIGNER, FINGERPRINT).joinToString(NEW_LINE) @Throws(VcsException::class) internal suspend fun loadCommitSignatures( project: Project, root: VirtualFile, commits: Collection<Hash> ): Map<Hash, GitCommitSignature> { val vcs = GitVcs.getInstance(project) val h = createGitHandler(project, root) h.setStdoutSuppressed(true) h.addParameters(GitLogUtil.getNoWalkParameter(vcs)) h.addParameters("--format=$COMMIT_SIGNATURES_FORMAT") h.addParameters(GitLogUtil.STDIN) h.endOptions() sendHashesToStdin(commits.map { it.asString() }, h) val output = withContext(Dispatchers.IO) { runUnderIndicator { Git.getInstance().runCommand(h).getOutputOrThrow() } } return parseSignatures(project, output.lineSequence()) } private fun parseSignatures(project: Project, lines: Sequence<String>): Map<Hash, GitCommitSignature> { val factory = project.service<VcsLogObjectsFactory>() val result = mutableMapOf<Hash, GitCommitSignature>() val iterator = lines.iterator() while (iterator.hasNext()) { val hash = factory.createHash(iterator.next()) val signature = createSignature(status = iterator.next(), signer = iterator.next(), fingerprint = iterator.next()) signature?.let { result[hash] = it } } return result } private fun createSignature(status: String, signer: String, fingerprint: String): GitCommitSignature? = when (status) { "B", "E" -> GitCommitSignature.NotVerified "G", "U", "X", "Y", "R" -> GitCommitSignature.Verified(signer, fingerprint) "N" -> null else -> null.also { LOG.error("Unknown signature status $status") } } private val LOG = logger<GitCommitSignatureLoader>() private object GitCommitSignatureLoader
apache-2.0
131bf2cfe53e652b1a004b5de4aca234
34.682353
158
0.769789
4.075269
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ScratchFileAutoRunner.kt
1
3207
// 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.scratch import com.intellij.openapi.Disposable import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Alarm import org.jetbrains.kotlin.idea.scratch.actions.RunScratchAction import org.jetbrains.kotlin.idea.scratch.actions.RunScratchFromHereAction import org.jetbrains.kotlin.idea.scratch.actions.ScratchCompilationSupport import org.jetbrains.kotlin.idea.scratch.ui.findScratchFileEditorWithPreview import org.jetbrains.kotlin.idea.util.application.getServiceSafe class ScratchFileAutoRunner(private val project: Project) : DocumentListener, Disposable { companion object { fun addListener(project: Project, editor: TextEditor) { if (editor.getScratchFile() != null) { editor.editor.document.addDocumentListener(getInstance(project)) Disposer.register(editor, Disposable { editor.editor.document.removeDocumentListener(getInstance(project)) }) } } private fun getInstance(project: Project): ScratchFileAutoRunner = project.getServiceSafe() const val AUTO_RUN_DELAY_IN_SECONDS = 2 } private val myAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this) override fun documentChanged(event: DocumentEvent) { val file = FileDocumentManager.getInstance().getFile(event.document) ?: return if (Disposer.isDisposed(this)) return val scratchFile = getScratchFile(file, project) ?: return if (!scratchFile.options.isInteractiveMode) return if (event.newFragment.isNotBlank()) { runScratch(scratchFile) } } private fun runScratch(scratchFile: ScratchFile) { myAlarm.cancelAllRequests() if (ScratchCompilationSupport.isInProgress(scratchFile) && !scratchFile.options.isRepl) { ScratchCompilationSupport.forceStop() } myAlarm.addRequest( { scratchFile.ktScratchFile?.takeIf { it.isValid && !scratchFile.hasErrors() }?.let { if (scratchFile.options.isRepl) { RunScratchFromHereAction.doAction(scratchFile) } else { RunScratchAction.doAction(scratchFile, true) } } }, AUTO_RUN_DELAY_IN_SECONDS * 1000, true ) } private fun getScratchFile(file: VirtualFile, project: Project): ScratchFile? { val editor = FileEditorManager.getInstance(project).getSelectedEditor(file) as? TextEditor return editor?.findScratchFileEditorWithPreview()?.scratchFile } override fun dispose() { } }
apache-2.0
be91634f714afbedff32c5d327350806
39.1
158
0.700967
4.896183
false
false
false
false
sandipv22/pointer_replacer
allusive/src/main/java/com/afterroot/allusive2/ui/fragment/NewPointerPost.kt
1
13644
/* * Copyright (C) 2016-2021 Sandip Vaghela * 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.afterroot.allusive2.ui.fragment import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.afollestad.materialdialogs.MaterialDialog import com.afterroot.allusive2.BuildConfig import com.afterroot.allusive2.Constants.RC_PICK_IMAGE import com.afterroot.allusive2.R import com.afterroot.allusive2.database.DatabaseFields import com.afterroot.allusive2.databinding.FragmentNewPointerPostBinding import com.afterroot.allusive2.model.Pointer import com.afterroot.allusive2.utils.FirebaseUtils import com.afterroot.allusive2.utils.whenBuildIs import com.afterroot.allusive2.viewmodel.MainSharedViewModel import com.afterroot.core.extensions.getAsBitmap import com.afterroot.core.extensions.getDrawableExt import com.afterroot.core.extensions.showStaticProgressDialog import com.afterroot.core.extensions.updateProgressText import com.bumptech.glide.Glide import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.rewarded.RewardedAd import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import com.google.firebase.Timestamp import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.storage.FirebaseStorage import org.jetbrains.anko.find import org.koin.android.ext.android.inject import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException class NewPointerPost : Fragment() { private lateinit var binding: FragmentNewPointerPostBinding private lateinit var rewardedAd: RewardedAd private val db: FirebaseFirestore by inject() private val pointerDescription: String get() = binding.editDesc.text.toString().trim() private val pointerName: String get() = binding.editName.text.toString().trim() private val remoteConfig: FirebaseRemoteConfig by inject() private val sharedViewModel: MainSharedViewModel by activityViewModels() private val storage: FirebaseStorage by inject() private var adLoaded: Boolean = false private var clickedUpload: Boolean = false private var isPointerImported = false private val firebaseUtils: FirebaseUtils by inject() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentNewPointerPostBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.actionUpload.setOnClickListener { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/png" } val pickIntent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI).apply { type = "image/png" } val chooserIntent = Intent.createChooser(intent, "Choose Pointer Image").apply { putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickIntent)) } // FIXME update method https://developer.android.com/training/basics/intents/result#kotlin startActivityForResult(chooserIntent, RC_PICK_IMAGE) } initFirebaseConfig() } private fun initFirebaseConfig() { remoteConfig.fetchAndActivate().addOnCompleteListener { result -> kotlin.runCatching { // Load Banner Ad val adView = AdView(requireContext()) adView.apply { adSize = AdSize.BANNER adUnitId = if (BuildConfig.DEBUG || (!result.isSuccessful && BuildConfig.DEBUG)) { getString(R.string.ad_banner_new_pointer) } else remoteConfig.getString("ad_banner_new_pointer") binding.adContainer.addView(this) loadAd(AdRequest.Builder().build()) } if (result.isSuccessful) { if (remoteConfig.getBoolean("FLAG_ENABLE_REWARDED_ADS")) { setUpRewardedAd() requireActivity().find<ExtendedFloatingActionButton>(R.id.fab_apply).apply { setOnClickListener { if (verifyData()) { clickedUpload = true MaterialDialog(requireContext()).show { title(R.string.text_action_upload) message(R.string.dialog_msg_rewarded_ad) positiveButton(android.R.string.ok) { /* if (rewardedAd.isLoaded) { showAd() } else { sharedViewModel.displayMsg("Ad is not loaded yet. Loading...") } */ } negativeButton(R.string.fui_cancel) } } } icon = requireContext().getDrawableExt(R.drawable.ic_action_apply) } } else { setFabAsDirectUpload() } } else { setFabAsDirectUpload() } } } } private fun setFabAsDirectUpload() { requireActivity().find<ExtendedFloatingActionButton>(R.id.fab_apply).apply { setOnClickListener { if (verifyData()) { upload(saveTmpPointer()) } } icon = requireContext().getDrawableExt(R.drawable.ic_action_apply) } } private fun showAd() { // TODO Rewrite logic rewardedAd.setOnPaidEventListener { } /* val adCallback = object : RewardedAdCallback() { override fun onUserEarnedReward(p0: RewardItem) { clickedUpload = false if (verifyData()) { upload(saveTmpPointer()) } } override fun onRewardedAdClosed() { super.onRewardedAdClosed() setUpRewardedAd() } } */ } private fun createAndLoadRewardedAd() { val adUnitId = whenBuildIs( debug = getString(R.string.ad_rewarded_1_id), release = remoteConfig.getString("ad_rewarded_1_id") ) val adLoadCallback = object : RewardedAdLoadCallback() { override fun onAdLoaded(ad: RewardedAd) { super.onAdLoaded(ad) adLoaded = true rewardedAd = ad if (clickedUpload) { showAd() } } override fun onAdFailedToLoad(p0: LoadAdError) { super.onAdFailedToLoad(p0) adLoaded = false } } RewardedAd.load(requireContext(), adUnitId, AdRequest.Builder().build(), adLoadCallback) } private fun setUpRewardedAd() { kotlin.runCatching { createAndLoadRewardedAd() } } // Handle retrieved image uri override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_PICK_IMAGE && resultCode == Activity.RESULT_OK) { isPointerImported = true data?.data?.also { uri -> Glide.with(this).load(uri).override(128, 128).centerCrop().into(binding.pointerThumb) binding.pointerThumb.background = context?.getDrawableExt(R.drawable.transparent_grid) } } } private fun upload(file: File) { val dialog = requireContext().showStaticProgressDialog(getString(R.string.text_progress_init)) val storageRef = storage.reference val fileUri = Uri.fromFile(file) val fileRef = storageRef.child("${DatabaseFields.COLLECTION_POINTERS}/${fileUri.lastPathSegment!!}") val uploadTask = fileRef.putFile(fileUri) uploadTask.addOnProgressListener { val progress = "${(100 * it.bytesTransferred) / it.totalByteCount}%" dialog.updateProgressText(String.format("%s..%s", getString(R.string.text_progress_uploading), progress)) }.addOnCompleteListener { task -> val map = hashMapOf<String, String>() map[firebaseUtils.uid!!] = firebaseUtils.firebaseUser?.displayName.toString() if (task.isSuccessful) { dialog.updateProgressText(getString(R.string.text_progress_finishing_up)) val pointer = Pointer( name = pointerName, filename = fileUri.lastPathSegment!!, description = pointerDescription, uploadedBy = map, time = Timestamp.now().toDate() ) Log.d(TAG, "upload: $pointer") db.collection(DatabaseFields.COLLECTION_POINTERS).add(pointer).addOnSuccessListener { requireActivity().apply { sharedViewModel.displayMsg(getString(R.string.msg_pointer_upload_success)) dialog.dismiss() findNavController().navigateUp() } }.addOnFailureListener { sharedViewModel.displayMsg(getString(R.string.msg_error)) } } }.addOnFailureListener { binding.pointerThumb.background = context?.getDrawableExt(R.drawable.transparent_grid) sharedViewModel.displayMsg(getString(R.string.msg_error)) } } /** * @throws IOException exception */ @Throws(IOException::class) private fun saveTmpPointer(): File { binding.pointerThumb.background = null val bitmap = binding.pointerThumb.getAsBitmap() val file = File.createTempFile("pointer", ".png", requireContext().cacheDir) val out: FileOutputStream try { out = FileOutputStream(file) bitmap?.compress(Bitmap.CompressFormat.PNG, 100, out) out.flush() out.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (iae: IllegalArgumentException) { iae.printStackTrace() } return file } private fun verifyData(): Boolean { var isOK = true binding.apply { if (pointerName.isEmpty()) { setListener(editName, inputName) setError(inputName) isOK = false } if (pointerDescription.length >= inputDesc.counterMaxLength) { setListener(editDesc, inputDesc) inputDesc.error = "Maximum Characters" isOK = false } if (!isPointerImported) { sharedViewModel.displayMsg(getString(R.string.msg_pointer_not_imported)) isOK = false } } return isOK } private fun setError(inputLayoutView: TextInputLayout) { inputLayoutView.apply { isErrorEnabled = true error = String.format(getString(R.string.format_text_empty_error), inputLayoutView.hint) } } private fun setListener(editTextView: TextInputEditText, inputLayoutView: TextInputLayout) { editTextView.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { inputLayoutView.isErrorEnabled = false } }) } companion object { private const val TAG = "NewPointerPost" } }
apache-2.0
447aca5a8b17eef4174216f0c88c8028
39.366864
117
0.60796
5.133183
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/LibraryDependencyCandidate.kt
2
1849
// 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.caches.project import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.IntellijInternalApi import org.jetbrains.kotlin.idea.klib.AbstractKlibLibraryInfo import org.jetbrains.kotlin.platform.TargetPlatform @IntellijInternalApi sealed class LibraryDependencyCandidate { abstract val platform: TargetPlatform abstract val libraries: List<LibraryInfo> companion object { fun fromLibraryOrNull(project: Project, library: Library): LibraryDependencyCandidate? { val libraryInfos = createLibraryInfo(project, library) val libraryInfo = libraryInfos.firstOrNull() ?: return null if(libraryInfo is AbstractKlibLibraryInfo) { return KlibLibraryDependencyCandidate( platform = libraryInfo.platform, libraries = libraryInfos, uniqueName = libraryInfo.uniqueName, isInterop = libraryInfo.isInterop ) } return DefaultLibraryDependencyCandidate( platform = libraryInfo.platform, libraries = libraryInfos ) } } } @IntellijInternalApi data class DefaultLibraryDependencyCandidate( override val platform: TargetPlatform, override val libraries: List<LibraryInfo> ): LibraryDependencyCandidate() @IntellijInternalApi data class KlibLibraryDependencyCandidate( override val platform: TargetPlatform, override val libraries: List<LibraryInfo>, val uniqueName: String?, val isInterop: Boolean ): LibraryDependencyCandidate()
apache-2.0
76904092d3e6ff1f113ff1a29c36c5be
35.98
158
0.711736
5.637195
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/find/usages/impl/impl.kt
2
3728
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.find.usages.impl import com.intellij.find.usages.api.* import com.intellij.find.usages.symbol.SearchTargetSymbol import com.intellij.find.usages.symbol.SymbolSearchTargetFactory import com.intellij.model.Pointer import com.intellij.model.Symbol import com.intellij.model.psi.impl.targetSymbols import com.intellij.model.search.SearchContext import com.intellij.model.search.SearchService import com.intellij.model.search.impl.buildTextUsageQuery import com.intellij.openapi.project.Project import com.intellij.openapi.util.ClassExtension import com.intellij.psi.PsiFile import com.intellij.psi.search.SearchScope import com.intellij.util.Query import org.jetbrains.annotations.ApiStatus import java.util.* import com.intellij.usages.Usage as UVUsage @ApiStatus.Internal fun searchTargets(file: PsiFile, offset: Int): List<SearchTarget> { val targetSymbols = targetSymbols(file, offset) if (targetSymbols.isEmpty()) { return emptyList() } return symbolSearchTargets(file.project, targetSymbols) } internal fun symbolSearchTargets(project: Project, targetSymbols: Collection<Symbol>): List<SearchTarget> { return targetSymbols.mapNotNullTo(LinkedHashSet()) { symbolSearchTarget(project, it) }.toList() } private val SYMBOL_SEARCH_TARGET_EXTENSION = ClassExtension<SymbolSearchTargetFactory<*>>("com.intellij.lang.symbolSearchTarget") @ApiStatus.Internal fun symbolSearchTarget(project: Project, symbol: Symbol): SearchTarget? { for (factory in SYMBOL_SEARCH_TARGET_EXTENSION.forKey(symbol.javaClass)) { @Suppress("UNCHECKED_CAST") val factory_ = factory as SymbolSearchTargetFactory<Symbol> val target = factory_.searchTarget(project, symbol) if (target != null) { return target } } if (symbol is SearchTargetSymbol) { return symbol.searchTarget } if (symbol is SearchTarget) { return symbol } return null } @ApiStatus.Internal fun buildUsageViewQuery( project: Project, target: SearchTarget, allOptions: AllSearchOptions, ): Query<out UVUsage> { return buildQuery(project, target, allOptions).transforming { if (it is PsiUsage && !it.declaration) { listOf(Psi2UsageInfo2UsageAdapter(PsiUsage2UsageInfo(it))) } else { emptyList() } } } @ApiStatus.Internal fun buildQuery( project: Project, target: SearchTarget, allOptions: AllSearchOptions, ): Query<out Usage> { val queries = ArrayList<Query<out Usage>>() val (options, textSearch) = allOptions if (options.isUsages) { queries += SearchService.getInstance().searchParameters(DefaultUsageSearchParameters(project, target, options.searchScope)) } if (textSearch == true) { target.textSearchRequests.mapTo(queries) { searchRequest -> buildTextUsageQuery(project, searchRequest, options.searchScope, textSearchContexts).mapping(::PlainTextUsage) } } return SearchService.getInstance().merge(queries) } private class DefaultUsageSearchParameters( private val project: Project, target: SearchTarget, override val searchScope: SearchScope ) : UsageSearchParameters { private val pointer: Pointer<out SearchTarget> = target.createPointer() override fun areValid(): Boolean = pointer.dereference() != null override fun getProject(): Project = project override val target: SearchTarget get() = requireNotNull(pointer.dereference()) } private val textSearchContexts: Set<SearchContext> = EnumSet.of( SearchContext.IN_COMMENTS, SearchContext.IN_STRINGS, SearchContext.IN_PLAIN_TEXT ) internal fun SearchTarget.hasTextSearchStrings(): Boolean = textSearchRequests.isNotEmpty()
apache-2.0
d26720696f65aa40387b2b07a0fbe163
33.201835
129
0.771727
4.151448
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/util/ExternalProjectUiUtil.kt
8
4484
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.externalSystem.dependency.analyzer.util import com.intellij.ide.plugins.newui.HorizontalLayout import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerProject import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.observable.util.bind import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.observable.util.whenItemSelected import com.intellij.openapi.observable.util.whenMousePressed import com.intellij.ui.ListUtil import com.intellij.ui.components.DropDownLink import com.intellij.ui.components.JBList import com.intellij.util.ui.JBUI import java.awt.Component import javax.swing.* internal class ExternalProjectSelector( property: ObservableMutableProperty<DependencyAnalyzerProject?>, externalProjects: List<DependencyAnalyzerProject>, private val iconProvider: ExternalSystemIconProvider ) : JPanel() { init { val dropDownLink = ExternalProjectDropDownLink(property, externalProjects) .apply { border = JBUI.Borders.empty(BORDER, ICON_TEXT_GAP / 2, BORDER, BORDER) } val label = JLabel(iconProvider.projectIcon) .apply { border = JBUI.Borders.empty(BORDER, BORDER, BORDER, ICON_TEXT_GAP / 2) } .apply { labelFor = dropDownLink } layout = HorizontalLayout(0) border = JBUI.Borders.empty() add(label) add(dropDownLink) } private fun createPopup(externalProjects: List<DependencyAnalyzerProject>, onChange: (DependencyAnalyzerProject) -> Unit): JBPopup { val content = ExternalProjectPopupContent(externalProjects) .apply { whenMousePressed { onChange(selectedValue) } } return JBPopupFactory.getInstance() .createComponentPopupBuilder(content, null) .createPopup() .apply { content.whenMousePressed(listener = ::closeOk) } } private inner class ExternalProjectPopupContent(externalProject: List<DependencyAnalyzerProject>) : JBList<DependencyAnalyzerProject>() { init { model = createDefaultListModel(externalProject) border = emptyListBorder() cellRenderer = ExternalProjectRenderer() selectionMode = ListSelectionModel.SINGLE_SELECTION ListUtil.installAutoSelectOnMouseMove(this) setupListPopupPreferredWidth(this) } } private inner class ExternalProjectRenderer : ListCellRenderer<DependencyAnalyzerProject?> { override fun getListCellRendererComponent( list: JList<out DependencyAnalyzerProject?>, value: DependencyAnalyzerProject?, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { return JLabel() .apply { if (value != null) icon = iconProvider.projectIcon } .apply { if (value != null) text = value.title } .apply { border = emptyListCellBorder(list, index) } .apply { iconTextGap = JBUI.scale(ICON_TEXT_GAP) } .apply { background = if (isSelected) list.selectionBackground else list.background } .apply { foreground = if (isSelected) list.selectionForeground else list.foreground } .apply { isOpaque = true } .apply { isEnabled = list.isEnabled } .apply { font = list.font } } } private inner class ExternalProjectDropDownLink( property: ObservableMutableProperty<DependencyAnalyzerProject?>, externalProjects: List<DependencyAnalyzerProject>, ) : DropDownLink<DependencyAnalyzerProject?>( property.get(), { createPopup(externalProjects, it::selectedItem.setter) } ) { override fun popupPoint() = super.popupPoint() .apply { x += insets.left } .apply { x -= JBUI.scale(BORDER) } .apply { x -= iconProvider.projectIcon.iconWidth } .apply { x -= JBUI.scale(ICON_TEXT_GAP) } override fun itemToString(item: DependencyAnalyzerProject?): String = when (item) { null -> ExternalSystemBundle.message("external.system.dependency.analyzer.projects.empty") else -> item.title } init { autoHideOnDisable = false foreground = JBUI.CurrentTheme.Label.foreground() whenItemSelected { text = itemToString(selectedItem) } bind(property) } } }
apache-2.0
3561fcb588ec63698dddf1d943588dff
40.137615
139
0.737957
4.755037
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/statistics/src/org/jetbrains/kotlin/idea/statistics/WizardStatsService.kt
2
16149
// 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.statistics import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.StringListEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin import kotlin.math.abs import kotlin.random.Random interface WizardStats { fun toPairs(): ArrayList<EventPair<*>> } class WizardStatsService : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { // Collector ID private val GROUP = EventLogGroup("kotlin.ide.new.project", 10) // Whitelisted values for the events fields private val allowedProjectTemplates = listOf( // Modules "JVM_|_IDEA", "JS_|_IDEA", // Java and Gradle groups "Kotlin/JVM", // Gradle group "Kotlin/JS", "Kotlin/JS_for_browser", "Kotlin/JS_for_Node.js", "Kotlin/Multiplatform_as_framework", "Kotlin/Multiplatform", // Kotlin group "backendApplication", "consoleApplication", "multiplatformMobileApplication", "multiplatformMobileLibrary", "multiplatformApplication", "multiplatformLibrary", "nativeApplication", "frontendApplication", "fullStackWebApplication", "nodejsApplication", "reactApplication", "none", // AppCode KMM "multiplatformMobileApplicationUsingAppleGradlePlugin", "multiplatformMobileApplicationUsingHybridProject", ) private val allowedModuleTemplates = listOf( "consoleJvmApp", "ktorServer", "mobileMppModule", "nativeConsoleApp", "reactJsClient", "simpleJsClient", "simpleNodeJs", "none", ) private val allowedWizardsGroups = listOf("Java", "Kotlin", "Gradle") private val allowedBuildSystems = listOf( "gradleKotlin", "gradleGroovy", "jps", "maven" ) private val settings = Settings( SettingIdWithPossibleValues.Enum( id = "buildSystem.type", values = listOf( "GradleKotlinDsl", "GradleGroovyDsl", "Jps", "Maven", ) ), SettingIdWithPossibleValues.Enum( id = "testFramework", values = listOf( "NONE", "JUNIT4", "JUNIT5", "TEST_NG", "JS", "COMMON", ) ), SettingIdWithPossibleValues.Enum( id = "targetJvmVersion", values = listOf( "JVM_1_6", "JVM_1_8", "JVM_9", "JVM_10", "JVM_11", "JVM_12", "JVM_13", ) ), SettingIdWithPossibleValues.Enum( id = "androidPlugin", values = listOf( "APPLICATION", "LIBRARY", ) ), SettingIdWithPossibleValues.Enum( id = "serverEngine", values = listOf( "Netty", "Tomcat", "Jetty", ) ), SettingIdWithPossibleValues.Enum( id = "kind", idToLog = "js.project.kind", values = listOf( "LIBRARY", "APPLICATION", ) ), SettingIdWithPossibleValues.Enum( id = "compiler", idToLog = "js.compiler", values = listOf( "IR", "LEGACY", "BOTH", ) ), SettingIdWithPossibleValues.Enum( id = "projectTemplates.template", values = allowedProjectTemplates ), SettingIdWithPossibleValues.Enum( id = "module.template", values = allowedModuleTemplates ), SettingIdWithPossibleValues.Enum( id = "buildSystem.type", values = allowedBuildSystems ), SettingIdWithPossibleValues.Boolean( id = "javaSupport", idToLog = "jvm.javaSupport" ), SettingIdWithPossibleValues.Boolean( id = "cssSupport", idToLog = "js.cssSupport" ), SettingIdWithPossibleValues.Boolean( id = "useReactRouterDom", idToLog = "js.useReactRouterDom" ), SettingIdWithPossibleValues.Boolean( id = "useReactRedux", idToLog = "js.useReactRedux" ), ) private val allowedModuleTypes = listOf( "androidNativeArm32Target", "androidNativeArm64Target", "iosArm32Target", "iosArm64Target", "iosX64Target", "iosTarget", "linuxArm32HfpTarget", "linuxMips32Target", "linuxMipsel32Target", "linuxX64Target", "macosX64Target", "mingwX64Target", "mingwX86Target", "nativeForCurrentSystem", "jsBrowser", "jsNode", "commonTarget", "jvmTarget", "androidTarget", "multiplatform", "JVM_Module", "android", "IOS_Module", "jsBrowserSinglePlatform", "jsNodeSinglePlatform", ) private val settingIdField = EventFields.String("setting_id", settings.allowedIds) private val settingValueField = EventFields.String("setting_value", settings.possibleValues) // Event fields val groupField = EventFields.String("group", allowedWizardsGroups) val projectTemplateField = EventFields.String("project_template", allowedProjectTemplates) val buildSystemField = EventFields.String("build_system", allowedBuildSystems) val modulesCreatedField = EventFields.Int("modules_created") val modulesRemovedField = EventFields.Int("modules_removed") val moduleTemplateChangedField = EventFields.Int("module_template_changed") private val moduleTemplateField = EventFields.String("module_template", allowedModuleTemplates) private val sessionIdField = EventFields.Int("session_id") val modulesListField = StringListEventField.ValidatedByAllowedValues("project_modules_list", allowedModuleTypes) private val moduleTypeField = EventFields.String("module_type", allowedModuleTypes) private val pluginInfoField = EventFields.PluginInfo.with(getPluginInfoById(KotlinIdePlugin.id)) // Events private val projectCreatedEvent = GROUP.registerVarargEvent( "project_created", groupField, projectTemplateField, buildSystemField, modulesCreatedField, modulesRemovedField, moduleTemplateChangedField, modulesListField, sessionIdField, EventFields.PluginInfo ) private val projectOpenedByHyperlinkEvent = GROUP.registerVarargEvent( "wizard_opened_by_hyperlink", projectTemplateField, sessionIdField, EventFields.PluginInfo ) private val moduleTemplateCreatedEvent = GROUP.registerVarargEvent( "module_template_created", projectTemplateField, moduleTemplateField, sessionIdField, EventFields.PluginInfo ) private val settingValueChangedEvent = GROUP.registerVarargEvent( "setting_value_changed", settingIdField, settingValueField, sessionIdField, EventFields.PluginInfo, ) private val jdkChangedEvent = GROUP.registerVarargEvent( "jdk_changed", sessionIdField, EventFields.PluginInfo, ) private val nextClickedEvent = GROUP.registerVarargEvent( "next_clicked", sessionIdField, EventFields.PluginInfo, ) private val prevClickedEvent = GROUP.registerVarargEvent( "prev_clicked", sessionIdField, EventFields.PluginInfo, ) private val moduleCreatedEvent = GROUP.registerVarargEvent( "module_created", moduleTypeField, sessionIdField, EventFields.PluginInfo, ) private val moduleRemovedEvent = GROUP.registerVarargEvent( "module_removed", moduleTypeField, sessionIdField, EventFields.PluginInfo, ) // Log functions fun logDataOnProjectGenerated(session: WizardLoggingSession?, project: Project?, projectCreationStats: ProjectCreationStats) { projectCreatedEvent.log( project, *projectCreationStats.toPairs().toTypedArray(), *session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(), pluginInfoField ) } fun logDataOnSettingValueChanged( session: WizardLoggingSession, settingId: String, settingValue: String ) { val idToLog = settings.getIdToLog(settingId) ?: return settingValueChangedEvent.log( settingIdField with idToLog, settingValueField with settingValue, sessionIdField with session.id, pluginInfoField, ) } fun logDataOnJdkChanged( session: WizardLoggingSession, ) { jdkChangedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logDataOnNextClicked( session: WizardLoggingSession, ) { nextClickedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logDataOnPrevClicked( session: WizardLoggingSession, ) { prevClickedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logOnModuleCreated( session: WizardLoggingSession, moduleType: String, ) { moduleCreatedEvent.log( sessionIdField with session.id, moduleTypeField with moduleType.withSpacesRemoved(), pluginInfoField, ) } fun logOnModuleRemoved( session: WizardLoggingSession, moduleType: String, ) { moduleRemovedEvent.log( sessionIdField with session.id, moduleTypeField with moduleType.withSpacesRemoved(), pluginInfoField, ) } fun logDataOnProjectGenerated( session: WizardLoggingSession?, project: Project?, projectCreationStats: ProjectCreationStats, uiEditorUsageStats: UiEditorUsageStats ) { projectCreatedEvent.log( project, *projectCreationStats.toPairs().toTypedArray(), *uiEditorUsageStats.toPairs().toTypedArray(), *session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(), pluginInfoField ) } fun logUsedModuleTemplatesOnNewWizardProjectCreated( session: WizardLoggingSession, project: Project?, projectTemplateId: String, moduleTemplates: List<String> ) { moduleTemplates.forEach { moduleTemplateId -> logModuleTemplateCreation(session, project, projectTemplateId, moduleTemplateId) } } fun logWizardOpenByHyperlink(session: WizardLoggingSession, project: Project?, templateId: String?) { projectOpenedByHyperlinkEvent.log( project, projectTemplateField.with(templateId ?: "none"), sessionIdField with session.id, pluginInfoField ) } private fun logModuleTemplateCreation( session: WizardLoggingSession, project: Project?, projectTemplateId: String, moduleTemplateId: String ) { moduleTemplateCreatedEvent.log( project, projectTemplateField.with(projectTemplateId), moduleTemplateField.with(moduleTemplateId), sessionIdField with session.id, pluginInfoField ) } } data class ProjectCreationStats( val group: String, val projectTemplateId: String, val buildSystemType: String, val moduleTypes: List<String> = emptyList(), ) : WizardStats { override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf( groupField.with(group), projectTemplateField.with(projectTemplateId), buildSystemField.with(buildSystemType), modulesListField with moduleTypes, ) } data class UiEditorUsageStats( var modulesCreated: Int = 0, var modulesRemoved: Int = 0, var moduleTemplateChanged: Int = 0 ) : WizardStats { override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf( modulesCreatedField.with(modulesCreated), modulesRemovedField.with(modulesRemoved), moduleTemplateChangedField.with(moduleTemplateChanged) ) } } private fun String.withSpacesRemoved(): String = replace(' ', '_') private sealed class SettingIdWithPossibleValues { abstract val id: String abstract val idToLog: String abstract val values: List<String> data class Enum( override val id: String, override val idToLog: String = id, override val values: List<String> ) : SettingIdWithPossibleValues() data class Boolean( override val id: String, override val idToLog: String = id, ) : SettingIdWithPossibleValues() { override val values: List<String> get() = listOf(true.toString(), false.toString()) } } private class Settings(settingIdWithPossibleValues: List<SettingIdWithPossibleValues>) { constructor(vararg settingIdWithPossibleValues: SettingIdWithPossibleValues) : this(settingIdWithPossibleValues.toList()) val allowedIds = settingIdWithPossibleValues.map { it.idToLog } val possibleValues = settingIdWithPossibleValues.flatMap { it.values }.distinct() private val id2IdToLog = settingIdWithPossibleValues.associate { it.id to it.idToLog } fun getIdToLog(id: String): String? = id2IdToLog.get(id) } class WizardLoggingSession private constructor(val id: Int) { companion object { fun createWithRandomId(): WizardLoggingSession = WizardLoggingSession(id = abs(Random.nextInt())) } }
apache-2.0
4dc59a301dd287ce25ee3fcb826f0b28
32.298969
134
0.564555
5.587889
false
false
false
false
jwren/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSynchronizer.kt
3
3033
package com.intellij.settingsSync import com.intellij.ide.ApplicationInitializedListener import com.intellij.ide.FrameStateListener import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.registry.Registry import com.intellij.settingsSync.plugins.SettingsSyncPluginManager import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresEdt import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit internal class SettingsSynchronizer : ApplicationInitializedListener, FrameStateListener, SettingsSyncEnabledStateListener { private val executorService = AppExecutorUtil.createBoundedScheduledExecutorService("Settings Sync Update", 1) private val autoSyncDelay get() = Registry.intValue("settingsSync.autoSync.frequency.sec", 60).toLong() private var scheduledFuture: ScheduledFuture<*>? = null // accessed only from the EDT override fun componentsInitialized() { if (!isSettingsSyncEnabledByKey()) { return } SettingsSyncPluginManager.getInstance() SettingsSyncEvents.getInstance().addEnabledStateChangeListener(this) if (isSettingsSyncEnabledInSettings()) { executorService.schedule(initializeSyncing(), 0, TimeUnit.SECONDS) return } } override fun onFrameActivated() { if (!isSettingsSyncEnabledByKey() || !isSettingsSyncEnabledInSettings() || !SettingsSyncMain.isAvailable()) { return } if (autoSyncDelay > 0 && scheduledFuture == null) { scheduledFuture = setupSyncingByTimer() } if (Registry.`is`("settingsSync.autoSync.on.focus", true)) { scheduleSyncing("Syncing settings on app focus") } } override fun onFrameDeactivated() { stopSyncingByTimer() } private fun initializeSyncing(): Runnable = Runnable { LOG.info("Initializing settings sync") val settingsSyncMain = SettingsSyncMain.getInstance() settingsSyncMain.controls.bridge.initialize(SettingsSyncBridge.InitMode.JustInit) settingsSyncMain.syncSettings() } override fun enabledStateChanged(syncEnabled: Boolean) { // syncEnabled part is handled inside SettingsSyncEnabler if (!syncEnabled) { stopSyncingByTimer() SettingsSyncMain.getInstance().disableSyncing() } } private fun scheduleSyncing(logMessage: String) { executorService.schedule(Runnable { LOG.info(logMessage) SettingsSyncMain.getInstance().syncSettings() }, 0, TimeUnit.SECONDS) } @RequiresEdt private fun setupSyncingByTimer(): ScheduledFuture<*> { val delay = autoSyncDelay return executorService.scheduleWithFixedDelay(Runnable { LOG.info("Syncing settings by timer") SettingsSyncMain.getInstance().syncSettings() }, delay, delay, TimeUnit.SECONDS) } @RequiresEdt private fun stopSyncingByTimer() { if (scheduledFuture != null) { scheduledFuture!!.cancel(true) scheduledFuture = null } } companion object { val LOG = logger<SettingsSynchronizer>() } }
apache-2.0
8e3393573a8583dc90ce6eaa383a07b5
31.276596
124
0.750082
5.193493
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/RedundantCoercionsCleaner.kt
1
12782
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.lower import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION import org.jetbrains.kotlin.backend.konan.getInlinedClassNative import org.jetbrains.kotlin.backend.konan.ir.isBoxOrUnboxCall import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl import org.jetbrains.kotlin.ir.types.classifierOrFail import org.jetbrains.kotlin.ir.util.dump import org.jetbrains.kotlin.ir.util.getArguments import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid internal class RedundantCoercionsCleaner(val context: Context) : FileLoweringPass, IrElementTransformerVoid() { private class PossiblyFoldedExpression(val expression: IrExpression, val folded: Boolean) { fun getFullExpression(coercion: IrCall, cast: IrTypeOperatorCall?): IrExpression { if (folded) return expression require (coercion.dispatchReceiver == null && coercion.extensionReceiver == null) { "Expected either <box> or <unbox> function without any receivers" } val castedExpression = if (cast == null) expression else with (cast) { IrTypeOperatorCallImpl(startOffset, endOffset, type, operator, typeOperand, expression) } with (coercion) { return IrCallImpl(startOffset, endOffset, type, symbol, typeArgumentsCount, symbol.owner.valueParameters.size, origin).apply { putValueArgument(0, castedExpression) } } } } private val returnableBlockValues = mutableMapOf<IrReturnableBlock, MutableList<IrExpression>>() private fun computeReturnableBlockValues(irFile: IrFile) { irFile.acceptChildrenVoid(object: IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitContainerExpression(expression: IrContainerExpression) { if (expression is IrReturnableBlock) returnableBlockValues[expression] = mutableListOf() super.visitContainerExpression(expression) } override fun visitReturn(expression: IrReturn) { val returnableBlock = expression.returnTargetSymbol.owner as? IrReturnableBlock if (returnableBlock != null) returnableBlockValues[returnableBlock]!!.add(expression.value) super.visitReturn(expression) } }) } override fun lower(irFile: IrFile) { computeReturnableBlockValues(irFile) irFile.transformChildrenVoid(this) } override fun visitCall(expression: IrCall): IrExpression { if (!expression.isBoxOrUnboxCall()) return super.visitCall(expression) val argument = expression.getArguments().single().second val foldedArgument = fold( expression = argument, coercion = expression, cast = null, transformRecursively = true) return foldedArgument.getFullExpression(expression, null) } private fun IrFunction.getCoercedClass(): IrClass { if (name.asString().endsWith("-box>")) return valueParameters[0].type.classifierOrFail.owner as IrClass if (name.asString().endsWith("-unbox>")) return returnType.classifierOrFail.owner as IrClass error("Unexpected coercion: ${this.dump()}") } private fun IrExpression.unwrapImplicitCasts(): IrExpression { var expression = this while (expression is IrTypeOperatorCall && expression.operator == IrTypeOperator.IMPLICIT_CAST) expression = expression.argument return expression } /** * TODO: JVM inliner crashed on attempt inline this function from transform.kt with: * j.l.IllegalStateException: Couldn't obtain compiled function body for * public inline fun <reified T : org.jetbrains.kotlin.ir.IrElement> kotlin.collections.MutableList<T>.transform... */ private inline fun <reified T : IrElement> MutableList<T>.transform(transformation: (T) -> IrElement) { forEachIndexed { i, item -> set(i, transformation(item) as T) } } private fun fold(expression: IrExpression, coercion: IrCall, cast: IrTypeOperatorCall?, transformRecursively: Boolean): PossiblyFoldedExpression { val transformer = this fun IrExpression.transformIfAsked() = if (transformRecursively) this.transform(transformer, data = null) else this fun IrElement.transformIfAsked() = if (transformRecursively) this.transform(transformer, data = null) else this val coercionDeclaringClass = coercion.symbol.owner.getCoercedClass() expression.unwrapImplicitCasts().let { if (it.isBoxOrUnboxCall()) { val result = if (coercionDeclaringClass == (it as IrCall).symbol.owner.getCoercedClass()) it.getArguments().single().second else expression return PossiblyFoldedExpression(result.transformIfAsked(), result != expression) } } return when (expression) { is IrReturnableBlock -> { val foldedReturnableBlockValues = returnableBlockValues[expression]!!.associate { it to fold(it, coercion, cast, false) } val someoneFolded = foldedReturnableBlockValues.any { it.value.folded } val transformedReturnableBlock = if (!someoneFolded) expression else { val oldSymbol = expression.symbol val newSymbol = IrReturnableBlockSymbolImpl() val transformedReturnableBlock = with(expression) { IrReturnableBlockImpl( startOffset = startOffset, endOffset = endOffset, type = coercion.type, symbol = newSymbol, origin = origin, statements = statements, inlineFunctionSymbol = inlineFunctionSymbol) } transformedReturnableBlock.transformChildrenVoid(object: IrElementTransformerVoid() { override fun visitExpression(expression: IrExpression): IrExpression { foldedReturnableBlockValues[expression]?.let { return it.getFullExpression(coercion, cast) } return super.visitExpression(expression) } override fun visitReturn(expression: IrReturn): IrExpression { expression.transformChildrenVoid(this) return if (expression.returnTargetSymbol != oldSymbol) expression else with(expression) { IrReturnImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.nothingType, returnTargetSymbol = newSymbol, value = value) } } }) transformedReturnableBlock } if (transformRecursively) transformedReturnableBlock.transformChildrenVoid(this) PossiblyFoldedExpression(transformedReturnableBlock, someoneFolded) } is IrBlock -> { val statements = expression.statements if (statements.isEmpty()) PossiblyFoldedExpression(expression, false) else { val lastStatement = statements.last() as IrExpression val foldedLastStatement = fold(lastStatement, coercion, cast, transformRecursively) statements.transform { if (it == lastStatement) foldedLastStatement.expression else it.transformIfAsked() } val transformedBlock = if (!foldedLastStatement.folded) expression else with(expression) { IrBlockImpl( startOffset = startOffset, endOffset = endOffset, type = coercion.type, origin = origin, statements = statements) } PossiblyFoldedExpression(transformedBlock, foldedLastStatement.folded) } } is IrWhen -> { val foldedBranches = expression.branches.map { fold(it.result, coercion, cast, transformRecursively) } val someoneFolded = foldedBranches.any { it.folded } val transformedWhen = with(expression) { IrWhenImpl(startOffset, endOffset, if (someoneFolded) coercion.type else type, origin, branches.asSequence().withIndex().map { (index, branch) -> IrBranchImpl( startOffset = branch.startOffset, endOffset = branch.endOffset, condition = branch.condition.transformIfAsked(), result = if (someoneFolded) foldedBranches[index].getFullExpression(coercion, cast) else foldedBranches[index].expression) }.toList()) } return PossiblyFoldedExpression(transformedWhen, someoneFolded) } is IrTypeOperatorCall -> if (expression.operator != IrTypeOperator.CAST && expression.operator != IrTypeOperator.IMPLICIT_CAST && expression.operator != IrTypeOperator.SAFE_CAST) PossiblyFoldedExpression(expression.transformIfAsked(), false) else { if (expression.typeOperand.getInlinedClassNative() != coercionDeclaringClass) PossiblyFoldedExpression(expression.transformIfAsked(), false) else { val foldedArgument = fold(expression.argument, coercion, expression, transformRecursively) if (foldedArgument.folded) foldedArgument else PossiblyFoldedExpression(expression.apply { argument = foldedArgument.expression }, false) } } else -> PossiblyFoldedExpression(expression.transformIfAsked(), false) } } }
apache-2.0
29c99b7c4a8035454255a54498791c62
48.351351
142
0.549992
6.281081
false
false
false
false
JayyyR/SimpleFragments
library/src/main/java/com/joeracosta/library/activity/FragmentMapFragment.kt
1
3353
package com.joeracosta.library.activity import android.os.Bundle /** * Created by Joe on 8/14/2017. * Meant to be a shell map fragment that has a map of SimpleFragments. Back presses etc are handled for you. * The back presses will be sent to the SimpleFragment thats currently shown in the map and handled there. If it's not handled * It will be sent to this activity. You shouldn't inflate a layout here inside the fragment container that is meant to be visible * to the user. */ abstract class FragmentMapFragment : SimpleFragment() { protected var mCurrentFragment: SimpleFragment? = null private set private var mCurrentFragmentTag: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.getString(CURRENT_FRAG_TAG)?.let { mCurrentFragmentTag = it mCurrentFragment = childFragmentManager.findFragmentByTag(mCurrentFragmentTag) as SimpleFragment } } override fun onSaveInstanceState(outState: Bundle) { outState.putString(CURRENT_FRAG_TAG, mCurrentFragmentTag) super.onSaveInstanceState(outState) } fun hasFragments(): Boolean { return childFragmentManager.fragments.size > 0 } /** * Show a fragment in the map * @param fragmentToAdd New Instance of the Fragment you want * @param fragmentContainerId container Id for the fragment * @param tag tag of the fragment transaction. If you want to show the same fragment that's * already added, just make sure the tag is correct and it won't use the new instance */ fun showFragmentInMap(fragmentToAdd: SimpleFragment, fragmentContainerId: Int, tag: String) { var fragmentToActuallyAdd = fragmentToAdd childFragmentManager.findFragmentByTag(tag)?.let { fragmentToActuallyAdd = it as SimpleFragment } val fragmentTransaction = childFragmentManager.beginTransaction().apply { if (mCurrentFragment != null) { hide(mCurrentFragment) } if (fragmentToActuallyAdd.isAdded) { show(fragmentToActuallyAdd) } else { fragmentToActuallyAdd.setAtForefront(true) add(fragmentContainerId, fragmentToActuallyAdd, tag) } } mCurrentFragmentTag = tag mCurrentFragment = fragmentToActuallyAdd fragmentTransaction.commitAllowingStateLoss() } override fun onSimpleBackPressed(): Boolean { return handleBackPress() } /** * Passes the back press to children fragments so they can consume it if they'd like * @return whether or not the back press was consumed by a child fragment */ protected fun handleBackPress() : Boolean{ return mCurrentFragment?.onSimpleBackPressed() ?: false } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) mCurrentFragment?.let { if (hidden) { it.setAtForefront(false) it.onHidden() } else { it.setAtForefront(true) it.onShown() } } } } private const val CURRENT_FRAG_TAG = "com.joeracosta.current_frag_tag_fragment_map"
mit
545e3028d78283c52d307e58366476f7
33.927083
130
0.660304
5.034535
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/IDEKotlinBinaryClassCache.kt
2
5855
// 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.caches import com.intellij.ide.highlighter.JavaClassFileType import com.intellij.model.ModelBranch import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.psi.PsiJavaModule import com.intellij.reference.SoftReference import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache import org.jetbrains.kotlin.load.kotlin.KotlinClassFinder import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion import org.jetbrains.kotlin.name.ClassId class IDEKotlinBinaryClassCache { class KotlinBinaryClassHeaderData( val classId: ClassId, val kind: KotlinClassHeader.Kind, val metadataVersion: JvmMetadataVersion, val partNamesIfMultifileFacade: List<String>, val packageName: String? ) data class KotlinBinaryData(val isKotlinBinary: Boolean, val timestamp: Long, val headerData: KotlinBinaryClassHeaderData?) /** * Checks if this file is a compiled Kotlin class file (not necessarily ABI-compatible with the current plugin) */ fun isKotlinJvmCompiledFile(file: VirtualFile, fileContent: ByteArray? = null): Boolean { if (file.extension != JavaClassFileType.INSTANCE!!.defaultExtension) { return false } getKotlinBinaryFromCache(file)?.let { return it.isKotlinBinary } return kotlinJvmBinaryClass(file, fileContent) != null } fun getKotlinBinaryClass(file: VirtualFile, fileContent: ByteArray? = null): KotlinJvmBinaryClass? { val cached = getKotlinBinaryFromCache(file) if (cached != null && !cached.isKotlinBinary) { return null } return kotlinJvmBinaryClass(file, fileContent) } private fun kotlinJvmBinaryClass( file: VirtualFile, fileContent: ByteArray? ): KotlinJvmBinaryClass? { val kotlinBinaryClass = binaryClassResult(file, fileContent)?.toKotlinJvmBinaryClass() val isKotlinBinaryClass = kotlinBinaryClass != null if (file is VirtualFileWithId) { attributeService.writeBooleanAttribute(KOTLIN_IS_COMPILED_FILE_ATTRIBUTE, file, isKotlinBinaryClass) } if (isKotlinBinaryClass) { val headerInfo = createHeaderInfo(kotlinBinaryClass!!) file.putUserData(KOTLIN_BINARY_DATA_KEY, SoftReference(KotlinBinaryData(isKotlinBinaryClass, file.timeStamp, headerInfo))) } return kotlinBinaryClass } private fun binaryClassResult(file: VirtualFile, fileContent: ByteArray?): KotlinClassFinder.Result? { if (ModelBranch.getFileBranch(file) != null) { if (file.fileType !== JavaClassFileType.INSTANCE) return null if (file.name == PsiJavaModule.MODULE_INFO_CLS_FILE) return null return runReadAction { @Suppress("DEPRECATION") VirtualFileKotlinClass.create(file, fileContent) } } return KotlinBinaryClassCache.getKotlinBinaryClassOrClassFileContent(file, fileContent) } fun getKotlinBinaryClassHeaderData(file: VirtualFile, fileContent: ByteArray? = null): KotlinBinaryClassHeaderData? { getKotlinBinaryFromCache(file)?.let { cached -> if (!cached.isKotlinBinary) { return null } if (cached.headerData != null) { return cached.headerData } } val kotlinBinaryClass = kotlinJvmBinaryClass(file, fileContent) ?: return null return createHeaderInfo(kotlinBinaryClass) } private val attributeService = service<FileAttributeService>() private fun createHeaderInfo(kotlinBinaryClass: KotlinJvmBinaryClass): KotlinBinaryClassHeaderData { val classId = kotlinBinaryClass.classId return kotlinBinaryClass.classHeader.toLightHeader(classId) } private fun KotlinClassHeader.toLightHeader(classId: ClassId) = KotlinBinaryClassHeaderData( classId, kind, metadataVersion, multifilePartNames, packageName ) private val KOTLIN_IS_COMPILED_FILE_ATTRIBUTE: String = "kotlin-is-binary-compiled".apply { service<FileAttributeService>().register(this, 1) } private val KOTLIN_BINARY_DATA_KEY = Key.create<SoftReference<KotlinBinaryData>>(KOTLIN_IS_COMPILED_FILE_ATTRIBUTE) private fun getKotlinBinaryFromCache(file: VirtualFile): KotlinBinaryData? { val userData = file.getUserData(KOTLIN_BINARY_DATA_KEY)?.get() if (userData != null && userData.timestamp == file.timeStamp) { return userData } val isKotlinBinaryAttribute = if (file is VirtualFileWithId) { attributeService.readBooleanAttribute(KOTLIN_IS_COMPILED_FILE_ATTRIBUTE, file) } else { null } if (isKotlinBinaryAttribute != null) { val isKotlinBinary = isKotlinBinaryAttribute.value val kotlinBinaryData = KotlinBinaryData(isKotlinBinary, file.timeStamp, null) if (isKotlinBinary) { file.putUserData(KOTLIN_BINARY_DATA_KEY, SoftReference(kotlinBinaryData)) } return kotlinBinaryData } return null } companion object { fun getInstance(): IDEKotlinBinaryClassCache = service() } }
apache-2.0
3e458234e77f6b7f60015eae15479cee
38.033333
158
0.70333
5.021441
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ExtractSuperRefactoring.kt
3
15103
// 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.introduce.extractClass import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractSuperclass.ExtractSuperClassUtil import com.intellij.refactoring.memberPullUp.PullUpProcessor import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.DocCommentPolicy import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.NewKotlinFileAction import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.introduce.insertDeclaration import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze import org.jetbrains.kotlin.idea.refactoring.memberInfo.toJavaMemberInfo import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForDeferredFile import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForExistingElement import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker import org.jetbrains.kotlin.idea.refactoring.pullUp.checkVisibilityInAbstractedMembers import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier data class ExtractSuperInfo( val originalClass: KtClassOrObject, val memberInfos: Collection<KotlinMemberInfo>, val targetParent: PsiElement, val targetFileName: String, val newClassName: String, val isInterface: Boolean, val docPolicy: DocCommentPolicy<*> ) class ExtractSuperRefactoring( private var extractInfo: ExtractSuperInfo ) { companion object { private fun getElementsToMove( memberInfos: Collection<KotlinMemberInfo>, originalClass: KtClassOrObject, isExtractInterface: Boolean ): Map<KtElement, KotlinMemberInfo?> { val project = originalClass.project val elementsToMove = LinkedHashMap<KtElement, KotlinMemberInfo?>() runReadAction { val superInterfacesToMove = ArrayList<KtElement>() for (memberInfo in memberInfos) { val member = memberInfo.member ?: continue if (memberInfo.isSuperClass) { superInterfacesToMove += member } else { elementsToMove[member] = memberInfo } } val superTypeList = originalClass.getSuperTypeList() if (superTypeList != null) { for (superTypeListEntry in originalClass.superTypeListEntries) { val superType = superTypeListEntry.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, superTypeListEntry.typeReference] ?: continue val superClassDescriptor = superType.constructor.declarationDescriptor ?: continue val superClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, superClassDescriptor) as? KtClass ?: continue if ((!isExtractInterface && !superClass.isInterface()) || superClass in superInterfacesToMove) { elementsToMove[superTypeListEntry] = null } } } } return elementsToMove } fun collectConflicts( originalClass: KtClassOrObject, memberInfos: List<KotlinMemberInfo>, targetParent: PsiElement, newClassName: String, isExtractInterface: Boolean ): MultiMap<PsiElement, String> { val conflicts = MultiMap<PsiElement, String>() val project = originalClass.project if (targetParent is KtElement) { val targetSibling = originalClass.parentsWithSelf.first { it.parent == targetParent } as KtElement targetSibling.getResolutionScope() .findClassifier(Name.identifier(newClassName), NoLookupLocation.FROM_IDE) ?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) } ?.let { conflicts.putValue( it, KotlinBundle.message( "text.class.0.already.exists.in.the.target.scope", newClassName ) ) } } val elementsToMove = getElementsToMove(memberInfos, originalClass, isExtractInterface).keys val moveTarget = if (targetParent is PsiDirectory) { val targetPackage = targetParent.getPackage() ?: return conflicts KotlinMoveTargetForDeferredFile(FqName(targetPackage.qualifiedName), targetParent.virtualFile) } else { KotlinMoveTargetForExistingElement(targetParent as KtElement) } val conflictChecker = MoveConflictChecker( project, elementsToMove, moveTarget, originalClass, memberInfos.asSequence().filter { it.isToAbstract }.mapNotNull { it.member }.toList() ) project.runSynchronouslyWithProgress(RefactoringBundle.message("detecting.possible.conflicts"), true) { runReadAction { val usages = LinkedHashSet<UsageInfo>() for (element in elementsToMove) { ReferencesSearch.search(element).mapTo(usages) { MoveRenameUsageInfo(it, element) } if (element is KtCallableDeclaration) { element.toLightMethods().flatMapTo(usages) { MethodReferencesSearch.search(it).map { reference -> MoveRenameUsageInfo(reference, element) } } } } conflictChecker.checkAllConflicts(usages, LinkedHashSet(), conflicts) if (targetParent is PsiDirectory) { ExtractSuperClassUtil.checkSuperAccessible(targetParent, conflicts, originalClass.toLightClass()) } checkVisibilityInAbstractedMembers(memberInfos, originalClass.getResolutionFacade(), conflicts) } } return conflicts } } private val project = extractInfo.originalClass.project private val psiFactory = KtPsiFactory(project) private val typeParameters = LinkedHashSet<KtTypeParameter>() private val bindingContext = extractInfo.originalClass.analyze(BodyResolveMode.PARTIAL) private fun collectTypeParameters(refTarget: PsiElement?) { if (refTarget is KtTypeParameter && refTarget.getStrictParentOfType<KtTypeParameterListOwner>() == extractInfo.originalClass) { typeParameters += refTarget refTarget.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { (expression.mainReference.resolve() as? KtTypeParameter)?.let { typeParameters += it } } } ) } } private fun analyzeContext() { val visitor = object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val refTarget = expression.mainReference.resolve() collectTypeParameters(refTarget) } } getElementsToMove(extractInfo.memberInfos, extractInfo.originalClass, extractInfo.isInterface) .asSequence() .flatMap { val (element, info) = it info?.getChildrenToAnalyze()?.asSequence() ?: sequenceOf(element) } .forEach { it.accept(visitor) } } private fun createClass(superClassEntry: KtSuperTypeListEntry?): KtClass? { val targetParent = extractInfo.targetParent val newClassName = extractInfo.newClassName.quoteIfNeeded() val originalClass = extractInfo.originalClass val kind = if (extractInfo.isInterface) "interface" else "class" val prototype = psiFactory.createClass("$kind $newClassName") val newClass = if (targetParent is PsiDirectory) { val file = targetParent.findFile(extractInfo.targetFileName) ?: run { val template = FileTemplateManager.getInstance(project).getInternalTemplate("Kotlin File") NewKotlinFileAction.createFileFromTemplate(extractInfo.targetFileName, template, targetParent) ?: return null } file.add(prototype) as KtClass } else { val targetSibling = originalClass.parentsWithSelf.first { it.parent == targetParent } insertDeclaration(prototype, targetSibling) } val shouldBeAbstract = extractInfo.memberInfos.any { it.isToAbstract } if (!extractInfo.isInterface) { newClass.addModifier(if (shouldBeAbstract) KtTokens.ABSTRACT_KEYWORD else KtTokens.OPEN_KEYWORD) } if (typeParameters.isNotEmpty()) { val typeParameterListText = typeParameters.sortedBy { it.startOffset }.joinToString(prefix = "<", postfix = ">") { it.text } newClass.addAfter(psiFactory.createTypeParameterList(typeParameterListText), newClass.nameIdentifier) } val targetPackageFqName = (targetParent as? PsiDirectory)?.getFqNameWithImplicitPrefix()?.quoteSegmentsIfNeeded() val superTypeText = buildString { if (!targetPackageFqName.isNullOrEmpty()) { append(targetPackageFqName).append('.') } append(newClassName) if (typeParameters.isNotEmpty()) { append(typeParameters.sortedBy { it.startOffset }.map { it.name }.joinToString(prefix = "<", postfix = ">")) } } val needSuperCall = !extractInfo.isInterface && (superClassEntry is KtSuperTypeCallEntry || originalClass.hasPrimaryConstructor() || originalClass.secondaryConstructors.isEmpty()) val newSuperTypeListEntry = if (needSuperCall) { psiFactory.createSuperTypeCallEntry("$superTypeText()") } else { psiFactory.createSuperTypeEntry(superTypeText) } if (superClassEntry != null) { val qualifiedTypeRefText = bindingContext[BindingContext.TYPE, superClassEntry.typeReference]?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } val superClassEntryToAdd = if (qualifiedTypeRefText != null) { superClassEntry.copied().apply { typeReference?.replace(psiFactory.createType(qualifiedTypeRefText)) } } else superClassEntry newClass.addSuperTypeListEntry(superClassEntryToAdd) ShortenReferences.DEFAULT.process(superClassEntry.replaced(newSuperTypeListEntry)) } else { ShortenReferences.DEFAULT.process(originalClass.addSuperTypeListEntry(newSuperTypeListEntry)) } ShortenReferences.DEFAULT.process(newClass) return newClass } fun performRefactoring() { val originalClass = extractInfo.originalClass val handler = if (extractInfo.isInterface) KotlinExtractInterfaceHandler else KotlinExtractSuperclassHandler handler.getErrorMessage(originalClass)?.let { throw CommonRefactoringUtil.RefactoringErrorHintException(it) } val superClassEntry = if (!extractInfo.isInterface) { val originalClassDescriptor = originalClass.unsafeResolveToDescriptor() as ClassDescriptor val superClassDescriptor = originalClassDescriptor.getSuperClassNotAny() originalClass.superTypeListEntries.firstOrNull { bindingContext[BindingContext.TYPE, it.typeReference]?.constructor?.declarationDescriptor == superClassDescriptor } } else null project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { analyzeContext() } } project.executeWriteCommand(KotlinExtractSuperclassHandler.REFACTORING_NAME) { val newClass = createClass(superClassEntry) ?: return@executeWriteCommand val subClass = extractInfo.originalClass.toLightClass() ?: return@executeWriteCommand val superClass = newClass.toLightClass() ?: return@executeWriteCommand PullUpProcessor( subClass, superClass, extractInfo.memberInfos.mapNotNull { it.toJavaMemberInfo() }.toTypedArray(), extractInfo.docPolicy ).moveMembersToBase() performDelayedRefactoringRequests(project) } } }
apache-2.0
7cd2cb452868d00fba9928494bd2baa5
48.356209
158
0.674502
5.906531
false
false
false
false
tlaukkan/kotlin-web-vr
client/src/vr/util/Util.kt
1
1254
package vr.util import lib.threejs.Quaternion import lib.webvrapi.Float32Array import java.util.* fun floatsToDoubles(float32Array: Float32Array) : List<Double> { val stringArray = float32Array.toString().split(",") val doubleList = ArrayList<Double>() for (str in stringArray) { doubleList.add(safeParseDouble(str)!!) } return doubleList } /** * Writes given plain data object containing only primitives, arrays and other similar data objects as JSON string. */ fun toJson(value: Any): String { return JSON.stringify(value) } /** * Parses JSON string to data object containing only primitives, arrays and other similar data objects. */ fun <T : Any> fromJson(string: String): T { return JSON.parse(string) } /** * Dynamic cast to be able to cast JSON parsed objects to their type. */ fun <T> dynamicCast(obj: Any) : T { val dynamicNode: dynamic = obj return dynamicNode } fun getDeltaQuaternion(startOrientation: Quaternion, currentOrientation: Quaternion): Quaternion { val originalOrientationConjugate = startOrientation!!.clone().conjugate() val orientationChange = currentOrientation.clone() orientationChange.multiply(originalOrientationConjugate) return orientationChange }
mit
2ba5e79c5d64bd179e00ea80aff85b9d
26.888889
115
0.735247
4.084691
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/v3/util/RxUtil.kt
1
971
package xyz.nulldev.ts.api.v3.util import com.pushtorefresh.storio.operations.PreparedOperation import com.pushtorefresh.storio.sqlite.operations.get.PreparedGetObject import kotlinx.coroutines.suspendCancellableCoroutine import rx.Scheduler import rx.Single import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException suspend fun <T> Single<T>.await(subscribeOn: Scheduler? = null): T { return suspendCancellableCoroutine { continuation -> val self = if (subscribeOn != null) subscribeOn(subscribeOn) else this val sub = self.subscribe({ continuation.resume(it) }, { if (!continuation.isCancelled) continuation.resumeWithException(it) }) continuation.invokeOnCancellation { sub.unsubscribe() } } } suspend fun <T> PreparedOperation<T>.await(): T = asRxSingle().await() suspend fun <T> PreparedGetObject<T>.await(): T? = asRxSingle().await()
apache-2.0
291f6c93b14d398810a58f720930a4ea
33.678571
78
0.707518
4.580189
false
false
false
false
glorantq/KalanyosiRamszesz
src/glorantq/ramszesz/commands/DictionaryCommand.kt
1
3378
package glorantq.ramszesz.commands import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import glorantq.ramszesz.utils.BotUtils import glorantq.ramszesz.utils.DictionaryResult import glorantq.ramszesz.utils.tryParseInt import okhttp3.* import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.IVoiceChannel import sx.blah.discord.util.EmbedBuilder import java.io.IOException /** * Created by glora on 2017. 07. 28.. */ class DictionaryCommand : ICommand { override val commandName: String get() = "dictionary" override val description: String get() = "Look up a word in the dictionary" override val permission: Permission get() = Permission.USER val httpClient: OkHttpClient by lazy { OkHttpClient.Builder().build() } override fun execute(event: MessageReceivedEvent, args: List<String>) { if (args.isEmpty()) { BotUtils.sendUsageEmbed("You ned to specify a word!", "Dictionary", event.author, event, this) return } var limit: Int = 3 if(args.size > 1) { limit = args[1].tryParseInt(3) } if(limit == 0) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Dictionary", "0 definitions aren't useful", event.author), event.channel) return } if(limit < 0) { limit *= -1 BotUtils.sendMessage(BotUtils.createSimpleEmbed("Dictionary", "The number `$limit` is negative, it has been changed to `$limit`", event.author), event.channel) } if(limit > 15) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Dictionary", "The number `$limit` is too large", event.author), event.channel) return } val url: String = "http://api.wordnik.com/v4/word.json/${args[0]}/definitions?limit=$limit&includeRelated=false&sourceDictionaries=ahd%2Ccentury&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" val request: Request = Request.Builder().url(url).get().build() httpClient.newCall(request).enqueue(object : Callback { override fun onFailure(p0: Call?, p1: IOException?) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Dictionary", "Failed to look up `${args[0]}` in the dictionary because @glorantq can't code!", event.author), event.channel) } override fun onResponse(p0: Call?, p1: Response?) { if(p1 == null) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Dictionary", "Failed to look up `${args[0]}` in the dictionary because @glorantq can't code!", event.author), event.channel) return } val results: List<DictionaryResult> = Gson().fromJson(p1.body()!!.string()) val embed: EmbedBuilder = BotUtils.embed("Dictionary", event.author) embed.withDescription("Definitions for \"${args[0]}\"") for(result: DictionaryResult in results) { embed.appendField("From ${result.sourceDictionary}", "${result.text}\n\n`Data sourced ${result.attributionText}`", false) } BotUtils.sendMessage(embed.build(), event.channel) } }) } }
gpl-3.0
2ad8ea28cd62e12d934d6b7a557b6ec6
41.772152
248
0.643872
4.314176
false
false
false
false
paoloach/zdomus
temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/TempSensorLocationDS.kt
1
8478
package it.achdjian.paolo.temperaturemonitor import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.util.Log import it.achdjian.paolo.temperaturemonitor.dagger.ForApplication import it.achdjian.paolo.temperaturemonitor.domusEngine.DomusEngine import it.achdjian.paolo.temperaturemonitor.ui.ZElementAdapter import it.achdjian.paolo.temperaturemonitor.zigbee.ZDevices import it.achdjian.paolo.temperaturemonitor.zigbee.nullZDevice import javax.inject.Inject import javax.inject.Singleton /** * Created by Paolo Achdjian on 31/08/16. */ @Singleton class TempSensorLocationDS @Inject constructor(@ForApplication val context: Context, val zDevices: ZDevices) { lateinit var domusEngine: DomusEngine companion object { private val TAG = "DATABASE" } init { cleanDatabase() } fun printContent() { val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.readableDatabase var query: Cursor? = null try { query = database.query(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, null, null, null, null, null, null) query.moveToFirst() while(!query.isAfterLast){ val sb = StringBuilder(); var i=0 while( i < query.columnCount){ sb.append(query.getColumnName(i)).append(": ").append(query.getString(i)).append(" ") i++ } Log.i(TAG, sb.toString()) if (!query.moveToNext()) break; } } finally { if (query != null) { query.close() } } database.close() } fun createTempSensorLocation(networkAddress: String, endpoint: Int, location: String) { Log.i(TAG,"Create: address: ${networkAddress}, location: ${location}") val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.writableDatabase try { val values = ContentValues() values.put(DomusViewDatabase.NETWORK_FIELD, networkAddress) values.put(DomusViewDatabase.ENDPOINT, endpoint) if (!isLocationUsedYet(location)) { Log.i(TAG, "Insert new row") values.put(DomusViewDatabase.LOCATION, location) database.beginTransaction() database.insert(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, null, values) } else { Log.i(TAG, "update row ${location}") database.beginTransaction() database.update(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, values, DomusViewDatabase.LOCATION + "='" + location + "'", null); } database.setTransactionSuccessful() database.endTransaction() } finally { database.close() } } fun cleanDatabase() { val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.writableDatabase val values = arrayOf("00:00:00:00::00:00:00:00") database.beginTransaction() database.delete(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, DomusViewDatabase.NETWORK_FIELD + "=?", values) database.setTransactionSuccessful() database.endTransaction() database.close() } fun removeTempSensorLocation(location: String) { val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.writableDatabase val values = arrayOf(location) database.beginTransaction() database.delete(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, DomusViewDatabase.LOCATION + "=?", values) database.setTransactionSuccessful() database.endTransaction() database.close() } fun createTempSensorLocation(element: ZElementAdapter.Element, location: String) { val network = element.shortAddress val zDevices = domusEngine.zDevices val device = zDevices.get(network) createTempSensorLocation(device.extendedAddr, element.endpointId, location) } fun isLocationUsedYet(location: String?): Boolean { val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.getReadableDatabase() var query: Cursor? = null try { query = database.query(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, arrayOf<String>(DomusViewDatabase.NETWORK_FIELD, DomusViewDatabase.ENDPOINT), DomusViewDatabase.LOCATION + "= ?", arrayOf(location), null, null, null) return query!!.count > 0 } finally { if (query != null) { query.close() } } } fun isUsed(networkId: Int, endpointId: Int): Boolean { val device = domusEngine.zDevices.get(networkId) val sqlQuery = StringBuilder() sqlQuery. append("SELECT "). append(DomusViewDatabase.LOCATION). append(" from "). append(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE). append(" WHERE "). append(DomusViewDatabase.NETWORK_FIELD). append("= '"). append(device.extendedAddr). append("' AND "). append(DomusViewDatabase.ENDPOINT). append(" = "). append(endpointId). append(";") val domusViewDatabase = DomusViewDatabase(context) var database: SQLiteDatabase? = null var query: Cursor? = null try { database = domusViewDatabase.readableDatabase query = database.rawQuery(sqlQuery.toString(), null) if (query.count <= 0) { return false } return true } finally { query?.close() database?.close() } } fun getRoom(networkId: Int, endpointId: Int): String { printContent() val device = domusEngine.zDevices.get(networkId) val sqlQuery = StringBuilder() sqlQuery. append("SELECT "). append(DomusViewDatabase.LOCATION). append(" from "). append(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE). append(" WHERE "). append(DomusViewDatabase.NETWORK_FIELD). append("= '"). append(device.extendedAddr). append("' AND "). append(DomusViewDatabase.ENDPOINT). append(" = "). append(endpointId). append(";") val domusViewDatabase = DomusViewDatabase(context) var database: SQLiteDatabase? = null var query: Cursor? = null try { database = domusViewDatabase.readableDatabase query = database.rawQuery(sqlQuery.toString(), null) if (query.count <= 0) { return "" } query.moveToFirst() return query.getString(0) } finally { query?.close() database?.close() } } fun getElement(roomName: String): ZElementAdapter.Element? { printContent() val domusViewDatabase = DomusViewDatabase(context) val database = domusViewDatabase.readableDatabase var query: Cursor? = null try { query = database.query(DomusViewDatabase.TEMP_SENSOR_LOCATION_TABLE, arrayOf(DomusViewDatabase.NETWORK_FIELD, DomusViewDatabase.ENDPOINT), DomusViewDatabase.LOCATION + "= ?", arrayOf(roomName), null, null, null) if (query!!.count <= 0) { return null } query.moveToFirst() val extAddress = query.getString(0) val device = zDevices.get(extAddress) if (device !== nullZDevice) return ZElementAdapter.Element(device.shortAddress, query.getInt(1), false, null) else return null } finally { if (query != null) { query.close() } } } }
gpl-2.0
fa2ce468007464528bb67d0996b01260
35.230769
144
0.581623
4.909091
false
false
false
false
luhaoaimama1/JavaZone
HttpTest3/src/main/java/socket/DstService.kt
1
1495
package socket import java.net.ServerSocket import java.net.Socket /** * @author csc * @description 从这里启动一个服务端监听某个端口 * copy from:https://www.cnblogs.com/sky-heaven/p/9287815.html */ object DstService { @JvmStatic fun main(args: Array<String>) { server() } private fun server() { try { // 启动监听端口 30000 val ss = ServerSocket(30000) // 没有连接这个方法就一直堵塞 val s = ss.accept() // 将请求指定一个线程去执行 Thread(DstServiceImpl(s)).start() } catch (e: Exception) { e.printStackTrace() } } /** * @author csc * @description 服务的启动的线程类 */ class DstServiceImpl(s: Socket?) : Runnable { var socket: Socket? = null override fun run() { try { var index = 1 while (true) { // 5秒后中断连接 if (index > 10) { socket!!.close() println("服务端已经关闭链接!") break } index++ Thread.sleep(1 * 1000.toLong()) //程序睡眠1秒钟 } } catch (e: Exception) { e.printStackTrace() } } init { socket = s } } }
epl-1.0
d5d4fa032a47f536672f3f392516776d
21.333333
62
0.433159
4.17134
false
false
false
false
nobumin/mstdn_light_android
app/src/main/java/view/mstdn/meas/jp/multimstdn/MainActivity.kt
1
5039
package view.mstdn.meas.jp.multimstdn import android.Manifest import android.app.AlertDialog import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.provider.Settings import android.support.v4.content.ContextCompat import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import view.mstdn.meas.jp.multimstdn.adapter.WebViewAdapter import view.mstdn.meas.jp.multimstdn.view.SiteListActivity /** * Created by nobu on 2017/04/21. */ class MainActivity : AppCompatActivity() { private var _adapter: WebViewAdapter? = null private var _viewPager: ViewPager? = null private var startOnCreate = false private val _hander = Handler() private var _ignorePermission = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startOnCreate = true setContentView(R.layout.main_layout) _viewPager = findViewById(R.id.viewpager) as ViewPager _adapter = WebViewAdapter(supportFragmentManager, this) _viewPager!!.adapter = _adapter _viewPager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { setTitle(position) } override fun onPageScrollStateChanged(state: Int) {} }) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.setting) { val intent = Intent(this, SiteListActivity::class.java) startActivity(intent) } else if (item.itemId == R.id.term_of_use) { //TODO 利用規約 val uri = Uri.parse("http://meas.jp/index.php?option=com_content&view=article&id=81&Itemid=476") val i = Intent(Intent.ACTION_VIEW, uri) startActivity(i) } else if (item.itemId == R.id.meas_site) { //TODO ウチのサイト val uri = Uri.parse("https://meas.jp") val i = Intent(Intent.ACTION_VIEW, uri) startActivity(i) } return true } override fun onResume() { super.onResume() if (Build.VERSION.SDK_INT >= 23 && !_ignorePermission && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA) requestPermissions(permissions, MainActivity.REQUEST_CAMERA) } else { val urls = SiteListActivity.getSites(this) if (urls.size > 0) { if (!startOnCreate) { _adapter!!.notifyDataSetChanged() } setTitle(_viewPager!!.currentItem) } else { val intent = Intent(this, SiteListActivity::class.java) startActivity(intent) } } startOnCreate = false } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == MainActivity.REQUEST_CAMERA) { if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) { _ignorePermission = true AlertDialog.Builder(this@MainActivity) .setMessage("画像を投稿するためには、設定画面からご自身で権限を許可して頂く必要があります。") .setPositiveButton("設定画面へ") { dialog, which -> val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri = Uri.fromParts("package", [email protected], null) intent.data = uri startActivity(intent) _ignorePermission = false } .setNegativeButton("今はしない") { dialog, which -> } .show() } } } override fun setTitle(index: Int) { val urls = SiteListActivity.getSites(this@MainActivity) val actionBar = supportActionBar val url = urls.toTypedArray()[index] actionBar!!.setTitle(url.toString()) actionBar.setDisplayHomeAsUpEnabled(false) } companion object { val REQUEST_CAMERA = 99 } }
mit
06019ca039f50cec44e14341ba2a0675
38.368
249
0.627718
4.673314
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/actions/CreateColorAction.kt
1
2415
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.actions import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinFile import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.SkinFileImpl import com.intellij.codeInsight.actions.SimpleCodeInsightAction import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiFile import com.intellij.ui.ColorChooser import java.awt.Color /* * Copyright 2018 Blue Box Ware * * 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. */ class CreateColorAction : SimpleCodeInsightAction() { override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean = file is SkinFile override fun startInWriteAction(): Boolean = false override fun update(e: AnActionEvent) { super.update(e) templatePresentation.icon = AllIcons.Gutter.Colors } override fun invoke(project: Project, editor: Editor, file: PsiFile) { if (file !is SkinFileImpl) return Messages.showInputDialogWithCheckBox( "Name for the new color", "Name", "Use float components", false, true, AllIcons.Gutter.Colors, null, null ).let { result -> if (result.first.isNullOrBlank()) { return } ColorChooser.chooseColor(editor.component, "Choose Color To Create", Color.WHITE, true)?.let { color -> ApplicationManager.getApplication().runWriteAction { file.addColor(result.first, color = color, useComponents = result.second ?: false) } } } } }
apache-2.0
623b883b9c2ff53bf480eb294f1017ac
33.014085
115
0.695238
4.556604
false
false
false
false
tommyettinger/SquidSetup
src/main/kotlin/com/github/czyzby/setup/config/configuration.kt
1
3322
package com.github.czyzby.setup.config import com.badlogic.gdx.Gdx import com.badlogic.gdx.scenes.scene2d.Actor import com.github.czyzby.autumn.annotation.Component import com.github.czyzby.autumn.annotation.Initiate import com.github.czyzby.autumn.mvc.component.i18n.LocaleService import com.github.czyzby.autumn.mvc.component.ui.InterfaceService import com.github.czyzby.autumn.mvc.component.ui.SkinService import com.github.czyzby.autumn.mvc.config.AutumnActionPriority import com.github.czyzby.autumn.mvc.stereotype.preference.* import com.github.czyzby.lml.parser.LmlParser import com.github.czyzby.lml.parser.tag.LmlAttribute import com.github.czyzby.lml.parser.tag.LmlTag import com.github.czyzby.lml.vis.parser.impl.VisLmlSyntax import com.github.czyzby.lml.vis.parser.impl.nongwt.ExtendedVisLml import com.github.czyzby.setup.views.widgets.ScrollableTextArea import com.kotcrab.vis.ui.Locales import com.kotcrab.vis.ui.VisUI import com.kotcrab.vis.ui.widget.Tooltip import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.file.FileChooser /** * Configures Autumn MVC application. * @author MJ */ @Component class Configuration { companion object { const val VERSION = "3.0.5-JITPACK" const val WIDTH = 600 const val HEIGHT = 700 const val PREFERENCES_PATH = "SquidSetup-prefs" } @LmlParserSyntax val syntax = VisLmlSyntax() @LmlMacro val macro = "templates/macros.lml" @I18nBundle val bundle = "i18n/nls" @I18nLocale(propertiesPath = PREFERENCES_PATH, defaultLocale = "en") val localePreference = "locale" @AvailableLocales val availableLocales = arrayOf("en", "pl") @Preference val preferencesPath = PREFERENCES_PATH; @Initiate(priority = AutumnActionPriority.TOP_PRIORITY) fun initiate(skinService: SkinService, interfaceService: InterfaceService, localeService: LocaleService) { VisUI.setSkipGdxVersionCheck(true) VisUI.load(Gdx.files.internal("skin/tinted.json")) skinService.addSkin("default", VisUI.getSkin()) FileChooser.setDefaultPrefsName(PREFERENCES_PATH) // Adding tags and attributes related to the file chooser: ExtendedVisLml.registerFileChooser(syntax) ExtendedVisLml.registerFileValidators(syntax) // Adding custom ScrollableTextArea widget: syntax.addTagProvider(ScrollableTextArea.ScrollableTextAreaLmlTagProvider(), "console") // Changing FileChooser locale bundle: interfaceService.setActionOnBundlesReload { Locales.setFileChooserBundle(localeService.i18nBundle) } // Adding custom tooltip tag attribute: interfaceService.parser.syntax.addAttributeProcessor(object : LmlAttribute<Actor> { override fun getHandledType(): Class<Actor> = Actor::class.java override fun process(parser: LmlParser, tag: LmlTag, actor: Actor, rawAttributeData: String) { val tooltip = Tooltip() val label = VisLabel(parser.parseString(rawAttributeData, actor), "small") label.setWrap(true) tooltip.clear() tooltip.add(label).width(200f) tooltip.pad(3f) tooltip.setTarget(actor) tooltip.pack() } }, "tooltip") } }
apache-2.0
bac8240d6478fc3d4c01157a7e827c11
41.589744
110
0.723058
3.992788
false
true
false
false
googlecodelabs/android-foldable-codelab
WindowManager/app/src/androidTest/java/com/example/codelab/windowmanager/ExampleInstrumentedTest.kt
1
2352
/* * * * Copyright (C) 2021 Google Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.example.codelab.windowmanager import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.PositionAssertions import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.window.layout.FoldingFeature.Orientation.Companion.VERTICAL import androidx.window.layout.FoldingFeature.State.Companion.FLAT import androidx.window.testing.layout.WindowLayoutInfoPublisherRule import androidx.window.testing.layout.FoldingFeature import androidx.window.testing.layout.TestWindowLayoutInfo import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MainActivityTest { private val activityRule = ActivityScenarioRule(MainActivity::class.java) private val publisherRule = WindowLayoutInfoPublisherRule() @get:Rule val testRule: TestRule init { testRule = RuleChain.outerRule(publisherRule).around(activityRule) } @Test fun testText_is_left_of_Vertical_FoldingFeature() { activityRule.scenario.onActivity { activity -> val hinge = FoldingFeature( activity = activity, state = FLAT, orientation = VERTICAL, size = 2 ) val expected = TestWindowLayoutInfo(listOf(hinge)) publisherRule.overrideWindowLayoutInfo(expected) } onView(withId(R.id.layout_change)).check( PositionAssertions.isCompletelyLeftOf(withId(R.id.folding_feature)) ) } }
apache-2.0
3437e58203b55f86986f50491cb7bfc8
33.588235
79
0.724065
4.355556
false
true
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/extensions/cursor/SearchApiPaging.kt
1
3285
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED") package jp.nephy.penicillin.extensions.cursor import jp.nephy.penicillin.core.exceptions.PenicillinException import jp.nephy.penicillin.core.i18n.LocalizedString import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.response.JsonObjectResponse import jp.nephy.penicillin.extensions.edit import jp.nephy.penicillin.models.Search /* Next operations */ /** * Whether if current search result has next page. */ val JsonObjectResponse<Search>.hasNext: Boolean get() = !result.searchMetadata.nextResults.isNullOrBlank() internal val NextQueryNotFound = LocalizedString("It is the last result of search.", "次の検索結果はありません。") /** * Creates next page api action. */ val JsonObjectResponse<Search>.next: JsonObjectApiAction<Search> get() { if (!hasNext) { throw PenicillinException(NextQueryNotFound) } result.searchMetadata.nextResults!!.removePrefix("?").split("&").map { it.split("=", limit = 2) }.forEach { (k, v) -> action.edit { parameters(k to v) } } return action.request.jsonObject() } /* Refresh operation */ /** * Whether if current search result is refreshable. */ val JsonObjectResponse<Search>.refreshable: Boolean get() = !result.searchMetadata.refreshUrl.isNullOrBlank() private val RefreshUrlNotFound = LocalizedString("It is not refreshable search endpoint.", "更新できる検索結果はありません。") /** * Creates refreshed page api action. */ val JsonObjectResponse<Search>.refresh: JsonObjectApiAction<Search> get() { if (!refreshable) { throw PenicillinException(RefreshUrlNotFound) } result.searchMetadata.refreshUrl!!.removePrefix("?").split("&").map { it.split("=", limit = 2) }.forEach { (k, v) -> action.edit { parameters(k to v) } } return action.request.jsonObject() }
mit
04d57b8fb5aaaa08d795d151ed9fde2b
31.59596
110
0.698172
4.246053
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/find/finders/rss/RSSFinder.kt
1
2487
package com.github.davinkevin.podcastserver.find.finders.rss import com.github.davinkevin.podcastserver.extension.java.util.orNull import com.github.davinkevin.podcastserver.find.FindCoverInformation import com.github.davinkevin.podcastserver.find.FindPodcastInformation import com.github.davinkevin.podcastserver.find.finders.fetchCoverInformationOrOption import com.github.davinkevin.podcastserver.find.finders.Finder import org.jdom2.Element import org.jdom2.Namespace import org.jdom2.input.SAXBuilder import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toMono import reactor.kotlin.core.util.function.component1 import reactor.kotlin.core.util.function.component2 import java.io.ByteArrayInputStream import java.net.URI import java.util.* import com.github.davinkevin.podcastserver.service.image.ImageService /** * Created by kevin on 22/02/15 */ class RSSFinder( private val imageService: ImageService, private val wcb: WebClient.Builder ) : Finder { private val itunesNS = Namespace.getNamespace("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd")!! override fun findInformation(url: String): Mono<FindPodcastInformation> = wcb .clone() .baseUrl(url) .build() .get() .retrieve() .bodyToMono<String>() .map { SAXBuilder().build(ByteArrayInputStream(it.toByteArray(Charsets.UTF_8))) } .map { it.rootElement.getChild("channel") } .flatMap { findCover(it).zipWith(it.toMono()) } .map { (cover, elem) -> FindPodcastInformation( type = "RSS", url = URI(url), title = elem.getChildText("title"), description = elem.getChildText("description"), cover = cover.orNull() ) } private fun findCover(channelElement: Element): Mono<Optional<FindCoverInformation>> { val rss = channelElement.getChild("image")?.getChildText("url") val itunes = channelElement.getChild("image", itunesNS)?.getAttributeValue("href") val url = rss ?: itunes ?: return Optional.empty<FindCoverInformation>().toMono() return imageService.fetchCoverInformationOrOption(URI(url)) } override fun compatibility(url: String): Int = Integer.MAX_VALUE - 1 }
apache-2.0
2b5d1ac72b1fc4fad6ba20544afa65df
40.45
107
0.701649
4.302768
false
false
false
false
arcao/Geocaching4Locus
geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/Image.kt
1
1449
package com.arcao.geocaching4locus.data.api.model import com.arcao.geocaching4locus.data.api.internal.moshi.adapter.LocalDateTimeUTC import com.arcao.geocaching4locus.data.api.util.ReferenceCode import com.squareup.moshi.JsonClass import java.time.Instant @JsonClass(generateAdapter = true) data class Image( val description: String?, // string val url: String, // string val thumbnailUrl: String?, val referenceCode: String?, // string @LocalDateTimeUTC val createdDate: Instant?, // 2018-06-06T06:16:54.165 val guid: String // string ) { val id by lazy { ReferenceCode.toId(requireNotNull(referenceCode) { "Reference code is null" }) } companion object { private const val FIELD_DESCRIPTION = "description" private const val FIELD_URL = "url" private const val FIELD_THUMBNAIL_URL = "thumbnailUrl" private const val FIELD_REFERENCE_CODE = "referenceCode" private const val FIELD_CREATED_DATE = "createdDate" private const val FIELD_GUID = "guid" val FIELDS_ALL = fieldsOf( FIELD_DESCRIPTION, FIELD_URL, FIELD_THUMBNAIL_URL, FIELD_REFERENCE_CODE, FIELD_CREATED_DATE, FIELD_GUID ) val FIELDS_MIN = fieldsOf( FIELD_DESCRIPTION, FIELD_URL, FIELD_THUMBNAIL_URL, FIELD_GUID ) } }
gpl-3.0
37e53a88d08c38cd89b858cf51f86190
29.829787
82
0.636301
4.325373
false
false
false
false
McGars/Zoomimage
zoomimage/src/main/java/mcgars/com/zoomimage/ui/UiContainer.kt
1
1673
package mcgars.com.zoomimage.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.viewpager.widget.ViewPager import mcgars.com.zoomimage.R class UiContainer( private val rootContainer: ViewGroup, modifier: (View.() -> Unit)? = null ) { internal val zoomPager: ViewPager by lazy { rootContainer.findViewById<ViewPager>(R.id.zoomFullPager) } val zoomToolbar: Toolbar by lazy { rootContainer.findViewById<Toolbar>(R.id.zoomFullToolbar).apply { setNavigationIcon(R.drawable.ic_arrow_back_black_24dp) } } private val vShadow: View by lazy { rootContainer.findViewById<View>(R.id.vZoomShadow) } private val back: View by lazy { rootContainer.findViewById<View>(R.id.zoomFullBackground) } init { val inflater = LayoutInflater.from(rootContainer.context) val v = inflater.inflate(R.layout.zoom_view_image, rootContainer, true) afterInflate() modifier?.invoke(v) } internal fun show(invisible: Boolean, alpha: Int) { val isInvisible = if (invisible) View.INVISIBLE else View.VISIBLE back.visibility = isInvisible back.background.alpha = alpha vShadow.visibility = isInvisible vShadow.background.alpha = alpha zoomToolbar.visibility = isInvisible zoomToolbar.alpha = alpha.toFloat() / 255f } private fun afterInflate() { if (rootContainer.fitsSystemWindows) { arrayOf(back, vShadow, zoomPager).forEach { it.fitsSystemWindows = true } } } }
apache-2.0
71d4b49e5883621a4a170a5ece4a7521
28.368421
107
0.67902
4.192982
false
false
false
false
azizbekian/Spyur
app/src/main/kotlin/com/incentive/yellowpages/misc/Extensions.kt
1
3054
package com.incentive.yellowpages.misc import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.res.Configuration import android.net.ConnectivityManager import android.os.Build import android.os.Parcel import android.os.Parcelable import android.os.ResultReceiver import android.support.annotation.CheckResult import android.support.annotation.ColorRes import android.support.annotation.LayoutRes import android.support.annotation.TransitionRes import android.support.v4.content.ContextCompat import android.transition.TransitionInflater import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.view.inputmethod.InputMethodManager import com.incentive.yellowpages.utils.LogUtils inline fun <reified T : Parcelable> createParcel( crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator<T> = object : Parcelable.Creator<T> { override fun createFromParcel(source: Parcel): T? = createFromParcel(source) override fun newArray(size: Int): Array<out T?> = arrayOfNulls(size) } fun isPortrait(activity: Activity) = activity.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT fun hasVersionM() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M inline fun View.waitForPreDraw(crossinline f: () -> Unit) = with(viewTreeObserver) { addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { viewTreeObserver.removeOnPreDrawListener(this) f() return true } }) } fun Context.getColorInt(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes) fun Context.isConnected(): Boolean { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } fun View.showIme() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager try { val showSoftInputUnchecked = InputMethodManager::class.java.getMethod( "showSoftInputUnchecked", Int::class.javaPrimitiveType, ResultReceiver::class.java) showSoftInputUnchecked.isAccessible = true showSoftInputUnchecked.invoke(imm, 0, null) } catch (e: Exception) { LogUtils.e(e.message) } } fun View.hideIme() { val imm = context.getSystemService(Context .INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @CheckResult fun Context.inflateTransition(@TransitionRes transitionId: Int) = TransitionInflater.from(this).inflateTransition(transitionId) fun View.inflate(@LayoutRes layoutId: Int, root : ViewGroup? = null, attachToRoot: Boolean = false) = LayoutInflater.from(context).inflate(layoutId, root, attachToRoot)
gpl-2.0
dd8f5c50f983e4e45dcaa5ea60ee0fab
39.184211
168
0.768173
4.734884
false
false
false
false
Kotlin/anko
anko/library/generated/sdk23/src/main/java/Layouts.kt
2
67639
@file:JvmName("Sdk23LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.widget.AbsoluteLayout import android.widget.ActionMenuView import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.Toolbar import android.app.ActionBar import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Toolbar(ctx: Context): Toolbar(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Toolbar.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
2ea53092455139a695a4fdf0fca8c829
30.770315
78
0.61055
4.872776
false
false
false
false