repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/messages/dto/MessagesMessageAttachment.kt
1
3383
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.audio.dto.AudioAudio import com.vk.sdk.api.base.dto.BaseSticker import com.vk.sdk.api.calls.dto.CallsCall import com.vk.sdk.api.docs.dto.DocsDoc import com.vk.sdk.api.gifts.dto.GiftsLayout import com.vk.sdk.api.market.dto.MarketMarketAlbum import com.vk.sdk.api.market.dto.MarketMarketItem import com.vk.sdk.api.photos.dto.PhotosPhoto import com.vk.sdk.api.polls.dto.PollsPoll import com.vk.sdk.api.stories.dto.StoriesStory import com.vk.sdk.api.video.dto.VideoVideoFull import com.vk.sdk.api.wall.dto.WallWallComment /** * @param type * @param audio * @param audioMessage * @param call * @param doc * @param gift * @param graffiti * @param market * @param marketMarketAlbum * @param photo * @param sticker * @param story * @param video * @param wallReply * @param poll */ data class MessagesMessageAttachment( @SerializedName("type") val type: MessagesMessageAttachmentType, @SerializedName("audio") val audio: AudioAudio? = null, @SerializedName("audio_message") val audioMessage: MessagesAudioMessage? = null, @SerializedName("call") val call: CallsCall? = null, @SerializedName("doc") val doc: DocsDoc? = null, @SerializedName("gift") val gift: GiftsLayout? = null, @SerializedName("graffiti") val graffiti: MessagesGraffiti? = null, @SerializedName("market") val market: MarketMarketItem? = null, @SerializedName("market_market_album") val marketMarketAlbum: MarketMarketAlbum? = null, @SerializedName("photo") val photo: PhotosPhoto? = null, @SerializedName("sticker") val sticker: BaseSticker? = null, @SerializedName("story") val story: StoriesStory? = null, @SerializedName("video") val video: VideoVideoFull? = null, @SerializedName("wall_reply") val wallReply: WallWallComment? = null, @SerializedName("poll") val poll: PollsPoll? = null )
mit
24ea0bb8e3a48a818320feb737cbde5d
35.771739
81
0.701448
3.94289
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/activity/CafeteriaNotificationSettingsActivity.kt
1
2326
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.activity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaNotificationSettings import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaNotificationSettingsAdapter import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaNotificationTime import kotlinx.android.synthetic.main.activity_cafeteria_notification_settings.* import org.joda.time.DateTime import org.joda.time.DateTimeConstants /** * This activity enables the user to set a preferred notification time for a day of the week. * The actual local storage of the preferences is done in the CafeteriaNotificationSettings class. */ class CafeteriaNotificationSettingsActivity : BaseActivity(R.layout.activity_cafeteria_notification_settings) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val layoutManager = LinearLayoutManager(this) layoutManager.orientation = LinearLayoutManager.VERTICAL notificationSettingsRecyclerView.layoutManager = layoutManager notificationSettingsRecyclerView.setHasFixedSize(true) val notificationSettings = CafeteriaNotificationSettings.getInstance(this) val dailySchedule = buildDailySchedule(notificationSettings) val adapter = CafeteriaNotificationSettingsAdapter(this, dailySchedule) notificationSettingsRecyclerView.adapter = adapter notificationSettingsSaveButton.setOnClickListener { notificationSettings.saveEntireSchedule(dailySchedule) finish() } } /** * Reloads the settings into the dailySchedule list. */ private fun buildDailySchedule( settings: CafeteriaNotificationSettings ): List<CafeteriaNotificationTime> { return (DateTimeConstants.MONDAY until DateTimeConstants.SATURDAY) .map { val day = DateTime.now().withDayOfWeek(it) val time = settings.retrieveLocalTime(day) CafeteriaNotificationTime(day, time) } .toList() } }
gpl-3.0
aa3aedbb60f25537a493b00990753721
42.074074
111
0.746346
5.460094
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/steps_incline/AddStepsInclineForm.kt
1
4162
package de.westnordost.streetcomplete.quests.steps_incline import android.content.res.Resources import android.os.Bundle import androidx.annotation.AnyThread import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.StreetSideRotater import de.westnordost.streetcomplete.quests.steps_incline.StepsIncline.* import de.westnordost.streetcomplete.util.getOrientationAtCenterLineInDegrees import de.westnordost.streetcomplete.view.DrawableImage import de.westnordost.streetcomplete.view.ResImage import de.westnordost.streetcomplete.view.ResText import de.westnordost.streetcomplete.view.RotatedCircleDrawable import de.westnordost.streetcomplete.view.image_select.* import kotlinx.android.synthetic.main.quest_street_side_puzzle.* import kotlinx.android.synthetic.main.view_little_compass.* import kotlin.math.PI class AddStepsInclineForm : AbstractQuestFormAnswerFragment<StepsIncline>() { override val contentLayoutResId = R.layout.quest_oneway override val contentPadding = false private var streetSideRotater: StreetSideRotater? = null private var selection: StepsIncline? = null private var mapRotation: Float = 0f private var wayRotation: Float = 0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.getString(SELECTION)?.let { selection = valueOf(it) } wayRotation = (elementGeometry as ElementPolylinesGeometry).getOrientationAtCenterLineInDegrees() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) puzzleView.showOnlyRightSide() puzzleView.onClickSideListener = { showDirectionSelectionDialog() } val defaultResId = R.drawable.ic_steps_incline_unknown puzzleView.setRightSideImage(ResImage(selection?.iconResId ?: defaultResId)) puzzleView.setRightSideText(selection?.titleResId?.let { resources.getString(it) }) if (selection == null && !HAS_SHOWN_TAP_HINT) { puzzleView.showRightSideTapHint() HAS_SHOWN_TAP_HINT = true } streetSideRotater = StreetSideRotater(puzzleView, compassNeedleView, elementGeometry as ElementPolylinesGeometry) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) selection?.let { outState.putString(SELECTION, it.name) } } override fun isFormComplete() = selection != null override fun onClickOk() { applyAnswer(selection!!) } @AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) { streetSideRotater?.onMapOrientation(rotation, tilt) mapRotation = (rotation * 180 / PI).toFloat() } private fun showDirectionSelectionDialog() { val ctx = context ?: return val items = StepsIncline.values().map { it.toItem(resources, wayRotation + mapRotation) } ImageListPickerDialog(ctx, items, R.layout.labeled_icon_button_cell, 2) { selected -> val dir = selected.value!! puzzleView.replaceRightSideImage(ResImage(dir.iconResId)) puzzleView.setRightSideText(resources.getString(dir.titleResId)) selection = dir checkIsFormComplete() }.show() } companion object { private const val SELECTION = "selection" private var HAS_SHOWN_TAP_HINT = false } } private fun StepsIncline.toItem(resources: Resources, rotation: Float): DisplayItem<StepsIncline> { val drawable = RotatedCircleDrawable(resources.getDrawable(iconResId)) drawable.rotation = rotation return Item2(this, DrawableImage(drawable), ResText(titleResId)) } private val StepsIncline.titleResId: Int get() = R.string.quest_steps_incline_up private val StepsIncline.iconResId: Int get() = when(this) { UP -> R.drawable.ic_steps_incline_up UP_REVERSED -> R.drawable.ic_steps_incline_up_reversed }
gpl-3.0
fd7ccd8b76d443494a44fecef1944ca9
38.264151
121
0.745315
4.588754
false
false
false
false
frendyxzc/KHttp
khttp/src/main/java/vip/frendy/khttp/KSocket.kt
1
2703
package vip.frendy.khttp import okhttp3.* /** * Created by frendy on 2017/9/18. */ class KSocket { var url: String? = null var mWebSocket: WebSocket? = null internal var _open: (webSocket: WebSocket?, response: Response?) -> Unit = { webSocket: WebSocket?, response: Response? -> } internal var _message: (webSocket: WebSocket?, text: String?) -> Unit = { webSocket: WebSocket?, text: String? -> } internal var _closing: (webSocket: WebSocket?, code: Int, reason: String?) -> Unit = { webSocket: WebSocket?, code: Int, reason: String? -> } internal var _closed: (webSocket: WebSocket?, code: Int, reason: String?) -> Unit = { webSocket: WebSocket?, code: Int, reason: String? -> } internal var _failure: (webSocket: WebSocket?, t: Throwable?, response: Response?) -> Unit = { webSocket: WebSocket?, t: Throwable?, response: Response? -> } fun onOpen(onOpen: (webSocket: WebSocket?, response: Response?) -> Unit) { _open = onOpen } fun onMessage(onMessage: (webSocket: WebSocket?, text: String?) -> Unit) { _message = onMessage } fun onClosing(onClosing: (webSocket: WebSocket?, code: Int, reason: String?) -> Unit) { _closing = onClosing } fun onClosed(onClosed: (webSocket: WebSocket?, code: Int, reason: String?) -> Unit) { _closed = onClosed } fun onFailure(onFailure: (webSocket: WebSocket?, t: Throwable?, response: Response?) -> Unit) { _failure = onFailure } fun connect() { val client = OkHttpClient() val request = try { Request.Builder().url(url).build() } catch (e: IllegalArgumentException) { error { "${e.message}" } } val listener = Listener(this) mWebSocket = client.newWebSocket(request, listener) } fun getWebSocket(): WebSocket? { return mWebSocket } } fun Socket(init: KSocket.() -> Unit): KSocket { val wrap = KSocket() wrap.init() wrap.connect() return wrap } class Listener(var wrap: KSocket): WebSocketListener() { override fun onOpen(webSocket: WebSocket?, response: Response?) { wrap._open(webSocket, response) } override fun onMessage(webSocket: WebSocket?, text: String?) { wrap._message(webSocket, text) } override fun onClosing(webSocket: WebSocket?, code: Int, reason: String?) { wrap._closing(webSocket, code, reason) } override fun onClosed(webSocket: WebSocket?, code: Int, reason: String?) { wrap._closed(webSocket, code, reason) } override fun onFailure(webSocket: WebSocket?, t: Throwable?, response: Response?) { wrap._failure(webSocket, t, response) } }
mit
06bb5d40e140082dd8d6ea82ed1e8905
35.053333
161
0.627451
4.152074
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/test/kotlin/examples/kotlin/mybatis3/joins/UserDynamicSQLSupport.kt
1
1291
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.kotlin.mybatis3.joins import org.mybatis.dynamic.sql.AliasableSqlTable import org.mybatis.dynamic.sql.util.kotlin.elements.column import java.sql.JDBCType object UserDynamicSQLSupport { val user = User() val userId = user.userId val userName = user.userName val parentId = user.parentId class User : AliasableSqlTable<User>("User", ::User) { val userId = column<Int>(name = "user_id", jdbcType = JDBCType.INTEGER) val userName = column<String>(name = "user_name", jdbcType = JDBCType.VARCHAR) val parentId = column<Int>(name = "parent_id", jdbcType = JDBCType.INTEGER) } }
apache-2.0
738d2530a7a799465cec3b20ecb27ba3
38.121212
86
0.707204
3.972308
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/PurchaseHandler.kt
1
18785
package com.habitrpg.android.habitica.helpers import android.app.Activity import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit import androidx.core.os.bundleOf import com.android.billingclient.api.AcknowledgePurchaseParams import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingClientStateListener import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.BillingResult import com.android.billingclient.api.ConsumeParams import com.android.billingclient.api.Purchase import com.android.billingclient.api.PurchasesResponseListener import com.android.billingclient.api.PurchasesUpdatedListener import com.android.billingclient.api.SkuDetails import com.android.billingclient.api.SkuDetailsParams import com.android.billingclient.api.acknowledgePurchase import com.android.billingclient.api.consumePurchase import com.android.billingclient.api.queryPurchasesAsync import com.android.billingclient.api.querySkuDetails import com.google.firebase.crashlytics.FirebaseCrashlytics import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.extensions.addOkButton import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.proxy.AnalyticsManager import com.habitrpg.android.habitica.ui.activities.PurchaseActivity import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import com.habitrpg.common.habitica.models.IAPGift import com.habitrpg.common.habitica.models.PurchaseValidationRequest import com.habitrpg.common.habitica.models.Transaction import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.json.JSONObject import retrofit2.HttpException import java.util.Date import kotlin.time.DurationUnit import kotlin.time.toDuration class PurchaseHandler( private val context: Context, private val analyticsManager: AnalyticsManager, private val apiClient: ApiClient, private val userViewModel: MainUserViewModel ) : PurchasesUpdatedListener, PurchasesResponseListener { private val billingClient = BillingClient .newBuilder(context) .setListener(this) .enablePendingPurchases() .build() override fun onPurchasesUpdated(result: BillingResult, purchases: MutableList<Purchase>?) { purchases?.let { processPurchases(result, it) } } override fun onQueryPurchasesResponse(result: BillingResult, purchases: MutableList<Purchase>) { processPurchases(result, purchases) } private fun processPurchases(result: BillingResult, purchases: MutableList<Purchase>) { when (result.responseCode) { BillingClient.BillingResponseCode.OK -> { val mostRecentSub = findMostRecentSubscription(purchases) val plan = userViewModel.user.value?.purchased?.plan for (purchase in purchases) { if (plan?.isActive == true && PurchaseTypes.allSubscriptionTypes.contains(purchase.skus.firstOrNull())) { if ((plan.additionalData?.data?.orderId == purchase.orderId && ((plan.dateTerminated != null) == purchase.isAutoRenewing)) || mostRecentSub?.orderId != purchase.orderId ) { return } } handle(purchase) } } BillingClient.BillingResponseCode.USER_CANCELED -> { return } BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> { CoroutineScope(Dispatchers.IO).launch(ExceptionHandler.coroutine()) { for (purchase in purchases) { consume(purchase) } } } else -> { FirebaseCrashlytics.getInstance().recordException(Throwable(result.debugMessage)) } } } init { startListening() } private var billingClientState: BillingClientState = BillingClientState.UNINITIALIZED private enum class BillingClientState { UNINITIALIZED, READY, UNAVAILABLE, DISCONNECTED; val canMaybePurchase: Boolean get() { return this == UNINITIALIZED || this == READY } } fun startListening() { billingClient.startConnection(object : BillingClientStateListener { override fun onBillingSetupFinished(billingResult: BillingResult) { if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) { billingClientState = BillingClientState.READY queryPurchases() } else { billingClientState = BillingClientState.UNAVAILABLE } } override fun onBillingServiceDisconnected() { billingClientState = BillingClientState.DISCONNECTED } }) } fun stopListening() { billingClient.endConnection() } fun queryPurchases(){ if (billingClientState == BillingClientState.READY){ billingClient.queryPurchasesAsync( BillingClient.SkuType.SUBS, this@PurchaseHandler ) billingClient.queryPurchasesAsync( BillingClient.SkuType.INAPP, this@PurchaseHandler ) } } suspend fun getAllGemSKUs(): List<SkuDetails> = getSKUs(BillingClient.SkuType.INAPP, PurchaseTypes.allGemTypes) suspend fun getAllSubscriptionProducts() = getSKUs(BillingClient.SkuType.SUBS, PurchaseTypes.allSubscriptionTypes) suspend fun getAllGiftSubscriptionProducts() = getSKUs(BillingClient.SkuType.INAPP, PurchaseTypes.allSubscriptionNoRenewTypes) suspend fun getInAppPurchaseSKU(identifier: String) = getSKU(BillingClient.SkuType.INAPP, identifier) private suspend fun getSKUs(type: String, identifiers: List<String>): List<SkuDetails> { return loadInventory(type, identifiers) ?: emptyList() } private suspend fun getSKU(type: String, identifier: String): SkuDetails? { val inventory = loadInventory(type, listOf(identifier)) return inventory?.firstOrNull() } private suspend fun loadInventory(type: String, skus: List<String>): List<SkuDetails>? { retryUntil { billingClientState.canMaybePurchase && billingClient.isReady } val params = SkuDetailsParams .newBuilder() .setSkusList(skus) .setType(type) .build() val skuDetailsResult = withContext(Dispatchers.IO) { billingClient.querySkuDetails(params) } return skuDetailsResult.skuDetailsList } fun purchase(activity: Activity, skuDetails: SkuDetails, recipient: String? = null, isSaleGemPurchase: Boolean = false) { this.isSaleGemPurchase = isSaleGemPurchase recipient?.let { addGift(skuDetails.sku, it) } val flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build() billingClient.launchBillingFlow(activity, flowParams) } private suspend fun consume(purchase: Purchase, retries: Int = 4) { retryUntil { billingClientState.canMaybePurchase && billingClient.isReady } val params = ConsumeParams.newBuilder() .setPurchaseToken(purchase.purchaseToken) .build() val result = billingClient.consumePurchase(params) if (result.billingResult.responseCode != BillingClient.BillingResponseCode.OK) { delay(500) consume(purchase, retries - 1) } } private fun handle(purchase: Purchase) { if (purchase.purchaseState != Purchase.PurchaseState.PURCHASED) { return } val sku = purchase.skus.firstOrNull() when { PurchaseTypes.allGemTypes.contains(sku) -> { val validationRequest = buildValidationRequest(purchase) apiClient.validatePurchase(validationRequest).subscribe({ processedPurchase(purchase) val gift = removeGift(sku) CoroutineScope(Dispatchers.IO).launch(ExceptionHandler.coroutine()) { consume(purchase) } displayConfirmationDialog(purchase, gift?.second) }) { throwable: Throwable -> handleError(throwable, purchase) } } PurchaseTypes.allSubscriptionNoRenewTypes.contains(sku) -> { val validationRequest = buildValidationRequest(purchase) apiClient.validateNoRenewSubscription(validationRequest).subscribe({ processedPurchase(purchase) val gift = removeGift(sku) CoroutineScope(Dispatchers.IO).launch(ExceptionHandler.coroutine()) { consume(purchase) } displayConfirmationDialog(purchase, gift?.second) }) { throwable: Throwable -> handleError(throwable, purchase) } } PurchaseTypes.allSubscriptionTypes.contains(sku) -> { val validationRequest = buildValidationRequest(purchase) apiClient.validateSubscription(validationRequest).subscribe({ processedPurchase(purchase) analyticsManager.logEvent("user_subscribed", bundleOf(Pair("sku", sku))) CoroutineScope(Dispatchers.IO).launch(ExceptionHandler.coroutine()) { acknowledgePurchase(purchase) } displayConfirmationDialog(purchase) }) { throwable: Throwable -> handleError(throwable, purchase) } } } } private suspend fun acknowledgePurchase(purchase: Purchase, retries: Int = 4) { val params = AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.purchaseToken) .build() val response = billingClient.acknowledgePurchase(params) if (response.responseCode != BillingClient.BillingResponseCode.OK) { delay(500) acknowledgePurchase(purchase, retries - 1) } } private fun processedPurchase(purchase: Purchase) { MainScope().launch(ExceptionHandler.coroutine()) { userViewModel.userRepository.retrieveUser(false, true) } } private fun buildValidationRequest(purchase: Purchase): PurchaseValidationRequest { val validationRequest = PurchaseValidationRequest() validationRequest.sku = purchase.skus.firstOrNull() validationRequest.transaction = Transaction() validationRequest.transaction?.receipt = purchase.originalJson validationRequest.transaction?.signature = purchase.signature pendingGifts[validationRequest.sku]?.let { gift -> // If the gift and the purchase happened within 5 minutes, we consider them to match. // Otherwise the gift is probably an old one that wasn't cleared out correctly if (kotlin.math.abs(gift.first.time - purchase.purchaseTime) < 5.toDuration(DurationUnit.MINUTES).inWholeMilliseconds) { validationRequest.gift = IAPGift(gift.second) } else { removeGift(validationRequest.sku ?: "") } } return validationRequest } private fun handleError(throwable: Throwable, purchase: Purchase) { (throwable as? HttpException)?.let { error -> if (error.code() == 401) { val res = apiClient.getErrorResponse(throwable) if (res.message != null && res.message == "RECEIPT_ALREADY_USED") { processedPurchase(purchase) removeGift(purchase.skus.firstOrNull()) CoroutineScope(Dispatchers.IO).launch(ExceptionHandler.coroutine()) { consume(purchase) } return } } } FirebaseCrashlytics.getInstance().recordException(throwable) } suspend fun checkForSubscription(): Purchase? { val result = withContext(Dispatchers.IO) { billingClient.queryPurchasesAsync(BillingClient.SkuType.SUBS) } var fallback: Purchase? = null if (result.billingResult.responseCode == BillingClient.BillingResponseCode.OK) { return findMostRecentSubscription(result.purchasesList) } return fallback } private fun findMostRecentSubscription(purchasesList: List<Purchase>): Purchase? { val purchases = purchasesList.filter { it.isAcknowledged }.sortedByDescending { it.purchaseTime } var fallback: Purchase? = null // If there is a subscription that is still active, prioritise that. Otherwise return the most recent one. for (purchase in purchases) { if (purchase.isAutoRenewing) { return purchase } else if (!purchase.isAutoRenewing && fallback == null) { fallback = purchase } } return fallback } suspend fun cancelSubscription(): User? { apiClient.cancelSubscription() return userViewModel.userRepository.retrieveUser(false, true) } private fun durationString(sku: String): String { return when (sku) { PurchaseTypes.Subscription1MonthNoRenew, PurchaseTypes.Subscription1Month -> "1" PurchaseTypes.Subscription3MonthNoRenew, PurchaseTypes.Subscription3Month -> "3" PurchaseTypes.Subscription6MonthNoRenew, PurchaseTypes.Subscription6Month -> "6" PurchaseTypes.Subscription12MonthNoRenew, PurchaseTypes.Subscription12Month -> "12" else -> "" } } private var isSaleGemPurchase = false private fun gemAmountString(sku: String): String { if (isSaleGemPurchase) { isSaleGemPurchase = false return when (sku) { PurchaseTypes.Purchase4Gems -> "5" PurchaseTypes.Purchase21Gems -> "30" PurchaseTypes.Purchase42Gems -> "60" PurchaseTypes.Purchase84Gems -> "125" else -> "" } } else { return when (sku) { PurchaseTypes.Purchase4Gems -> "4" PurchaseTypes.Purchase21Gems -> "21" PurchaseTypes.Purchase42Gems -> "42" PurchaseTypes.Purchase84Gems -> "84" else -> "" } } } private fun displayConfirmationDialog(purchase: Purchase, giftedTo: String? = null) { CoroutineScope(Dispatchers.Main).launch(ExceptionHandler.coroutine()) { val application = (context as? HabiticaBaseApplication) ?: (context.applicationContext as? HabiticaBaseApplication) ?: return@launch val sku = purchase.skus.firstOrNull() ?: return@launch var title = context.getString(R.string.successful_purchase_generic) val message = when { PurchaseTypes.allSubscriptionNoRenewTypes.contains(sku) -> { title = context.getString(R.string.gift_confirmation_title) context.getString(R.string.gift_confirmation_text_sub, giftedTo, durationString(sku)) } PurchaseTypes.allSubscriptionTypes.contains(sku) -> { if (sku == PurchaseTypes.Subscription1Month) { context.getString(R.string.subscription_confirmation) } else { context.getString(R.string.subscription_confirmation_multiple, durationString(sku)) } } PurchaseTypes.allGemTypes.contains(sku) && giftedTo != null -> { title = context.getString(R.string.gift_confirmation_title) context.getString(R.string.gift_confirmation_text_gems_new, giftedTo, gemAmountString(sku)) } PurchaseTypes.allGemTypes.contains(sku) && giftedTo == null -> { context.getString(R.string.gem_purchase_confirmation, gemAmountString(sku)) } else -> null } application.currentActivity?.get()?.let { activity -> val alert = HabiticaAlertDialog(activity) alert.setTitle(title) message?.let { alert.setMessage(it) } alert.addOkButton { dialog, _ -> dialog.dismiss() if (activity is PurchaseActivity) { activity.finish() } } alert.enqueue() } } } companion object { private const val PENDING_GIFTS_KEY = "PENDING_GIFTS_DATED" private var pendingGifts: MutableMap<String, Pair<Date, String>> = HashMap() private var preferences: SharedPreferences? = null fun addGift(sku: String, userID: String) { pendingGifts[sku] = Pair(Date(), userID) savePendingGifts() } private fun removeGift(sku: String?): Pair<Date, String>? { val gift = pendingGifts.remove(sku) savePendingGifts() return gift } private fun savePendingGifts() { val jsonObject = JSONObject(pendingGifts as Map<*, *>) val jsonString = jsonObject.toString() preferences?.edit { putString(PENDING_GIFTS_KEY, jsonString) } } } } suspend fun retryUntil( times: Int = Int.MAX_VALUE, initialDelay: Long = 100, // 0.1 second maxDelay: Long = 1000, // 1 second factor: Double = 2.0, block: suspend () -> Boolean ) { var currentDelay = initialDelay repeat(times - 1) { if (block()) return delay(currentDelay) currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) } }
gpl-3.0
73ac75a5cd4ba56bd7824e563f73077b
40.285714
132
0.626298
5.33059
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/payCard/PayCardViewModel.kt
1
1579
package com.marknkamau.justjava.ui.payCard import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.marknjunge.core.data.model.ApiResponse import com.marknjunge.core.data.model.CardDetails import com.marknjunge.core.data.model.Resource import com.marknjunge.core.data.repository.PaymentsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class PayCardViewModel @Inject constructor( private val paymentsRepository: PaymentsRepository ) : ViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = _loading fun initiateCardPayment( orderId: String, cardNo: String, expiryMonth: String, expiryYear: String, cvv: String ): LiveData<Resource<ApiResponse>> { val livedata = MutableLiveData<Resource<ApiResponse>>() viewModelScope.launch { _loading.value = true livedata.value = paymentsRepository.initiateCardPayment( orderId, CardDetails( cardNo, cvv, expiryMonth, expiryYear, "07205", "Hillside", "470 Mundet PI", "NJ", "US" ) ) _loading.value = false } return livedata } }
apache-2.0
552029bb580b07fc274f1a2eb38ca065
29.365385
68
0.623179
5.028662
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsSecurityScreen.kt
1
3615
package eu.kanade.presentation.more.settings.screen import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.fragment.app.FragmentActivity import eu.kanade.presentation.more.settings.Preference import eu.kanade.presentation.util.collectAsState import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.core.security.SecurityPreferences import eu.kanade.tachiyomi.util.system.AuthenticatorUtil.authenticate import eu.kanade.tachiyomi.util.system.AuthenticatorUtil.isAuthenticationSupported import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class SettingsSecurityScreen : SearchableSettings { @ReadOnlyComposable @Composable @StringRes override fun getTitleRes() = R.string.pref_category_security @Composable override fun getPreferences(): List<Preference> { val context = LocalContext.current val securityPreferences = remember { Injekt.get<SecurityPreferences>() } val authSupported = remember { context.isAuthenticationSupported() } val useAuthPref = securityPreferences.useAuthenticator() val useAuth by useAuthPref.collectAsState() return listOf( Preference.PreferenceItem.SwitchPreference( pref = useAuthPref, title = stringResource(R.string.lock_with_biometrics), enabled = authSupported, onValueChanged = { (context as FragmentActivity).authenticate( title = context.getString(R.string.lock_with_biometrics), ) }, ), Preference.PreferenceItem.ListPreference( pref = securityPreferences.lockAppAfter(), title = stringResource(R.string.lock_when_idle), subtitle = "%s", enabled = authSupported && useAuth, entries = LockAfterValues .associateWith { when (it) { -1 -> stringResource(R.string.lock_never) 0 -> stringResource(R.string.lock_always) else -> pluralStringResource(id = R.plurals.lock_after_mins, count = it, it) } }, onValueChanged = { (context as FragmentActivity).authenticate( title = context.getString(R.string.lock_when_idle), ) }, ), Preference.PreferenceItem.SwitchPreference( pref = securityPreferences.hideNotificationContent(), title = stringResource(R.string.hide_notification_content), ), Preference.PreferenceItem.ListPreference( pref = securityPreferences.secureScreen(), title = stringResource(R.string.secure_screen), subtitle = "%s", entries = SecurityPreferences.SecureScreenMode.values() .associateWith { stringResource(it.titleResId) }, ), Preference.PreferenceItem.InfoPreference(stringResource(R.string.secure_screen_summary)), ) } } private val LockAfterValues = listOf( 0, // Always 1, 2, 5, 10, -1, // Never )
apache-2.0
a216c1f190ad0c8dcbf1d5c291d1ecb4
38.725275
104
0.628216
5.246734
false
false
false
false
Asqatasun/Asqatasun
engine/scenarioloader/src/main/kotlin/org.asqatasun.service/ScenarioLoaderServiceImpl.kt
1
3453
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * This file is part of Asqatasun. * * Asqatasun is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.service import com.fasterxml.jackson.databind.ObjectMapper import org.asqatasun.entity.audit.Content import org.asqatasun.entity.service.subject.WebResourceDataService import org.asqatasun.entity.subject.Page import org.asqatasun.entity.subject.Site import org.asqatasun.entity.subject.WebResource import org.asqatasun.scenarioloader.ScenarioLoaderFactory import org.asqatasun.scenarioloader.model.SeleniumIdeScenarioBuilder import org.asqatasun.util.FileNaming import org.springframework.stereotype.Service import java.net.URL /** * * @author jkowalczyk */ @Service("scenarioLoaderService") class ScenarioLoaderServiceImpl(private val scenarioLoaderFactory: ScenarioLoaderFactory, private val webResourceDataService: WebResourceDataService): ScenarioLoaderService{ companion object { const val CHUNK_SIZE = 50 } override fun loadScenario(webResource: WebResource, scenarioFile: String?): List<Content> = scenarioLoaderFactory.create(webResource, scenarioFile, 0).run { run(); result} override fun loadScenario(webResource: WebResource, urlList: List<URL>, startRank: Int): List<Content> { val scenario = ObjectMapper().writeValueAsString(SeleniumIdeScenarioBuilder().build(webResource.url, urlList)) return scenarioLoaderFactory.create(webResource, scenario, startRank).run { run(); result} } override fun loadScenario(webResource: WebResource): List<Content> { return when (webResource) { is Page -> { val scenario = ObjectMapper().writeValueAsString(SeleniumIdeScenarioBuilder().build(webResource.url)) loadScenario(webResource, scenario) } is Site -> { val nbUrls = webResourceDataService.getChildWebResourceCount(webResource) var counter = 0 while (counter < nbUrls) { val urlList = webResourceDataService.getWebResourceFromItsParent(webResource, counter, CHUNK_SIZE) .map { URL(FileNaming.addProtocolToUrl(it.url)) } // loadScenario returns a list of Content, but as each content is persisted on the fly, we don't need // to store the returned list, and thus avoid keeping it in memory (in case of big site audits) loadScenario(webResource, urlList, counter + 1) counter += CHUNK_SIZE } emptyList() } else -> emptyList() } } }
agpl-3.0
bda1d61ed6d862e99ac60247a7bd1766
41.62963
121
0.691283
4.641129
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/barcodescanner/BarCodeScannerViewManager.kt
2
1591
package abi43_0_0.expo.modules.barcodescanner import android.content.Context import abi43_0_0.expo.modules.core.ModuleRegistry import abi43_0_0.expo.modules.core.ModuleRegistryDelegate import abi43_0_0.expo.modules.core.ViewManager import abi43_0_0.expo.modules.core.interfaces.ExpoProp import abi43_0_0.expo.modules.interfaces.barcodescanner.BarCodeScannerSettings import java.util.* class BarCodeScannerViewManager( private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ViewManager<BarCodeScannerView>() { enum class Events(private val mName: String) { EVENT_ON_BAR_CODE_SCANNED("onBarCodeScanned"); override fun toString() = mName } override fun getName() = TAG override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } override fun createViewInstance(context: Context) = BarCodeScannerView(context, moduleRegistryDelegate) override fun getViewManagerType() = ViewManagerType.GROUP override fun getExportedEventNames() = Events.values().map { it.toString() } @ExpoProp(name = "type") fun setType(view: BarCodeScannerView, type: Int) { view.setCameraType(type) } @ExpoProp(name = "barCodeTypes") fun setBarCodeTypes(view: BarCodeScannerView, barCodeTypes: ArrayList<Double?>?) { if (barCodeTypes != null) { val settings = BarCodeScannerSettings().apply { putTypes(barCodeTypes) } view.setBarCodeScannerSettings(settings) } } companion object { private const val TAG = "ExpoBarCodeScannerView" } }
bsd-3-clause
3678eab002ef5ef3e0adb124c420baa9
29.018868
87
0.7555
4.121762
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt
1
2454
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.AlertUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer import java.util.* import kotlin.experimental.and class DefaultStatusResponse( encoded: ByteArray ) : ResponseBase(ResponseType.DEFAULT_STATUS_RESPONSE, encoded) { val messageType: Byte = encoded[0] private var first4bytes = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3], encoded[4], encoded[5])).int private var last4bytes = ByteBuffer.wrap(byteArrayOf(encoded[6], encoded[7], encoded[8], encoded[9])).int val podStatus: PodStatus = byValue((encoded[1] and 0x0f), PodStatus.UNKNOWN) val deliveryStatus: DeliveryStatus = byValue(((encoded[1].toInt() and 0xff) shr 4 and 0x0f).toByte(), DeliveryStatus.UNKNOWN) val totalPulsesDelivered: Short = (first4bytes ushr 11 ushr 4 and 0x1FFF).toShort() val sequenceNumberOfLastProgrammingCommand: Short = (first4bytes ushr 11 and 0X0F).toShort() val bolusPulsesRemaining: Short = (first4bytes and 0X7FF).toShort() val activeAlerts: EnumSet<AlertType> = AlertUtil.decodeAlertSet((last4bytes ushr 10 ushr 13 and 0xFF).toByte()) val minutesSinceActivation: Short = ((last4bytes ushr 10 and 0x1FFF)).toShort() val reservoirPulsesRemaining: Short = (last4bytes and 0X3FF).toShort() override fun toString(): String { return "DefaultStatusResponse(" + "messageType=$messageType" + ", deliveryStatus=$deliveryStatus" + ", podStatus=$podStatus" + ", totalPulsesDelivered=$totalPulsesDelivered" + ", sequenceNumberOfLastProgrammingCommand=$sequenceNumberOfLastProgrammingCommand" + ", bolusPulsesRemaining=$bolusPulsesRemaining" + ", activeAlerts=$activeAlerts" + ", minutesSinceActivation=$minutesSinceActivation" + ", reservoirPulsesRemaining=$reservoirPulsesRemaining)" } } infix fun Byte.ushr(i: Int) = toInt() ushr i infix fun Byte.shl(i: Int): Int = toInt() shl i
agpl-3.0
155852cb4ec6a7ab16b8fc768751f25d
50.125
129
0.741239
4.069652
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/ui/preference/ColorPickerPreference.kt
1
1549
package com.sjn.stamp.ui.preference import android.content.Context import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import com.sjn.stamp.R import com.sjn.stamp.utils.getCurrent import io.multimoon.colorful.Colorful import io.multimoon.colorful.ThemeColor class ColorPickerPreference(context: Context, attrs: AttributeSet) : Preference(context, attrs), ColorPickerDialog.OnColorSelectedListener { private var primary: Boolean = false private var accent: Boolean = false init { widgetLayoutResource = R.layout.preference_colorpicker val typedArray = context.obtainStyledAttributes(attrs, R.styleable.colorpicker) try { primary = typedArray.getBoolean(R.styleable.colorpicker_primary_color, false) accent = typedArray.getBoolean(R.styleable.colorpicker_accent_color, false) } finally { typedArray.recycle() } } override fun onColorSelected(color: ThemeColor) { onPreferenceChangeListener?.onPreferenceChange(this, color) } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) (holder.findViewById(R.id.color_indicator) as CircularView).setColor(Colorful().getCurrent(primary).asInt()) } override fun onClick() { super.onClick() ColorPickerDialog(context, primary).apply { setOnColorSelectedListener(this@ColorPickerPreference) }.show() } }
apache-2.0
615ac9a3ca66e696204c46377ba1591e
35.880952
140
0.730148
4.665663
false
false
false
false
TeamMeanMachine/meanlib
src/main/kotlin/org/team2471/frc/lib/math/Fresnel.kt
1
4883
package org.team2471.frc.lib.math /* * This file contains functions for approximating the Fresnel Integrals. */ /** S(x) for small x numerator. */ private val SN = doubleArrayOf( -2.99181919401019853726E3, 7.08840045257738576863E5, -6.29741486205862506537E7, 2.54890880573376359104E9, -4.42979518059697779103E10, 3.18016297876567817986E11 ) /** S(x) for small x denominator. */ private val SD = doubleArrayOf( 2.81376268889994315696E2, 4.55847810806532581675E4, 5.17343888770096400730E6, 4.19320245898111231129E8, 2.24411795645340920940E10, 6.07366389490084639049E11 ) /** C(x) for small x numerator. */ private val CN = doubleArrayOf( -4.98843114573573548651E-8, 9.50428062829859605134E-6, -6.45191435683965050962E-4, 1.88843319396703850064E-2, -2.05525900955013891793E-1, 9.99999999999999998822E-1 ) /** C(x) for small x denominator. */ private val CD = doubleArrayOf( 3.99982968972495980367E-12, 9.15439215774657478799E-10, 1.25001862479598821474E-7, 1.22262789024179030997E-5, 8.68029542941784300606E-4, 4.12142090722199792936E-2, 1.00000000000000000118E0 ) /** Auxiliary function f(x) numerator. */ private val FN = doubleArrayOf( 4.21543555043677546506E-1, 1.43407919780758885261E-1, 1.15220955073585758835E-2, 3.45017939782574027900E-4, 4.63613749287867322088E-6, 3.05568983790257605827E-8, 1.02304514164907233465E-10, 1.72010743268161828879E-13, 1.34283276233062758925E-16, 3.76329711269987889006E-20 ) /** Auxiliary function f(x) denominator. */ private val FD = doubleArrayOf( 7.51586398353378947175E-1, 1.16888925859191382142E-1, 6.44051526508858611005E-3, 1.55934409164153020873E-4, 1.84627567348930545870E-6, 1.12699224763999035261E-8, 3.60140029589371370404E-11, 5.88754533621578410010E-14, 4.52001434074129701496E-17, 1.25443237090011264384E-20 ) /** Auxiliary function g(x) numerator. */ private val GN = doubleArrayOf( 5.04442073643383265887E-1, 1.97102833525523411709E-1, 1.87648584092575249293E-2, 6.84079380915393090172E-4, 1.15138826111884280931E-5, 9.82852443688422223854E-8, 4.45344415861750144738E-10, 1.08268041139020870318E-12, 1.37555460633261799868E-15, 8.36354435630677421531E-19, 1.86958710162783235106E-22 ) /** Auxiliary function g(x) denominator. */ private val GD = doubleArrayOf( 1.47495759925128324529E0, 3.37748989120019970451E-1, 2.53603741420338795122E-2, 8.14679107184306179049E-4, 1.27545075667729118702E-5, 1.04314589657571990585E-7, 4.60680728146520428211E-10, 1.10273215066240270757E-12, 1.38796531259578871258E-15, 8.39158816283118707363E-19, 1.86958710162783236342E-22 ) /** * Compute first polynomial in x. * @param x x * @param coefficients coefficients * @return polynomial in x */ private fun polevl(x: Double, coefficients: DoubleArray): Double = coefficients.fold(coefficients.first()) { acc, c -> acc * x + c } /** * Compute first polynomial in x. * @param x x * @param coefficients coefficients * @return polynomial in x */ private fun p1evl(x: Double, coefficients: DoubleArray): Double = coefficients.fold(x + coefficients.first()) { acc, c -> acc * x + c } /** * Approximate the Fresnel function. * @param xxa the xxa parameter * @return pair of two double values third and s */ fun fresnel(xxa: Double): Pair<Double, Double> { val x = Math.abs(xxa) val x2 = x * x var cc: Double var ss: Double @Suppress("CascadeIf") if (x2 < 2.5625) { val t = x2 * x2 ss = x * x2 * polevl(t, SN) / p1evl(t, SD) cc = x * polevl(t, CN) / polevl(t, CD) } else if (x > 36974.0) { cc = 0.5 ss = 0.5 } else { var t = Math.PI * x2 val u = 1.0 / (t * t) t = 1.0 / t val f = 1.0 - u * polevl(u, FN) / p1evl(u, FD) val g = t * polevl(u, GN) / p1evl(u, GD) t = Math.PI * 0.5 * x2 val c = Math.cos(t) val s = Math.sin(t) t = Math.PI * x cc = 0.5 + (f * s - g * c) / t ss = 0.5 - (f * c + g * s) / t } if (xxa < 0.0) { cc = -cc ss = -ss } return cc to ss } /** * Approximate one point of the "standard" spiral (curvature at start is 0). * @param s run-length along spiral * @param cDot first derivative of curvature [1/m2] * @param initialCurvature curvature at start * @return triple of three double values containing x, y, and tangent direction */ fun odrSpiral(s: Double, cDot: Double, initialCurvature: Double): Triple<Double, Double, Double> { val a = Math.sqrt(Math.PI / Math.abs(cDot)) val (cc, ss) = fresnel(initialCurvature + s / a) return Triple(cc * a, ss * a * Math.signum(cDot), s * s * cDot * 0.5) }
unlicense
030123690930897f923b8fd6d16f79b2
25.977901
118
0.660045
2.515714
false
false
false
false
swjjxyxty/Sault
app/src/main/java/com/bestxty/sault/demo/SingleTaskActivity.kt
2
2637
package com.bestxty.sault.demo import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast import com.bestxty.sault.Sault import kotlinx.android.synthetic.main.activity_single_task.* class SingleTaskActivity : AppCompatActivity(), View.OnClickListener, SingleTaskView { private lateinit var singleViewController: SingleViewController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_single_task) btn_start.setOnClickListener(this) btn_pause.setOnClickListener(this) btn_resume.setOnClickListener(this) btn_cancel.setOnClickListener(this) singleViewController = SingleViewController() singleViewController.attachView(this) enableStartBtn() showStatus("Ready") } override fun onClick(v: View?) { when (v?.id) { R.id.btn_start -> singleViewController.start("http://download.ydstatic.cn/cidian/static/7.0/20170222/YoudaoDictSetup.exe") R.id.btn_pause -> singleViewController.pause() R.id.btn_resume -> singleViewController.resume() R.id.btn_cancel -> singleViewController.cancel() } } override fun onBackPressed() { super.onBackPressed() finish() } override fun showError(msg: String?) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } override fun clearProgress() { pb_progress.progress = 0 text_progress_tip.text = "" } override fun showProgress(totalSize: Long, finishedSize: Long) { pb_progress.progress = Sault.calculateProgress(finishedSize, totalSize) text_progress_tip.text = String.format(getString(R.string.progress_tip), finishedSize, totalSize) } override fun showStatus(status: String?) { text_status.text = status } override fun getContext(): Context = this.applicationContext override fun enableResumeAndCancelBtn() { btn_start.isEnabled = false btn_pause.isEnabled = false btn_resume.isEnabled = true btn_cancel.isEnabled = true } override fun enablePauseAndCancelBtn() { btn_start.isEnabled = false btn_pause.isEnabled = true btn_resume.isEnabled = false btn_cancel.isEnabled = true } override fun enableStartBtn() { btn_start.isEnabled = true btn_pause.isEnabled = false btn_resume.isEnabled = false btn_cancel.isEnabled = false } }
apache-2.0
110342e57aca56e9f03b4f37eba706b7
28.3
134
0.675009
4.380399
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/datamodel/HighlightedCharactersDataModel.kt
1
1127
package com.github.felipehjcosta.marvelapp.wiki.datamodel import com.github.felipehjcosta.marvelapp.base.character.data.CharacterRepository import com.github.felipehjcosta.marvelapp.base.character.data.pojo.Character import io.reactivex.Observable import io.reactivex.Observable.just import javax.inject.Inject class HighlightedCharactersDataModel @Inject constructor(private val repository: CharacterRepository) { companion object { private const val HULK_CHARACTER_ID = 1009351 private const val SPIDER_MAN_CHARACTER_ID = 1009610 private const val WOLVERINE_CHARACTER_ID = 1009718 private const val IRON_MAN_CHARACTER_ID = 1009368 } fun getHighlightedCharacters(): Observable<List<Character>> = just( HULK_CHARACTER_ID, SPIDER_MAN_CHARACTER_ID, WOLVERINE_CHARACTER_ID, IRON_MAN_CHARACTER_ID ) .concatMap { repository.getCharacter(it).toObservable() } .reduce(mutableListOf<Character>()) { acc, element -> acc.apply { add(element) } } .toObservable() .map { it } }
mit
e0ff63404d626f512905811e0caf2dbf
36.566667
103
0.695652
4.318008
false
false
false
false
EmmanuelMess/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/ZipExtractor.kt
2
5660
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents.helpers import android.content.Context import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.file_operations.filesystem.compressed.ArchivePasswordCache import com.amaze.filemanager.file_operations.utils.UpdatePosition import com.amaze.filemanager.filesystem.FileUtil import com.amaze.filemanager.filesystem.MakeDirectoryOperation import com.amaze.filemanager.filesystem.compressed.CompressedHelper import com.amaze.filemanager.filesystem.compressed.extractcontents.Extractor import com.amaze.filemanager.filesystem.files.GenericCopyUtil import net.lingala.zip4j.ZipFile import net.lingala.zip4j.exception.ZipException import net.lingala.zip4j.model.FileHeader import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.File import java.io.IOException import java.util.* class ZipExtractor( context: Context, filePath: String, outputPath: String, listener: OnUpdate, updatePosition: UpdatePosition ) : Extractor(context, filePath, outputPath, listener, updatePosition) { @Throws(IOException::class) override fun extractWithFilter(filter: Filter) { var totalBytes: Long = 0 val entriesToExtract: MutableList<FileHeader> = ArrayList() try { val zipfile = ZipFile(filePath) if (ArchivePasswordCache.getInstance().containsKey(filePath)) { zipfile.setPassword(ArchivePasswordCache.getInstance()[filePath]!!.toCharArray()) } // iterating archive elements to find file names that are to be extracted zipfile.fileHeaders.forEach { obj -> val fileHeader = obj as FileHeader if (CompressedHelper.isEntryPathValid(fileHeader.fileName)) { if (filter.shouldExtract(fileHeader.fileName, fileHeader.isDirectory)) { entriesToExtract.add(fileHeader) totalBytes += fileHeader.uncompressedSize } } else { invalidArchiveEntries.add(fileHeader.fileName) } } if (entriesToExtract.size > 0) { listener.onStart(totalBytes, entriesToExtract[0].fileName) for (entry in entriesToExtract) { if (!listener.isCancelled) { listener.onUpdate(entry.fileName) extractEntry(context, zipfile, entry, outputPath) } } } else { throw EmptyArchiveNotice() } listener.onFinish() } catch (e: ZipException) { throw IOException(e) } } /** * Method extracts [FileHeader] from [ZipFile] * * @param zipFile zip file from which entriesToExtract are to be extracted * @param entry zip entry that is to be extracted * @param outputDir output directory */ @Throws(IOException::class) private fun extractEntry( context: Context, zipFile: ZipFile, entry: FileHeader, outputDir: String ) { val outputFile = File(outputDir, fixEntryName(entry.fileName)) if (!outputFile.canonicalPath.startsWith(outputDir)) { throw IOException("Incorrect ZipEntry path!") } if (entry.isDirectory) { // zip entry is a directory, return after creating new directory MakeDirectoryOperation.mkdir(outputFile, context) return } if (!outputFile.parentFile.exists()) { // creating directory if not already exists MakeDirectoryOperation.mkdir(outputFile.parentFile, context) } val inputStream = BufferedInputStream(zipFile.getInputStream(entry)) FileUtil.getOutputStream(outputFile, context)?.let { fileOutputStream -> BufferedOutputStream(fileOutputStream).run { var len: Int val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE) while (inputStream.read(buf).also { len = it } != -1) { if (!listener.isCancelled) { write(buf, 0, len) updatePosition.updatePosition(len.toLong()) } else break } close() outputFile.setLastModified(entry.lastModifiedTimeEpoch) } } ?: AppConfig.toast( context, context.getString( R.string.error_archive_cannot_extract, entry.fileName, outputDir ) ) } }
gpl-3.0
7d6033c7063362597eba5efa4a393b34
40.014493
107
0.643993
5.094509
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/CustomSourceRootPropertiesEntityImpl.kt
1
9927
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CustomSourceRootPropertiesEntityImpl : CustomSourceRootPropertiesEntity, WorkspaceEntityBase() { companion object { internal val SOURCEROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java, CustomSourceRootPropertiesEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( SOURCEROOT_CONNECTION_ID, ) } override val sourceRoot: SourceRootEntity get() = snapshot.extractOneToOneParent(SOURCEROOT_CONNECTION_ID, this)!! @JvmField var _propertiesXmlTag: String? = null override val propertiesXmlTag: String get() = _propertiesXmlTag!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: CustomSourceRootPropertiesEntityData?) : ModifiableWorkspaceEntityBase<CustomSourceRootPropertiesEntity>(), CustomSourceRootPropertiesEntity.Builder { constructor() : this(CustomSourceRootPropertiesEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CustomSourceRootPropertiesEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(SOURCEROOT_CONNECTION_ID, this) == null) { error("Field CustomSourceRootPropertiesEntity#sourceRoot should be initialized") } } else { if (this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] == null) { error("Field CustomSourceRootPropertiesEntity#sourceRoot should be initialized") } } if (!getEntityData().isPropertiesXmlTagInitialized()) { error("Field CustomSourceRootPropertiesEntity#propertiesXmlTag should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CustomSourceRootPropertiesEntity this.entitySource = dataSource.entitySource this.propertiesXmlTag = dataSource.propertiesXmlTag if (parents != null) { this.sourceRoot = parents.filterIsInstance<SourceRootEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var sourceRoot: SourceRootEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(SOURCEROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity } else { this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneParentOfChild(SOURCEROOT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] = value } changedProperty.add("sourceRoot") } override var propertiesXmlTag: String get() = getEntityData().propertiesXmlTag set(value) { checkModificationAllowed() getEntityData().propertiesXmlTag = value changedProperty.add("propertiesXmlTag") } override fun getEntityData(): CustomSourceRootPropertiesEntityData = result ?: super.getEntityData() as CustomSourceRootPropertiesEntityData override fun getEntityClass(): Class<CustomSourceRootPropertiesEntity> = CustomSourceRootPropertiesEntity::class.java } } class CustomSourceRootPropertiesEntityData : WorkspaceEntityData<CustomSourceRootPropertiesEntity>() { lateinit var propertiesXmlTag: String fun isPropertiesXmlTagInitialized(): Boolean = ::propertiesXmlTag.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CustomSourceRootPropertiesEntity> { val modifiable = CustomSourceRootPropertiesEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): CustomSourceRootPropertiesEntity { val entity = CustomSourceRootPropertiesEntityImpl() entity._propertiesXmlTag = propertiesXmlTag entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CustomSourceRootPropertiesEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CustomSourceRootPropertiesEntity(propertiesXmlTag, entitySource) { this.sourceRoot = parents.filterIsInstance<SourceRootEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(SourceRootEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CustomSourceRootPropertiesEntityData if (this.entitySource != other.entitySource) return false if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CustomSourceRootPropertiesEntityData if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + propertiesXmlTag.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + propertiesXmlTag.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
ad6d19929182fdfda688772b65117d4b
37.777344
178
0.711091
5.698622
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/CodeVisionSelectionController.kt
2
7222
package com.intellij.codeInsight.codeVision.ui.model import com.intellij.codeInsight.codeVision.CodeVisionEntry import com.intellij.codeInsight.codeVision.codeVisionEntryMouseEventKey import com.intellij.codeInsight.codeVision.ui.* import com.intellij.codeInsight.codeVision.ui.renderers.CodeVisionRenderer import com.intellij.codeInsight.codeVision.ui.renderers.painters.CodeVisionTheme import com.intellij.ide.IdeTooltip import com.intellij.ide.IdeTooltipManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.rd.createLifetime import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.UIUtil import com.jetbrains.rd.util.asProperty import com.jetbrains.rd.util.debounceNotNull import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.lifetime.onTermination import com.jetbrains.rd.util.reactive.adviseWithPrev import com.jetbrains.rd.util.reactive.map import com.jetbrains.rd.util.reactive.viewNotNull import java.awt.Cursor import java.awt.Point import java.awt.event.MouseEvent import java.time.Duration import javax.swing.JLabel import javax.swing.SwingUtilities class CodeVisionSelectionController private constructor(val lifetime: Lifetime, val editor: EditorImpl, val projectModel: ProjectCodeVisionModel) { companion object { val map: HashMap<Editor, CodeVisionSelectionController> = HashMap<Editor, CodeVisionSelectionController>() val logger: Logger = logger<CodeVisionSelectionController>() fun install(editor: EditorImpl, projectModel: ProjectCodeVisionModel) { var controller = map[editor] if (controller != null) return val lifetime = editor.disposable.createLifetime() controller = CodeVisionSelectionController(lifetime, editor, projectModel) map[editor] = controller lifetime.onTermination { map.remove(editor) } } } private val hovered = projectModel.hoveredInlay private val hoveredEntry = projectModel.hoveredEntry private val lensPopupActive = projectModel.lensPopupActive init { editor.contentComponent.windowAncestor().map { it != null }.view(lifetime) { ltmain, inHierarchy -> if (inHierarchy) { hovered.adviseWithPrev(ltmain) { previousInlay, currentInlay -> previousInlay.asNullable?.repaint() currentInlay?.repaint() } hovered.view(ltmain) { lt, _ -> hoveredEntry.view(lt) { entryLifetime, _ -> hovered.value?.repaint() editor.mousePressed().advise(entryLifetime) { entryPressHandler(it) } editor.mouseReleased().advise(entryLifetime) { val mouseEvent: MouseEvent = it.mouseEvent checkEditorMousePosition(mouseEvent.point) ?: return@advise if (mouseEvent.isPopupTrigger) it.consume() } } lensPopupActive.view(lt) { activePopupLifetime, popupActive -> if (!popupActive) { hoveredEntry.debounceNotNull(Duration.ofMillis(1000), SwingScheduler).asProperty(null) .viewNotNull(activePopupLifetime) { lt1, it -> showTooltip(lt1, it) } } } } hoveredEntry.map { it != null }.advise(ltmain) { hasHoveredEntry -> updateCursor(hasHoveredEntry) } editor.mousePoint().advise(ltmain) { checkEditorMousePosition(it) } } else if (hovered.value?.editor == editor) { clearHovered() } } } private fun entryPressHandler(event: EditorMouseEvent) { val mouseEvent: MouseEvent = event.mouseEvent val entry = checkEditorMousePosition(mouseEvent.point) ?: return editor.contentComponent.requestFocus() event.consume() val rangeLensesModel = hovered.value?.getUserData(CodeVisionListData.KEY)?.rangeCodeVisionModel ?: return entry.putUserData(codeVisionEntryMouseEventKey, mouseEvent) if (SwingUtilities.isLeftMouseButton(mouseEvent)) { logger.trace { "entryPressHandler :: isLeftMouseButton" } rangeLensesModel.handleLensClick(entry) } else if (SwingUtilities.isRightMouseButton(mouseEvent)) { logger.trace { "entryPressHandler :: isRightMouseButton" } rangeLensesModel.handleLensRightClick() } } private fun updateCursor(hasHoveredEntry: Boolean) { val cursor = if (hasHoveredEntry) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) if (editor.contentComponent.cursor != cursor) UIUtil.setCursor(editor.contentComponent, cursor) } private fun showTooltip(lt: Lifetime, entry: CodeVisionEntry) { val text = entry.tooltipText() if (text.isEmpty()) return val ld = lt.createNested() val inlay = hovered.value ?: return val inlayBounds = inlay.bounds ?: return val renderer = inlay.renderer as CodeVisionRenderer val entryBounds = renderer.entryBounds(inlay, entry) ?: return val x = inlayBounds.x + entryBounds.x + (entryBounds.width / 2) val y = inlayBounds.y + (inlayBounds.height / 2) val contentComponent = inlay.editor.contentComponent val component = inlay.editor.component val relativePoint = RelativePoint(contentComponent, Point(x, y)) val tooltip = IdeTooltip(component, relativePoint.getPoint(component), JLabel(text)) val currentTooltip = IdeTooltipManager.getInstance().show(tooltip, false, false) inlay.editor.scrollingModel.visibleAreaChanged().advise(ld) { ld.terminate() } ld.onTermination { currentTooltip.hide() } } private fun checkEditorMousePosition(editorMousePosition: Point?): CodeVisionEntry? { if (editorMousePosition == null) { clearHovered() return null } val hoveredInlay = editor.inlayModel.getElementAt(editorMousePosition) return updateHovered(hoveredInlay, editorMousePosition) } private fun updateHovered(hoveredInlay: Inlay<EditorCustomElementRenderer>?, mouseOnInlay: Point?): CodeVisionEntry? { if (mouseOnInlay == null || hoveredInlay == null || hoveredInlay.renderer !is CodeVisionRenderer) { clearHovered() return null } val bounds = hoveredInlay.bounds ?: run { clearHovered() return null } if (CodeVisionTheme.yInInlayBounds(mouseOnInlay.y, bounds)) { val renderer = hoveredInlay.renderer as CodeVisionRenderer val entry = renderer.hoveredEntry(hoveredInlay, mouseOnInlay.x - bounds.x, mouseOnInlay.y - bounds.y) hovered.set(hoveredInlay) hoveredEntry.set(entry) return entry } clearHovered() return null } private fun clearHovered() { hovered.set(null) hoveredEntry.set(null) } }
apache-2.0
9eef422cc632f6d46cdd7b427656ba6d
34.063107
120
0.707837
4.542138
false
false
false
false
DanielGrech/anko
preview/xml-converter/testData/linearLayout/layout.kt
6
305
linearLayout { button.layoutParams(width = matchParent, height = wrapContent) { gravity = Gravity.END bottomMargin = dip(5) } textView.layoutParams(width = wrapContent, height = matchParent) { gravity = Gravity.CENTER weight = 5 margin = dip(10) } }
apache-2.0
37fcf1ef5f8e9eefc66610335d12e906
26.818182
70
0.613115
4.621212
false
false
true
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/china/ChinaCard.kt
1
5877
/* * ChinaCard.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.china import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface import au.id.micolous.metrodroid.card.iso7816.* import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.ui.ListItemRecursive import au.id.micolous.metrodroid.util.ImmutableByteArray import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable data class ChinaCard( override val generic: ISO7816ApplicationCapsule, val balances: Map<Int, ImmutableByteArray>) : ISO7816Application() { @Transient override val rawData: List<ListItem>? get() = balances.map { (idx, data) -> ListItemRecursive.collapsedValue( Localizer.localizeString(R.string.china_balance, idx), data.toHexDump()) } private fun findFactory() = ChinaRegistry.allFactories.find { it.check(this) } override fun parseTransitIdentity(card: ISO7816Card): TransitIdentity? = findFactory()?.parseTransitIdentity(this) override fun parseTransitData(card: ISO7816Card): TransitData? = findFactory()?.parseTransitData(this) fun getBalance(idx: Int): ImmutableByteArray? = balances[idx] @Transient override val type: String get() = TYPE companion object { private const val TAG = "ChinaCard" private const val TYPE = "china" private const val INS_GET_BALANCE: Byte = 0x5c private const val BALANCE_RESP_LEN: Byte = 4 val FACTORY: ISO7816ApplicationFactory = object : ISO7816ApplicationFactory { override val typeMap: Map<String, KSerializer<out ISO7816Application>> get() = mapOf(TYPE to ChinaCard.serializer() ) override val applicationNames: Collection<ImmutableByteArray> get() = ChinaRegistry.allFactories.flatMap { it.appNames } /** * Dumps a China card in the field. * @param protocol Tag to dump. * @param capsule ISO7816 app interface * @return Dump of the card contents. Returns null if an unsupported card is in the * field. * @throws Exception On communication errors. */ override suspend fun dumpTag(protocol: ISO7816Protocol, capsule: ISO7816ApplicationMutableCapsule, feedbackInterface: TagReaderFeedbackInterface): List<ISO7816Application>? { val bals = mutableMapOf<Int, ImmutableByteArray>() try { feedbackInterface.updateProgressBar(0, 6) capsule.dumpAllSfis(protocol, feedbackInterface, 0, 32) factories@ for (f in ChinaRegistry.allFactories) { for (transitAppName in f.appNames) { if (capsule.appName?.contentEquals(transitAppName) == true) { val cl = f.allCards if (!cl.isEmpty()) { val ci = cl[0] feedbackInterface.updateStatusText(Localizer.localizeString(R.string.card_reading_type, ci.name)) feedbackInterface.showCardType(ci) } break@factories } } } feedbackInterface.updateProgressBar(0, 5) for (i in 0..3) { try { bals[i] = protocol.sendRequest(ISO7816Protocol.CLASS_80, INS_GET_BALANCE, i.toByte(), 2.toByte(), BALANCE_RESP_LEN) } catch (e: Exception) { Log.w(TAG, "Caught exception on balance $i: $e") } } feedbackInterface.updateProgressBar(1, 16) var progress = 2 for (j in 0..1) for (f in intArrayOf(4, 5, 8, 9, 10, 21, 24, 25)) { val sel = if (j == 1) ISO7816Selector.makeSelector(0x1001, f) else ISO7816Selector.makeSelector(f) try { capsule.dumpFile(protocol, sel, 0) } catch (e: Exception) { Log.w(TAG, "Caught exception on file " + sel.formatString() + ": " + e) } feedbackInterface.updateProgressBar(progress++, 16) } } catch (e: Exception) { Log.w(TAG, "Got exception $e") return null } return listOf<ISO7816Application>(ChinaCard(capsule.freeze(), bals)) } } } }
gpl-3.0
4b057ddce31f6e0237a81a729e028bcd
40.978571
186
0.580738
4.901585
false
false
false
false
carltonwhitehead/crispy-fish
library/src/main/kotlin/org/coner/crispyfish/query/ThsccConeKillerQuery.kt
1
2913
package org.coner.crispyfish.query import org.coner.crispyfish.filetype.classdefinition.ClassDefinitionFile import org.coner.crispyfish.filetype.ecf.EventControlFile import org.coner.crispyfish.model.* class ThsccConeKillerQuery( private val classDefinitionFile: ClassDefinitionFile, private val eventControlFile: EventControlFile, private val eventDay: EventDay = EventDay.ONE ) { fun query(): List<ThsccConeKillerResult> { val categories = CategoriesQuery(classDefinitionFile).query() val handicaps = HandicapsQuery(classDefinitionFile).query() val registrations = RegistrationsQuery( eventControlFile = eventControlFile, categories = categories, handicaps = handicaps ).query() val registrationsAndConedRuns = registrations .map { registration -> registration to registration.runs.filter { run -> run.penalty is RegistrationRun.Penalty.Cone } } .map { (registration, conedRuns) -> registration to conedRuns.sortedByDescending { (it.penalty as RegistrationRun.Penalty.Cone).count } } return registrationsAndConedRuns.sortedWith(comparator) .mapIndexed { index, (registration, conedRuns) -> ThsccConeKillerResult( position = index + 1, registration = registration, conedRuns = conedRuns ) } } private val comparator = Comparator<Pair<Registration, List<RegistrationRun>>> { left, right -> val (leftRegistration, leftConedRuns) = left val (rightRegistration, rightConedRuns) = right val padToSize = maxOf(leftConedRuns.size, rightConedRuns.size) val mapCones = { run: RegistrationRun -> (run.penalty as RegistrationRun.Penalty.Cone).count } val leftCones = leftConedRuns.map(mapCones).sortedDescending() val rightCones = rightConedRuns.map(mapCones).sortedDescending() val compareLeftCones = leftCones.padded(toSize = padToSize, withValue = 0) val compareRightCones = rightCones.padded(toSize = padToSize, withValue = 0) for ((leftCone, rightCone) in compareLeftCones.zip(compareRightCones)) { if (leftCone == rightCone) continue else if (leftCone < rightCone) return@Comparator 1 else if (leftCone > rightCone) return@Comparator -1 } 0 } private fun List<Int>.padded(toSize: Int, withValue: Int): List<Int> { if (this.size >= toSize) return toList() return toMutableList().apply { while (size < toSize) { add(withValue) } } } }
gpl-2.0
00e4a2305cb17e0919f100642b9a03de
42.492537
102
0.607964
4.77541
false
false
false
false
YutaKohashi/FakeLineApp
app/src/main/java/jp/yuta/kohashi/fakelineapp/activities/ImagePreviewActivity.kt
1
3041
package jp.yuta.kohashi.fakelineapp.activities import android.content.Intent import android.net.Uri import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.FrameLayout import android.widget.ImageView import jp.yuta.kohashi.fakelineapp.R import jp.yuta.kohashi.fakelineapp.ad.BaseAdBannerActivity import jp.yuta.kohashi.fakelineapp.managers.FileManager import jp.yuta.kohashi.fakelineapp.managers.IntentHelper import jp.yuta.kohashi.fakelineapp.utils.ToastUtil import jp.yuta.kohashi.fakelineapp.utils.Util import kotlinx.android.synthetic.main.activity_ad_banner.* /** * Author : yutakohashi * Project name : FakeLineApp * Date : 07 / 09 / 2017 */ class ImagePreviewActivity : BaseAdBannerActivity() { private var mImageView: ImageView? = null // scheme file private var mImagePathUri: Uri? = null companion object { val KEY_IMAGE_PATH: String = "image_path" } override fun setView(): View? { mImageView = ImageView(this) mImageView!!.scaleType = ImageView.ScaleType.FIT_CENTER mImageView!!.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) return mImageView } override fun setFragment(): Fragment? = null override fun setEvent() { toolbarVisibility = true toolbarBackable = true toolbar.title = "" super.setEvent() mImagePathUri = Util.strToUri(intent.getStringExtra(KEY_IMAGE_PATH), "file") if (mImagePathUri != null) Util.setImageByGlide(mImagePathUri!!, mImageView!!) else { // TODO toast error when imagepath is empty finish() } fragmentContainer.setBackgroundColor(Util.getColor(R.color.bg_image_preview)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_image_preview, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.action_share -> actionShare() R.id.action_delete -> actionDelete() } return super.onOptionsItemSelected(item) } private fun actionShare() { mImagePathUri?.let { IntentHelper.actionShare(this@ImagePreviewActivity, it) } } private fun actionDelete() { mImagePathUri?.let { AlertDialog.Builder(this) .setTitle(Util.getString(R.string.confirmation)) .setMessage(Util.getString(R.string.text_delete_dialog)) .setPositiveButton(Util.getString(R.string.yes)) { _, _ -> FileManager(this).deleteFile(it) ToastUtil.doneDelete() finish() } .setNegativeButton(Util.getString(R.string.no), null) .show() } } }
mit
4b74b5123025d4b0392e53c4f38b09c0
31.010526
138
0.658336
4.247207
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/infos/CapturedInInlinedClosure.kt
8
2837
// FIR_IDENTICAL <info descr="null" tooltip="null">inline</info> fun <T> run(f: () -> T) = f() fun run2(f: () -> Unit) = f() fun inline() { val x = 1 run { x } val x1 = 1 run ({ x1 }) val x2 = 1 run (<info descr="null" tooltip="null">f =</info> { x2 }) val x3 = 1 run { run { x3 } } } fun notInline() { val y2 = 1 run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">y2</info> } run2 { <warning><info descr="Value captured in a closure" tooltip="Value captured in a closure">y2</info></warning> } val y3 = 1 run2 { <warning><info descr="Value captured in a closure" tooltip="Value captured in a closure">y3</info></warning> } run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">y3</info> } // wrapped, using in not inline val z = 2 { <info descr="Value captured in a closure" tooltip="Value captured in a closure">z</info> }() val z1 = 3 run2 { <warning><info descr="Value captured in a closure" tooltip="Value captured in a closure">z1</info></warning> } } fun nestedDifferent() { // inline within non-inline and vice-versa val y = 1 { run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">y</info> } }() val y1 = 1 run { { <info descr="Value captured in a closure" tooltip="Value captured in a closure">y1</info> }() } } fun localFunctionAndClass() { val u = 1 fun localFun() { run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">u</info> } } val v = 1 class LocalClass { fun f() { run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">v</info> } } } } fun objectExpression() { val u1 = 1 object : Any() { fun f() { run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">u1</info> } } } val u2 = 1 object : Any() { val prop = run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">u2</info> } } val u3 = "" object : Throwable(run { <info descr="Value captured in a closure" tooltip="Value captured in a closure">u3</info> }) { } } <info>inline</info> fun withNoInlineParam(<info>noinline</info> task1: () -> Unit, task2: () -> Unit) { task1() task2() } fun usage(param1: Int, param2: Int) { withNoInlineParam({ println(<info descr="Value captured in a closure" tooltip="Value captured in a closure">param1</info>) }, { println(param2) }) } fun println(<warning>a</warning>: Any) {}
apache-2.0
625f8b206dbc89a35e1bf724cfed6bcd
26.543689
150
0.570321
3.604828
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/ChapterKnownBackupPutResolver.kt
2
1408
package eu.kanade.tachiyomi.data.database.resolvers import androidx.core.content.contentValuesOf import com.pushtorefresh.storio.sqlite.StorIOSQLite import com.pushtorefresh.storio.sqlite.operations.put.PutResolver import com.pushtorefresh.storio.sqlite.operations.put.PutResult import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.inTransactionReturn import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.tables.ChapterTable class ChapterKnownBackupPutResolver : PutResolver<Chapter>() { override fun performPut(db: StorIOSQLite, chapter: Chapter) = db.inTransactionReturn { val updateQuery = mapToUpdateQuery(chapter) val contentValues = mapToContentValues(chapter) val numberOfRowsUpdated = db.lowLevel().update(updateQuery, contentValues) PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table()) } fun mapToUpdateQuery(chapter: Chapter) = UpdateQuery.builder() .table(ChapterTable.TABLE) .where("${ChapterTable.COL_ID} = ?") .whereArgs(chapter.id) .build() fun mapToContentValues(chapter: Chapter) = contentValuesOf( ChapterTable.COL_READ to chapter.read, ChapterTable.COL_BOOKMARK to chapter.bookmark, ChapterTable.COL_LAST_PAGE_READ to chapter.last_page_read ) }
apache-2.0
3d7328f939e40d4e4348f71373b831b0
40.411765
90
0.753551
4.386293
false
false
false
false
cmzy/okhttp
okhttp/src/test/java/okhttp3/CacheCorruptionTest.kt
2
5802
/* * Copyright (C) 2020 Square, 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 okhttp3 import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.internal.buildCache import okhttp3.okio.LoggingFilesystem import okhttp3.testing.PlatformRule import okhttp3.tls.internal.TlsUtil.localhost import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import java.net.CookieManager import java.net.ResponseCache import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone import java.util.concurrent.TimeUnit import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSession class CacheCorruptionTest( var server: MockWebServer ) { var fileSystem = FakeFileSystem() @JvmField @RegisterExtension val clientTestRule = OkHttpClientTestRule() @JvmField @RegisterExtension val platform = PlatformRule() private val handshakeCertificates = localhost() private lateinit var client: OkHttpClient private lateinit var cache: Cache private val NULL_HOSTNAME_VERIFIER = HostnameVerifier { _: String?, _: SSLSession? -> true } private val cookieManager = CookieManager() @BeforeEach fun setUp() { platform.assumeNotOpenJSSE() platform.assumeNotBouncyCastle() server.protocolNegotiationEnabled = false val loggingFileSystem = LoggingFilesystem(fileSystem) cache = buildCache("/cache/".toPath(), Int.MAX_VALUE.toLong(), loggingFileSystem) client = clientTestRule.newClientBuilder() .cache(cache) .cookieJar(JavaNetCookieJar(cookieManager)) .build() } @AfterEach fun tearDown() { ResponseCache.setDefault(null) if (this::cache.isInitialized) { cache.delete() } } @Test fun corruptedCipher() { val response = testCorruptingCache { corruptMetadata { // mess with cipher suite it.replace("TLS_", "SLT_") } } assertThat(response.body!!.string()).isEqualTo("ABC.1") // cached assertThat(cache.requestCount()).isEqualTo(2) assertThat(cache.networkCount()).isEqualTo(1) assertThat(cache.hitCount()).isEqualTo(1) assertThat(response.handshake?.cipherSuite?.javaName).startsWith("SLT_") } @Test fun truncatedMetadataEntry() { val response = testCorruptingCache { corruptMetadata { // truncate metadata to 1/4 of length it.substring(0, it.length / 4) } } assertThat(response.body!!.string()).isEqualTo("ABC.2") // not cached assertThat(cache.requestCount()).isEqualTo(2) assertThat(cache.networkCount()).isEqualTo(2) assertThat(cache.hitCount()).isEqualTo(0) } @Test fun corruptedUrl() { val response = testCorruptingCache { corruptMetadata { // strip https scheme it.substring(5) } } assertThat(response.body!!.string()).isEqualTo("ABC.2") // not cached assertThat(cache.requestCount()).isEqualTo(2) assertThat(cache.networkCount()).isEqualTo(2) assertThat(cache.hitCount()).isEqualTo(0) } private fun corruptMetadata(corruptor: (String) -> String) { val metadataFile = fileSystem.allPaths.find { it.name.endsWith(".0") } if (metadataFile != null) { val contents = fileSystem.read(metadataFile) { readUtf8() } fileSystem.write(metadataFile) { writeUtf8(corruptor(contents)) } } } private fun testCorruptingCache(corruptor: () -> Unit): Response { server.useHttps(handshakeCertificates.sslSocketFactory(), false) server.enqueue( MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC.1") ) server.enqueue( MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC.2") ) client = client.newBuilder() .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager ) .hostnameVerifier(NULL_HOSTNAME_VERIFIER) .build() val request: Request = Request.Builder().url(server.url("/")).build() val response1: Response = client.newCall(request).execute() val bodySource = response1.body!!.source() assertThat(bodySource.readUtf8()).isEqualTo("ABC.1") corruptor() return client.newCall(request).execute() } /** * @param delta the offset from the current date to use. Negative values yield dates in the past; * positive values yield dates in the future. */ private fun formatDate(delta: Long, timeUnit: TimeUnit): String? { return formatDate(Date(System.currentTimeMillis() + timeUnit.toMillis(delta))) } private fun formatDate(date: Date): String? { val rfc1123: DateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US) rfc1123.timeZone = TimeZone.getTimeZone("GMT") return rfc1123.format(date) } }
apache-2.0
cdd7f87a863dfd110cadeb98a9849d66
30.026738
99
0.705274
4.253666
false
true
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/render/RenderReeds.kt
1
3090
package mods.betterfoliage.client.render import mods.betterfoliage.BetterFoliageMod import mods.betterfoliage.client.Client import mods.betterfoliage.client.config.Config import mods.betterfoliage.client.integration.ShadersModIntegration import mods.octarinecore.client.render.* import mods.octarinecore.common.Int3 import mods.octarinecore.common.Rotation import mods.octarinecore.random import net.minecraft.block.material.Material import net.minecraft.client.renderer.BlockRendererDispatcher import net.minecraft.client.renderer.BufferBuilder import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumFacing.UP import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import org.apache.logging.log4j.Level @SideOnly(Side.CLIENT) class RenderReeds : AbstractBlockRenderingHandler(BetterFoliageMod.MOD_ID) { val noise = simplexNoise() val reedIcons = iconSet(Client.genReeds.generatedResource("${BetterFoliageMod.LEGACY_DOMAIN}:blocks/better_reed_%d")) val reedModels = modelSet(64) { modelIdx -> val height = random(Config.reed.heightMin, Config.reed.heightMax) val waterline = 0.875f val vCutLine = 0.5 - waterline / height listOf( // below waterline verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.5, yTop = 0.5 + waterline) .setFlatShader(FlatOffsetNoColor(up1)).clampUV(minV = vCutLine), // above waterline verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.5 + waterline, yTop = 0.5 + height) .setFlatShader(FlatOffsetNoColor(up2)).clampUV(maxV = vCutLine) ).forEach { it.clampUV(minU = -0.25, maxU = 0.25) .toCross(UP) { it.move(xzDisk(modelIdx) * Config.reed.hOffset) }.addAll() } } override fun afterPreStitch() { Client.log(Level.INFO, "Registered ${reedIcons.num} reed textures") } override fun isEligible(ctx: BlockContext) = Config.enabled && Config.reed.enabled && ctx.blockState(up2).material == Material.AIR && ctx.blockState(up1).material == Material.WATER && Config.blocks.dirt.matchesClass(ctx.block) && ctx.biomeId in Config.reed.biomes && noise[ctx.pos] < Config.reed.population override fun render(ctx: BlockContext, dispatcher: BlockRendererDispatcher, renderer: BufferBuilder, layer: BlockRenderLayer): Boolean { val baseRender = renderWorldBlockBase(ctx, dispatcher, renderer, layer) if (!layer.isCutout) return baseRender modelRenderer.updateShading(Int3.zero, allFaces) val iconVar = ctx.random(1) ShadersModIntegration.grass(renderer, Config.reed.shaderWind) { modelRenderer.render( renderer, reedModels[ctx.random(0)], Rotation.identity, forceFlat = true, icon = { _, _, _ -> reedIcons[iconVar]!! }, postProcess = noPost ) } return true } }
mit
138421a74775d06cba1d453af8ffd2fb
40.77027
140
0.676375
3.824257
false
true
false
false
kunny/RxBinding
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/view/RxMenuItem.kt
1
4538
package com.jakewharton.rxbinding.view import android.graphics.drawable.Drawable import android.view.MenuItem import com.jakewharton.rxbinding.internal.Functions import rx.Observable import rx.functions.Action1 import rx.functions.Func1 /** * Create an observable which emits on `menuItem` click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. * * *Warning:* The created observable uses [MenuItem.setOnMenuItemClickListener] to * observe clicks. Only one observable can be used for a menu item at a time. */ public inline fun MenuItem.clicks(): Observable<Unit> = RxMenuItem.clicks(this).map { Unit } /** * Create an observable which emits on `menuItem` click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. * * *Warning:* The created observable uses [MenuItem.setOnMenuItemClickListener] to * observe clicks. Only one observable can be used for a menu item at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [MenuItem.OnMenuItemClickListener]. */ public inline fun MenuItem.clicks(handled: Func1<in MenuItem, Boolean>): Observable<Unit> = RxMenuItem.clicks(this, handled).map { Unit } /** * Create an observable of action view events for `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. * * *Warning:* The created observable uses [MenuItem.setOnActionExpandListener] to * observe action view events. Only one observable can be used for a menu item at a time. */ public inline fun MenuItem.actionViewEvents(): Observable<MenuItemActionViewEvent> = RxMenuItem.actionViewEvents(this) /** * Create an observable of action view events for `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. * * *Warning:* The created observable uses [MenuItem.setOnActionExpandListener] to * observe action view events. Only one observable can be used for a menu item at a time. * * @param handled Function invoked with each value to determine the return value of the * underlying [MenuItem.OnActionExpandListener]. */ public inline fun MenuItem.actionViewEvents(handled: Func1<in MenuItemActionViewEvent, Boolean>): Observable<MenuItemActionViewEvent> = RxMenuItem.actionViewEvents(this, handled) /** * An action which sets the checked property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.checked(): Action1<in Boolean> = RxMenuItem.checked(this) /** * An action which sets the enabled property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.enabled(): Action1<in Boolean> = RxMenuItem.enabled(this) /** * An action which sets the icon property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.icon(): Action1<in Drawable> = RxMenuItem.icon(this) /** * An action which sets the icon property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.iconRes(): Action1<in Int> = RxMenuItem.iconRes(this) /** * An action which sets the title property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.title(): Action1<in CharSequence> = RxMenuItem.title(this) /** * An action which sets the title property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.titleRes(): Action1<in Int> = RxMenuItem.titleRes(this) /** * An action which sets the visibility property of `menuItem`. * * *Warning:* The created observable keeps a strong reference to `menuItem`. * Unsubscribe to free this reference. */ public inline fun MenuItem.visible(): Action1<in Boolean> = RxMenuItem.visible(this)
apache-2.0
f13bb28885c60131da51da99261a95a6
38.12069
178
0.754738
4.313688
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/login/ResetPasswordActivity.kt
1
6403
package org.wikipedia.login import android.accounts.AccountAuthenticatorResponse import android.accounts.AccountManager import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.inputmethod.EditorInfo import com.google.android.material.textfield.TextInputLayout import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.BaseActivity import org.wikipedia.auth.AccountUtil.updateAccount import org.wikipedia.createaccount.CreateAccountActivity.Companion.validateInput import org.wikipedia.createaccount.CreateAccountActivity.ValidateResult import org.wikipedia.databinding.ActivityResetPasswordBinding import org.wikipedia.login.LoginClient.LoginFailedException import org.wikipedia.util.DeviceUtil import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.log.L import org.wikipedia.views.NonEmptyValidator class ResetPasswordActivity : BaseActivity() { private lateinit var binding: ActivityResetPasswordBinding private lateinit var firstStepToken: String private lateinit var userName: String private var loginClient: LoginClient? = null private val loginCallback = LoginCallback() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityResetPasswordBinding.inflate(layoutInflater) setContentView(binding.root) binding.viewLoginError.backClickListener = View.OnClickListener { onBackPressed() } binding.viewLoginError.retryClickListener = View.OnClickListener { binding.viewLoginError.visibility = View.GONE } NonEmptyValidator(binding.loginButton, binding.resetPasswordInput, binding.resetPasswordRepeat) binding.resetPasswordInput.editText?.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { validateThenLogin() return@setOnEditorActionListener true } false } binding.loginButton.setOnClickListener { validateThenLogin() } userName = intent.getStringExtra(LOGIN_USER_NAME).orEmpty() firstStepToken = intent.getStringExtra(LOGIN_TOKEN).orEmpty() } override fun onBackPressed() { DeviceUtil.hideSoftKeyboard(this) super.onBackPressed() } override fun onStop() { showProgressBar(false) super.onStop() } private fun clearErrors() { binding.resetPasswordInput.isErrorEnabled = false binding.resetPasswordRepeat.isErrorEnabled = false } private fun validateThenLogin() { clearErrors() when (validateInput(userName, getText(binding.resetPasswordInput), getText(binding.resetPasswordRepeat), "")) { ValidateResult.INVALID_PASSWORD -> { binding.resetPasswordInput.requestFocus() binding.resetPasswordInput.error = getString(R.string.create_account_password_error) return } ValidateResult.PASSWORD_MISMATCH -> { binding.resetPasswordRepeat.requestFocus() binding.resetPasswordRepeat.error = getString(R.string.create_account_passwords_mismatch_error) return } else -> { } } doLogin() } private fun getText(input: TextInputLayout): String { return input.editText?.text?.toString().orEmpty() } private fun doLogin() { val password = getText(binding.resetPasswordInput) val retypedPassword = getText(binding.resetPasswordRepeat) val twoFactorCode = binding.login2faText.text.toString() showProgressBar(true) if (loginClient == null) { loginClient = LoginClient() } loginClient?.login(WikipediaApp.getInstance().wikiSite, userName, password, retypedPassword, twoFactorCode, firstStepToken, loginCallback) } private inner class LoginCallback : LoginClient.LoginCallback { override fun success(result: LoginResult) { showProgressBar(false) if (result.pass()) { val extras = intent.extras val response = extras?.getParcelable<AccountAuthenticatorResponse>(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE) updateAccount(response, result) DeviceUtil.hideSoftKeyboard(this@ResetPasswordActivity) setResult(RESULT_OK) finish() } else if (result.fail()) { val message = result.message FeedbackUtil.showMessage(this@ResetPasswordActivity, message!!) L.w("Login failed with result $message") } } override fun twoFactorPrompt(caught: Throwable, token: String) { showProgressBar(false) firstStepToken = token binding.login2faText.visibility = View.VISIBLE binding.login2faText.requestFocus() FeedbackUtil.showError(this@ResetPasswordActivity, caught) } override fun passwordResetPrompt(token: String?) { // This case should not happen here, and we wouldn't have much to do anyway. } override fun error(caught: Throwable) { showProgressBar(false) if (caught is LoginFailedException) { FeedbackUtil.showError(this@ResetPasswordActivity, caught) } else { showError(caught) } } } private fun showProgressBar(enable: Boolean) { binding.viewProgressBar.visibility = if (enable) View.VISIBLE else View.GONE binding.loginButton.isEnabled = !enable binding.loginButton.setText(if (enable) R.string.login_in_progress_dialog_message else R.string.menu_login) } private fun showError(caught: Throwable) { binding.viewLoginError.setError(caught) binding.viewLoginError.visibility = View.VISIBLE } companion object { const val LOGIN_USER_NAME = "userName" const val LOGIN_TOKEN = "token" fun newIntent(context: Context, userName: String, token: String?): Intent { return Intent(context, ResetPasswordActivity::class.java) .putExtra(LOGIN_USER_NAME, userName) .putExtra(LOGIN_TOKEN, token) } } }
apache-2.0
109960360cbbb09343921d7ded7f4e09
39.01875
133
0.677183
5.114217
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/parser/constraints/MarkdownConstraints.kt
1
12720
package org.intellij.markdown.parser.constraints import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.markerblocks.providers.HorizontalRuleProvider public open class MarkdownConstraints protected constructor(private val indents: IntArray, private val types: CharArray, private val isExplicit: BooleanArray, private val charsEaten: Int) { open val base: MarkdownConstraints get() = BASE public open fun createNewConstraints(indents: IntArray, types: CharArray, isExplicit: BooleanArray, charsEaten: Int): MarkdownConstraints { return MarkdownConstraints(indents, types, isExplicit, charsEaten) } public fun eatItselfFromString(s: CharSequence): CharSequence { if (s.length < charsEaten) { return "" } else { return s.subSequence(charsEaten, s.length) } } public fun getIndent(): Int { if (indents.size == 0) { return 0 } return indents.last() } public fun getCharsEaten(s: CharSequence): Int { return Math.min(charsEaten, s.length) } public open fun getLastType(): Char? { return types.lastOrNull() } public fun getLastExplicit(): Boolean? { return isExplicit.lastOrNull() } public fun upstreamWith(other: MarkdownConstraints): Boolean { return other.startsWith(this) && !containsListMarkers() } public fun extendsPrev(other: MarkdownConstraints): Boolean { return startsWith(other) && !containsListMarkers(other.types.size) } public fun extendsList(other: MarkdownConstraints): Boolean { if (other.types.size == 0) { throw IllegalArgumentException("List constraints should contain at least one item") } return startsWith(other) && !containsListMarkers(other.types.size - 1) } private fun startsWith(other: MarkdownConstraints): Boolean { val n = indents.size val m = other.indents.size if (n < m) { return false } for (i in 0..m - 1) { if (types[i] != other.types[i]) { return false } } return true } private fun containsListMarkers(): Boolean { return containsListMarkers(types.size) } private fun containsListMarkers(upToIndex: Int): Boolean { for (i in 0..upToIndex - 1) { if (types[i] != BQ_CHAR && isExplicit[i]) { return true } } return false } public fun addModifierIfNeeded(pos: LookaheadText.Position?): MarkdownConstraints? { if (pos == null || pos.char == '\n') return null if (HorizontalRuleProvider.isHorizontalRule(pos.currentLine, pos.offsetInCurrentLine)) { return null } return tryAddListItem(pos) ?: tryAddBlockQuote(pos) } protected open fun fetchListMarker(pos: LookaheadText.Position): ListMarkerInfo? { if (pos.char == '*' || pos.char == '-' || pos.char == '+') { return ListMarkerInfo(pos.char.toString(), pos.char, 1) } val line = pos.currentLine var offset = pos.offsetInCurrentLine while (offset < line.length && line[offset] in '0'..'9') { offset++ } if (offset > pos.offsetInCurrentLine && offset - pos.offsetInCurrentLine <= 9 && offset < line.length && (line[offset] == '.' || line[offset] == ')')) { return ListMarkerInfo(line.subSequence(pos.offsetInCurrentLine, offset + 1), line[offset], offset + 1 - pos.offsetInCurrentLine) } else { return null } } data class ListMarkerInfo(val markerText: CharSequence, val markerType: Char, val markerIndent: Int) private fun tryAddListItem(pos: LookaheadText.Position): MarkdownConstraints? { val line = pos.currentLine var offset = pos.offsetInCurrentLine var spacesBefore = 0 // '\t' can be omitted here since it'll add at least 4 indent while (offset < line.length && line[offset] == ' ' && spacesBefore < 3) { spacesBefore++ offset++ } if (offset == line.length) return null val markerInfo = fetchListMarker(pos.nextPosition(spacesBefore)!!) ?: return null offset += markerInfo.markerText.length var spacesAfter = 0 val markerEndOffset = offset afterSpaces@ while (offset < line.length) { when (line[offset]) { ' ' -> spacesAfter++ '\t' -> spacesAfter += 4 - spacesAfter % 4 else -> break@afterSpaces } offset++ } // By the classification http://spec.commonmark.org/0.20/#list-items // 1. Basic case if (spacesAfter > 0 && spacesAfter < 5 && offset < line.length) { return MarkdownConstraints(this, spacesBefore + markerInfo.markerIndent + spacesAfter, markerInfo.markerType, true, offset) } if (spacesAfter >= 5 && offset < line.length // 2. Starts with an indented code || offset == line.length) { // 3. Starts with an empty string return MarkdownConstraints(this, spacesBefore + markerInfo.markerIndent + 1, markerInfo.markerType, true, Math.min(offset, markerEndOffset + 1)) } return null } private fun tryAddBlockQuote(pos: LookaheadText.Position): MarkdownConstraints? { val line = pos.currentLine var offset = pos.offsetInCurrentLine var spacesBefore = 0 // '\t' can be omitted here since it'll add at least 4 indent while (offset < line.length && line[offset] == ' ' && spacesBefore < 3) { spacesBefore++ offset++ } if (offset == line.length || line[offset] != BQ_CHAR) { return null } offset++ var spacesAfter = 0 if (offset >= line.length || line[offset] == ' ' || line[offset] == '\t') { spacesAfter = 1 if (offset < line.length) { offset++ } } return MarkdownConstraints(this, spacesBefore + 1 + spacesAfter, BQ_CHAR, true, offset) } override fun toString(): String { return "MdConstraints: " + String(types) + "(" + getIndent() + ")" } companion object { public val BASE: MarkdownConstraints = MarkdownConstraints(IntArray(0), CharArray(0), BooleanArray(0), 0) public val BQ_CHAR: Char = '>' private fun MarkdownConstraints(parent: MarkdownConstraints, newIndentDelta: Int, newType: Char, newExplicit: Boolean, newOffset: Int): MarkdownConstraints { val n = parent.indents.size val _indents = IntArray(n + 1) val _types = CharArray(n + 1) val _isExplicit = BooleanArray(n + 1) System.arraycopy(parent.indents, 0, _indents, 0, n) System.arraycopy(parent.types, 0, _types, 0, n) System.arraycopy(parent.isExplicit, 0, _isExplicit, 0, n) _indents[n] = parent.getIndent() + newIndentDelta _types[n] = newType _isExplicit[n] = newExplicit return parent.createNewConstraints(_indents, _types, _isExplicit, newOffset) } public fun fromBase(pos: LookaheadText.Position, prevLineConstraints: MarkdownConstraints): MarkdownConstraints { assert(pos.char == '\n') val line = pos.currentLine var result = fillFromPrevious(line, 0, prevLineConstraints) while (true) { val offset = result.getCharsEaten(line) result = result.addModifierIfNeeded(pos.nextPosition(1 + offset)) ?: break } return result } public fun fillFromPrevious(line: String, startOffset: Int, prevLineConstraints: MarkdownConstraints): MarkdownConstraints { val prevN = prevLineConstraints.indents.size var indexPrev = 0 val getBlockQuoteIndent = { startOffset: Int -> var offset = startOffset var blockQuoteIndent = 0 // '\t' can be omitted here since it'll add at least 4 indent while (blockQuoteIndent < 3 && offset < line.length && line[offset] == ' ') { blockQuoteIndent++ offset++ } if (offset < line.length && line[offset] == BQ_CHAR) { blockQuoteIndent + 1 } else { null } } val fillMaybeBlockquoteAndListIndents = fun(constraints: MarkdownConstraints): MarkdownConstraints { if (indexPrev >= prevN) { return constraints } var offset = startOffset + constraints.getCharsEaten(line) var spacesSeen = 0 val hasKMoreSpaces = { k: Int -> val oldSpacesSeen = spacesSeen val oldOffset = offset afterSpaces@ while (spacesSeen < k && offset < line.length) { when (line[offset]) { ' ' -> spacesSeen++ '\t' -> spacesSeen += 4 - spacesSeen % 4 else -> break@afterSpaces } offset++ } if (offset == line.length) { spacesSeen = Integer.MAX_VALUE } if (k <= spacesSeen) { spacesSeen -= k true } else { offset = oldOffset spacesSeen = oldSpacesSeen false } } val bqIndent: Int? if (prevLineConstraints.types[indexPrev] == BQ_CHAR) { bqIndent = getBlockQuoteIndent(offset) ?: return constraints offset += bqIndent indexPrev++ } else { bqIndent = null } val oldIndexPrev = indexPrev while (indexPrev < prevN && prevLineConstraints.types[indexPrev] != BQ_CHAR) { val deltaIndent = prevLineConstraints.indents[indexPrev] - if (indexPrev == 0) 0 else prevLineConstraints.indents[indexPrev - 1] if (!hasKMoreSpaces(deltaIndent)) { break } indexPrev++ } var result = constraints if (bqIndent != null) { val bonusForTheBlockquote = if (hasKMoreSpaces(1)) 1 else 0 result = MarkdownConstraints(result, bqIndent + bonusForTheBlockquote, BQ_CHAR, true, offset) } for (index in oldIndexPrev..indexPrev - 1) { val deltaIndent = prevLineConstraints.indents[index] - if (index == 0) 0 else prevLineConstraints.indents[index - 1] result = MarkdownConstraints(result, deltaIndent, prevLineConstraints.types[index], false, offset) } return result } var result = prevLineConstraints.base while (true) { val nextConstraints = fillMaybeBlockquoteAndListIndents(result) if (nextConstraints == result) { return result } result = nextConstraints } } } }
apache-2.0
3d76458c21c675c55e39cbd87b6c848e
35.342857
135
0.508962
5.264901
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/opencl/src/templates/kotlin/opencl/CLTypes.kt
1
25445
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opencl import org.lwjgl.generator.* // numeric val cl_char = typedef(int8_t, "cl_char") val cl_uchar = typedef(uint8_t, "cl_uchar") val cl_short = typedef(int16_t, "cl_short") val cl_ushort = typedef(uint16_t, "cl_ushort") val cl_int = typedef(int32_t, "cl_int") val cl_uint = typedef(uint32_t, "cl_uint") val cl_long = typedef(int64_t, "cl_long") val cl_ulong = typedef(uint64_t, "cl_ulong") val cl_half = PrimitiveType("cl_half", PrimitiveMapping.SHORT) val cl_float = typedef(float, "cl_float") val cl_double = typedef(double, "cl_double") // objects val cl_platform_id = "cl_platform_id".handle val cl_device_id = "cl_device_id".handle val cl_context = "cl_context".handle val cl_command_queue = "cl_command_queue".handle val cl_mem = "cl_mem".handle val cl_program = "cl_program".handle val cl_kernel = "cl_kernel".handle val cl_event = "cl_event".handle val cl_sampler = "cl_sampler".handle // typedefs val cl_bool = typedef(intb, "cl_bool") val cl_bitfield = typedef(cl_ulong, "cl_bitfield") val cl_properties = typedef(cl_ulong, "cl_properties") val cl_device_type = typedef(cl_bitfield, "cl_device_type") val cl_platform_info = typedef(cl_uint, "cl_platform_info") val cl_device_info = typedef(cl_uint, "cl_device_info") val cl_device_fp_config = typedef(cl_bitfield, "cl_device_fp_config") val cl_device_mem_cache_type = typedef(cl_uint, "cl_device_mem_cache_type") val cl_device_local_mem_type = typedef(cl_uint, "cl_device_local_mem_type") val cl_device_exec_capabilities = typedef(cl_bitfield, "cl_device_exec_capabilities") val cl_device_svm_capabilities = typedef(cl_bitfield, "cl_device_svm_capabilities") val cl_command_queue_properties = typedef(cl_bitfield, "cl_command_queue_properties") val cl_device_partition_property = typedef(intptr_t, "cl_device_partition_property") val cl_device_affinity_domain = typedef(cl_bitfield, "cl_device_affinity_domain") val cl_context_properties = typedef(intptr_t, "cl_context_properties") val cl_context_info = typedef(cl_uint, "cl_context_info") val cl_queue_properties = typedef(cl_properties, "cl_queue_properties") val cl_command_queue_info = typedef(cl_uint, "cl_command_queue_info") val cl_channel_order = typedef(cl_uint, "cl_channel_order") val cl_channel_type = typedef(cl_uint, "cl_channel_type") val cl_mem_flags = typedef(cl_bitfield, "cl_mem_flags") val cl_svm_mem_flags = typedef(cl_bitfield, "cl_svm_mem_flags") val cl_mem_object_type = typedef(cl_uint, "cl_mem_object_type") val cl_mem_info = typedef(cl_uint, "cl_mem_info") val cl_mem_migration_flags = typedef(cl_bitfield, "cl_mem_migration_flags") val cl_image_info = typedef(cl_uint, "cl_image_info") val cl_buffer_create_type = typedef(cl_uint, "cl_buffer_create_type") val cl_addressing_mode = typedef(cl_uint, "cl_addressing_mode") val cl_filter_mode = typedef(cl_uint, "cl_filter_mode") val cl_sampler_info = typedef(cl_uint, "cl_sampler_info") val cl_map_flags = typedef(cl_bitfield, "cl_map_flags") val cl_pipe_properties = typedef(intptr_t, "cl_pipe_properties") val cl_pipe_info = typedef(cl_uint, "cl_pipe_info") val cl_program_info = typedef(cl_uint, "cl_program_info") val cl_program_build_info = typedef(cl_uint, "cl_program_build_info") val cl_program_binary_type = typedef(cl_uint, "cl_program_binary_type") val cl_build_status = typedef(cl_int, "cl_build_status") val cl_kernel_info = typedef(cl_uint, "cl_kernel_info") val cl_kernel_arg_info = typedef(cl_uint, "cl_kernel_arg_info") val cl_kernel_arg_address_qualifier = typedef(cl_uint, "cl_kernel_arg_address_qualifier") val cl_kernel_arg_access_qualifier = typedef(cl_uint, "cl_kernel_arg_access_qualifier") val cl_kernel_arg_type_qualifier = typedef(cl_bitfield, "cl_kernel_arg_type_qualifier") val cl_kernel_work_group_info = typedef(cl_uint, "cl_kernel_work_group_info") val cl_kernel_sub_group_info = typedef(cl_uint, "cl_kernel_sub_group_info") val cl_event_info = typedef(cl_uint, "cl_event_info") val cl_command_type = typedef(cl_uint, "cl_command_type") val cl_profiling_info = typedef(cl_uint, "cl_profiling_info") val cl_sampler_properties = typedef(cl_properties, "cl_sampler_properties") val cl_kernel_exec_info = typedef(cl_uint, "cl_kernel_exec_info") val cl_device_atomic_capabilities = typedef(cl_bitfield, "cl_device_atomic_capabilities") val cl_device_device_enqueue_capabilities = typedef(cl_bitfield, "cl_device_device_enqueue_capabilities") val cl_khronos_vendor_id = typedef(cl_uint, "cl_khronos_vendor_id") val cl_mem_properties = typedef(cl_properties, "cl_mem_properties") val cl_version = typedef(cl_uint, "cl_version") // strings val cl_charASCII = CharType("cl_char", CharMapping.ASCII) val cl_charUTF8 = CharType("cl_char", CharMapping.UTF8) // structs val cl_image_format = struct(Module.OPENCL, "CLImageFormat", nativeName = "cl_image_format") { documentation = "The image format descriptor struct." cl_channel_order( "image_channel_order", "specifies the number of channels and the channel layout i.e. the memory layout in which channels are stored in the image" ) cl_channel_type( "image_channel_data_type", """ describes the size of the channel data type. The number of bits per element determined by the {@code image_channel_data_type} and {@code image_channel_order} must be a power of two. """ ) } val cl_image_desc = struct(Module.OPENCL, "CLImageDesc", nativeName = "cl_image_desc") { documentation = "Describes the type and dimensions of the image or image array." cl_mem_object_type("image_type", "describes the image type") size_t( "image_width", """ the width of the image in pixels. For a 2D image and image array, the image width must be &le; #DEVICE_IMAGE2D_MAX_WIDTH. For a 3D image, the image width must be &le; #DEVICE_IMAGE3D_MAX_WIDTH. For a 1D image buffer, the image width must be &le; #DEVICE_IMAGE_MAX_BUFFER_SIZE. For a 1D image and 1D image array, the image width must be &le; #DEVICE_IMAGE2D_MAX_WIDTH. """ ) size_t( "image_height", """ the height of the image in pixels. This is only used if the image is a 2D, 3D or 2D image array. For a 2D image or image array, the image height must be &le; #DEVICE_IMAGE2D_MAX_HEIGHT. For a 3D image, the image height must be &le; #DEVICE_IMAGE3D_MAX_HEIGHT. """ ) size_t( "image_depth", "the depth of the image in pixels. This is only used if the image is a 3D image and must be a value &ge; 1 and &le; #DEVICE_IMAGE3D_MAX_DEPTH." ) size_t( "image_array_size", """ the number of images in the image array. This is only used if the image is a 1D or 2D image array. The values for {@code image_array_size}, if specified, must be a value &ge; 1 and &le; #DEVICE_IMAGE_MAX_ARRAY_SIZE. Note that reading and writing 2D image arrays from a kernel with {@code image_array_size = 1} may be lower performance than 2D images. """ ) size_t( "image_row_pitch", """ the scan-line pitch in bytes. This must be 0 if {@code host_ptr} is #NULL and can be either 0 or &ge; {@code image_width * size} of element in bytes if {@code host_ptr} is not #NULL. If {@code host_ptr} is not #NULL and {@code image_row_pitch = 0}, {@code image_row_pitch} is calculated as {@code image_width * size} of element in bytes. If {@code image_row_pitch} is not 0, it must be a multiple of the image element size in bytes. """ ) size_t( "image_slice_pitch", """ the size in bytes of each 2D slice in the 3D image or the size in bytes of each image in a 1D or 2D image array. This must be 0 if {@code host_ptr} is #NULL. If {@code host_ptr} is not #NULL, {@code image_slice_pitch} can be either 0 or &ge; {@code image_row_pitch * image_height} for a 2D image array or 3D image and can be either 0 or &ge; {@code image_row_pitch} for a 1D image array. If {@code host_ptr} is not #NULL and {@code image_slice_pitch = 0}, {@code image_slice_pitch} is calculated as {@code image_row_pitch * image_height} for a 2D image array or 3D image and {@code image_row_pitch} for a 1D image array. If {@code image_slice_pitch} is not 0, it must be a multiple of the {@code image_row_pitch}. """ ) cl_uint("num_mip_levels", "must be 0") cl_uint("num_samples", "must be 0") union { nullable..cl_mem("buffer", "alias for {@code mem_object}") nullable..cl_mem( "mem_object", """ refers to a valid buffer or image memory object. {@code mem_object} can be a buffer memory object if {@code image_type} is #MEM_OBJECT_IMAGE1D_BUFFER or #MEM_OBJECT_IMAGE2D. {@code mem_object} can be an image object if {@code image_type} is #MEM_OBJECT_IMAGE2D. Otherwise it must be #NULL. The image pixels are taken from the memory object’s data store. When the contents of the specified memory object’s data store are modified, those changes are reflected in the contents of the image object and vice-versa at corresponding sychronization points. For a 1D image buffer object, the {@code image_width * size} of element in bytes must be &le; size of buffer object data store. For a 2D image created from a buffer, the {@code image_row_pitch * image_height} must be &le; size of buffer object data store. For an image object created from another image object, the values specified in the image descriptor except for {@code mem_object} must match the image descriptor information associated with {@code mem_object}. """ ) } } val cl_bus_address_amd = struct(Module.OPENCL, "CLBusAddressAMD", nativeName = "cl_bus_address_amd") { documentation = "Bus address information used in #EnqueueMakeBuffersResidentAMD()." cl_long( "surfbusaddress", "contains the page aligned physical starting address of the backing store preallocated by the application on a remote device" ) cl_long( "signalbusaddress", "contains the page aligned physical starting address of preallocated signaling surface" ) } fun config() { struct(Module.OPENCL, "CLBufferRegion", nativeName = "cl_buffer_region") { documentation = "Buffer region struct." size_t("origin", "the region offset, in bytes") size_t("size", "the region size, in bytes") } val CL_NAME_VERSION_MAX_NAME_SIZE = 64 struct(Module.OPENCL, "CLNameVersion", nativeName = "cl_name_version", mutable = false) { cl_version("version", "") charASCII("name", "")[CL_NAME_VERSION_MAX_NAME_SIZE] }.definition.hasUsageOutput() union(Module.OPENCL, "CLDeviceTopologyAMD", nativeName = "cl_device_topology_amd", mutable = false) { documentation = "The struct returned by #GetDeviceInfo() with {@code param_name} set to #DEVICE_TOPOLOGY_AMD." struct { cl_uint("type", "") cl_uint("data", "")[5] }("raw", "") struct { cl_uint("type", "") padding(17) cl_char("bus", "") cl_char("device", "") cl_char("function", "") }("pcie", "") }.definition.hasUsageOutput() struct(Module.OPENCL, "CLMotionEstimationDescINTEL", nativeName = "cl_motion_estimation_desc_intel") { documentation = "Describes the configuration of the motion estimation algorithm." cl_uint("mb_block_type", "describes the size of the blocks described by the motion estimator") cl_uint("subpixel_mode", "defines the search precision (and hence, the precision of the returned motion vectors)") cl_uint("sad_adjust_mode", "specifies distortion measure adjustment used for the motion search SAD comparison") cl_uint( "search_path_type", """ specifies the search path and search radius when matching blocks in the neighborhood of each pixel block (optionally offset by the predicted motion vector). Currently, all search algorithms match the source block with pixel blocks in the reference area exhaustively within a {@code [Rx, Ry]} radius from the current source pixel block location (optionally offset by the predicted motion vector) """ ) }.definition.hasUsageInput() val CL_QUEUE_FAMILY_MAX_NAME_SIZE_INTEL = 64 struct(Module.OPENCL, "CLQueueFamilyPropertiesINTEL", nativeName = "cl_queue_family_properties_intel", mutable = false) { cl_command_queue_properties("properties", "") cl_command_queue_capabilities_intel("capabilities", "") cl_uint("count", "") charASCII("name", "")[CL_QUEUE_FAMILY_MAX_NAME_SIZE_INTEL] }.definition.hasUsageOutput() struct(Module.OPENCL, "CLDevicePCIBusInfoKHR", nativeName = "cl_device_pci_bus_info_khr", mutable = false) { cl_uint("pci_domain", "") cl_uint("pci_bus", "") cl_uint("pci_device", "") cl_uint("pci_function", "") }.definition.hasUsageOutput() struct(Module.OPENCL, "CLDeviceIntegerDotProductAccelerationPropertiesKHR", nativeName = "cl_device_integer_dot_product_acceleration_properties_khr", mutable = false) { documentation = """ Describes the exact dot product operations that are accelerated on the device. A dot product operation is deemed accelerated if its implementation provides a performance advantage over application-provided code composed from elementary instructions and/or other dot product instructions, either because the implementation uses optimized machine code sequences whose generation from application-provided code cannot be guaranteed or because it uses hardware features that cannot otherwise be targeted from application-provided code. """ cl_bool("signed_accelerated", "is #TRUE when signed dot product operations are accelerated, #FALSE otherwise") cl_bool("unsigned_accelerated", "is #TRUE when unsigned dot product operations are accelerated, #FALSE otherwise") cl_bool("mixed_signedness_accelerated", "is #TRUE when mixed signedness dot product operations are accelerated, #FALSE otherwise") cl_bool( "accumulating_saturating_signed_accelerated", "is #TRUE when accumulating saturating signed dot product operations are accelerated, #FALSE otherwise" ) cl_bool( "accumulating_saturating_unsigned_accelerated", "is #TRUE when accumulating saturating unsigned dot product operations are accelerated, #FALSE otherwise" ) cl_bool( "accumulating_saturating_mixed_signedness_accelerated", "is #TRUE when accumulating saturating mixed signedness dot product operations are accelerated, #FALSE otherwise" ) }.definition.hasUsageOutput() val CL_NAME_VERSION_MAX_NAME_SIZE_KHR = 64 struct(Module.OPENCL, "CLNameVersionKHR", nativeName = "cl_name_version_khr", mutable = false) { documentation = "Describes a combination of a name alongside a version number." cl_version_khr("version", "") charASCII("name", "")[CL_NAME_VERSION_MAX_NAME_SIZE_KHR] }.definition.hasUsageOutput() } // callback functions val cl_context_callback = Module.OPENCL.callback { void( "CLContextCallback", "Will be called when a debug message is generated.", NullTerminated..cl_charUTF8.const.p("errinfo", "a pointer to the message string representation"), void.const.p( "private_info", "a pointer to binary data that is returned by the OpenCL implementation that can be used to log additional information helpful in debugging the error" ), AutoSize("private_info")..size_t("cb", "the number of bytes in the {@code private_info} pointer"), void.p("user_data", "the user-specified value that was passed when calling #CreateContext() or #CreateContextFromType()") ) { documentation = "Instances of this interface may be passed to the #CreateContext() and #CreateContextFromType() methods." } } val cl_program_callback = Module.OPENCL.callback { void( "CLProgramCallback", "Will be called when the program is built, compiled or linked.", cl_program("program", "the program that was built, compiled or linked"), void.p( "user_data", "the user-specified value that was passed when calling #BuildProgram(), #CompileProgram() or #LinkProgram()" ) ) { documentation = "Instances of this interface may be passed to the #BuildProgram(), #CompileProgram() and #LinkProgram() methods." } } val cl_native_kernel = Module.OPENCL.callback { void( "CLNativeKernel", "Will be called by the OpenCL using #EnqueueNativeKernel().", void.p("args", "a pointer to the arguments list") ) { documentation = "Instances of this interface may be passed to the #EnqueueNativeKernel() method." } } val cl_mem_object_destructor_callback = Module.OPENCL.callback { void( "CLMemObjectDestructorCallback", "Will be called when a memory object is deleted.", cl_mem("memobj", "the memory object that was deleted"), void.p("user_data", "the user-specified value that was passed when calling #SetMemObjectDestructorCallback()") ) { documentation = "Instances of this interface may be passed to the #SetMemObjectDestructorCallback() method." } } val cl_event_callback = Module.OPENCL.callback { void( "CLEventCallback", """ Will be called when the execution status of the command associated with {@code event} changes to an execution status equal or past the status specified by {@code command_exec_status}. """, cl_event("event", "the event"), cl_int( "event_command_exec_status", """ represents the execution status of command for which this callback function is invoked. If the callback is called as the result of the command associated with event being abnormally terminated, an appropriate error code for the error that caused the termination will be passed to {@code event_command_exec_status} instead. """ ), void.p("user_data", "the user-specified value that was passed when calling #SetEventCallback()") ) { documentation = "Instances of this interface may be passed to the #SetEventCallback() method." } } val cl_svmfree_callback = Module.OPENCL.callback { void( "CLSVMFreeCallback", "Will be called to free shared virtual memory pointers.", cl_command_queue("queue", "a valid host command-queue"), AutoSize("svm_pointers")..cl_uint("num_svm_pointers", "the number of pointers in the {@code svm_pointers} array"), void.p.p("svm_pointers", "an array of shared virtual memory pointers to be freed"), void.p("user_data", "the user-specified value that was passed when calling #EnqueueSVMFree()") ) { documentation = "Instances of this interface may be passed to the #EnqueueSVMFree() method." } } val cl_program_release_callback = Module.OPENCL.callback { void( "CLProgramReleaseCallback", "Will be called after destructors (if any) for program scope global variables (if any) are called and before the program is released.", cl_program( "program", """ the program object whose destructors are being called. When the user callback is called by the implementation, this program object is no longer valid. {@code program} is only provided for reference purposes. """ ), void.p("user_data", "the user-specified value that was passed when calling #SetProgramReleaseCallback()") ) { documentation = "Instances of this interface may be passed to the #SetProgramReleaseCallback() method." } } val cl_context_destructor_callback = Module.OPENCL.callback { void( "CLContextDestructorCallback", "Will be called when a context is destroyed.", cl_context( "context", """ the OpenCL context being deleted. When the callback function is called by the implementation, this context is no longer valid. {@code context} is only provided for reference purposes. """ ), void.p("user_data", "the user-specified value that was passed when calling #SetContextDestructorCallback()") ) { documentation = "Instances of this interface may be passed to the #SetContextDestructorCallback() method." } } // OpenGL interop val GLint = IntegerType("GLint", PrimitiveMapping.INT) val GLuint = IntegerType("GLuint", PrimitiveMapping.INT, unsigned = true) val GLenum = IntegerType("GLenum", PrimitiveMapping.INT, unsigned = true) val GLsync = "GLsync".handle val cl_gl_context_info = IntegerType("cl_gl_context_info", PrimitiveMapping.INT) val cl_gl_platform_info = IntegerType("cl_gl_platform_info", PrimitiveMapping.INT) val cl_gl_object_type = IntegerType("cl_gl_object_type", PrimitiveMapping.INT) val cl_gl_texture_info = IntegerType("cl_gl_texture_info", PrimitiveMapping.INT) // EGL interop val CLeglImageKHR = "CLeglImageKHR".handle val CLeglDisplayKHR = "CLeglDisplayKHR".handle val CLeglSyncKHR = "CLeglSyncKHR".handle val cl_egl_image_properties_khr = typedef(intptr_t, "cl_egl_image_properties_khr") // APPLE val cl_queue_properties_APPLE = typedef(intptr_t, "cl_queue_properties_APPLE") // ARM val cl_import_properties_arm = typedef(intptr_t, "cl_import_properties_arm") // EXT val cl_report_live_objects_altera_callback = Module.OPENCL.callback { void( "CLReportLiveObjectsAlteraCallback", "Reports a live OpenCL API object.", void.p("user_data", "the {@code user_data} argument specified to #ReportLiveObjectsAltera()"), void.p("obj_ptr", "a pointer to the live object"), charASCII.const.p( "type_name", "a C string corresponding to the OpenCL API object type. For example, a leaked {@code cl_mem} object will have \"cl_mem\" as its type string." ), cl_uint("refcount", "an instantaneous reference count for the object. Consider it to be immediately stale.") ) { documentation = "Instances of this interface may be passed to the #ReportLiveObjectsAltera() method." } } val cl_device_partition_property_ext = typedef(cl_bitfield, "cl_device_partition_property_ext") val cl_mem_migration_flags_ext = typedef(cl_bitfield, "cl_mem_migration_flags_ext") val cl_image_pitch_info_qcom = typedef(cl_uint, "cl_image_pitch_info_qcom") val cl_mem_ext_host_ptr = struct(Module.OPENCL, "CLMemEXTHostPtr", nativeName = "cl_mem_ext_host_ptr") { documentation = "Accepted by the {@code host_ptr} argument of #CreateBuffer(), #CreateImage2D() and #CreateImage3D()." cl_uint("allocation_type", "type of external memory allocation. Legal values will be defined in layered extensions.") cl_uint("host_cache_policy", "host cache policy for this external memory allocation") }.p // IMG val cl_mipmap_filter_mode_img = typedef(cl_uint, "cl_mipmap_filter_mode_img") // INTEL val cl_accelerator_intel = "cl_accelerator_intel".handle val cl_accelerator_type_intel = typedef(cl_uint, "cl_accelerator_type_intel") val cl_accelerator_info_intel = typedef(cl_uint, "cl_accelerator_info_intel") val cl_mem_info_intel = typedef(cl_uint, "cl_mem_info_intel") val cl_mem_advice_intel = typedef(cl_bitfield, "cl_mem_advice_intel") val cl_mem_properties_intel = typedef(cl_bitfield, "cl_mem_properties_intel") val cl_va_api_device_source_intel = typedef(cl_uint, "cl_va_api_device_source_intel") val cl_va_api_device_set_intel = typedef(cl_uint, "cl_va_api_device_set_intel") val VASurfaceID = typedef(unsigned_int, "VASurfaceID") val VAImageFormat = "VAImageFormat".handle // struct val cl_command_queue_capabilities_intel = typedef(cl_bitfield, "cl_command_queue_capabilities_intel") // KHR val cl_command_buffer_khr = "cl_command_buffer_khr".handle val cl_mutable_command_khr = "cl_mutable_command_khr".handle val cl_semaphore_khr = "cl_semaphore_khr".handle val cl_command_buffer_info_khr = typedef(cl_uint, "cl_command_buffer_info_khr") val cl_command_buffer_properties_khr = typedef(cl_properties, "cl_command_buffer_properties_khr") val cl_ndrange_kernel_command_properties_khr = typedef(cl_properties, "cl_ndrange_kernel_command_properties_khr") val cl_queue_properties_khr = typedef(cl_properties, "cl_queue_properties_khr") val cl_semaphore_properties_khr = typedef(cl_properties, "cl_semaphore_properties_khr") val cl_semaphore_info_khr = typedef(cl_uint, "cl_semaphore_info_khr") val cl_semaphore_type_khr = typedef(cl_uint, "cl_semaphore_type_khr") val cl_semaphore_payload_khr = typedef(cl_ulong, "cl_semaphore_payload_khr") val cl_sync_point_khr = typedef(cl_uint, "cl_sync_point_khr") val cl_version_khr = typedef(cl_uint, "cl_version_khr") // NV val cl_mem_flags_NV = typedef(cl_bitfield, "cl_mem_flags_NV")
bsd-3-clause
af5fc5e688c38058997d919d6a2952d5
47.831094
172
0.684525
3.662684
false
false
false
false
akhbulatov/wordkeeper
app/src/main/java/com/akhbulatov/wordkeeper/data/wordcategory/WordCategoryDatabaseMapper.kt
1
823
package com.akhbulatov.wordkeeper.data.wordcategory import com.akhbulatov.wordkeeper.data.global.local.database.wordcategory.WordCategoryDbModel import com.akhbulatov.wordkeeper.domain.global.models.Word import com.akhbulatov.wordkeeper.domain.global.models.WordCategory import javax.inject.Inject class WordCategoryDatabaseMapper @Inject constructor() { fun mapTo(model: WordCategory): WordCategoryDbModel = model.let { WordCategoryDbModel( name = it.name ).also { db -> db.id = it.id } } fun mapFrom(model: WordCategoryDbModel, words: List<Word>): WordCategory = model.let { WordCategory( id = it.id, name = it.name, words = words ) } }
apache-2.0
369513ca5fd2f0543a6f86db5f160af4
29.481481
92
0.619684
4.702857
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/git/GitCredential.kt
1
1847
package hamburg.remme.tinygit.git import hamburg.remme.tinygit.domain.Credentials private val credentialWincredGet = arrayOf("credential-wincred", "get") private val credentialWincredStore = arrayOf("credential-wincred", "store") private val credentialKeychainGet = arrayOf("credential-osxkeychain", "get") private val credentialKeychainStore = arrayOf("credential-osxkeychain", "store") private const val usernamePrefix = "username=" private const val passwordPrefix = "password=" private const val hostPrefix = "host=" private const val protocolPrefix = "protocol=" fun gitCredentialWincredGet(host: String, protocol: String) = gitCredentialGet(host, protocol, *credentialWincredGet) fun gitCredentialWincredStore(credentials: Credentials) = gitCredentialStore(credentials, *credentialWincredStore) fun gitCredentialKeychainGet(host: String, protocol: String) = gitCredentialGet(host, protocol, *credentialKeychainGet) fun gitCredentialKeychainStore(credentials: Credentials) = gitCredentialStore(credentials, *credentialKeychainStore) private fun gitCredentialGet(host: String, protocol: String, vararg args: String): Credentials { var username = "" var password = "" git(arrayOf("$hostPrefix$host", "$protocolPrefix$protocol", "\n"), *args) { if (it.startsWith(usernamePrefix)) username = it.substringAfter(usernamePrefix) else if (it.startsWith(passwordPrefix)) password = it.substringAfter(passwordPrefix) } return Credentials(username, password, host, protocol) } private fun gitCredentialStore(credentials: Credentials, vararg args: String) { git(arrayOf("$hostPrefix${credentials.host}", "$protocolPrefix${credentials.protocol}", "$usernamePrefix${credentials.username}", "$passwordPrefix${credentials.password}", "\n"), *args) }
bsd-3-clause
adc6eac701e4f54a4c45ba38af4d33e5
46.358974
119
0.755279
4.325527
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/AbstractModuleType.kt
1
3481
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.insight.generation.ui.EventGenerationPanel import com.demonwav.mcdev.util.findContainingClass import com.intellij.codeInspection.ex.EntryPointsManager import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import java.awt.Color import java.util.LinkedHashMap import javax.swing.Icon import org.apache.commons.lang.builder.ToStringBuilder abstract class AbstractModuleType<out T : AbstractModule>(val groupId: String, val artifactId: String) { val colorMap = LinkedHashMap<String, Color>() abstract val platformType: PlatformType abstract val icon: Icon? open val hasIcon = true abstract val id: String abstract val ignoredAnnotations: List<String> abstract val listenerAnnotations: List<String> val classToColorMappings: Map<String, Color> get() = this.colorMap abstract fun generateModule(facet: MinecraftFacet): T fun performCreationSettingSetup(project: Project) { if (project.isDisposed) { return } val manager = EntryPointsManager.getInstance(project) val annotations = (manager as? EntryPointsManagerBase)?.ADDITIONAL_ANNOTATIONS as? MutableList<String> ?: return ignoredAnnotations.asSequence() .filter { annotation -> !annotations.contains(annotation) } .forEach { annotations.add(it) } } open fun getEventGenerationPanel(chosenClass: PsiClass): EventGenerationPanel { return EventGenerationPanel(chosenClass) } open val isEventGenAvailable: Boolean get() = false open fun getDefaultListenerName(psiClass: PsiClass) = "on" + psiClass.name!!.replace("Event", "") override fun toString(): String { return ToStringBuilder(this) .append("groupId", groupId) .append("artifactId", artifactId) .toString() } /** * Given any PsiElement, determine if it resides in a module of this [AbstractModuleType]. * @param element The element to check. * * * @return True if this element resides in a module of this type */ fun isInModule(element: PsiElement): Boolean { val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false val facet = MinecraftFacet.getInstance(module) return facet != null && facet.isOfType(this) } protected fun defaultNameForSubClassEvents(psiClass: PsiClass): String { val isInnerClass = psiClass.parent !is PsiFile val name = StringBuilder() if (isInnerClass) { val containingClass = psiClass.parent.findContainingClass() if (containingClass != null && containingClass.name != null) { name.append(containingClass.name!!.replace("Event", "")) } } var className = psiClass.name!! if (className.startsWith(name.toString())) { className = className.substring(name.length) } name.append(className.replace("Event", "")) name.insert(0, "on") return name.toString() } }
mit
bde55cf1361c926e3e5d70e3f1255993
30.645455
120
0.689457
4.710419
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/agility/Agility.kt
1
2412
package org.runestar.client.plugins.agility import org.runestar.client.api.forms.RgbaForm import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.game.SceneElement import org.runestar.client.api.game.live.Game import org.runestar.client.api.game.live.Canvas import org.runestar.client.api.game.live.Scene import org.runestar.client.api.game.live.Viewport import org.runestar.client.api.game.live.SceneElements import org.runestar.client.api.game.live.VisibilityMap import org.runestar.client.api.plugins.PluginSettings import java.awt.Color import java.awt.Graphics2D import java.awt.RenderingHints class Agility : DisposablePlugin<Agility.Settings>() { override val defaultSettings = Settings() private val obstacles: MutableSet<SceneElement> = LinkedHashSet() override fun onStart() { add(SceneElements.cleared.subscribe { obstacles.clear() }) add(SceneElements.Loc.added.filter(::isObstacle).subscribe { obstacles.add(it) }) add(SceneElements.Loc.removed.filter(::isObstacle).subscribe { obstacles.remove(it) }) Scene.reload() add(Canvas.repaints.subscribe(::onRepaint)) } override fun onStop() { obstacles.clear() } private fun isObstacle(o: SceneElement): Boolean { return o.tag.id in OBSTACLE_IDS } private fun onRepaint(g: Graphics2D) { if (obstacles.isEmpty()) return g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.clip(Viewport.shape) obstacles.forEach { obstacle -> drawObstacle(g, obstacle) } } private fun drawObstacle(g: Graphics2D, obstacle: SceneElement) { val loc = obstacle.location if (loc.plane != Game.plane || !VisibilityMap.isVisible(loc)) return val model = obstacle.model ?: return val shape = model.objectClickBox() if (settings.fill) { g.color = settings.fillColor.value g.fill(shape) } if (settings.outline) { g.color = settings.outlineColor.value g.draw(shape) } } class Settings( val outline: Boolean = true, val fill: Boolean = true, val outlineColor: RgbaForm = RgbaForm(Color.WHITE), val fillColor: RgbaForm = RgbaForm(Color(255, 255, 255, 100)) ) : PluginSettings() }
mit
1d777b833bbfbec57a9db853689bf003
31.608108
94
0.679104
4.04698
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt
2
11005
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences.Options import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.core.toKeywordToken import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.getCallableSubstitutor import org.jetbrains.kotlin.idea.refactoring.changeSignature.setValOrVar import org.jetbrains.kotlin.idea.refactoring.dropOperatorKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.toSubstitutor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.sure class KotlinCallableDefinitionUsage<T : PsiElement>( function: T, val originalCallableDescriptor: CallableDescriptor, baseFunction: KotlinCallableDefinitionUsage<PsiElement>?, private val samCallType: KotlinType?, private val canDropOverride: Boolean = true ) : KotlinUsageInfo<T>(function) { val baseFunction: KotlinCallableDefinitionUsage<*> = baseFunction ?: this val hasExpectedType: Boolean = checkIfHasExpectedType(originalCallableDescriptor, isInherited) val currentCallableDescriptor: CallableDescriptor? by lazy { when (val element = declaration) { is KtFunction, is KtProperty, is KtParameter -> (element as KtDeclaration).unsafeResolveToDescriptor() as CallableDescriptor is KtClass -> (element.unsafeResolveToDescriptor() as ClassDescriptor).unsubstitutedPrimaryConstructor is PsiMethod -> element.getJavaMethodDescriptor() else -> null } } val typeSubstitutor: TypeSubstitutor? by lazy { if (!isInherited) return@lazy null if (samCallType == null) { getCallableSubstitutor(this.baseFunction, this) } else { val currentBaseDescriptor = this.baseFunction.currentCallableDescriptor val classDescriptor = currentBaseDescriptor?.containingDeclaration as? ClassDescriptor ?: return@lazy null getTypeSubstitution(classDescriptor.defaultType, samCallType)?.toSubstitutor() } } private fun checkIfHasExpectedType(callableDescriptor: CallableDescriptor, isInherited: Boolean): Boolean { if (!(callableDescriptor is AnonymousFunctionDescriptor && isInherited)) return false val functionLiteral = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as KtFunctionLiteral? assert(functionLiteral != null) { "No declaration found for $callableDescriptor" } val parent = functionLiteral!!.parent as? KtLambdaExpression ?: return false return parent.analyze(BodyResolveMode.PARTIAL)[BindingContext.EXPECTED_EXPRESSION_TYPE, parent] != null } val declaration: PsiElement get() = element!! val isInherited: Boolean get() = baseFunction !== this override fun processUsage(changeInfo: KotlinChangeInfo, element: T, allUsages: Array<out UsageInfo>): Boolean { if (element !is KtNamedDeclaration) return true val psiFactory = KtPsiFactory(element.project) if (changeInfo.isNameChanged) { val identifier = (element as KtCallableDeclaration).nameIdentifier identifier?.replace(psiFactory.createIdentifier(changeInfo.newName)) } changeReturnTypeIfNeeded(changeInfo, element) val parameterList = element.getValueParameterList() if (changeInfo.isParameterSetOrOrderChanged) { processParameterListWithStructuralChanges(changeInfo, element, parameterList, psiFactory) } else if (parameterList != null) { val offset = if (originalCallableDescriptor.extensionReceiverParameter != null) 1 else 0 for ((paramIndex, parameter) in parameterList.parameters.withIndex()) { val parameterInfo = changeInfo.newParameters[paramIndex + offset] changeParameter(paramIndex, parameter, parameterInfo) } parameterList.addToShorteningWaitSet(Options.DEFAULT) } if (element is KtCallableDeclaration && changeInfo.isReceiverTypeChanged()) { val receiverTypeText = changeInfo.renderReceiverType(this) val receiverTypeRef = if (receiverTypeText != null) psiFactory.createType(receiverTypeText) else null val newReceiverTypeRef = element.setReceiverTypeReference(receiverTypeRef) newReceiverTypeRef?.addToShorteningWaitSet(Options.DEFAULT) } if (changeInfo.isVisibilityChanged() && !KtPsiUtil.isLocal(element as KtDeclaration)) { changeVisibility(changeInfo, element) } if (canDropOverride) { dropOverrideKeywordIfNecessary(element) } dropOperatorKeywordIfNecessary(element) return true } private fun changeReturnTypeIfNeeded(changeInfo: KotlinChangeInfo, element: PsiElement) { if (element !is KtCallableDeclaration) return if (element is KtConstructor<*>) return val returnTypeIsNeeded = (element is KtFunction && element !is KtFunctionLiteral) || element is KtProperty || element is KtParameter if (changeInfo.isReturnTypeChanged && returnTypeIsNeeded) { element.typeReference = null val returnTypeText = changeInfo.renderReturnType(this) val returnType = changeInfo.newReturnTypeInfo.type if (returnType == null || !returnType.isUnit()) { element.setTypeReference(KtPsiFactory(element).createType(returnTypeText))!!.addToShorteningWaitSet(Options.DEFAULT) } } } private fun processParameterListWithStructuralChanges( changeInfo: KotlinChangeInfo, element: PsiElement, originalParameterList: KtParameterList?, psiFactory: KtPsiFactory ) { var parameterList = originalParameterList val parametersCount = changeInfo.getNonReceiverParametersCount() val isLambda = element is KtFunctionLiteral var canReplaceEntireList = false var newParameterList: KtParameterList? = null if (isLambda) { if (parametersCount == 0) { if (parameterList != null) { parameterList.delete() val arrow = (element as KtFunctionLiteral).arrow arrow?.delete() parameterList = null } } else { newParameterList = psiFactory.createLambdaParameterList(changeInfo.getNewParametersSignatureWithoutParentheses(this)) canReplaceEntireList = true } } else if (!(element is KtProperty || element is KtParameter)) { newParameterList = psiFactory.createParameterList(changeInfo.getNewParametersSignature(this)) } if (newParameterList == null) return if (parameterList != null) { newParameterList = if (canReplaceEntireList) { parameterList.replace(newParameterList) as KtParameterList } else { replaceListPsiAndKeepDelimiters(changeInfo, parameterList, newParameterList) { parameters } } } else { if (element is KtClass) { val constructor = element.createPrimaryConstructorIfAbsent() val oldParameterList = constructor.valueParameterList.sure { "primary constructor from factory has parameter list" } newParameterList = oldParameterList.replace(newParameterList) as KtParameterList } else if (isLambda) { val functionLiteral = element as KtFunctionLiteral val anchor = functionLiteral.lBrace newParameterList = element.addAfter(newParameterList, anchor) as KtParameterList if (functionLiteral.arrow == null) { val whitespaceAndArrow = psiFactory.createWhitespaceAndArrow() element.addRangeAfter(whitespaceAndArrow.first, whitespaceAndArrow.second, newParameterList) } } } newParameterList.addToShorteningWaitSet(Options.DEFAULT) } private fun changeVisibility(changeInfo: KotlinChangeInfo, element: PsiElement) { val newVisibilityToken = changeInfo.newVisibility.toKeywordToken() when (element) { is KtCallableDeclaration -> element.setVisibility(newVisibilityToken) is KtClass -> element.createPrimaryConstructorIfAbsent().setVisibility(newVisibilityToken) else -> throw AssertionError("Invalid element: " + element.getElementTextWithContext()) } } private fun changeParameter(parameterIndex: Int, parameter: KtParameter, parameterInfo: KotlinParameterInfo) { parameter.setValOrVar(parameterInfo.valOrVar) val psiFactory = KtPsiFactory(project) if (parameterInfo.isTypeChanged && parameter.typeReference != null) { val renderedType = parameterInfo.renderType(parameterIndex, this) parameter.typeReference = psiFactory.createType(renderedType) } val inheritedName = parameterInfo.getInheritedName(this) if (Name.isValidIdentifier(inheritedName)) { val newIdentifier = psiFactory.createIdentifier(inheritedName) parameter.nameIdentifier?.replace(newIdentifier) } } }
apache-2.0
c5480c21b7aeada9cf1d1de5ccb271ea
46.640693
158
0.720218
5.795155
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddAccessorIntentions.kt
2
3425
// 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.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddAccessorApplicator import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtProperty abstract class AddAccessorsIntention( protected val addGetter: Boolean, protected val addSetter: Boolean ) : SelfTargetingRangeIntention<KtProperty>(KtProperty::class.java, AddAccessorApplicator.applicator(addGetter, addSetter).getFamilyName()) { override fun applyTo(element: KtProperty, editor: Editor?) { AddAccessorApplicator.applicator(addGetter, addSetter).applyTo(element, KotlinApplicatorInput.Empty, element.project, editor) } override fun applicabilityRange(element: KtProperty): TextRange? { if (element.isLocal || element.isAbstract() || element.hasDelegate() || element.hasModifier(KtTokens.LATEINIT_KEYWORD) || element.hasModifier(KtTokens.CONST_KEYWORD) || element.hasJvmFieldAnnotation() ) { return null } val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return null if (descriptor.isExpect) return null val hasInitializer = element.hasInitializer() if (element.typeReference == null && !hasInitializer) return null if (addSetter && (!element.isVar || element.setter != null)) return null if (addGetter && element.getter != null) return null return if (hasInitializer) element.nameIdentifier?.textRange else element.textRange } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val property = diagnostic.psiElement as? KtProperty ?: return null return if (property.isVar) { val getter = property.getter val setter = property.setter when { getter == null && setter == null -> AddPropertyAccessorsIntention() getter == null -> AddPropertyGetterIntention() else -> AddPropertySetterIntention() } } else { AddPropertyGetterIntention() } } } } class AddPropertyAccessorsIntention : AddAccessorsIntention(true, true), LowPriorityAction class AddPropertyGetterIntention : AddAccessorsIntention(true, false) class AddPropertySetterIntention : AddAccessorsIntention(false, true)
apache-2.0
2c944e484afaef18b2594527f7d559a5
47.928571
158
0.735474
5.173716
false
false
false
false
google/intellij-community
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/bus/FlowBus.kt
1
2597
package com.intellij.ide.starter.bus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch /** * @author https://github.com/Kosert/FlowBus * @license Apache 2.0 https://github.com/Kosert/FlowBus/blob/master/LICENSE * * This class holds all shared flows and handles event posting. * You can use [StarterBus] that is just plain instance of this class or create your own implementation. */ open class FlowBus { private val flows = mutableMapOf<Class<*>, MutableSharedFlow<*>>() /** * Gets a MutableSharedFlow for events of the given type. Creates new if one doesn't exist. * @return MutableSharedFlow for events that are instances of clazz */ internal fun <T : Any> forEvent(clazz: Class<T>): MutableSharedFlow<T?> { return flows.getOrPut(clazz) { MutableSharedFlow<T?>(extraBufferCapacity = 5000) } as MutableSharedFlow<T?> } /** * Gets a Flow for events of the given type. * * **This flow never completes.** * * The returned Flow is _hot_ as it is based on a [SharedFlow]. This means a call to [collect] never completes normally, calling [toList] will suspend forever, etc. * * You are entirely responsible to cancel this flow. To cancel this flow, the scope in which the coroutine is running needs to be cancelled. * @see [SharedFlow] */ fun <T : Any> getFlow(clazz: Class<T>): Flow<T> { return forEvent(clazz).filterNotNull() } /** * Posts new event to SharedFlow of the [event] type. * @param retain If the [event] should be retained in the flow for future subscribers. This is true by default. */ @JvmOverloads fun <T : Any> post(event: T, retain: Boolean = true) { val flow = forEvent(event.javaClass) flow.tryEmit(event).also { if (!it) throw IllegalStateException("SharedFlow cannot take element, this should never happen") } if (!retain) { // without starting a coroutine here, the event is dropped immediately // and not delivered to subscribers CoroutineScope(Job() + Dispatchers.IO).launch { dropEvent(event.javaClass) } } } /** * Removes retained event of type [clazz] */ fun <T> dropEvent(clazz: Class<T>) { if (!flows.contains(clazz)) return val channel = flows[clazz] as MutableSharedFlow<T?> channel.tryEmit(null) } /** * Removes all retained events */ fun dropAll() { flows.values.forEach { (it as MutableSharedFlow<Any?>).tryEmit(null) } } }
apache-2.0
785296023bcc70f9035724c0fd016500
30.682927
166
0.683096
4.070533
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/UrlRequester.kt
1
1661
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Type.* import java.net.URL import java.util.* class UrlRequester : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.interfaces == listOf(Runnable::class.type) } .and { it.instanceFields.count { it.type == Queue::class.type } == 1 } class requests : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Queue::class.type } } class thread : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Thread::class.type } } class isClosed : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE } } @MethodParameters("url") class request : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.arguments.startsWith(URL::class.type) } } @MethodParameters() class close : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.name != Runnable::run.name } } }
mit
ac5671e08bd679ad72842effcf3c6d86
37.651163
98
0.72366
4.162907
false
false
false
false
atrujillofalcon/spring-guides-kotlin
gs-uploading-files/src/main/kotlin/storage/FileSystemStorageService.kt
1
1705
package storage import org.springframework.beans.factory.annotation.Autowired import org.springframework.core.io.Resource import org.springframework.core.io.UrlResource import org.springframework.stereotype.Service import org.springframework.util.FileSystemUtils import org.springframework.web.multipart.MultipartFile import service.StorageService import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.stream.Stream @Service class FileSystemStorageService @Autowired constructor(properties: StorageProperties) : StorageService { private val rootLocation: Path = Paths.get(properties.location) override fun init() { Files.createDirectory(rootLocation) } override fun store(file: MultipartFile) { if (file.isEmpty) throw StorageException("Failed to store empty file " + file.originalFilename) Files.copy(file.inputStream, this.rootLocation.resolve(file.originalFilename)) } override fun loadAll(): Stream<Path> { return Files.walk(this.rootLocation, 1) .filter { path -> path != this.rootLocation } .map { path -> this.rootLocation.relativize(path) } } override fun loadAsResource(filename: String): Resource { val file = load(filename) val resource = UrlResource(file.toUri()) return if (resource.exists() || resource.isReadable) resource else throw StorageFileNotFoundException("Could not read file: " + filename) } override fun deleteAll() = FileSystemUtils.deleteRecursively(rootLocation.toFile()) override fun load(filename: String): Path = rootLocation.resolve(filename) }
apache-2.0
f901905a590febf3ba88cce467d455f0
33.795918
89
0.723754
4.558824
false
false
false
false
heitorcolangelo/kappuccino
kappuccino/src/main/kotlin/br/com/concretesolutions/kappuccino/custom/runtimePermission/runtimePermission.kt
1
4213
package br.com.concretesolutions.kappuccino.custom.runtimePermission import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.support.test.InstrumentationRegistry import android.support.test.InstrumentationRegistry.getInstrumentation import android.support.test.uiautomator.UiDevice import android.support.test.uiautomator.UiObjectNotFoundException import android.support.test.uiautomator.UiSelector import android.support.v4.content.ContextCompat /** * This method allows you to check if your app behaves as expected when denying or allowing the permission requested. * For example: * * - If after denying the permission, your app displays a message or dialog to the user. * - If after allowing the permission, your app displays a message or dialog to the user. * * In case you just want to avoid the permission dialogs to execute your tests, it would be a good idea to use * [GrantPermissionRule](https://developer.android.com/reference/android/support/test/rule/GrantPermissionRule) * * @param permissionNeeded The [android.Manifest.permission] or [android.Manifest.permission_group] value corresponding * to the requested permission. * @param action The action [RuntimePermissionHandler.allow] or [RuntimePermissionHandler.deny] * on the current permission request dialog. */ fun runtimePermission(permissionNeeded: String, action: RuntimePermissionHandler.() -> Unit) { RuntimePermissionHandler(permissionNeeded).apply { action() } } class RuntimePermissionHandler(private val permissionNeeded: String) { private companion object { private const val PERMISSIONS_DIALOG_DELAY = 500L private const val ALLOW_BUTTON_ID = "com.android.packageinstaller:id/permission_allow_button" private const val DENY_BUTTON_ID = "com.android.packageinstaller:id/permission_deny_button" } /** * Click on ALLOW button from current permission request dialog */ fun allow() { handlePermission(ALLOW_BUTTON_ID) } /** * Click on DENY button from current permission request dialog */ fun deny() { handlePermission(DENY_BUTTON_ID) } /** * This method will check the Android version before handling the permission. It will also properly handle the * permission based on action from [allow] or [deny] methods. * * @param actionButtonId The id of the action button * * From: https://gist.github.com/rocboronat/65b1187a9fca9eabfebb5121d818a3c4 */ private fun handlePermission(actionButtonId: String) { try { val context = InstrumentationRegistry.getTargetContext() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasNeededPermission(context, permissionNeeded)) { // This sleeping is just to make sure that we wait time enough for the dialog be displayed. sleep(PERMISSIONS_DIALOG_DELAY) // Finding the correct button to perform the click action val device = UiDevice.getInstance(getInstrumentation()) val allowPermissions = device.findObject(UiSelector() .clickable(true) .checkable(false) .resourceId(actionButtonId)) if (allowPermissions.exists()) { allowPermissions.click() } else { println("Could not find button with Id: $actionButtonId") } } } catch (e: UiObjectNotFoundException) { println("There is no permissions dialog to interact with") } } private fun hasNeededPermission(context: Context, permissionNeeded: String): Boolean { val permissionStatus = ContextCompat.checkSelfPermission(context, permissionNeeded) return permissionStatus == PackageManager.PERMISSION_GRANTED } private fun sleep(millis: Long) { try { Thread.sleep(millis) } catch (e: InterruptedException) { throw RuntimeException("Cannot execute Thread.sleep()") } } }
apache-2.0
b237b78f4588674344556e4c76e68ed1
39.912621
119
0.681462
4.881808
false
true
false
false
JetBrains/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableModuleLibraryTableBridge.kt
1
10523
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots import com.google.common.collect.HashBiMap import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.openapi.roots.impl.ModuleLibraryTableBase import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.openapi.util.Disposer import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap import com.intellij.workspaceModel.storage.bridgeEntities.* import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer internal class ModifiableModuleLibraryTableBridge(private val modifiableModel: ModifiableRootModelBridgeImpl) : ModuleLibraryTableBase(), ModuleLibraryTableBridge { private val copyToOriginal = HashBiMap.create<LibraryBridge, LibraryBridge>() init { val storage = modifiableModel.moduleBridge.entityStorage.current libraryEntities() .forEach { libraryEntry -> val originalLibrary = storage.libraryMap.getDataByEntity(libraryEntry) if (originalLibrary != null) { //if a module-level library from ModifiableRootModel is changed, the changes must not be committed to the model until //ModifiableRootModel is committed. So we place copies of LibraryBridge instances to the modifiable model. If the model is disposed //these copies are disposed; if the model is committed only changed copies will be included to the model, otherwise they will be disposed. val modifiableCopy = LibraryBridgeImpl(this, modifiableModel.project, libraryEntry.symbolicId, modifiableModel.entityStorageOnDiff, modifiableModel.diff) copyToOriginal[modifiableCopy] = originalLibrary modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntry, modifiableCopy) } } } private fun libraryEntities(): Sequence<LibraryEntity> { val moduleLibraryTableId = getTableId() return modifiableModel.entityStorageOnDiff.current .entities(LibraryEntity::class.java) .filter { it.tableId == moduleLibraryTableId } } override fun getLibraryIterator(): Iterator<Library> { val storage = modifiableModel.entityStorageOnDiff.current return libraryEntities().mapNotNull { storage.libraryMap.getDataByEntity(it) }.iterator() } override fun createLibrary(name: String?, type: PersistentLibraryKind<*>?, externalSource: ProjectModelExternalSource?): Library { modifiableModel.assertModelIsLive() val tableId = getTableId() val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(name) { existsName -> LibraryId(existsName, tableId) in modifiableModel.diff } val libraryEntity = modifiableModel.diff.addLibraryEntity( roots = emptyList(), tableId = tableId, name = libraryEntityName, excludedRoots = emptyList(), source = modifiableModel.moduleEntity.entitySource ) if (type != null) { modifiableModel.diff.addLibraryPropertiesEntity( library = libraryEntity, libraryType = type.kindId, propertiesXmlTag = LegacyBridgeModifiableBase.serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, type.createDefaultProperties()) ) } return createAndAddLibrary(libraryEntity, false, ModuleDependencyItem.DependencyScope.COMPILE) } private fun createAndAddLibrary(libraryEntity: LibraryEntity, exported: Boolean, scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl { val libraryId = libraryEntity.symbolicId modifiableModel.appendDependency(ModuleDependencyItem.Exportable.LibraryDependency(library = libraryId, exported = exported, scope = scope)) val library = LibraryBridgeImpl( libraryTable = ModuleRootComponentBridge.getInstance(modifiableModel.module).moduleLibraryTable, project = modifiableModel.project, initialId = libraryEntity.symbolicId, initialEntityStorage = modifiableModel.entityStorageOnDiff, targetBuilder = modifiableModel.diff ) modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntity, library) return library } private fun getTableId() = LibraryTableId.ModuleLibraryTableId(modifiableModel.moduleEntity.symbolicId) internal fun addLibraryCopy(original: LibraryBridgeImpl, exported: Boolean, scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl { val tableId = getTableId() val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(original.name) { existsName -> LibraryId(existsName, tableId) in modifiableModel.diff } val originalEntity = original.librarySnapshot.libraryEntity val libraryEntity = modifiableModel.diff.addLibraryEntityWithExcludes( roots = originalEntity.roots, tableId = tableId, name = libraryEntityName, excludedRoots = originalEntity.excludedRoots, source = modifiableModel.moduleEntity.entitySource ) val originalProperties = originalEntity.libraryProperties if (originalProperties != null) { modifiableModel.diff.addLibraryPropertiesEntity( library = libraryEntity, libraryType = originalProperties.libraryType, propertiesXmlTag = originalProperties.propertiesXmlTag ) } return createAndAddLibrary(libraryEntity, exported, scope) } override fun removeLibrary(library: Library) { modifiableModel.assertModelIsLive() library as LibraryBridge var copyBridgeForDispose: LibraryBridge? = null val libraryEntity = modifiableModel.diff.findLibraryEntity(library) ?: run { copyToOriginal.inverse()[library]?.let { libraryCopy -> copyBridgeForDispose = libraryCopy modifiableModel.diff.findLibraryEntity(libraryCopy) } } if (libraryEntity == null) { LOG.error("Cannot find entity for library ${library.name}") return } val libraryId = libraryEntity.symbolicId modifiableModel.removeDependencies { _, item -> item is ModuleDependencyItem.Exportable.LibraryDependency && item.library == libraryId } modifiableModel.diff.removeEntity(libraryEntity) Disposer.dispose(library) if (copyBridgeForDispose != null) { Disposer.dispose(copyBridgeForDispose!!) } } internal fun restoreLibraryMappingsAndDisposeCopies() { libraryIterator.forEach { val originalLibrary = copyToOriginal[it] //originalLibrary may be null if the library was added after the table was created if (originalLibrary != null) { val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(it as LibraryBridge).single(), originalLibrary) } Disposer.dispose(it) } } internal fun restoreMappingsForUnchangedLibraries(changedLibs: Set<LibraryId>) { if (copyToOriginal.isEmpty()) return copyToOriginal.forEach { (copyBridge, originBridge) -> // If library was removed its instance of bridge already be disposed if (copyBridge.isDisposed || originBridge.isDisposed) return@forEach if (!changedLibs.contains(originBridge.libraryId) && originBridge.hasSameContent(copyBridge)) { val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(copyBridge as LibraryBridge).single(), originBridge) Disposer.dispose(copyBridge) } } } /** * We should iterate through all created bridges' copies and original one which are actual for this moment and * update storage and libraryTable for them. * For the newly created libs this will be done in [ModuleManagerComponentBridge#processModuleLibraryChange] */ internal fun disposeOriginalLibrariesAndUpdateCopies() { if (copyToOriginal.isEmpty()) return val storage = WorkspaceModel.getInstance(modifiableModel.project).entityStorage copyToOriginal.forEach { (copyBridge, originBridge) -> // It's possible if we removed old library, its copy will be disposed [ModifiableModuleLibraryTableBridge.removeLibrary] // but original bridge will be disposed in during events handling. This method will be called the last thus both of them will be disposed if (copyBridge.isDisposed && originBridge.isDisposed) return@forEach val (actualBridge, outdatedBridge) = if (storage.current.libraryMap.getFirstEntity(copyBridge) != null) { copyBridge to originBridge } else if (storage.current.libraryMap.getFirstEntity(originBridge) != null) { originBridge to copyBridge } else { error("Unexpected state that both bridges are not actual") } actualBridge as LibraryBridgeImpl actualBridge.entityStorage = storage actualBridge.libraryTable = ModuleRootComponentBridge.getInstance(module).moduleLibraryTable actualBridge.clearTargetBuilder() Disposer.dispose(outdatedBridge) } } override fun isChanged(): Boolean { return modifiableModel.isChanged } override val module: Module get() = modifiableModel.module companion object { private val LOG = logger<ModifiableModuleLibraryTableBridge>() } }
apache-2.0
1861be4d4fc8622db46a1e9f178c4acd
44.558442
148
0.737622
5.51231
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/highlighter/deprecated/ClassObject.kt
1
1112
fun test() { <warning descr="[DEPRECATION] 'companion object of MyClass' is deprecated. Use A instead">MyClass</warning>.test MyClass() val a: MyClass? = null val b: MyInterface? = null <warning descr="[DEPRECATION] 'companion object of MyInterface' is deprecated. Use A instead">MyInterface</warning>.test MyInterface.<warning descr="[DEPRECATION] 'companion object of MyInterface' is deprecated. Use A instead">Companion</warning> <warning descr="[DEPRECATION] 'companion object of MyInterface' is deprecated. Use A instead">MyInterface</warning> MyClass.<warning descr="[DEPRECATION] 'companion object of MyClass' is deprecated. Use A instead">Companion</warning> MyClass.<warning descr="[DEPRECATION] 'companion object of MyClass' is deprecated. Use A instead">Companion</warning>.test a == b } class MyClass(): MyInterface { @Deprecated("Use A instead") companion object { val test: String = "" } } interface MyInterface { @Deprecated("Use A instead") companion object { val test: String = "" } } // NO_CHECK_INFOS // NO_CHECK_WEAK_WARNINGS
apache-2.0
e161ed582cb3847fe22f514e2327fc05
38.714286
128
0.709532
4.395257
false
true
false
false
square/okhttp
okhttp/src/jvmTest/java/okhttp3/SocketChannelTest.kt
2
7608
/* * Copyright (C) 2021 Square, 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 okhttp3 import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_2 import okhttp3.Provider.CONSCRYPT import okhttp3.Provider.JSSE import okhttp3.TlsExtensionMode.DISABLED import okhttp3.TlsExtensionMode.STANDARD import okhttp3.TlsVersion.TLS_1_2 import okhttp3.TlsVersion.TLS_1_3 import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assumptions.assumeFalse import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.io.IOException import java.net.InetAddress import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit.SECONDS import javax.net.ssl.SNIHostName import javax.net.ssl.SNIMatcher import javax.net.ssl.SNIServerName import javax.net.ssl.SSLSocket import javax.net.ssl.StandardConstants import org.junit.jupiter.api.BeforeEach @Suppress("UsePropertyAccessSyntax") @Timeout(6) @Tag("slow") class SocketChannelTest { @JvmField @RegisterExtension val platform = PlatformRule() @JvmField @RegisterExtension val clientTestRule = OkHttpClientTestRule().apply { recordFrames = true // recordSslDebug = true } // https://tools.ietf.org/html/rfc6066#page-6 specifies a FQDN is required. val hostname = "local.host" private val handshakeCertificates = run { // Generate a self-signed cert for the server to serve and the client to trust. val heldCertificate = HeldCertificate.Builder() .commonName(hostname) .addSubjectAlternativeName(hostname) .build() HandshakeCertificates.Builder() .heldCertificate(heldCertificate) .addTrustedCertificate(heldCertificate.certificate) .build() } private var acceptedHostName: String? = null private lateinit var server: MockWebServer @BeforeEach fun setUp(server: MockWebServer) { this.server = server // Test designed for Conscrypt and JSSE platform.assumeNotBouncyCastle() } @ParameterizedTest @MethodSource("connectionTypes") fun testConnection(socketMode: SocketMode) { // https://github.com/square/okhttp/pull/6554 assumeFalse( socketMode is TlsInstance && socketMode.socketMode == Channel && socketMode.protocol == HTTP_2 && socketMode.tlsExtensionMode == STANDARD, "failing for channel and h2" ) if (socketMode is TlsInstance) { assumeTrue((socketMode.provider == CONSCRYPT) == platform.isConscrypt()) } val client = clientTestRule.newClientBuilder() .dns { listOf(InetAddress.getByName("localhost")) } .callTimeout(4, SECONDS) .writeTimeout(2, SECONDS) .readTimeout(2, SECONDS) .apply { if (socketMode is TlsInstance) { if (socketMode.socketMode == Channel) { socketFactory(ChannelSocketFactory()) } connectionSpecs( listOf( ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) .tlsVersions(socketMode.tlsVersion) .supportsTlsExtensions(socketMode.tlsExtensionMode == STANDARD) .build() ) ) val sslSocketFactory = handshakeCertificates.sslSocketFactory() sslSocketFactory( sslSocketFactory, handshakeCertificates.trustManager ) when (socketMode.protocol) { HTTP_2 -> protocols(listOf(HTTP_2, HTTP_1_1)) HTTP_1_1 -> protocols(listOf(HTTP_1_1)) else -> TODO() } val serverSslSocketFactory = object: DelegatingSSLSocketFactory(sslSocketFactory) { override fun configureSocket(sslSocket: SSLSocket): SSLSocket { return sslSocket.apply { sslParameters = sslParameters.apply { sniMatchers = listOf(object : SNIMatcher(StandardConstants.SNI_HOST_NAME) { override fun matches(serverName: SNIServerName): Boolean { acceptedHostName = (serverName as SNIHostName).asciiName return true } }) } } } } server.useHttps(serverSslSocketFactory) } else if (socketMode == Channel) { socketFactory(ChannelSocketFactory()) } } .build() server.enqueue(MockResponse().setBody("abc")) @Suppress("HttpUrlsUsage") val url = if (socketMode is TlsInstance) "https://$hostname:${server.port}/get" else "http://$hostname:${server.port}/get" val request = Request.Builder() .url(url) .build() val promise = CompletableFuture<Response>() val call = client.newCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { promise.completeExceptionally(e) } override fun onResponse(call: Call, response: Response) { promise.complete(response) } }) val response = promise.get(4, SECONDS) assertThat(response).isNotNull() assertThat(response.body.string()).isNotBlank() if (socketMode is TlsInstance) { assertThat(response.handshake!!.tlsVersion).isEqualTo(socketMode.tlsVersion) assertThat(acceptedHostName).isEqualTo(hostname) if (socketMode.tlsExtensionMode == STANDARD) { assertThat(response.protocol).isEqualTo(socketMode.protocol) } else { assertThat(response.protocol).isEqualTo(HTTP_1_1) } } } companion object { @Suppress("unused") @JvmStatic fun connectionTypes(): List<SocketMode> = listOf(CONSCRYPT, JSSE).flatMap { provider -> listOf(HTTP_1_1, HTTP_2).flatMap { protocol -> listOf(TLS_1_3, TLS_1_2).flatMap { tlsVersion -> listOf(Channel, Standard).flatMap { socketMode -> listOf(DISABLED, STANDARD).map { tlsExtensionMode -> TlsInstance(provider, protocol, tlsVersion, socketMode, tlsExtensionMode) } } } } } + Channel + Standard } } sealed class SocketMode object Channel : SocketMode() { override fun toString(): String = "Channel" } object Standard : SocketMode() { override fun toString(): String = "Standard" } data class TlsInstance( val provider: Provider, val protocol: Protocol, val tlsVersion: TlsVersion, val socketMode: SocketMode, val tlsExtensionMode: TlsExtensionMode ) : SocketMode() { override fun toString(): String = "$provider/$protocol/$tlsVersion/$socketMode/$tlsExtensionMode" } enum class Provider { JSSE, CONSCRYPT } enum class TlsExtensionMode { DISABLED, STANDARD }
apache-2.0
76beb76b2b8e635c8c428f7c364d8b4a
30.308642
99
0.679285
4.441331
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/activity/chat/ClyChatAdapter.kt
1
7015
package io.customerly.activity.chat /* * 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. */ import android.view.ViewGroup import io.customerly.R import io.customerly.entity.chat.ClyMessage import io.customerly.sxdependencies.SXRecyclerView import io.customerly.sxdependencies.SXRecyclerViewAdapter import io.customerly.utils.ggkext.activity import io.customerly.utils.ggkext.dp2px import io.customerly.utils.ggkext.weak import kotlinx.android.synthetic.main.io_customerly__activity_chat.* /** * Created by Gianni on 27/04/18. * Project: Customerly-KAndroid-SDK */ internal class ClyChatAdapter(chatActivity : ClyChatActivity) : SXRecyclerViewAdapter<ClyChatViewHolder>() { private val weakChatActivity = chatActivity.weak() private fun position2listIndex(position: Int) = when { this.weakChatActivity.get()?.typingAccountId != TYPING_NO_ONE -> position - 1 else -> position } internal fun listIndex2position(listIndex: Int) = when { this.weakChatActivity.get()?.typingAccountId != TYPING_NO_ONE -> listIndex + 1 else -> listIndex } override fun getItemViewType(position: Int): Int { return when(val listIndex = this.position2listIndex(position = position)) { -1 -> R.layout.io_customerly__li_bubble_account_typing else -> { when (position) { this.itemCount - 1 -> { R.layout.io_customerly__li_bubble_accountinfos } else -> { when(val message = this.weakChatActivity.get()?.chatList?.get(index = listIndex)) { null -> R.layout.io_customerly__li_bubble_account_rich is ClyMessage.Human -> when { message.writer.isUser -> R.layout.io_customerly__li_bubble_user message.richMailLink == null -> R.layout.io_customerly__li_bubble_account_text else -> R.layout.io_customerly__li_bubble_account_rich } is ClyMessage.Bot -> when(message) { is ClyMessage.Bot.Text -> R.layout.io_customerly__li_bubble_bot_text is ClyMessage.Bot.Form.AskEmail -> R.layout.io_customerly__li_bubble_bot_askemail is ClyMessage.Bot.Form.Profiling -> R.layout.io_customerly__li_bubble_bot_profilingform } } } } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClyChatViewHolder { val recyclerView: SXRecyclerView = (parent as? SXRecyclerView) ?: (parent.activity as ClyChatActivity).io_customerly__recycler_view return when (viewType) { R.layout.io_customerly__li_bubble_user -> ClyChatViewHolder.Bubble.Message.User(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_account_text -> ClyChatViewHolder.Bubble.Message.Account.Text(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_account_rich -> ClyChatViewHolder.Bubble.Message.Account.Rich(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_bot_text -> ClyChatViewHolder.Bubble.Message.Bot.Text(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_bot_profilingform -> ClyChatViewHolder.Bubble.Message.Bot.Form.Profiling(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_bot_askemail -> ClyChatViewHolder.Bubble.Message.Bot.Form.AskEmail(recyclerView = recyclerView) R.layout.io_customerly__li_bubble_accountinfos -> ClyChatViewHolder.AccountInfos(recyclerView = recyclerView) else/* R.layout.io_customerly__li_bubble_account_typing */ -> ClyChatViewHolder.Bubble.Typing(recyclerView = recyclerView) } } override fun onBindViewHolder(holder: ClyChatViewHolder, position: Int) { this.weakChatActivity.get()?.let { chatActivity -> when (holder) { is ClyChatViewHolder.Bubble -> { val listIndex = this.position2listIndex(position = position) val message: ClyMessage? = if (listIndex == -1) { null } else { chatActivity.chatList[listIndex] } val previousMessage: ClyMessage? = if (listIndex == chatActivity.chatList.size - 1) { null } else { chatActivity.chatList[listIndex + 1] } val isFirstMessageOfSender = when { previousMessage == null -> true message == null && !previousMessage.writer.isUser -> true message != null && message.writer != previousMessage.writer -> true else -> false } val dateToDisplay = if (message == null || previousMessage != null && message.isSentSameDay(of = previousMessage)) { null } else { message.dateString } holder.apply(chatActivity = chatActivity, message = message, dateToDisplay = dateToDisplay, isFirstMessageOfSender = isFirstMessageOfSender) holder.itemView.setPadding(0, if (isFirstMessageOfSender) 15.dp2px else 0, 0, if (listIndex <= 0 /* -1 is typing item */) 5.dp2px else 0) //paddingTop = 15dp to every first message of the group //paddingBottom = 5dp to the last message of the chat } is ClyChatViewHolder.AccountInfos -> { holder.apply(chatActivity = chatActivity) } } } } override fun getItemCount(): Int = 1 + (this.weakChatActivity.get()?.let { it.chatList.size + if (it.typingAccountId == TYPING_NO_ONE) { 0 } else { 1 } } ?: 0) override fun onViewDetachedFromWindow(holder: ClyChatViewHolder) { holder.itemView.clearAnimation() } fun notifyAccountCardChanged() { this.notifyItemChanged(this.itemCount - 1) } }
apache-2.0
b80507421a5f709c079d0f075bc2e8d4
49.84058
160
0.594013
4.736664
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/comment/model/DiscussionThreadContainer.kt
2
894
package org.stepik.android.view.comment.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes import org.stepic.droid.R enum class DiscussionThreadContainer( @StringRes val disabledStringRes: Int, @StringRes val showStringRes: Int, @StringRes val writeFirstStringRes: Int, @DrawableRes val containerDrawable: Int ) { DEFAULT( disabledStringRes = R.string.comment_disabled, showStringRes = R.string.step_discussion_show, writeFirstStringRes = R.string.step_discussion_write_first, containerDrawable = R.drawable.ic_step_discussion ), SOLUTIONS( disabledStringRes = R.string.solution_disabled, showStringRes = R.string.step_solutions_show, writeFirstStringRes = R.string.step_solutions_write_first, containerDrawable = R.drawable.ic_step_solutions ) }
apache-2.0
18fedc01519f6031fb12878d68a9b138
26.96875
67
0.718121
4.197183
false
false
false
false
allotria/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/problems/ProblemCollector.kt
4
3786
// 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.codeInsight.daemon.problems import com.intellij.pom.Navigatable import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope internal class ProblemCollector { companion object { @JvmName("collect") @JvmStatic internal fun collect(prevMember: ScopedMember?, curMember: PsiMember): Set<Problem>? { val containingFile = curMember.containingFile // member properties were changed if (prevMember != null && prevMember.name == curMember.name) { return processMemberChange(prevMember, curMember, containingFile) } val problems = mutableSetOf<Problem>() // member was renamed if (prevMember != null) { val memberProblems = processUsages(containingFile, prevMember) ?: return null problems.addAll(memberProblems) } val memberProblems = processUsages(containingFile, curMember) ?: return null problems.addAll(memberProblems) return problems } private fun processMemberChange(prevMember: ScopedMember, curMember: PsiMember, containingFile: PsiFile): Set<Problem>? { val unionScope = getUnionScope(prevMember, curMember) ?: return null val memberType = MemberType.create(curMember) ?: return null val memberName = prevMember.name return processUsages(memberName, memberType, containingFile, unionScope) } private fun processUsages(containingFile: PsiFile, psiMember: PsiMember): Set<Problem>? { val memberName = psiMember.name ?: return null val scope = psiMember.useScope as? GlobalSearchScope ?: return null val memberType = MemberType.create(psiMember) ?: return null return processUsages(memberName, memberType, containingFile, scope) } private fun processUsages(containingFile: PsiFile, member: ScopedMember): Set<Problem>? { val scope = member.scope as? GlobalSearchScope ?: return null val memberName = member.name val memberType = MemberType.create(member.member) return processUsages(memberName, memberType, containingFile, scope) } private fun processUsages(memberName: String, memberType: MemberType, containingFile: PsiFile, scope: GlobalSearchScope): Set<Problem>? { val usageExtractor: (PsiFile, Int) -> PsiElement? = { file, index -> extractUsage(file, index, memberType) } val usages = MemberUsageCollector.collect(memberName, containingFile, scope, usageExtractor) ?: return null return usages.flatMapTo(mutableSetOf()) { ProblemSearcher.getProblems(it, containingFile, memberType) } } private fun extractUsage(psiFile: PsiFile, index: Int, memberType: MemberType): PsiElement? { val identifier = psiFile.findElementAt(index) as? PsiIdentifier ?: return null val parent = identifier.parent val usage = when { parent is PsiReference -> { val javaReference = parent.element as? PsiJavaReference if (javaReference != null) javaReference as? PsiElement else null } parent is PsiMethod && memberType == MemberType.METHOD -> parent else -> null } return if (usage is Navigatable) usage else null } private fun getUnionScope(prevMember: ScopedMember, curMember: PsiMember): GlobalSearchScope? { val prevScope = prevMember.scope as? GlobalSearchScope val curScope = curMember.useScope as? GlobalSearchScope ?: return prevScope if (prevScope == null) return curScope return if (prevScope == curScope) return curScope else prevScope.union(curScope) } } }
apache-2.0
8f620028a1807fd2c22424e25e35cd04
41.550562
140
0.698362
4.955497
false
false
false
false
allotria/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyTypeHintsUtil.kt
1
3025
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInsight.hint import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.codeInsight.hints.presentation.SpacePresentation import com.intellij.psi.* fun PresentationFactory.buildRepresentation(type: PsiType, postfix: String = ""): InlayPresentation { return type.accept(object : PsiTypeVisitor<InlayPresentation>() { private val visitor = this override fun visitClassType(classType: PsiClassType): InlayPresentation { val classParameters = if (classType.hasParameters()) { listOf(smallText("<"), *classType.parameters.map { it.accept(visitor) }.intersperse(smallText(", ")).toTypedArray(), smallText(">")) } else { emptyList() } val className: String = classType.className ?: classType.presentableText return seq( psiSingleReference(smallText(className)) { classType.resolve() }, *classParameters.toTypedArray() ) } override fun visitArrayType(arrayType: PsiArrayType): InlayPresentation { return seq( arrayType.componentType.accept(visitor), smallText("[]") ) } override fun visitWildcardType(wildcardType: PsiWildcardType): InlayPresentation { val boundRepresentation = wildcardType.bound?.accept(visitor) val boundKeywordRepresentation = when { wildcardType.isExtends -> seq(smallText(" extends "), boundRepresentation!!) wildcardType.isSuper -> seq(smallText(" super "), boundRepresentation!!) else -> SpacePresentation(0, 0) } return seq( smallText("?"), boundKeywordRepresentation ) } override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): InlayPresentation { return smallText(primitiveType.name) } }).run { if (postfix.isEmpty()) this else seq(this, smallText(postfix)) } } private fun <T> Iterable<T>.intersperse(delimiter: T): List<T> { val collector = mutableListOf<T>() for (element in this) { if (collector.isNotEmpty()) { collector.add(delimiter) } collector.add(element) } return collector } fun PresentationFactory.buildRepresentation(typeParameterList: PsiTypeParameterList): InlayPresentation { return typeParameterList.typeParameters.map { typeParameter -> val name = typeParameter.name!! val bound = typeParameter.extendsListTypes.map { buildRepresentation(it) }.intersperse(smallText(" & ")) if (bound.isEmpty()) { smallText(name) } else { seq(smallText("$name extends "), seq(*bound.toTypedArray()) ) } }.intersperse(smallText(", ")) .run { seq(smallText("<"), *this.toTypedArray(), smallText(">")) } .let { roundWithBackground(it) } }
apache-2.0
c143f34ff58cfb693b92eafad17d127f
34.186047
140
0.682314
4.733959
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/actions/GitSingleCommitActionGroup.kt
1
1633
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.VcsLog import com.intellij.vcs.log.VcsLogDataKeys import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager internal abstract class GitSingleCommitActionGroup() : ActionGroup(), DumbAware { constructor(actionText: String, isPopup: Boolean) : this() { templatePresentation.text = actionText setPopup(isPopup) } override fun hideIfNoVisibleChildren(): Boolean { return true } override fun getChildren(e: AnActionEvent?): Array<AnAction> { if (e == null) return AnAction.EMPTY_ARRAY val project = e.project val log = e.getData(VcsLogDataKeys.VCS_LOG) if (project == null || log == null) { return AnAction.EMPTY_ARRAY } val commits = log.selectedCommits if (commits.size != 1) return AnAction.EMPTY_ARRAY val commit = commits.first() val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(commit.root) ?: return AnAction.EMPTY_ARRAY return getChildren(e, project, log, repository, commit) } abstract fun getChildren(e: AnActionEvent, project: Project, log: VcsLog, repository: GitRepository, commit: CommitId): Array<AnAction> }
apache-2.0
51a9f74cfa0e331024ba1b28b7388ccb
36.136364
140
0.766687
4.343085
false
false
false
false
leafclick/intellij-community
platform/configuration-store-impl/src/ComponentStoreWithExtraComponents.kt
1
4385
// 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.configurationStore import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean // A way to remove obsolete component data. internal val OBSOLETE_STORAGE_EP = ExtensionPointName<ObsoleteStorageBean>("com.intellij.obsoleteStorage") abstract class ComponentStoreWithExtraComponents : ComponentStoreImpl() { @Suppress("DEPRECATION") private val settingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<SettingsSavingComponent>() private val asyncSettingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<com.intellij.configurationStore.SettingsSavingComponent>() // todo do we really need this? private val isSaveSettingsInProgress = AtomicBoolean() override suspend fun save(forceSavingAllSettings: Boolean) { if (!isSaveSettingsInProgress.compareAndSet(false, true)) { LOG.warn("save call is ignored because another save in progress", Throwable()) return } try { super.save(forceSavingAllSettings) } finally { isSaveSettingsInProgress.set(false) } } override fun initComponent(component: Any, serviceDescriptor: ServiceDescriptor?) { @Suppress("DEPRECATION") if (component is com.intellij.configurationStore.SettingsSavingComponent) { asyncSettingsSavingComponents.add(component) } else if (component is SettingsSavingComponent) { settingsSavingComponents.add(component) } super.initComponent(component, serviceDescriptor) } internal suspend fun saveSettingsSavingComponentsAndCommitComponents(result: SaveResult, forceSavingAllSettings: Boolean, saveSessionProducerManager: SaveSessionProducerManager) { coroutineScope { // expects EDT launch(storeEdtCoroutineDispatcher) { @Suppress("Duplicates") val errors = SmartList<Throwable>() for (settingsSavingComponent in settingsSavingComponents) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } launch { val errors = SmartList<Throwable>() for (settingsSavingComponent in asyncSettingsSavingComponents) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } } // SchemeManager (old settingsSavingComponent) must be saved before saving components (component state uses scheme manager in an ipr project, so, we must save it before) // so, call sequentially it, not inside coroutineScope commitComponentsOnEdt(result, forceSavingAllSettings, saveSessionProducerManager) } override fun commitComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>) { // ensure that this task will not interrupt regular saving LOG.runAndLogException { commitObsoleteComponents(session, false) } super.commitComponents(isForce, session, errors) } internal open fun commitObsoleteComponents(session: SaveSessionProducerManager, isProjectLevel: Boolean) { for (bean in OBSOLETE_STORAGE_EP.extensionList) { if (bean.isProjectLevel != isProjectLevel) { continue } val storage = (storageManager as StateStorageManagerImpl).getOrCreateStorage(bean.file ?: continue) for (componentName in bean.components) { session.getProducer(storage)?.setState(null, componentName, null) } } } } private inline fun <T> runAndCollectException(errors: MutableList<Throwable>, runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { errors.add(e) return null } }
apache-2.0
11ab5bebf19d060aa0ef2c3410f9b082
36.478632
173
0.73455
5.315152
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/substitutionInSuperClass/enum.kt
5
607
interface A<T> { open fun foo(t: T) = "A" } interface B : A<String> enum class Z(val aname: String) : B { Z1("Z1"), Z2("Z2"); override fun foo(t: String) = aname } fun box(): String { val z1b: B = Z.Z1 val z2b: B = Z.Z2 val z1a: A<String> = Z.Z1 val z2a: A<String> = Z.Z2 return when { Z.Z1.foo("") != "Z1" -> "Fail #1" Z.Z2.foo("") != "Z2" -> "Fail #2" z1b.foo("") != "Z1" -> "Fail #3" z2b.foo("") != "Z2" -> "Fail #4" z1a.foo("") != "Z1" -> "Fail #5" z2a.foo("") != "Z2" -> "Fail #6" else -> "OK" } }
apache-2.0
5feddde79707d4fdf7be44e4b02d5812
20.678571
41
0.425041
2.307985
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/intLikeVarSpilling/loadFromBooleanArray.kt
2
694
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { suspend fun suspendHere(): Unit = suspendCoroutineOrReturn { x -> x.resume(Unit) COROUTINE_SUSPENDED } } fun builder(c: suspend Controller.() -> Unit) { c.startCoroutine(Controller(), EmptyContinuation) } private var booleanResult = false fun setBooleanRes(x: Boolean) { booleanResult = x } fun box(): String { builder { val a = booleanArrayOf(true) val x = a[0] suspendHere() setBooleanRes(x) } if (!booleanResult) return "fail 1" return "OK" }
apache-2.0
c6ab3860c7f6e1211b5b611d70e90aff
19.411765
69
0.657061
4.082353
false
false
false
false
AndroidX/androidx
camera/camera-video/src/androidTest/java/androidx/camera/video/VideoCaptureDeviceTest.kt
3
15924
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.video import android.content.Context import android.graphics.SurfaceTexture import android.os.Build import android.view.Surface import androidx.camera.camera2.Camera2Config import androidx.camera.camera2.pipe.integration.CameraPipeConfig import androidx.camera.core.CameraInfo import androidx.camera.core.CameraSelector import androidx.camera.core.CameraXConfig import androidx.camera.core.SurfaceRequest import androidx.camera.core.impl.MutableStateObservable import androidx.camera.core.impl.Observable import androidx.camera.core.internal.CameraUseCaseAdapter import androidx.camera.testing.CameraPipeConfigTestRule import androidx.camera.testing.CameraUtil import androidx.camera.testing.CameraXUtil import androidx.camera.testing.GLUtil import androidx.camera.video.VideoOutput.SourceState import androidx.concurrent.futures.await import androidx.test.core.app.ApplicationProvider import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.testutils.fail import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.collectIndexed import kotlinx.coroutines.flow.dropWhile import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.getAndUpdate import kotlinx.coroutines.flow.last import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.junit.After import org.junit.Assume.assumeFalse import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) @SdkSuppress(minSdkVersion = 21) class VideoCaptureDeviceTest( private val implName: String, private val cameraConfig: CameraXConfig ) { @get:Rule val cameraPipeConfigTestRule = CameraPipeConfigTestRule( active = implName == CameraPipeConfig::class.simpleName, ) @get:Rule val cameraRule = CameraUtil.grantCameraPermissionAndPreTest( CameraUtil.PreTestCameraIdList(cameraConfig) ) companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = listOf( arrayOf(Camera2Config::class.simpleName, Camera2Config.defaultConfig()), arrayOf(CameraPipeConfig::class.simpleName, CameraPipeConfig.defaultConfig()) ) } private val context: Context = ApplicationProvider.getApplicationContext() private val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA private lateinit var cameraUseCaseAdapter: CameraUseCaseAdapter private lateinit var cameraInfo: CameraInfo @Before fun setUp() { CameraXUtil.initialize( context, cameraConfig ).get() cameraUseCaseAdapter = CameraUtil.createCameraUseCaseAdapter(context, cameraSelector) cameraInfo = cameraUseCaseAdapter.cameraInfo } @After fun tearDown(): Unit = runBlocking { if (::cameraUseCaseAdapter.isInitialized) { withContext(Dispatchers.Main) { cameraUseCaseAdapter.apply { removeUseCases(useCases) } } } val timeout = 10.seconds withTimeoutOrNull(timeout) { CameraXUtil.shutdown().await() ?: "Shutdown succeeded." } ?: fail("Timed out waiting for CameraX to shutdown. Waited $timeout.") } @Test fun addUseCases_canReceiveFrame(): Unit = runBlocking { // Arrange. val videoOutput = TestVideoOutput() val videoCapture = VideoCapture.withOutput(videoOutput) // Act. withContext(Dispatchers.Main) { cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Assert. val surfaceRequest = videoOutput.nextSurfaceRequest(5, TimeUnit.SECONDS) val frameCountFlow = surfaceRequest.provideUpdatingSurface() val timeout = 10.seconds withTimeoutOrNull(timeout) { frameCountFlow.takeWhile { frameCount -> frameCount <= 5 }.last() } ?: fail("Timed out waiting for `frameCount >= 5`. Waited $timeout.") } @Test fun changeStreamState_canReceiveFrame(): Unit = runBlocking { // Arrange. val videoOutput = TestVideoOutput( streamInfo = StreamInfo.of( StreamInfo.STREAM_ID_ANY, StreamInfo.StreamState.INACTIVE ) ) val videoCapture = VideoCapture.withOutput(videoOutput) // Act. withContext(Dispatchers.Main) { cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Assert. val surfaceRequest = videoOutput.nextSurfaceRequest(5, TimeUnit.SECONDS) val frameCountFlow = surfaceRequest.provideUpdatingSurface() // No frame should be updated by INACTIVE state val expectedTimeout = 2.seconds withTimeoutOrNull(expectedTimeout) { // assertThat should never run since timeout should occur, but if it does, // we'll get a nicer error message. assertThat(frameCountFlow.dropWhile { frameCount -> frameCount < 1 } .first()).isAtMost(0) } // Act. videoOutput.setStreamInfo( StreamInfo.of( StreamInfo.STREAM_ID_ANY, StreamInfo.StreamState.ACTIVE ) ) // Assert. val timeout = 10.seconds withTimeoutOrNull(timeout) { frameCountFlow.take(5).last() } ?: fail("Timed out waiting for 5 frame updates. Waited $timeout.") } @Test fun addUseCases_setSupportedQuality_getCorrectResolution() = runBlocking { assumeTrue(QualitySelector.getSupportedQualities(cameraInfo).isNotEmpty()) // Cuttlefish API 29 has inconsistent resolution issue. See b/184015059. assumeFalse(Build.MODEL.contains("Cuttlefish") && Build.VERSION.SDK_INT == 29) // Arrange. val qualityList = QualitySelector.getSupportedQualities(cameraInfo) qualityList.forEach loop@{ quality -> val targetResolution = QualitySelector.getResolution(cameraInfo, quality)!! val videoOutput = TestVideoOutput( mediaSpec = MediaSpec.builder().configureVideo { it.setQualitySelector(QualitySelector.from(quality)) }.build() ) val videoCapture = VideoCapture.withOutput(videoOutput) // Act. if (!cameraUseCaseAdapter.isUseCasesCombinationSupported(videoCapture)) { return@loop } withContext(Dispatchers.Main) { cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Assert. assertWithMessage("Set quality value by $quality") .that(videoCapture.attachedSurfaceResolution).isEqualTo(targetResolution) // Cleanup. withContext(Dispatchers.Main) { cameraUseCaseAdapter.apply { removeUseCases(listOf(videoCapture)) } } } } @Test fun useCaseCanBeReused(): Unit = runBlocking { // Arrange. val videoOutput = TestVideoOutput() val videoCapture = VideoCapture.withOutput(videoOutput) // Act. withContext(Dispatchers.Main) { cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Assert. var surfaceRequest = videoOutput.nextSurfaceRequest(5, TimeUnit.SECONDS) var frameCountFlow = surfaceRequest.provideUpdatingSurface() val timeout = 10.seconds withTimeoutOrNull(timeout) { frameCountFlow.takeWhile { frameCount -> frameCount <= 5 }.last() } ?: fail("Timed out waiting for `frameCount >= 5`. Waited $timeout.") // Act. // Reuse use case withContext(Dispatchers.Main) { cameraUseCaseAdapter.apply { removeUseCases(listOf(videoCapture)) } cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Assert. surfaceRequest = videoOutput.nextSurfaceRequest(5, TimeUnit.SECONDS) frameCountFlow = surfaceRequest.provideUpdatingSurface() withTimeoutOrNull(timeout) { frameCountFlow.takeWhile { frameCount -> frameCount <= 5 }.last() } ?: fail("Timed out waiting for `frameCount >= 5`. Waited $timeout.") } @Test fun activeStreamingVideoCaptureStaysInactive_afterUnbind(): Unit = runBlocking { // Arrange. val videoOutput = TestVideoOutput( streamInfo = StreamInfo.of(1, StreamInfo.StreamState.ACTIVE) ) val videoCapture = VideoCapture.withOutput(videoOutput) val finalSourceState = CompletableDeferred<SourceState>() launch { val flowScope = this val inactiveWaitTimeMs = 2000L videoOutput.sourceStateFlow .buffer(Channel.UNLIMITED) .dropWhile { it != SourceState.INACTIVE } // Drop all states until next INACTIVE .collectIndexed { index, value -> // We should not receive any other states besides INACTIVE if (value != SourceState.INACTIVE) { finalSourceState.complete(value) flowScope.cancel() return@collectIndexed } if (index == 0) { launch { // Cancel collection after waiting for a delay after INACTIVE state. delay(inactiveWaitTimeMs) finalSourceState.complete(SourceState.INACTIVE) flowScope.cancel() } } } } withContext(Dispatchers.Main) { cameraUseCaseAdapter.addUseCases(listOf(videoCapture)) } // Act. val surfaceRequest = videoOutput.nextSurfaceRequest(5, TimeUnit.SECONDS) val frameCountFlow = surfaceRequest.provideUpdatingSurface() // Assert. // Frames should be streaming var timeout = 10.seconds withTimeoutOrNull(timeout) { frameCountFlow.takeWhile { frameCount -> frameCount <= 5 }.last() } ?: fail("Timed out waiting for `frameCount >= 5`. Waited $timeout.") // Act. // Send a new StreamInfo with inactive stream state to emulate a recording stopping videoOutput.setStreamInfo(StreamInfo.of(1, StreamInfo.StreamState.INACTIVE)) // Detach use case asynchronously with launch rather than synchronously with withContext // so VideoCapture.onStateDetach() is in a race with the StreamInfo observable launch(Dispatchers.Main) { cameraUseCaseAdapter.removeUseCases(listOf(videoCapture)) } // Send a new StreamInfo delayed to emulate resetting the surface of an encoder videoOutput.setStreamInfo( StreamInfo.of(StreamInfo.STREAM_ID_ANY, StreamInfo.StreamState.INACTIVE) ) // Assert. // Final state should be INACTIVE timeout = 5.seconds withTimeoutOrNull(timeout) { assertThat(finalSourceState.await()).isEqualTo(SourceState.INACTIVE) } ?: fail("Timed out waiting for INACTIVE state. Waited $timeout.") } private class TestVideoOutput( streamInfo: StreamInfo = StreamInfo.of( StreamInfo.STREAM_ID_ANY, StreamInfo.StreamState.ACTIVE ), mediaSpec: MediaSpec = MediaSpec.builder().build() ) : VideoOutput { private val surfaceRequests = ArrayBlockingQueue<SurfaceRequest>(10) private val streamInfoObservable: MutableStateObservable<StreamInfo> = MutableStateObservable.withInitialState(streamInfo) private val mediaSpecObservable: MutableStateObservable<MediaSpec> = MutableStateObservable.withInitialState(mediaSpec) private val sourceStateListeners = CopyOnWriteArraySet<(SourceState) -> Unit>() val sourceStateFlow = callbackFlow { val listener: (SourceState) -> Unit = { sourceState -> trySend(sourceState) } sourceStateListeners.add(listener) awaitClose { sourceStateListeners.remove(listener) } } override fun onSurfaceRequested(surfaceRequest: SurfaceRequest) { surfaceRequests.put(surfaceRequest) } override fun getStreamInfo(): Observable<StreamInfo> = streamInfoObservable override fun getMediaSpec(): Observable<MediaSpec> = mediaSpecObservable override fun onSourceStateChanged(sourceState: SourceState) { for (listener in sourceStateListeners) { listener(sourceState) } } fun nextSurfaceRequest(timeout: Long, timeUnit: TimeUnit): SurfaceRequest { return surfaceRequests.poll(timeout, timeUnit) } fun setStreamInfo(streamInfo: StreamInfo) = streamInfoObservable.setState(streamInfo) } private suspend fun SurfaceRequest.provideUpdatingSurface(): StateFlow<Int> { var isReleased = false val frameCountFlow = MutableStateFlow(0) val executor = Executors.newFixedThreadPool(1) val surfaceTexture = withContext(executor.asCoroutineDispatcher()) { SurfaceTexture(0).apply { setDefaultBufferSize(640, 480) detachFromGLContext() attachToGLContext(GLUtil.getTexIdFromGLContext()) setOnFrameAvailableListener { frameCountFlow.getAndUpdate { frameCount -> frameCount + 1 } executor.execute { if (!isReleased) { updateTexImage() } } } } } val surface = Surface(surfaceTexture) provideSurface(surface, executor) { surfaceTexture.release() surface.release() executor.shutdown() isReleased = true } return frameCountFlow.asStateFlow() } }
apache-2.0
c567bebf7854a9c5a567b27ef222e396
36.380282
96
0.657749
5.367037
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/inspections/InspectionUtils.kt
6
2522
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.GlobalInspectionTool import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ex.LocalInspectionToolWrapper import com.intellij.codeInspection.ui.InspectionToolPresentation import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.InspectionTestUtil import com.intellij.testFramework.createGlobalContextForTool import org.jdom.Element fun runInspection( inspection: LocalInspectionTool, project: Project, files: List<VirtualFile>? = null, withTestDir: String? = null ): InspectionToolPresentation { val wrapper = LocalInspectionToolWrapper(inspection) val tool = wrapper.tool if (tool is PluginVersionDependentInspection) { tool.testVersionMessage = "\$PLUGIN_VERSION" } val scope = if (files != null) AnalysisScope(project, files) else AnalysisScope(project) scope.invalidate() val globalContext = createGlobalContextForTool(scope, project, listOf(wrapper)) InspectionTestUtil.runTool(wrapper, scope, globalContext) if (withTestDir != null) { InspectionTestUtil.compareToolResults(globalContext, wrapper, false, withTestDir) } return globalContext.getPresentation(wrapper) } fun runInspection( inspectionClass: Class<*>, project: Project, settings: Element? = null, files: List<VirtualFile>? = null, withTestDir: String? = null ): InspectionToolPresentation { @Suppress("UNCHECKED_CAST") val profileEntryClass = inspectionClass as Class<InspectionProfileEntry> val inspection = InspectionTestUtil.instantiateTools(listOf(profileEntryClass)).singleOrNull() ?: error("Can't create `$inspectionClass` inspection") if (settings != null) { inspection.readSettings(settings) } val localInspection = when (inspection) { is LocalInspectionTool -> inspection is GlobalInspectionTool -> inspection.sharedLocalInspectionTool ?: error("Global inspection ${inspection::class} without local counterpart") else -> error("Unknown class for inspection instance") } return runInspection(localInspection, project, files, withTestDir) }
apache-2.0
eb98725eb208c3f4453ff141ecdfcade
41.745763
158
0.769627
4.887597
false
true
false
false
evernote/android-state
library-lint/src/main/kotlin/com/evernote/android/state/lint/detector/AndroidStateDetector.kt
1
4630
package com.evernote.android.state.lint.detector import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Context import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.getContainingUFile import java.util.EnumSet /** * This detector crawls through the Java and Kotlin files and looks for non-matching instances of * saveInstanceState and restoreInstanceState for the StateSaver library. * * Created by junchengc on 5/15/17. */ class AndroidStateDetector : Detector(), Detector.UastScanner { companion object Issues { private val IMPLEMENTATION = Implementation(AndroidStateDetector::class.java, Scope.JAVA_FILE_SCOPE) private const val ADVICE = "StateSaver calls should always occur in pairs. StateSaver.saveInstanceState() should always have a matching call to StateSaver.restoreInstanceState()." @JvmField val ISSUE = Issue.create( "NonMatchingStateSaverCalls", ADVICE, "$ADVICE Failing to do so could result in weird behaviors after activity recreation where certain states are not persisted.", Category.CORRECTNESS, 6, Severity.WARNING, IMPLEMENTATION ) private const val SAVE_INSTANCE_STATE_METHOD = "saveInstanceState" private const val RESTORE_INSTANCE_STATE_METHOD = "restoreInstanceState" private val APPLICABLE_METHODS = listOf(SAVE_INSTANCE_STATE_METHOD, RESTORE_INSTANCE_STATE_METHOD) private const val STATE_SAVER_CLASS_SIMPLE = "StateSaver" private const val STATE_SAVER_CLASS = "com.evernote.android.state.$STATE_SAVER_CLASS_SIMPLE" } private val saveCalls = mutableMapOf<UDeclaration, UCallExpression>() private val restoreCalls = mutableMapOf<UDeclaration, UCallExpression>() override fun afterCheckFile(context: Context) { try { if (context !is JavaContext) return val allClasses = mutableSetOf<UDeclaration>().apply { addAll(saveCalls.keys) addAll(restoreCalls.keys) } allClasses .filter { saveCalls.containsKey(it) xor restoreCalls.containsKey(it) } .map { (saveCalls[it] ?: restoreCalls[it])!! } .forEach { context.report(ISSUE, it, context.getLocation(it), ADVICE) } } finally { saveCalls.clear() restoreCalls.clear() } } override fun createUastHandler(context: JavaContext) = object : UElementHandler() { override fun visitCallExpression(node: UCallExpression) { val methodName = node.methodIdentifier?.name ?: return val uastParent = node.uastParent ?: return if (!APPLICABLE_METHODS.contains(methodName)) return val uFile = node.getContainingUFile() ?: return val imports = uFile.imports.mapNotNull { it.importReference?.asSourceString() } val parent = uastParent.psi?.text ?: return // StateSaver.restoreInstanceState or surrounding method with direct import if (!isStateSaverMethod(methodName, imports, parent)) return val cls = node.getContainingUClass()!! when (methodName) { SAVE_INSTANCE_STATE_METHOD -> saveCalls[cls] = node RESTORE_INSTANCE_STATE_METHOD -> restoreCalls[cls] = node } } private fun isStateSaverMethod(methodName: String, imports: List<String>, parent: String) = if (imports.contains("$STATE_SAVER_CLASS.$methodName")) { true // direct import } else { // StateSaver.methodName check imports.contains(STATE_SAVER_CLASS) && parent.startsWith("$STATE_SAVER_CLASS_SIMPLE.$methodName") } } override fun getApplicableUastTypes(): List<Class<out UElement>> = listOf(UCallExpression::class.java) override fun getApplicableFiles(): EnumSet<Scope> = Scope.JAVA_FILE_SCOPE override fun getApplicableMethodNames(): List<String> = APPLICABLE_METHODS }
epl-1.0
776f6b9919d90f1fd4a514e00b34eb24
43.519231
187
0.68121
4.783058
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/activities/PrivacyActivity.kt
1
4586
package com.kickstarter.ui.activities import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import com.kickstarter.R import com.kickstarter.databinding.ActivityPrivacyBinding import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.utils.Secrets import com.kickstarter.libs.utils.SwitchCompatUtils import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.isFalse import com.kickstarter.libs.utils.extensions.isTrue import com.kickstarter.models.User import com.kickstarter.viewmodels.PrivacyViewModel import rx.android.schedulers.AndroidSchedulers @RequiresActivityViewModel(PrivacyViewModel.ViewModel::class) class PrivacyActivity : BaseActivity<PrivacyViewModel.ViewModel>() { private val cancelString = R.string.Cancel private val unableToSaveString = R.string.profile_settings_error private val yesTurnOffString = R.string.Yes_turn_off private var followingConfirmationDialog: AlertDialog? = null private lateinit var binding: ActivityPrivacyBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPrivacyBinding.inflate(layoutInflater) setContentView(binding.root) this.viewModel.outputs.hideConfirmFollowingOptOutPrompt() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { SwitchCompatUtils.setCheckedWithoutAnimation(binding.followingSwitch, true) } this.viewModel.outputs.showConfirmFollowingOptOutPrompt() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { lazyFollowingOptOutConfirmationDialog().show() } this.viewModel.errors.unableToSavePreferenceError() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ViewUtils.showToast(this, getString(this.unableToSaveString)) } this.viewModel.outputs.user() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.displayPreferences(it) } this.viewModel.outputs.hidePrivateProfileRow() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.privateProfileRow.isGone = it binding.privateProfileTextView.isGone = it binding.publicProfileTextView.isGone = it } binding.followingSwitch.setOnClickListener { this.viewModel.inputs.optIntoFollowing(binding.followingSwitch.isChecked) } binding.privateProfileSwitch.setOnClickListener { this.viewModel.inputs.showPublicProfile(binding.privateProfileSwitch.isChecked) } binding.recommendationsSwitch.setOnClickListener { this.viewModel.inputs.optedOutOfRecommendations(binding.recommendationsSwitch.isChecked) } binding.settingsRequestData.setOnClickListener { showPrivacyWebpage(Secrets.Privacy.REQUEST_DATA) } binding.settingsDeleteAccount.setOnClickListener { showPrivacyWebpage(Secrets.Privacy.DELETE_ACCOUNT) } } private fun displayPreferences(user: User) { SwitchCompatUtils.setCheckedWithoutAnimation(binding.followingSwitch, user.social().isTrue()) SwitchCompatUtils.setCheckedWithoutAnimation(binding.privateProfileSwitch, user.showPublicProfile().isFalse()) SwitchCompatUtils.setCheckedWithoutAnimation(binding.recommendationsSwitch, user.optedOutOfRecommendations().isFalse()) } private fun lazyFollowingOptOutConfirmationDialog(): AlertDialog { if (this.followingConfirmationDialog == null) { this.followingConfirmationDialog = AlertDialog.Builder(this) .setCancelable(false) .setTitle(getString(R.string.Are_you_sure)) .setMessage(getString(R.string.If_you_turn_following_off)) .setNegativeButton(this.cancelString) { _, _ -> this.viewModel.inputs.optOutOfFollowing(false) } .setPositiveButton(this.yesTurnOffString) { _, _ -> this.viewModel.inputs.optOutOfFollowing(true) } .create() } return this.followingConfirmationDialog!! } private fun showPrivacyWebpage(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } }
apache-2.0
f6aefb24bbc45189ee1d4122f7341230
46.278351
149
0.738334
5.06181
false
false
false
false
DanielGrech/anko
preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/DslWorker.kt
3
10650
/* * Copyright 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.kotlin.android.dslpreview import com.google.common.io.Files import com.google.common.io.Resources import com.google.gson.Gson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import org.zeromq.ZMQ import java.io.File import java.net.URL import java.util.* import org.jetbrains.kotlin.android.dslpreview import com.intellij.openapi.application.PathManager import java.util.jar.JarFile import java.util.zip.ZipEntry import java.io.FileOutputStream import com.intellij.openapi.diagnostic.Logger public class DslWorker(private val myListener: DslWorker.Listener) { private val GSON = Gson() private val START_MARKER = "" + (5.toChar()) + (7.toChar()) + (5.toChar()) private val END_MARKER = START_MARKER + START_MARKER private volatile var myAlive = false private volatile var myPort = 0 private volatile var myLastProcess: Process? = null private val ROBOWRAPPER_LOCK = Object() private val DOWNLOAD_LOCK = Object() private fun downloadRobowrapperDependencies(cmd: RobowrapperContext, deps: List<Dependency>) { val downloadTask = DependencyDownloadTask(cmd, deps) ProgressManager.getInstance().run(downloadTask) } private fun checkRobowrapperDependencies(cmd: RobowrapperContext): Boolean { val tempDirectory = File(RobowrapperDependencies.DEPENDENCIES_DIRECTORY, "tmp/") if (!tempDirectory.exists()) { tempDirectory.mkdirs() } val downloaded = RobowrapperDependencies.DEPENDENCIES.all { it.file.exists() } if (!downloaded) { downloadRobowrapperDependencies(cmd, RobowrapperDependencies.DEPENDENCIES) } return downloaded } public fun finishWorkingProcess() { if (myLastProcess != null) { myLastProcess!!.destroy() } } public fun exec(cmd: RobowrapperContext) { if (!checkRobowrapperDependencies(cmd)) { return } if (myAlive && myPort > 0) { execAlive(cmd) return } val robowrapperDirectory = RobowrapperDependencies.DEPENDENCIES_DIRECTORY.getAbsolutePath() if (robowrapperDirectory.isEmpty()) { myListener.onXmlError(ErrorKind.INVALID_ROBOWRAPPER_DIRECTORY, "Robowrapper directory is empty.", false) return } ProgressManager.getInstance().run(RobowrapperExecTask(cmd)) } private fun execAlive(cmd: RobowrapperContext) { if (myPort <= 0) { myAlive = false exec(cmd) return } ProgressManager.getInstance().run(RobowrapperExecAliveTask(cmd)) } private fun processData(cmd: RobowrapperContext, outputText: String, alive: Boolean) { val processor = DataProcessor(cmd, outputText, alive) ApplicationManager.getApplication().invokeLater(processor) } public interface Listener { public fun onXmlError(kind: ErrorKind, description: String, alive: Boolean) public fun onXmlReceived(cmd: RobowrapperContext, xml: String) } public enum class ErrorKind { INVALID_ROBOWRAPPER_DIRECTORY, UNKNOWN, UNKNOWN_ANDROID_VERSION } private inner class DataProcessor(val cmd: RobowrapperContext, private val outputText: String, private val alive: Boolean) : Runnable { override fun run() { val startMarker = outputText.indexOf(START_MARKER) val endMarker = outputText.indexOf(END_MARKER, startMarker + START_MARKER.length()) if (startMarker < 0 || endMarker < 0 || endMarker <= startMarker) { myAlive = false myListener.onXmlError(ErrorKind.UNKNOWN, "Unable to find message markers.", false) return } val rawData = outputText.substring(startMarker + START_MARKER.length(), endMarker) val pack = GSON.fromJson<dslpreview.Pack>(rawData, javaClass<dslpreview.Pack>()) myPort = pack.port myAlive = pack.alive if (pack.error_code != 0 || pack.xml.isEmpty()) { if (!alive) { myListener.onXmlError(ErrorKind.UNKNOWN, "Unknown error ${pack.error_code}: ${pack.error}", myAlive) } else exec(cmd) } else { debug(pack.xml) myListener.onXmlReceived(cmd, pack.xml) } } } private inner class RobowrapperExecTask(val ctx: RobowrapperContext) : Task.Backgroundable(ctx.androidFacet.getModule().getProject(), "Executing DSL", false) { override fun run(progressIndicator: ProgressIndicator) { progressIndicator.setIndeterminate(true) val pluginJarFile = PathManager.getJarPathForClass(javaClass)!! val pluginDirectory = File(pluginJarFile).getParent() val policyFile = File(RobowrapperDependencies.DEPENDENCIES_DIRECTORY, "custom.policy") synchronized (ROBOWRAPPER_LOCK) { try { if (!policyFile.exists()) { var robowrapperJar: JarFile? = null try { robowrapperJar = JarFile(File(pluginDirectory, "../robowrapper/robowrapper.jar")) robowrapperJar .getInputStream(ZipEntry("custom.policy")) .copyTo(FileOutputStream(policyFile)) } finally { robowrapperJar?.close() } } val builder = ProcessBuilder(ctx.makeArguments()) debug("Robowrapper command-line: " + builder.command().joinToString(" ")) val process = builder.start() myLastProcess = process val text = process.getInputStream().reader("UTF-8").useLines { it.takeWhile { !it.contains(END_MARKER) }.joinToString("\n", postfix = END_MARKER) } processData(ctx, text, false) } catch (e: Exception) { ctx.removeManifest() e.printStackTrace() } } } } private inner class RobowrapperExecAliveTask(private val ctx: RobowrapperContext) : Task.Backgroundable(ctx.androidFacet.getModule().getProject(), "Executing DSL", false) { override fun run(progressIndicator: ProgressIndicator) { progressIndicator.setIndeterminate(true) synchronized (ROBOWRAPPER_LOCK) { try { val context = ZMQ.context(1) val requester = context.socket(ZMQ.REQ) requester.setSendTimeOut(1000) requester.setReceiveTimeOut(20000) requester.connect("tcp://localhost:" + myPort) requester.send(ctx.activityClassName.toByteArray("UTF-8"), 0) val reply = requester.recv(0) val replyString = reply.toString("UTF-8") debug(replyString) processData(ctx, replyString, true) requester.close() context.term() } catch (e: Exception) { e.printStackTrace() ctx.removeManifest() myLastProcess?.destroy() // If alive task failed, launch non-alive version ApplicationManager.getApplication().invokeLater(object : Runnable { override fun run() { myAlive = false exec(ctx) } }) } } } } private inner class DependencyDownloadTask( private val ctx: RobowrapperContext, private val dependencies: List<Dependency> ) : Task.Backgroundable(ctx.androidFacet.getModule().getProject(), "Downloading dependencies", false) { override fun run(progressIndicator: ProgressIndicator) { progressIndicator.setIndeterminate(true) fun reportDownloadError(url: String) { ApplicationManager.getApplication().invokeLater(object : Runnable { override fun run() { myListener.onXmlError(ErrorKind.UNKNOWN, "Failed to download $url", false) } }) } val result = synchronized(DOWNLOAD_LOCK) { dependencies.all { dependency -> try { if (!dependency.file.exists()) { val url = URL(dependency.downloadUrl) Resources.asByteSource(url).copyTo(Files.asByteSink(dependency.file)) } true } catch (e: Exception) { e.printStackTrace() if (dependency.file.exists()) { dependency.file.delete() } reportDownloadError(dependency.downloadUrl) false } } } if (result) { ApplicationManager.getApplication().invokeLater(object : Runnable { override fun run() { exec(ctx) } }) } } } private fun debug(s: String) { if (DEBUG) { println(s) Logger.getInstance(javaClass).debug(s) } } }
apache-2.0
b15d6d71dd79e9c60e250fb27e4b8939
36.368421
139
0.57615
4.941995
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/propertyDetection.kt
1
22419
// 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.j2k import com.intellij.psi.* import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.j2k.ast.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.utils.addIfNotNull import java.util.* class PropertyInfo( val identifier: Identifier, val isVar: Boolean, val psiType: PsiType, val field: PsiField?, val getMethod: PsiMethod?, val setMethod: PsiMethod?, val isGetMethodBodyFieldAccess: Boolean, val isSetMethodBodyFieldAccess: Boolean, val modifiers: Modifiers, val specialSetterAccess: Modifier?, val superInfo: SuperInfo? ) { init { assert(field != null || getMethod != null || setMethod != null) if (isGetMethodBodyFieldAccess) { assert(field != null && getMethod != null) } if (isSetMethodBodyFieldAccess) { assert(field != null && setMethod != null) } } val name: String get() = identifier.name //TODO: what if annotations are not empty? val needExplicitGetter: Boolean get() { if (getMethod != null) { if (getMethod.hasModifierProperty(PsiModifier.NATIVE)) return true if (getMethod.body != null && !isGetMethodBodyFieldAccess) return true } return modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) } //TODO: what if annotations are not empty? val needExplicitSetter: Boolean get() { if (!isVar) return false if (specialSetterAccess != null) return true if (setMethod != null) { if (setMethod.hasModifierProperty(PsiModifier.NATIVE)) return true if (setMethod.body != null && !isSetMethodBodyFieldAccess) return true } return modifiers.contains(Modifier.EXTERNAL) || modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) } companion object { fun fromFieldWithNoAccessors(field: PsiField, converter: Converter): PropertyInfo { val isVar = field.isVar(converter.referenceSearcher) val isInObject = field.containingClass?.let { converter.shouldConvertIntoObject(it) } == true val modifiers = converter.convertModifiers(field, false, isInObject) return PropertyInfo( field.declarationIdentifier(), isVar, field.type, field, getMethod = null, setMethod = null, isGetMethodBodyFieldAccess = false, isSetMethodBodyFieldAccess = false, modifiers = modifiers, specialSetterAccess = null, superInfo = null ) } } } class PropertyDetectionCache(private val converter: Converter) { private val cache = HashMap<PsiClass, Map<PsiMember, PropertyInfo>>() operator fun get(psiClass: PsiClass): Map<PsiMember, PropertyInfo> { cache[psiClass]?.let { return it } assert(converter.inConversionScope(psiClass)) val detected = PropertyDetector(psiClass, converter).detectProperties() cache[psiClass] = detected return detected } } sealed class SuperInfo { class Property( val isVar: Boolean, val name: String, val hasAbstractModifier: Boolean //TODO: add visibility ) : SuperInfo() object Function : SuperInfo() fun isAbstract(): Boolean { return if (this is Property) hasAbstractModifier else false } } private class PropertyDetector( private val psiClass: PsiClass, private val converter: Converter ) { private val isOpenClass = converter.needOpenModifier(psiClass) fun detectProperties(): Map<PsiMember, PropertyInfo> { val propertyInfos = detectPropertyCandidates() val memberToPropertyInfo = buildMemberToPropertyInfoMap(propertyInfos) dropPropertiesWithConflictingAccessors(memberToPropertyInfo) dropPropertiesConflictingWithFields(memberToPropertyInfo) val mappedFields = memberToPropertyInfo.values .mapNotNull { it.field } .toSet() // map all other fields for (field in psiClass.fields) { if (field !in mappedFields) { memberToPropertyInfo[field] = PropertyInfo.fromFieldWithNoAccessors(field, converter) } } return memberToPropertyInfo } private fun detectPropertyCandidates(): List<PropertyInfo> { val methodsToCheck = ArrayList<Pair<PsiMethod, SuperInfo.Property?>>() for (method in psiClass.methods) { val name = method.name if (!name.startsWith("get") && !name.startsWith("set") && !name.startsWith("is")) continue val superInfo = superInfo(method) if (superInfo is SuperInfo.Function) continue methodsToCheck.add(method to (superInfo as SuperInfo.Property?)) } val propertyNamesWithConflict = HashSet<String>() val propertyNameToGetterInfo = detectGetters(methodsToCheck, propertyNamesWithConflict) val propertyNameToSetterInfo = detectSetters(methodsToCheck, propertyNameToGetterInfo.keys, propertyNamesWithConflict) val propertyNames = propertyNameToGetterInfo.keys + propertyNameToSetterInfo.keys val propertyInfos = ArrayList<PropertyInfo>() for (propertyName in propertyNames) { val getterInfo = propertyNameToGetterInfo[propertyName] var setterInfo = propertyNameToSetterInfo[propertyName] // no property without getter except for overrides if (getterInfo == null && setterInfo!!.method.hierarchicalMethodSignature.superSignatures.isEmpty()) continue if (setterInfo != null && getterInfo != null && setterInfo.method.parameterList.parameters.single().type != getterInfo.method.returnType) { setterInfo = null } var field = getterInfo?.field ?: setterInfo?.field if (field != null) { fun PsiReferenceExpression.canBeReplacedWithFieldAccess(): Boolean { if (getterInfo?.method?.isAncestor(this) != true && setterInfo?.method?.isAncestor(this) != true) return false // not inside property return qualifier == null || qualifier is PsiThisExpression //TODO: check it's correct this } if (getterInfo != null && getterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForReading(it) && !it.canBeReplacedWithFieldAccess() } ) { field = null } } else if (setterInfo != null && setterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForWriting(it) && !it.canBeReplacedWithFieldAccess() } ) { field = null } } } //TODO: no body for getter OR setter val isVar = if (setterInfo != null) true else if (getterInfo!!.superProperty != null && getterInfo.superProperty!!.isVar) true else field != null && field.isVar(converter.referenceSearcher) val type = getterInfo?.method?.returnType ?: setterInfo!!.method.parameterList.parameters.single()?.type!! val superProperty = getterInfo?.superProperty ?: setterInfo?.superProperty val isOverride = superProperty != null val modifiers = convertModifiers(field, getterInfo?.method, setterInfo?.method, isOverride) val propertyAccess = modifiers.accessModifier() val setterAccess = if (setterInfo != null) converter.convertModifiers(setterInfo.method, isMethodInOpenClass = false, isInObject = false).accessModifier() else if (field != null && field.isVar(converter.referenceSearcher)) converter.convertModifiers(field, isMethodInOpenClass = false, isInObject = false).accessModifier() else propertyAccess val specialSetterAccess = setterAccess?.takeIf { it != propertyAccess } val propertyInfo = PropertyInfo( Identifier.withNoPrototype(propertyName), isVar, type, field, getterInfo?.method, setterInfo?.method, field != null && getterInfo?.field == field, field != null && setterInfo?.field == field, modifiers, specialSetterAccess, superProperty ) propertyInfos.add(propertyInfo) } return propertyInfos } private fun buildMemberToPropertyInfoMap(propertyInfos: List<PropertyInfo>): MutableMap<PsiMember, PropertyInfo> { val memberToPropertyInfo = HashMap<PsiMember, PropertyInfo>() for (propertyInfo in propertyInfos) { val field = propertyInfo.field if (field != null) { if (memberToPropertyInfo.containsKey(field)) { // field already in use by other property continue } else { memberToPropertyInfo[field] = propertyInfo } } propertyInfo.getMethod?.let { memberToPropertyInfo[it] = propertyInfo } propertyInfo.setMethod?.let { memberToPropertyInfo[it] = propertyInfo } } return memberToPropertyInfo } private fun detectGetters( methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>, propertyNamesWithConflict: MutableSet<String> ): Map<String, AccessorInfo> { val propertyNameToGetterInfo = LinkedHashMap<String, AccessorInfo>() for ((method, superInfo) in methodsToCheck) { val info = getGetterInfo(method, superInfo) ?: continue val prevInfo = propertyNameToGetterInfo[info.propertyName] if (prevInfo != null) { propertyNamesWithConflict.add(info.propertyName) continue } propertyNameToGetterInfo[info.propertyName] = info } return propertyNameToGetterInfo } private fun detectSetters( methodsToCheck: List<Pair<PsiMethod, SuperInfo.Property?>>, propertyNamesFromGetters: Set<String>, propertyNamesWithConflict: MutableSet<String> ): Map<String, AccessorInfo> { val propertyNameToSetterInfo = LinkedHashMap<String, AccessorInfo>() for ((method, superInfo) in methodsToCheck) { val info = getSetterInfo(method, superInfo, propertyNamesFromGetters) ?: continue val prevInfo = propertyNameToSetterInfo[info.propertyName] if (prevInfo != null) { propertyNamesWithConflict.add(info.propertyName) continue } propertyNameToSetterInfo[info.propertyName] = info } return propertyNameToSetterInfo } private fun dropPropertiesWithConflictingAccessors(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) { val propertyInfos = memberToPropertyInfo.values.distinct() val mappedMethods = propertyInfos.mapNotNull { it.getMethod }.toSet() + propertyInfos.mapNotNull { it.setMethod }.toSet() //TODO: bases val prohibitedSignatures = psiClass.methods .filter { it !in mappedMethods } .map { it.getSignature(PsiSubstitutor.EMPTY) } .toSet() for (propertyInfo in propertyInfos) { if (propertyInfo.modifiers.contains(Modifier.OVERRIDE)) continue // cannot drop override //TODO: test this case val getterName = JvmAbi.getterName(propertyInfo.name) val getterSignature = MethodSignatureUtil.createMethodSignature(getterName, emptyArray(), emptyArray(), PsiSubstitutor.EMPTY) if (getterSignature in prohibitedSignatures) { memberToPropertyInfo.dropProperty(propertyInfo) continue } if (propertyInfo.isVar) { val setterName = JvmAbi.setterName(propertyInfo.name) val setterSignature = MethodSignatureUtil.createMethodSignature( setterName, arrayOf(propertyInfo.psiType), emptyArray(), PsiSubstitutor.EMPTY ) if (setterSignature in prohibitedSignatures) { memberToPropertyInfo.dropProperty(propertyInfo) continue } } } } private fun dropPropertiesConflictingWithFields(memberToPropertyInfo: MutableMap<PsiMember, PropertyInfo>) { val fieldsByName = psiClass.fields.associateBy { it.name } //TODO: fields from base fun isPropertyNameInUse(name: String): Boolean { val field = fieldsByName[name] ?: return false return !memberToPropertyInfo.containsKey(field) } var repeatLoop: Boolean do { repeatLoop = false for (propertyInfo in memberToPropertyInfo.values.distinct()) { if (isPropertyNameInUse(propertyInfo.name)) { //TODO: what about overrides in this case? memberToPropertyInfo.dropProperty(propertyInfo) if (propertyInfo.field != null) { repeatLoop = true // need to repeat loop because a new field appeared } } } } while (repeatLoop) } private fun MutableMap<PsiMember, PropertyInfo>.dropProperty(propertyInfo: PropertyInfo) { propertyInfo.field?.let { remove(it) } propertyInfo.getMethod?.let { remove(it) } propertyInfo.setMethod?.let { remove(it) } } private fun convertModifiers(field: PsiField?, getMethod: PsiMethod?, setMethod: PsiMethod?, isOverride: Boolean): Modifiers { val fieldModifiers = field?.let { converter.convertModifiers(it, isMethodInOpenClass = false, isInObject = false) } ?: Modifiers.Empty val getterModifiers = getMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty val setterModifiers = setMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty val modifiers = ArrayList<Modifier>() //TODO: what if one is abstract and another is not? val isGetterAbstract = getMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true val isSetterAbstract = setMethod?.hasModifierProperty(PsiModifier.ABSTRACT) ?: true if (field == null && isGetterAbstract && isSetterAbstract) { modifiers.add(Modifier.ABSTRACT) } if (getterModifiers.contains(Modifier.OPEN) || setterModifiers.contains(Modifier.OPEN)) { modifiers.add(Modifier.OPEN) } if (isOverride) { modifiers.add(Modifier.OVERRIDE) } when { getMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) setMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) else -> modifiers.addIfNotNull(fieldModifiers.accessModifier()) } val prototypes = listOfNotNull<PsiElement>(field, getMethod, setMethod) .map { PrototypeInfo(it, CommentsAndSpacesInheritance.NO_SPACES) } return Modifiers(modifiers).assignPrototypes(*prototypes.toTypedArray()) } private class AccessorInfo( val method: PsiMethod, val field: PsiField?, val kind: AccessorKind, val propertyName: String, val superProperty: SuperInfo.Property? ) private fun getGetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?): AccessorInfo? { val propertyName = propertyNameByGetMethod(method) ?: return null val field = fieldFromGetterBody(method) return AccessorInfo(method, field, AccessorKind.GETTER, propertyName, superProperty) } private fun getSetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?, propertyNamesFromGetters: Set<String>): AccessorInfo? { val allowedPropertyNames = if (superProperty != null) setOf(superProperty.name) else propertyNamesFromGetters val propertyName = propertyNameBySetMethod(method, allowedPropertyNames) ?: return null val field = fieldFromSetterBody(method) return AccessorInfo(method, field, AccessorKind.SETTER, propertyName, superProperty) } private fun superInfo(getOrSetMethod: PsiMethod): SuperInfo? { //TODO: multiple val superMethod = converter.services.superMethodsSearcher.findDeepestSuperMethods(getOrSetMethod).firstOrNull() ?: return null val containingClass = superMethod.containingClass!! return when { converter.inConversionScope(containingClass) -> { val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod] if (propertyInfo != null) { SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) } else { SuperInfo.Function } } superMethod is KtLightMethod -> { val origin = superMethod.kotlinOrigin if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD)) else SuperInfo.Function } else -> { SuperInfo.Function } } } private fun propertyNameByGetMethod(method: PsiMethod): String? { if (method.isConstructor) return null if (method.parameterList.parametersCount != 0) return null val name = method.name if (!Name.isValidIdentifier(name)) return null val propertyName = SyntheticJavaPropertyDescriptor.propertyNameByGetMethodName(Name.identifier(name))?.identifier ?: return null val returnType = method.returnType ?: return null if (returnType.canonicalText == "void") return null if (method.typeParameters.isNotEmpty()) return null return propertyName } private fun propertyNameBySetMethod(method: PsiMethod, allowedNames: Set<String>): String? { if (method.isConstructor) return null if (method.parameterList.parametersCount != 1) return null val name = method.name if (!Name.isValidIdentifier(name)) return null val propertyName1 = SyntheticJavaPropertyDescriptor.propertyNameBySetMethodName(Name.identifier(name), false)?.identifier val propertyName2 = SyntheticJavaPropertyDescriptor.propertyNameBySetMethodName(Name.identifier(name), true)?.identifier val propertyName = if (propertyName1 != null && propertyName1 in allowedNames) propertyName1 else if (propertyName2 != null && propertyName2 in allowedNames) propertyName2 else return null if (method.returnType?.canonicalText != "void") return null if (method.typeParameters.isNotEmpty()) return null return propertyName } private fun fieldFromGetterBody(getter: PsiMethod): PsiField? { val body = getter.body ?: return null val returnStatement = (body.statements.singleOrNull() as? PsiReturnStatement) ?: return null val isStatic = getter.hasModifierProperty(PsiModifier.STATIC) val field = fieldByExpression(returnStatement.returnValue, isStatic) ?: return null if (field.type != getter.returnType) return null if (converter.typeConverter.variableMutability(field) != converter.typeConverter.methodMutability(getter)) return null return field } private fun fieldFromSetterBody(setter: PsiMethod): PsiField? { val body = setter.body ?: return null val statement = (body.statements.singleOrNull() as? PsiExpressionStatement) ?: return null val assignment = statement.expression as? PsiAssignmentExpression ?: return null if (assignment.operationTokenType != JavaTokenType.EQ) return null val isStatic = setter.hasModifierProperty(PsiModifier.STATIC) val field = fieldByExpression(assignment.lExpression, isStatic) ?: return null val parameter = setter.parameterList.parameters.single() if ((assignment.rExpression as? PsiReferenceExpression)?.resolve() != parameter) return null if (field.type != parameter.type) return null return field } private fun fieldByExpression(expression: PsiExpression?, static: Boolean): PsiField? { val refExpr = expression as? PsiReferenceExpression ?: return null if (static) { if (!refExpr.isQualifierEmptyOrClass(psiClass)) return null } else { if (!refExpr.isQualifierEmptyOrThis()) return null } val field = refExpr.resolve() as? PsiField ?: return null if (field.containingClass != psiClass || field.hasModifierProperty(PsiModifier.STATIC) != static) return null return field } }
apache-2.0
a835ab72300f5c44ca93d7dfe76888b9
41.381853
158
0.639993
5.281272
false
false
false
false
siosio/intellij-community
platform/lang-api/src/com/intellij/ide/bookmark/BookmarkType.kt
1
5295
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark import com.intellij.ide.ui.UISettings import com.intellij.lang.LangBundle import com.intellij.openapi.editor.colors.EditorColorsUtil import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.util.registry.Registry import com.intellij.util.ui.RegionPainter import com.intellij.ui.IconWrapperWithToolTip import com.intellij.ui.JBColor import com.intellij.ui.paint.RectanglePainter import com.intellij.util.ui.RegionPaintIcon import java.awt.Component import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.geom.Path2D import javax.swing.Icon enum class BookmarkType(val mnemonic: Char, private val painter: RegionPainter<Component?>) { DIGIT_1('1'), DIGIT_2('2'), DIGIT_3('3'), DIGIT_4('4'), DIGIT_5('5'), DIGIT_6('6'), DIGIT_7('7'), DIGIT_8('8'), DIGIT_9('9'), DIGIT_0('0'), LETTER_A('A'), LETTER_B('B'), LETTER_C('C'), LETTER_D('D'), LETTER_E('E'), LETTER_F('F'), LETTER_G('G'), LETTER_H('H'), LETTER_I('I'), LETTER_J('J'), LETTER_K('K'), LETTER_L('L'), LETTER_M('M'), LETTER_N('N'), LETTER_O('O'), LETTER_P('P'), LETTER_Q('Q'), LETTER_R('R'), LETTER_S('S'), LETTER_T('T'), LETTER_U('U'), LETTER_V('V'), LETTER_W('W'), LETTER_X('X'), LETTER_Y('Y'), LETTER_Z('Z'), DEFAULT(0.toChar(), BookmarkPainter()); constructor(mnemonic: Char) : this(mnemonic, MnemonicPainter(mnemonic.toString())) val icon by lazy { createIcon(16, 1) } val gutterIcon by lazy { createIcon(12, 0) } private fun createIcon(size: Int, insets: Int): Icon = IconWrapperWithToolTip( RegionPaintIcon(size, size, insets, painter).withIconPreScaled(false), LangBundle.messagePointer("tooltip.bookmarked")) companion object { @JvmStatic fun get(mnemonic: Char) = values().firstOrNull { it.mnemonic == mnemonic } ?: DEFAULT } } private val BOOKMARK_ICON_BACKGROUND = EditorColorsUtil.createColorKey("BookmarkIcon.background", JBColor(0xF7C777, 0xAA8542)) private class BookmarkPainter : RegionPainter<Component?> { override fun toString() = "BookmarkIcon" override fun hashCode() = toString().hashCode() override fun equals(other: Any?) = other === this || other is BookmarkPainter override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) { val background = EditorColorsUtil.getColor(c, BOOKMARK_ICON_BACKGROUND) if (background != null) { val xL = width / 6f val xR = width - xL val xC = width / 2f val yT = height / 24f val yB = height - yT val yC = yB + xL - xC val path = Path2D.Float() path.moveTo(x + xL, y + yT) path.lineTo(x + xL, y + yB) path.lineTo(x + xC, y + yC) path.lineTo(x + xR, y + yB) path.lineTo(x + xR, y + yT) path.closePath() g.paint = background g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.fill(path) } } } private val MNEMONIC_ICON_FOREGROUND = EditorColorsUtil.createColorKey("MnemonicIcon.foreground", JBColor(0x000000, 0xBBBBBB)) private val MNEMONIC_ICON_BACKGROUND = EditorColorsUtil.createColorKey("MnemonicIcon.background", JBColor(0xFEF7EC, 0x5B5341)) private val MNEMONIC_ICON_BORDER_COLOR = EditorColorsUtil.createColorKey("MnemonicIcon.borderColor", JBColor(0xF4AF3D, 0xD9A343)) private class MnemonicPainter(val mnemonic: String) : RegionPainter<Component?> { override fun toString() = "MnemonicIcon:$mnemonic" override fun hashCode() = mnemonic.hashCode() override fun equals(other: Any?): Boolean { if (other === this) return true val painter = other as? MnemonicPainter ?: return false return painter.mnemonic == mnemonic } override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) { val foreground = EditorColorsUtil.getColor(c, MNEMONIC_ICON_FOREGROUND) val background = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BACKGROUND) val borderColor = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BORDER_COLOR) val divisor = Registry.intValue("ide.mnemonic.icon.round", 0) val round = if (divisor > 0) width.coerceAtLeast(height) / divisor else null if (background != null) { g.paint = background RectanglePainter.FILL.paint(g, x, y, width, height, round) } if (foreground != null) { g.paint = foreground UISettings.setupAntialiasing(g) val frc = g.fontRenderContext val font = EditorFontType.PLAIN.globalFont val size1 = .8f * height val vector1 = font.deriveFont(size1).createGlyphVector(frc, mnemonic) val bounds1 = vector1.visualBounds val size2 = .8f * size1 * size1 / bounds1.height.toFloat() val vector2 = font.deriveFont(size2).createGlyphVector(frc, mnemonic) val bounds2 = vector2.visualBounds val dx = x - bounds2.x + .5 * (width - bounds2.width) val dy = y - bounds2.y + .5 * (height - bounds2.height) g.drawGlyphVector(vector2, dx.toFloat(), dy.toFloat()) } if (borderColor != null && borderColor != background) { g.paint = borderColor RectanglePainter.DRAW.paint(g, x, y, width, height, round) } } }
apache-2.0
c781073a6f1ca2aad570bb72f1d507e0
39.730769
140
0.691407
3.429404
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtParserDefinition.kt
1
2767
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at import com.demonwav.mcdev.platform.mcp.at.gen.parser.AtParser import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtTypes import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.lang.ParserDefinition import com.intellij.openapi.project.Project import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet class AtParserDefinition : ParserDefinition { override fun createLexer(project: Project) = AtLexerAdapter() override fun getWhitespaceTokens() = WHITE_SPACES override fun getCommentTokens() = COMMENTS override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY override fun createParser(project: Project) = AtParser() override fun getFileNodeType() = FILE override fun createFile(viewProvider: FileViewProvider) = AtFile(viewProvider) override fun createElement(node: ASTNode): PsiElement = AtTypes.Factory.createElement(node) override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode) = map.entries.firstOrNull { e -> left.elementType == e.key.first || right.elementType == e.key.second }?.value ?: ParserDefinition.SpaceRequirements.MUST_NOT companion object { private val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE) private val COMMENTS = TokenSet.create(AtTypes.COMMENT) private val FILE = IFileElementType(Language.findInstance(AtLanguage::class.java)) private val map: Map<Pair<IElementType, IElementType>, ParserDefinition.SpaceRequirements> = mapOf( (AtTypes.KEYWORD to AtTypes.CLASS_NAME) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.CLASS_NAME to AtTypes.FIELD_NAME) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.CLASS_NAME to AtTypes.FUNCTION) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.CLASS_NAME to AtTypes.ASTERISK) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.FIELD_NAME to AtTypes.COMMENT) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.ASTERISK to AtTypes.COMMENT) to ParserDefinition.SpaceRequirements.MUST, (AtTypes.COMMENT to AtTypes.KEYWORD) to ParserDefinition.SpaceRequirements.MUST_LINE_BREAK, (AtTypes.COMMENT to AtTypes.COMMENT) to ParserDefinition.SpaceRequirements.MUST_LINE_BREAK, (AtTypes.FUNCTION to AtTypes.COMMENT) to ParserDefinition.SpaceRequirements.MUST ) } }
mit
493ff677647960761fbd8e8f04029572
45.898305
116
0.756053
4.558484
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/ObjCExport.kt
1
12320
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.objcexport import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.descriptors.getPackageFragments import org.jetbrains.kotlin.backend.konan.descriptors.isInterface import org.jetbrains.kotlin.backend.konan.getExportedDependencies import org.jetbrains.kotlin.backend.konan.llvm.CodeGenerator import org.jetbrains.kotlin.backend.konan.llvm.objcexport.ObjCExportBlockCodeGenerator import org.jetbrains.kotlin.backend.konan.llvm.objcexport.ObjCExportCodeGenerator import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.SourceFile import org.jetbrains.kotlin.ir.util.SymbolTable import org.jetbrains.kotlin.konan.exec.Command import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.konan.file.createTempFile import org.jetbrains.kotlin.konan.target.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.isSubpackageOf internal class ObjCExportedInterface( val generatedClasses: Set<ClassDescriptor>, val categoryMembers: Map<ClassDescriptor, List<CallableMemberDescriptor>>, val topLevel: Map<SourceFile, List<CallableMemberDescriptor>>, val headerLines: List<String>, val namer: ObjCExportNamer, val mapper: ObjCExportMapper ) internal class ObjCExport(val context: Context, symbolTable: SymbolTable) { private val target get() = context.config.target private val exportedInterface = produceInterface() private val codeSpec = exportedInterface?.createCodeSpec(symbolTable) private fun produceInterface(): ObjCExportedInterface? { if (!target.family.isAppleFamily) return null if (!context.config.produce.isFinalBinary) return null // TODO: emit RTTI to the same modules as classes belong to. // Not possible yet, since ObjCExport translates the entire "world" API at once // and can't do this per-module, e.g. due to global name conflict resolution. val produceFramework = context.config.produce == CompilerOutputKind.FRAMEWORK return if (produceFramework) { val mapper = ObjCExportMapper(context.frontendServices.deprecationResolver) val moduleDescriptors = listOf(context.moduleDescriptor) + context.getExportedDependencies() val objcGenerics = context.configuration.getBoolean(KonanConfigKeys.OBJC_GENERICS) val namer = ObjCExportNamerImpl( moduleDescriptors.toSet(), context.moduleDescriptor.builtIns, mapper, context.moduleDescriptor.namePrefix, local = false, objcGenerics = objcGenerics ) val headerGenerator = ObjCExportHeaderGeneratorImpl(context, moduleDescriptors, mapper, namer, objcGenerics) headerGenerator.translateModule() headerGenerator.buildInterface() } else { null } } lateinit var namer: ObjCExportNamer internal fun generate(codegen: CodeGenerator) { if (!target.family.isAppleFamily) return if (context.producedLlvmModuleContainsStdlib) { ObjCExportBlockCodeGenerator(codegen).generate() } if (!context.config.produce.isFinalBinary) return // TODO: emit RTTI to the same modules as classes belong to. val mapper = exportedInterface?.mapper ?: ObjCExportMapper() namer = exportedInterface?.namer ?: ObjCExportNamerImpl( setOf(codegen.context.moduleDescriptor), context.moduleDescriptor.builtIns, mapper, context.moduleDescriptor.namePrefix, local = false ) val objCCodeGenerator = ObjCExportCodeGenerator(codegen, namer, mapper) if (exportedInterface != null) { produceFrameworkSpecific(exportedInterface.headerLines) exportedInterface.generateWorkaroundForSwiftSR10177() } objCCodeGenerator.generate(codeSpec) objCCodeGenerator.dispose() } private fun produceFrameworkSpecific(headerLines: List<String>) { val framework = File(context.config.outputFile) val frameworkContents = when(target.family) { Family.IOS, Family.WATCHOS, Family.TVOS -> framework Family.OSX -> framework.child("Versions/A") else -> error(target) } val headers = frameworkContents.child("Headers") val frameworkName = framework.name.removeSuffix(".framework") val headerName = frameworkName + ".h" val header = headers.child(headerName) headers.mkdirs() header.writeLines(headerLines) val modules = frameworkContents.child("Modules") modules.mkdirs() val moduleMap = """ |framework module $frameworkName { | umbrella header "$headerName" | | export * | module * { export * } |} """.trimMargin() modules.child("module.modulemap").writeBytes(moduleMap.toByteArray()) emitInfoPlist(frameworkContents, frameworkName) if (target.family == Family.OSX) { framework.child("Versions/Current").createAsSymlink("A") for (child in listOf(frameworkName, "Headers", "Modules", "Resources")) { framework.child(child).createAsSymlink("Versions/Current/$child") } } } private fun emitInfoPlist(frameworkContents: File, name: String) { val directory = when (target.family) { Family.IOS, Family.WATCHOS, Family.TVOS -> frameworkContents Family.OSX -> frameworkContents.child("Resources").also { it.mkdirs() } else -> error(target) } val file = directory.child("Info.plist") val pkg = guessMainPackage() // TODO: consider showing warning if it is root. val bundleId = pkg.child(Name.identifier(name)).asString() val platform = when (target) { KonanTarget.IOS_ARM32, KonanTarget.IOS_ARM64 -> "iPhoneOS" KonanTarget.IOS_X64 -> "iPhoneSimulator" KonanTarget.TVOS_ARM64 -> "AppleTVOS" KonanTarget.TVOS_X64 -> "AppleTVSimulator" KonanTarget.MACOS_X64, KonanTarget.MACOS_ARM64 -> "MacOSX" KonanTarget.WATCHOS_ARM32, KonanTarget.WATCHOS_ARM64 -> "WatchOS" KonanTarget.WATCHOS_X86, KonanTarget.WATCHOS_X64 -> "WatchSimulator" else -> error(target) } val properties = context.config.platform.configurables as AppleConfigurables val minimumOsVersion = properties.osVersionMin val contents = StringBuilder() contents.append(""" <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleExecutable</key> <string>$name</string> <key>CFBundleIdentifier</key> <string>$bundleId</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$name</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>$platform</string> </array> <key>CFBundleVersion</key> <string>1</string> """.trimIndent()) fun addUiDeviceFamilies(vararg values: Int) { val xmlValues = values.joinToString(separator = "\n") { " <integer>$it</integer>" } contents.append(""" | <key>MinimumOSVersion</key> | <string>$minimumOsVersion</string> | <key>UIDeviceFamily</key> | <array> |$xmlValues | </array> """.trimMargin()) } // UIDeviceFamily mapping: // 1 - iPhone // 2 - iPad // 3 - AppleTV // 4 - Apple Watch when (target.family) { Family.IOS -> addUiDeviceFamilies(1, 2) Family.TVOS -> addUiDeviceFamilies(3) Family.WATCHOS -> addUiDeviceFamilies(4) else -> {} } if (target == KonanTarget.IOS_ARM64) { contents.append(""" | <key>UIRequiredDeviceCapabilities</key> | <array> | <string>arm64</string> | </array> """.trimMargin() ) } if (target == KonanTarget.IOS_ARM32) { contents.append(""" | <key>UIRequiredDeviceCapabilities</key> | <array> | <string>armv7</string> | </array> """.trimMargin() ) } contents.append(""" </dict> </plist> """.trimIndent()) // TODO: Xcode also add some number of DT* keys. file.writeBytes(contents.toString().toByteArray()) } // See https://bugs.swift.org/browse/SR-10177 private fun ObjCExportedInterface.generateWorkaroundForSwiftSR10177() { // Code for all protocols from the header should get into the binary. // Objective-C protocols ABI is complicated (consider e.g. undocumented extended type encoding), // so the easiest way to achieve this (quickly) is to compile a stub by clang. val protocolsStub = listOf( "__attribute__((used)) static void __workaroundSwiftSR10177() {", buildString { append(" ") generatedClasses.forEach { if (it.isInterface) { val protocolName = namer.getClassOrProtocolName(it).objCName append("@protocol($protocolName); ") } } }, "}" ) val source = createTempFile("protocols", ".m").deleteOnExit() source.writeLines(headerLines + protocolsStub) val bitcode = createTempFile("protocols", ".bc").deleteOnExit() val clangCommand = context.config.clang.clangC( source.absolutePath, "-O2", "-emit-llvm", "-c", "-o", bitcode.absolutePath ) val result = Command(clangCommand).getResult(withErrors = true) if (result.exitCode == 0) { context.llvm.additionalProducedBitcodeFiles += bitcode.absolutePath } else { // Note: ignoring compile errors intentionally. // In this case resulting framework will likely be unusable due to compile errors when importing it. } } private fun guessMainPackage(): FqName { val allPackages = (context.getIncludedLibraryDescriptors() + context.moduleDescriptor).flatMap { it.getPackageFragments() // Includes also all parent packages, e.g. the root one. } val nonEmptyPackages = allPackages .filter { it.getMemberScope().getContributedDescriptors().isNotEmpty() } .map { it.fqName }.distinct() return allPackages.map { it.fqName }.distinct() .filter { candidate -> nonEmptyPackages.all { it.isSubpackageOf(candidate) } } // Now there are all common ancestors of non-empty packages. Longest of them is the least common accessor: .maxByOrNull { it.asString().length }!! } }
apache-2.0
f29541088cb098fcf34e0bb413ae64be
38.111111
120
0.603571
4.852304
false
false
false
false
vovagrechka/fucking-everything
vgrechka-kt/xplatf/src/vgrechka/vgxplatf.kt
1
7782
package vgrechka import vgrechka.fuckaround.* import java.sql.Timestamp import kotlin.properties.Delegates import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty import kotlin.reflect.jvm.isAccessible fun wtf(msg: String = "...WTF didn't you describe this WTF?"): Nothing = throw BreakOnMeException("WTF: $msg") fun die(msg: String = "You've just killed me, motherfucker!"): Nothing = throw BreakOnMeException("Aarrgghh... $msg") fun imf(what: String = "me"): Nothing = throw BreakOnMeException("Implement $what, please, fuck you") fun bitch(msg: String = "Just bitching..."): Nothing = throw BreakOnMeException(msg) fun bitchNoBreak(msg: String = "Just bitching..."): Nothing = throw RuntimeException(msg) var exhaustive: Any? = null fun <T: Any> notNull(): ReadWriteProperty<Any?, T> = Delegates.notNull() class notNullOnce<T: Any>(val noisy: Boolean = false) : ReadWriteProperty<Any?, T> { val __tests by lazy {listOf(FuckAround_notNullOnce_1)} var _value: T? = null var assignmentStack by notNull<StackCaptureException>() override fun getValue(thisRef: Any?, property: KProperty<*>): T { val descr = debugPropertyDescription(thisRef, property) return _value ?: throw BreakOnMeException("Property $descr should be initialized before get.") } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { val descr = debugPropertyDescription(thisRef, property) check(this._value == null) { clog("\n********** Previous assignment **********\n") clog(assignmentStack.stackTraceString) "Property $descr should be assigned only once" } this._value = value assignmentStack = StackCaptureException() if (noisy) { (thisRef as? WithDebugId)?.let { clog("===== $descr = $value") } } } private fun debugPropertyDescription(thisRef: Any?, property: KProperty<*>): String { val withDebugId = thisRef as? WithDebugId return when { withDebugId == null -> "`${property.name}`" else -> "${withDebugId.debugId}.${property.name}" } } companion object } class maybeNullOnce<T: Any> : ReadWriteProperty<Any?, T?> { // TODO:vgrechka Unify with notNullOnce var assigned = false var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T? { if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.") return _value } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { check(!assigned) {"Property `${property.name}` should be assigned only once"} this.assigned = true this._value = value } } class maybeNull<T: Any> : ReadWriteProperty<Any?, T?> { var assigned = false var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T? { if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.") return _value } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { this.assigned = true this._value = value } } class StackCaptureException(message: String = "Capturing freaking stack") : Exception(message) interface WithDebugId { val debugId: String class Impl(host: Any) : WithDebugId { override val debugId = Debug.nextDebugId(host) } } fun <T> l(vararg elements: T): List<T> = listOf(*elements) fun <T> l(block: (MutableList<T>) -> Unit): List<T> = mutableListOf<T>().also(block) inline fun <reified T> a(vararg elements: T): Array<T> = arrayOf(*elements) fun clamp(x: Int, min: Int, max: Int) = when { x < min -> min x > max -> max else -> x } fun clamp(x: Double, min: Double, max: Double) = when { x < min -> min x > max -> max else -> x } class place<T> : ReadWriteProperty<Any?, T> { var assigned = false var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.") return _value as T } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.assigned = true this._value = value } companion object { fun <T> isAssigned(prop: KMutableProperty0<T>): Boolean { prop.isAccessible = true return (prop.getDelegate() as place<*>).assigned } } } class once<T> : ReadWriteProperty<Any?, T> { var assigned = false var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.") return _value as T } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { check(!assigned) {"Property `${property.name}` should be assigned only once"} this.assigned = true this._value = value } } fun <T> named(make: (ident: String) -> T) = object : ReadOnlyProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (value == null) value = make(property.name) return bang(value) } } fun myName() = named {it} fun slashMyName() = named {"/" + it} fun StringBuilder.ln(x: Any? = "") { append(x) append("\n") } fun String.indexOfOrNull(needle: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int? { val index = indexOf(needle, startIndex, ignoreCase) return if (index >= 0) index else null } fun CharSequence.lastIndexOfOrNull(string: String, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int? { val res = this.lastIndexOf(string, startIndex, ignoreCase) return when (res) { -1 -> null else -> res } } fun String.indexOfOrBitch(needle: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int = this.indexOfOrNull(needle, startIndex, ignoreCase) ?: bitchNeedleNotFound(needle, this) fun String.lastIndexOfOrBitch(needle: String, startIndex: Int = this.lastIndex, ignoreCase: Boolean = false): Int = this.lastIndexOfOrNull(needle, startIndex, ignoreCase) ?: bitchNeedleNotFound(needle, this) private fun bitchNeedleNotFound(needle: String, haystack: String): Nothing { bitch("I want needle `$needle` in haystack `$haystack`") } inline fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? { val index = this.indexOfFirst(predicate) return when (index) { -1 -> null else -> index } } fun <T> bang(x: T?): T { if (x == null) bitch("Banging on freaking null") return x } fun <T> List<T>.indexOfOrNull(element: T): Int? { val index = this.indexOf(element) return when (index) { -1 -> null else -> index } } fun stringBuild(block: (StringBuilder) -> Unit) = StringBuilder().also(block).toString() fun String.camelToKebab() = stringBuild { for (c in this) { it += when { c == c.toUpperCase() -> "-${c.toLowerCase()}" else -> c } } } operator fun StringBuilder.plusAssign(x: Any?) { this.append(x) } interface Dancer<out T> { fun dance(): T operator fun not(): T = dance() } abstract class DancerBase<out T> : Dancer<T> { override fun toString(): String = bitch("You probably forgot to use ! operator with dancer") } fun <T> dance(x: Dancer<T>) = x.dance()
apache-2.0
da70d65bb8b222f00615ab5f27de32f1
28.477273
117
0.63724
3.926337
false
false
false
false
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/KnownRepositories.kt
2
2275
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration internal sealed class KnownRepositories( open val repositories: List<RepositoryModel> ) : Collection<RepositoryModel> by repositories { fun containsAnyId(ids: Iterable<String>) = ids.any { repoId -> containsId(repoId) } fun containsId(id: String) = findById(id) != null fun findById(id: String) = find { repo -> repo.id == id } fun excludingById(repoIdsToExclude: Iterable<String>) = filter { repo -> repoIdsToExclude.contains(repo.id) } data class All(override val repositories: List<RepositoryModel>) : KnownRepositories(repositories) { fun filterOnlyThoseUsedIn(targetModules: TargetModules) = InTargetModules( repositories.filter { repo -> if (repo.usageInfo.isEmpty()) return@filter false repo.usageInfo.any { usageInfo -> targetModules.modules.map { it.projectModule } .contains(usageInfo.projectModule) } }, this) companion object { val EMPTY = All(emptyList()) } } data class InTargetModules( override val repositories: List<RepositoryModel>, val allKnownRepositories: All ) : KnownRepositories(repositories) { fun repositoryToAddWhenInstallingOrUpgrading( project: Project, packageModel: PackageModel, selectedVersion: PackageVersion ): RepositoryModel? { if (!PackageSearchGeneralConfiguration.getInstance(project).autoAddMissingRepositories) return null val versionRepositoryIds = packageModel.remoteInfo?.versions ?.find { it.version == selectedVersion.versionName } ?.repositoryIds ?: return null if (containsAnyId(versionRepositoryIds)) return null return versionRepositoryIds.map { repoId -> allKnownRepositories.findById(repoId) } .firstOrNull() } companion object { val EMPTY = InTargetModules(emptyList(), All.EMPTY) } } }
apache-2.0
83cee1f8f163c6861abcc132803be8c0
34.546875
111
0.656703
5.340376
false
false
false
false
janishar/Tutorials
tinder-swipe-kotlin/app/src/main/java/tinderswipe/swipe/mindorks/demo/MainActivity.kt
1
2473
package tinderswipe.swipe.mindorks.demo import android.graphics.Point import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Gravity import android.widget.Toast import com.mindorks.placeholderview.SwipeDecor import kotlinx.android.synthetic.main.activity_main.* import kotlin.tinderswipe.swipe.mindorks.demo.R class MainActivity : AppCompatActivity(), TinderCard.Callback { companion object { val TAG = "MainActivity" } private val animationDuration = 300 private var isToUndo = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val bottomMargin = Utils.dpToPx(160) val windowSize = Utils.getDisplaySize(windowManager) swipeView!!.builder .setDisplayViewCount(3) .setIsUndoEnabled(true) .setSwipeVerticalThreshold(Utils.dpToPx(50)) .setSwipeHorizontalThreshold(Utils.dpToPx(50)) .setHeightSwipeDistFactor(10f) .setWidthSwipeDistFactor(5f) .setSwipeDecor(SwipeDecor() .setViewWidth(windowSize.x) .setViewHeight(windowSize.y - bottomMargin) .setViewGravity(Gravity.TOP) .setPaddingTop(20) .setSwipeAnimTime(animationDuration) .setRelativeScale(0.01f) .setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view) .setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view)) val cardViewHolderSize = Point(windowSize.x, windowSize.y - bottomMargin) for (profile in Utils.loadProfiles(applicationContext)) { swipeView!!.addView(TinderCard(applicationContext, profile, cardViewHolderSize, this)) } rejectBtn.setOnClickListener({ swipeView!!.doSwipe(false) }) acceptBtn.setOnClickListener({ swipeView!!.doSwipe(true) }) undoBtn.setOnClickListener({ swipeView!!.undoLastSwipe() }) swipeView!!.addItemRemoveListener { if (isToUndo) { isToUndo = false swipeView!!.undoLastSwipe() } } } override fun onSwipeUp() { Toast.makeText(this, "SUPER LIKE! Show any dialog here.", Toast.LENGTH_SHORT).show() isToUndo = true } }
apache-2.0
eca179f1420f156a8024269734f93744
34.328571
98
0.634452
4.639775
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/TypeMismatchFactories.kt
3
3004
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.fixes import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.fir.api.fixes.diagnosticFixFactory import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability import org.jetbrains.kotlin.idea.quickfix.AddExclExclCallFix import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs object TypeMismatchFactories { val argumentTypeMismatchFactory = diagnosticFixFactory(KtFirDiagnostic.ArgumentTypeMismatch::class) { diagnostic -> getFixesForTypeMismatch(diagnostic.psi, diagnostic.expectedType, diagnostic.actualType) } val returnTypeMismatchFactory = diagnosticFixFactory(KtFirDiagnostic.ReturnTypeMismatch::class) { diagnostic -> getFixesForTypeMismatch(diagnostic.psi, diagnostic.expectedType, diagnostic.actualType) } val assignmentTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.AssignmentTypeMismatch::class) { diagnostic -> getFixesForTypeMismatch(diagnostic.psi, diagnostic.expectedType, diagnostic.actualType) } val initializerTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.InitializerTypeMismatch::class) { diagnostic -> diagnostic.psi.initializer?.let { getFixesForTypeMismatch(it, diagnostic.expectedType, diagnostic.actualType) } ?: emptyList() } val smartcastImpossibleFactory = diagnosticFixFactory(KtFirDiagnostic.SmartcastImpossible::class) { diagnostic -> val psi = diagnostic.psi val actualType = psi.getKtType() ?: return@diagnosticFixFactory emptyList() getFixesForTypeMismatch(psi, expectedType = diagnostic.desiredType, actualType = actualType) } private fun KtAnalysisSession.getFixesForTypeMismatch( psi: PsiElement, expectedType: KtType, actualType: KtType ): List<AddExclExclCallFix> { // TODO: Add more fixes than just AddExclExclCallFix when available. if (!expectedType.canBeNull && actualType.canBeNull) { // We don't want to offer AddExclExclCallFix if we know the expression is definitely null, e.g.: // // if (nullableInt == null) { // val x: Int = nullableInt // No AddExclExclCallFix here // } if (psi.safeAs<KtExpression>()?.isDefinitelyNull() == true) { return emptyList() } val nullableExpectedType = expectedType.withNullability(KtTypeNullability.NULLABLE) if (actualType isSubTypeOf nullableExpectedType) { return listOfNotNull(psi.asAddExclExclCallFix()) } } return emptyList() } }
apache-2.0
2583485b7c86166777c2c9ddd7757983
49.066667
158
0.734354
5.108844
false
false
false
false
androidx/androidx
room/room-compiler/src/test/test-data/kotlinCodeGen/abstractClassWithParam.kt
3
1610
import android.database.Cursor import androidx.room.RoomDatabase import androidx.room.RoomSQLiteQuery import androidx.room.RoomSQLiteQuery.Companion.acquire import androidx.room.util.getColumnIndexOrThrow import androidx.room.util.query import java.lang.Class import javax.`annotation`.processing.Generated import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.collections.List import kotlin.jvm.JvmStatic @Generated(value = ["androidx.room.RoomProcessor"]) @Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"]) public class MyDao_Impl( __db: RoomDatabase, ) : MyDao(__db) { private val __db: RoomDatabase init { this.__db = __db } public override fun getEntity(): MyEntity { val _sql: String = "SELECT * FROM MyEntity" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, false, null) try { val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk") val _result: MyEntity if (_cursor.moveToFirst()) { val _tmpPk: Int _tmpPk = _cursor.getInt(_cursorIndexOfPk) _result = MyEntity(_tmpPk) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } public companion object { @JvmStatic public fun getRequiredConverters(): List<Class<*>> = emptyList() } }
apache-2.0
213e60fb44c948109a4700b4f9bc6572
30.588235
76
0.632919
4.548023
false
false
false
false
aksiksi/workshop-jb
src/i_introduction/_7_Data_Classes/DataClasses.kt
3
1601
package i_introduction._7_Data_Classes import util.TODO class Person1(val name: String, val age: Int) // No 'new' keyword necessary fun create() = Person1("Alice", 29) fun useFromJava() { // property 'val name' = backing field + getter // => from Java you access it through 'getName()' JavaCode7().useKotlinClass(Person1("Bob", 31)) // property 'var mutable' = backing field + getter + setter } // This is the same as the following (getters are generated by default): class Person2(_name: String, _age: Int) { //_name, _age are constructor parameters val name: String = _name //property initialization is part of the constructor get(): String { return $name // You can access the backing field of property with '$' + property name } val age: Int = _age get(): Int { return $age } } // If you add a 'data' annotation to your class, some additional methods will be generated for you. // These include 'equals', 'hashCode', and 'toString'. data class Person3(val name: String, val age: Int) // This class is as good as Person4 (written in Java), but is 42 lines shorter. =) fun todoTask7() = TODO( """ There is no task for you here. Just make sure you're not forgetting to carefully read all code examples and comments and ask questions if you have any. =) Then return 'true' from 'task7'. More information about classes in Kotlin can be found in the syntax/classesObjectsInterfaces.kt file. """, references = { JavaCode7.Person4("???", -1) } ) fun task7(): Boolean = todoTask7()
mit
83e3beee4f6df78e42c2b02b6058b888
32.354167
109
0.662711
3.953086
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/database/helpers/migration/V156_RecipientUnregisteredTimestampMigration.kt
1
1255
package org.thoughtcrime.securesms.database.helpers.migration import android.app.Application import net.zetetic.database.sqlcipher.SQLiteDatabase import org.signal.core.util.update import java.util.concurrent.TimeUnit /** * Adds an 'unregistered timestamp' on a recipient to keep track of when they became unregistered. * Also updates all currently-unregistered users to have an unregistered time of "now". */ object V156_RecipientUnregisteredTimestampMigration : SignalDatabaseMigration { const val UNREGISTERED = 2 const val GROUP_NONE = 0 override fun migrate(context: Application, db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("ALTER TABLE recipient ADD COLUMN unregistered_timestamp INTEGER DEFAULT 0") // We currently delete from storage service after 30 days, so initialize time to 31 days ago. // Unregistered users won't have a storageId to begin with, so it won't affect much -- just want all unregistered users to have a timestamp populated. val expiredTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(31) db.update("recipient") .values("unregistered_timestamp" to expiredTime) .where("registered = ? AND group_type = ?", UNREGISTERED, GROUP_NONE) .run() } }
gpl-3.0
80a914d567241000a8674a40dbaa9b45
43.821429
154
0.761753
4.419014
false
false
false
false
androidx/androidx
fragment/fragment-ktx/src/androidTest/java/androidx/fragment/app/FragmentTest.kt
3
2417
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app import android.os.Bundle import androidx.core.os.bundleOf import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.testutils.withActivity import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class FragmentTest { @Test fun setFragmentResult() { with(ActivityScenario.launch(TestActivity::class.java)) { val fragment1 = ResultFragment() val fm = withActivity { supportFragmentManager } withActivity { fm.commitNow { add(fragment1, null) } } val expectedResult = "resultGood" val fragment2 = SetResultFragment(expectedResult) withActivity { fm.commitNow { add(fragment2, null) } } assertWithMessage("The result is incorrect") .that(fragment1.actualResult) .isEqualTo(expectedResult) } } class ResultFragment : Fragment() { var actualResult: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setFragmentResultListener("requestKey") { _, bundle -> actualResult = bundle.getString("bundleKey") } } } class SetResultFragment(val resultString: String) : Fragment() { override fun onStart() { super.onStart() setFragmentResult("requestKey", bundleOf("bundleKey" to resultString)) } } }
apache-2.0
ba84dd145fc4ada9fe8e2a57bbafb271
28.839506
82
0.637981
4.963039
false
true
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/JButtonAction.kt
2
2499
// 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.util.ui import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.NlsActions.ActionDescription import com.intellij.openapi.util.NlsActions.ActionText import javax.swing.Icon import javax.swing.JButton import javax.swing.JComponent abstract class JButtonAction(text: @ActionText String?, @ActionDescription description: String? = null, icon: Icon? = null) : DumbAwareAction(text, description, icon), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String): JComponent { val button = createButton() button.isOpaque = false button.addActionListener { performAction(button, place, presentation) } button.text = presentation.getText(true) return button } protected fun performAction(component: JComponent, place: String, presentation: Presentation) { val dataContext = ActionToolbar.getDataContextFor(component) val event = AnActionEvent.createFromInputEvent(null, place, presentation, dataContext) if (ActionUtil.lastUpdateAndCheckDumb(this, event, true)) { ActionUtil.performActionDumbAwareWithCallbacks(this, event) } } protected open fun createButton(): JButton = JButton().configureForToolbar() private fun JButton.configureForToolbar(): JButton = apply { isFocusable = false font = JBUI.Fonts.toolbarFont() putClientProperty("ActionToolbar.smallVariant", true) } override fun updateCustomComponent(component: JComponent, presentation: Presentation) { if (component is JButton) { updateButtonFromPresentation(component, presentation) } } protected open fun updateButtonFromPresentation(button: JButton, presentation: Presentation) { button.isEnabled = presentation.isEnabled button.isVisible = presentation.isVisible button.text = presentation.getText(true) button.icon = presentation.icon button.mnemonic = presentation.mnemonic button.displayedMnemonicIndex = presentation.displayedMnemonicIndex button.toolTipText = presentation.description } }
apache-2.0
32aa3230030753db0d238a3a82e7bf94
38.68254
123
0.781513
5.028169
false
false
false
false
howard-e/just-quotes-kt
app/src/main/java/com/heed/justquotes/adapters/QuoteRecyclerAdapter.kt
1
2088
package com.heed.justquotes.adapters import android.content.Context import android.graphics.Color import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.heed.justquotes.R import com.heed.justquotes.models.Quote import kotlinx.android.synthetic.main.item_quote.view.* import java.util.* /** * @author Howard. */ class QuoteRecyclerAdapter(private val context: Context, private val quotes: List<Any>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when (viewType) { _itemQuote -> return QuoteViewHolder(LayoutInflater.from(context).inflate(R.layout.item_quote, parent, false)) } return QuoteViewHolder(LayoutInflater.from(context).inflate(R.layout.item_quote, parent, false)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val itemType = getItemViewType(position) if (itemType == _itemQuote) { val mHolder = holder as QuoteViewHolder mHolder.bind(context, quotes[position] as Quote) } } override fun getItemCount(): Int { return quotes.size } override fun getItemViewType(position: Int): Int { if (quotes[position] is Quote) return _itemQuote return super.getItemViewType(position) } class QuoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(context: Context, quote: Quote) { val rnd = Random() val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)) itemView.container.setBackgroundColor(color) itemView.quote.text = (quote.quote) itemView.author.text = context.getString(R.string.string_hyphen_prepend, quote.author) } } companion object { private val _tag = QuoteRecyclerAdapter::class.java.simpleName private val _itemQuote = 100 } }
apache-2.0
943c3ce891642128d6c1b2a04733dc97
32.677419
139
0.689655
4.33195
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt
1
10871
// 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.inspections import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = binaryExpressionVisitor(fun(binaryExpression) { if (binaryExpression.right == null) return val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return if (operationToken !in targetOperations) return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return if (!property.isVar) return val context = binaryExpression.analyze() val leftType = left.getType(context) ?: return val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return val fixes = mutableListOf<LocalQuickFix>() if (ChangeTypeToMutableFix.isApplicable(property)) { fixes.add(ChangeTypeToMutableFix(leftType)) } if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) { fixes.add(ReplaceWithFilterFix()) } when { ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix()) JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken)) } if (fixes.isEmpty()) return val typeText = leftDefaultType.toString().takeWhile { it != '<' }.lowercase() val operationReference = binaryExpression.operationReference holder.registerProblem( operationReference, KotlinBundle.message("0.on.a.readonly.1.creates.a.new.1.under.the.hood", operationReference.text, typeText), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixes.toTypedArray() ) }) private class ChangeTypeToMutableFix(@SafeFieldForPreview private val type: KotlinType) : LocalQuickFix { override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return ChangeToMutableCollectionFix.applyFix(property, type) property.valOrVarKeyword.replace(KtPsiFactory(property).createValKeyword()) binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset) } companion object { fun isApplicable(property: KtProperty): Boolean { return ChangeToMutableCollectionFix.isApplicable(property) } } } private class ReplaceWithFilterFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.filter.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val psiFactory = KtPsiFactory(operationReference) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right)) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false if (leftType == binaryExpression.builtIns.map.defaultType) return false return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true } } } private class ReplaceWithAssignmentFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val psiFactory = KtPsiFactory(operationReference) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) } companion object { val emptyCollectionFactoryMethods = listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" } fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false if (!property.isLocal) return false val initializer = property.initializer as? KtCallExpression ?: return false if (initializer.valueArguments.isNotEmpty()) return false val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString() if (fqName !in emptyCollectionFactoryMethods) return false val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false if (binaryExpression.siblings(forward = false, withItself = false) .filter { it != property } .any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } } ) return false return true } } } private class JoinWithInitializerFix(@SafeFieldForPreview private val op: KtSingleValueToken) : LocalQuickFix { override fun getName() = KotlinBundle.message("join.with.initializer.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return val initializer = property.initializer ?: return val psiFactory = KtPsiFactory(operationReference) val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right)) binaryExpression.delete() property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean { if (!property.isLocal || property.initializer == null) return false return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property } } } } private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ) private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean { val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType) }
apache-2.0
2b8a139232bf0e511dc1e42c004c37f3
53.36
158
0.715482
5.810262
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/PortableCompilationCache.kt
1
11088
// 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.intellij.build.impl.compilation import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.NioFiles import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.CompilationTasks import org.jetbrains.intellij.build.impl.JpsCompilationRunner import org.jetbrains.intellij.build.impl.compilation.cache.CommitsHistory import org.jetbrains.jps.incremental.storage.ProjectStamps import java.nio.file.Files import java.nio.file.Path class PortableCompilationCache(private val context: CompilationContext) { companion object { @JvmStatic val IS_ENABLED = ProjectStamps.PORTABLE_CACHES && IS_CONFIGURED private var isAlreadyUpdated = false } init { require(IS_ENABLED) { "JPS Caches are expected to be enabled" } } private val git = Git(context.paths.projectHome) /** * JPS data structures allowing incremental compilation for [CompilationOutput] */ private class JpsCaches(context: CompilationContext) { val skipDownload = bool(SKIP_DOWNLOAD_PROPERTY) val skipUpload = bool(SKIP_UPLOAD_PROPERTY) val dir: Path by lazy { context.compilationData.dataStorageRoot } val maybeAvailableLocally: Boolean by lazy { val files = dir.toFile().list() context.messages.info("$dir: ${files.joinToString()}") Files.isDirectory(dir) && files != null && files.isNotEmpty() } } /** * Server which stores [PortableCompilationCache] */ private class RemoteCache(context: CompilationContext) { val url by lazy { require(URL_PROPERTY, "Remote Cache url", context) } val uploadUrl by lazy { require(UPLOAD_URL_PROPERTY, "Remote Cache upload url", context) } } private val forceDownload = bool(FORCE_DOWNLOAD_PROPERTY) private val forceRebuild = bool(FORCE_REBUILD_PROPERTY) private val remoteCache = RemoteCache(context) private val jpsCaches by lazy { JpsCaches(context) } private val remoteGitUrl by lazy { val result = require(GIT_REPOSITORY_URL_PROPERTY, "Repository url", context) context.messages.info("Git remote url $result") result } private val downloader by lazy { val availableForHeadCommit = bool(AVAILABLE_FOR_HEAD_PROPERTY) PortableCompilationCacheDownloader(context, git, remoteCache.url, remoteGitUrl, availableForHeadCommit, jpsCaches.skipDownload) } private val uploader by lazy { val s3Folder = require(AWS_SYNC_FOLDER_PROPERTY, "AWS S3 sync folder", context) val commitHash = require(COMMIT_HASH_PROPERTY, "Repository commit", context) PortableCompilationCacheUploader(context, remoteCache.uploadUrl, remoteGitUrl, commitHash, s3Folder, jpsCaches.skipUpload, forceRebuild) } /** * Download the latest available [PortableCompilationCache], * [org.jetbrains.intellij.build.CompilationTasks.resolveProjectDependencies] * and perform incremental compilation if necessary. * * When force rebuilding incremental compilation flag has to be set to false otherwise backward-refs won't be created. * During rebuild JPS checks condition [org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.exists] || [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.isRebuildInAllJavaModules] * and if incremental compilation is enabled JPS won't create [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter]. * For more details see [org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize] */ fun downloadCacheAndCompileProject() { synchronized(PortableCompilationCache) { if (isAlreadyUpdated) { context.messages.info("PortableCompilationCache is already updated") return } if (forceRebuild || forceDownload) { clean() } if (!forceRebuild && !isLocalCacheUsed()) { downloadCache() } CompilationTasks.create(context).resolveProjectDependencies() if (isCompilationRequired()) { context.options.incrementalCompilation = !forceRebuild context.messages.block("Compiling project") { compileProject(context) } } isAlreadyUpdated = true context.options.incrementalCompilation = true } } private fun isCompilationRequired() = forceRebuild || isLocalCacheUsed() || isRemoteCacheStale() private fun isLocalCacheUsed() = !forceRebuild && !forceDownload && jpsCaches.maybeAvailableLocally private fun isRemoteCacheStale() = !downloader.availableForHeadCommit /** * Upload local [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun upload() { if (!forceRebuild && downloader.availableForHeadCommit) { context.messages.info("Nothing new to upload") } else { uploader.upload(context.messages) } val metadataFile = context.paths.artifactDir.resolve(COMPILATION_CACHE_METADATA_JSON) Files.createDirectories(metadataFile.parent) Files.writeString(metadataFile, "This is stub file required only for TeamCity artifact dependency. " + "Compiled classes will be resolved via ${remoteCache.url}") context.messages.artifactBuilt("$metadataFile") } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] */ fun publish() { uploader.updateCommitHistory() } /** * Publish already uploaded [PortableCompilationCache] to [PortableCompilationCache.RemoteCache] overriding existing [CommitsHistory]. * Used in force rebuild and cleanup. */ fun overrideCommitHistory(forceRebuiltCommits: Set<String>) { uploader.updateCommitHistory(CommitsHistory(mapOf(remoteGitUrl to forceRebuiltCommits)), true) } private fun clean() { for (it in listOf(jpsCaches.dir, context.classesOutputDirectory)) { context.messages.info("Cleaning $it") NioFiles.deleteRecursively(it) } } private fun compileProject(context: CompilationContext) { // fail-fast in case of KTIJ-17296 if (SystemInfoRt.isWindows && git.lineBreaksConfig() != "input") { context.messages.error("PortableCompilationCache cannot be used with CRLF line breaks, " + "please execute `git config --global core.autocrlf input` before checkout " + "and upvote https://youtrack.jetbrains.com/issue/KTIJ-17296") } context.compilationData.statisticsReported = false val jps = JpsCompilationRunner(context) try { jps.buildAll() } catch (e: Exception) { if (!context.options.incrementalCompilation) { throw e } val successMessage: String if (forceDownload) { context.messages.warning("Incremental compilation using Remote Cache failed. Re-trying without any caches.") clean() context.options.incrementalCompilation = false successMessage = "Compilation successful after clean build retry" } else { // Portable Compilation Cache is rebuilt from scratch on CI and re-published every night to avoid possible incremental compilation issues. // If download isn't forced then locally available cache will be used which may suffer from those issues. // Hence, compilation failure. Replacing local cache with remote one may help. context.messages.warning("Incremental compilation using locally available caches failed. Re-trying using Remote Cache.") downloadCache() successMessage = "Compilation successful after retry with fresh Remote Cache" } context.compilationData.reset() jps.buildAll() context.messages.info(successMessage) println("##teamcity[buildStatus status='SUCCESS' text='$successMessage']") context.messages.reportStatisticValue("Incremental compilation failures", "1") } } private fun downloadCache() { context.messages.block("Downloading Portable Compilation Cache") { downloader.download() } } } /** * [PortableCompilationCache.JpsCaches] archive upload may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_UPLOAD_PROPERTY = "intellij.jps.remote.cache.uploadCompilationOutputsOnly" /** * [PortableCompilationCache.JpsCaches] archive download may be skipped if only [CompilationOutput]s are required * without any incremental compilation (for tests execution as an example) */ private const val SKIP_DOWNLOAD_PROPERTY = "intellij.jps.remote.cache.downloadCompilationOutputsOnly" /** * URL for read/write operations */ private const val UPLOAD_URL_PROPERTY = "intellij.jps.remote.cache.upload.url" /** * URL for read-only operations */ private const val URL_PROPERTY = "intellij.jps.remote.cache.url" /** * If true then [PortableCompilationCache.RemoteCache] is configured to be used */ private val IS_CONFIGURED = !System.getProperty(URL_PROPERTY).isNullOrBlank() /** * IntelliJ repository git remote url */ private const val GIT_REPOSITORY_URL_PROPERTY = "intellij.remote.url" /** * If true then [PortableCompilationCache] for head commit is expected to exist and search in [CommitsHistory.JSON_FILE] is skipped. * Required for temporary branch caches which are uploaded but not published in [CommitsHistory.JSON_FILE]. */ private const val AVAILABLE_FOR_HEAD_PROPERTY = "intellij.jps.cache.availableForHeadCommit" /** * Download [PortableCompilationCache] even if there are caches available locally */ private const val FORCE_DOWNLOAD_PROPERTY = "intellij.jps.cache.download.force" /** * If true then [PortableCompilationCache] will be rebuilt from scratch */ private const val FORCE_REBUILD_PROPERTY = "intellij.jps.cache.rebuild.force" /** * Folder to store [PortableCompilationCache] for later upload to AWS S3 bucket. * Upload performed in a separate process on CI. */ private const val AWS_SYNC_FOLDER_PROPERTY = "jps.caches.aws.sync.folder" /** * Commit hash for which [PortableCompilationCache] is to be built/downloaded */ private const val COMMIT_HASH_PROPERTY = "build.vcs.number" private fun require(systemProperty: String, description: String, context: CompilationContext): String { val value = System.getProperty(systemProperty) if (value.isNullOrBlank()) { context.messages.error("$description is not defined. Please set '$systemProperty' system property.") } return value } private fun bool(systemProperty: String): Boolean { return System.getProperty(systemProperty).toBoolean() } /** * Compiled bytecode of project module, cannot be used for incremental compilation without [PortableCompilationCache.JpsCaches] */ internal class CompilationOutput( name: String, type: String, @JvmField val hash: String, // Some hash of compilation output, could be non-unique across different CompilationOutput's @JvmField val path: String, // Local path to compilation output ) { val remotePath = "$type/$name/$hash" }
apache-2.0
d27c40dde7c5b0e06536b5d98af16351
38.741935
204
0.736923
4.465566
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutinesUtils.kt
2
15596
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.util import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.openapi.application.EDT import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.impl.ProgressManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import com.intellij.psi.PsiFile import com.intellij.util.flow.throttle import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncModuleTransformer import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleChangesSignalProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.produce import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.scan import kotlinx.coroutines.flow.toList import kotlinx.coroutines.future.await import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.select import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.jetbrains.annotations.Nls import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext import kotlin.time.Duration import kotlin.time.TimedValue import kotlin.time.measureTimedValue internal fun <T> Flow<T>.onEach(context: CoroutineContext, action: suspend (T) -> Unit) = onEach { withContext(context) { action(it) } } internal fun <T, R> Flow<T>.map(context: CoroutineContext, action: suspend (T) -> R) = map { withContext(context) { action(it) } } internal fun <T> Flow<T>.replayOnSignals(vararg signals: Flow<Any>) = channelFlow { var lastValue: T? = null onEach { send(it) } .onEach { lastValue = it } .launchIn(this) merge(*signals) .onEach { lastValue?.let { send(it) } } .launchIn(this) } suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend CoroutineScope.(T) -> R) = coroutineScope { map { async { transform(it) } }.awaitAll() } internal suspend fun <T> Iterable<T>.parallelFilterNot(transform: suspend (T) -> Boolean) = channelFlow { parallelForEach { if (!transform(it)) send(it) } }.toList() internal suspend fun <T, R> Iterable<T>.parallelMapNotNull(transform: suspend (T) -> R?) = channelFlow { parallelForEach { transform(it)?.let { send(it) } } }.toList() internal suspend fun <T> Iterable<T>.parallelForEach(action: suspend CoroutineScope.(T) -> Unit) = coroutineScope { forEach { launch { action(it) } } } internal suspend fun <T, R, K> Map<T, R>.parallelMap(transform: suspend (Map.Entry<T, R>) -> K) = coroutineScope { map { async { transform(it) } }.awaitAll() } internal suspend fun <T, R> Iterable<T>.parallelFlatMap(transform: suspend (T) -> Iterable<R>) = coroutineScope { map { async { transform(it) } }.flatMap { it.await() } } internal suspend inline fun <K, V> Map<K, V>.parallelUpdatedKeys(keys: Iterable<K>, crossinline action: suspend (K) -> V): Map<K, V> { val map = toMutableMap() keys.parallelForEach { map[it] = action(it) } return map } internal fun timer(each: Duration, emitAtStartup: Boolean = true) = flow { if (emitAtStartup) emit(Unit) while (true) { delay(each) emit(Unit) } } internal fun <T> Flow<T>.throttle(time: Duration) = throttle(time.inWholeMilliseconds) internal inline fun <reified T, reified R> Flow<T>.modifiedBy( modifierFlow: Flow<R>, noinline transform: suspend (T, R) -> T ): Flow<T> = flatMapLatest { modifierFlow.scan(it, transform) } internal fun <T, R> Flow<T>.mapLatestTimedWithLoading( loggingContext: String, loadingFlow: MutableStateFlow<Boolean>? = null, transform: suspend CoroutineScope.(T) -> R ) = mapLatest { measureTimedValue { loadingFlow?.emit(true) val result = try { coroutineScope { transform(it) } } finally { loadingFlow?.emit(false) } result } }.map { logDebug(loggingContext) { "Took ${it.duration.absoluteValue} to process" } it.value } internal fun <T> Flow<T>.catchAndLog(context: String, message: String? = null) = catch { if (message != null) { logDebug(context, it) { message } } else logDebug(context, it) } internal suspend inline fun <R> MutableStateFlow<Boolean>.whileLoading(action: () -> R): TimedValue<R> { emit(true) val r = measureTimedValue { action() } emit(false) return r } internal inline fun <reified T> Flow<T>.batchAtIntervals(duration: Duration) = channelFlow { val mutex = Mutex() val buffer = mutableListOf<T>() var job: Job? = null collect { mutex.withLock { buffer.add(it) } if (job == null || job?.isCompleted == true) { job = launch { delay(duration) mutex.withLock { send(buffer.toTypedArray()) buffer.clear() } } } } } internal suspend fun showBackgroundLoadingBar( project: Project, @Nls title: String, @Nls upperMessage: String, cancellable: Boolean = false, isSafe: Boolean = true ): BackgroundLoadingBarController { val syncSignal = Mutex(true) val externalScopeJob = coroutineContext.job val progressManager = ProgressManager.getInstance() val progressController = BackgroundLoadingBarController(syncSignal) progressManager.run(object : Task.Backgroundable(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { if (isSafe && progressManager is ProgressManagerImpl && indicator is UserDataHolder) { progressManager.markProgressSafe(indicator) } indicator.text = upperMessage // ??? why does it work? runBlocking { indicator.text = upperMessage // ??? why does it work? val indicatorCancelledPollingJob = launch { while (true) { if (indicator.isCanceled) break delay(50) } } val internalJob = launch { syncSignal.lock() } select { internalJob.onJoin { } externalScopeJob.onJoin { internalJob.cancel() indicatorCancelledPollingJob.cancel() } indicatorCancelledPollingJob.onJoin { syncSignal.unlock() progressController.triggerCallbacks() } } indicatorCancelledPollingJob.cancel() } } }) return progressController } internal class BackgroundLoadingBarController(private val syncMutex: Mutex) { private val callbacks = mutableSetOf<() -> Unit>() fun addOnComputationInterruptedCallback(callback: () -> Unit) { callbacks.add(callback) } internal fun triggerCallbacks() = callbacks.forEach { it.invoke() } fun clear() { runCatching { syncMutex.unlock() } } } suspend fun <R> writeAction(action: () -> R): R = withContext(Dispatchers.EDT) { action() } internal fun ModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer { override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> = [email protected](project, nativeModules) } internal fun AsyncModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer { override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> = [email protected](project, nativeModules).await() } internal fun ModuleChangesSignalProvider.asCoroutine() = object : FlowModuleChangesSignalProvider { override fun registerModuleChangesListener(project: Project) = callbackFlow { val sub = registerModuleChangesListener(project) { trySend() } awaitClose { sub.unsubscribe() } } } internal fun ProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider { override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile) override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType) override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).toList() override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).toList() override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).toList() override suspend fun declaredDependenciesInModule(module: ProjectModule) = [email protected](module).toList() override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) = [email protected](module, scopes).toList() override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) = [email protected](repository, module).toList() override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) = [email protected](repository, module).toList() override suspend fun listRepositoriesInModule(module: ProjectModule) = [email protected](module).toList() } internal fun AsyncProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider { override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile) override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType) override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).await().toList() override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).await().toList() override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) = [email protected](operationMetadata, module).await().toList() override suspend fun declaredDependenciesInModule(module: ProjectModule) = [email protected](module).await().toList() override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) = [email protected](module, scopes).await().toList() override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) = [email protected](repository, module).await().toList() override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) = [email protected](repository, module).await().toList() override suspend fun listRepositoriesInModule(module: ProjectModule) = [email protected](module).await().toList() } fun SendChannel<Unit>.trySend() = trySend(Unit) fun ProducerScope<Unit>.trySend() = trySend(Unit) suspend fun SendChannel<Unit>.send() = send(Unit) suspend fun ProducerScope<Unit>.send() = send(Unit) data class CombineLatest3<A, B, C>(val a: A, val b: B, val c: C) fun <A, B, C, Z> combineLatest( flowA: Flow<A>, flowB: Flow<B>, flowC: Flow<C>, transform: suspend (CombineLatest3<A, B, C>) -> Z ) = combine(flowA, flowB, flowC) { a, b, c -> CombineLatest3(a, b, c) } .mapLatest(transform) fun <T> Flow<T>.pauseOn(flow: Flow<Boolean>): Flow<T> = flow { coroutineScope { val buffer = produce { collect { send(it) } } flow.flatMapLatest { isOpen -> if (isOpen) buffer.receiveAsFlow() else EMPTY_UNCLOSED_FLOW } .collect { emit(it) } } } private val EMPTY_UNCLOSED_FLOW = flow<Nothing> { suspendCancellableCoroutine { } }
apache-2.0
0c4db39c9a06dd5d28e8c02daa0b571f
41.614754
134
0.721403
4.841975
false
false
false
false
alisle/Penella
src/test/java/org/penella/codecs/ShardGetCodecTest.kt
1
1757
package org.penella.codecs import com.fasterxml.jackson.module.kotlin.KotlinModule import io.vertx.core.buffer.Buffer import io.vertx.core.json.Json import org.junit.Assert import org.junit.Before import org.junit.Test import org.penella.index.IndexType import org.penella.messages.ShardGet import org.penella.structures.triples.HashTriple /** * 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. * * * Created by alisle on 1/26/17. */ class ShardGetCodecTest { @Before fun setUp() { Json.mapper.registerModule(KotlinModule()) } @Test fun testName() { val codec = ShardGetCodec() Assert.assertEquals(codec.name(), "ShardGet") } @Test fun testEncodeDecode() { val codec = ShardGetCodec() val buffer = Buffer.buffer() val value = ShardGet(IndexType.SO, HashTriple(1L, 10L, 100L)) codec.encodeToWire(buffer, value) val newValue = codec.decodeFromWire(0, buffer) Assert.assertEquals(value, newValue) } @Test fun testTransform() { val codec = ShardGetCodec() val value = ShardGet(IndexType.SO, HashTriple(1L, 10L, 100L)) val newValue = codec.transform(value) Assert.assertEquals(value, newValue) } }
apache-2.0
1a254f2b6dff7b586a61d6a392181324
27.354839
75
0.697211
3.948315
false
true
false
false
vovagrechka/fucking-everything
vgrechka-kt/jvm/src/vgrechka/vgjvm-tests.kt
1
1142
package vgrechka import java.util.* import java.util.concurrent.CountDownLatch import kotlin.concurrent.thread object Test1 {val __for = Debug::nextDebugId object fucker1; object fucker2 val fuckers = listOf(fucker1, fucker2) val numThreadsPerFucker = 4 val numIterationsPerThread = 100 val generatedIds = Collections.synchronizedSet(mutableSetOf<String>()) val expectedNumGeneratedUniqueIds = fuckers.size * numThreadsPerFucker * numIterationsPerThread val fartsMade = CountDownLatch(expectedNumGeneratedUniqueIds) @JvmStatic fun main(args: Array<String>) { for (fucker in fuckers) { for (i in 1..numThreadsPerFucker) { runThread(fucker) } } fartsMade.await() assertEquals(expectedNumGeneratedUniqueIds, generatedIds.size) clog("\nOK") } fun runThread(obj: Any) { thread { for (i in 1..numIterationsPerThread) { val id = Debug.nextDebugId(obj) generatedIds += id clog(id) fartsMade.countDown() } } } }
apache-2.0
309ca80570319b8f3f9d941208abf9e5
24.954545
99
0.62697
4.342205
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/data/DaoOperations.kt
2
2281
package com.github.kerubistan.kerub.data import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.Named /** * Collection of common DAO operations to pick from when building DAO interfaces. */ interface DaoOperations { /** * Interface to allow adding entities to the backing data store. */ interface Add<T : Entity<I>, I> { fun add(entity: T): I fun addAll(entities: Collection<T>) } /** * Interface to allow removing entities from the backing data store. */ interface Remove<T : Entity<I>, I> { fun remove(entity: T) fun remove(id: I) } /** * Interface to allow replacing/updating entities on the backing store. */ interface Update<T : Entity<I>, I> { fun update(entity: T) } /** * Interface to allow retrieving entities from the backing store. */ interface Read<T : Entity<I>, I> { operator fun get(id: I): T? operator fun get(ids: Collection<I>): List<T> } interface ByName<T : Named> { fun getByName(name: String, max: Int? = null): List<T> fun existsByName(name: String) = getByName(name, 1).isNotEmpty() } /** * List operations for DAOs. */ interface PagedList<T : Entity<I>, I> { /** * Get the total count of entities. */ fun count(): Int /** * List the entities. */ fun list( start: Long = 0, limit: Int = Int.MAX_VALUE, sort: String = "id"): List<T> } /** * Interface for the data that can be listed safely with a single operation. * This should only be applied in cases where the number of entities is low. */ interface SimpleList<T : Any> { fun listAll(): List<T> } interface ListMany<I, T> { fun list(ids: Collection<I>): List<T> } interface SimpleSearch<T : Entity<*>> { fun fieldSearch( field: String, value: String, start: Long = 0, limit: Int = Int.MAX_VALUE ): List<T> } interface Listen<I, T : Entity<I>> { fun listenCreate(action: (T) -> Boolean) fun listenCreate(id: I, action: (T) -> Boolean) fun listenUpdate(action: (T) -> Boolean) fun listenUpdate(id: I, action: (T) -> Boolean) fun listenDelete(action: (T) -> Boolean) fun listenDelete(id: I, action: (T) -> Boolean) /** * Get the entity and perform the action */ fun waitFor(id: I, action: (T) -> Boolean) } }
apache-2.0
09bc236ca8f15e93277fdd597b00d30a
22.040404
81
0.646208
3.137552
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinLineMarkerProvider.kt
1
22377
// 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.highlighter.markers import com.intellij.codeInsight.daemon.* import com.intellij.codeInsight.daemon.impl.LineMarkerNavigator import com.intellij.codeInsight.daemon.impl.MarkerType import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator import com.intellij.codeInsight.navigation.BackgroundUpdaterTask import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.editor.markup.SeparatorPlacement import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.asJava.classes.KtFakeLightClass import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod import org.jetbrains.kotlin.asJava.toFakeLightClass import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.core.isOverridable import org.jetbrains.kotlin.idea.editor.fixers.startLine import org.jetbrains.kotlin.idea.presentation.DeclarationByModuleRenderer import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import java.awt.event.MouseEvent import javax.swing.ListCellRenderer class KotlinLineMarkerProvider : LineMarkerProviderDescriptor() { override fun getName() = KotlinBundle.message("highlighter.name.kotlin.line.markers") override fun getOptions(): Array<Option> = KotlinLineMarkerOptions.options override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? { if (DaemonCodeAnalyzerSettings.getInstance().SHOW_METHOD_SEPARATORS) { if (element.canHaveSeparator()) { val prevSibling = element.getPrevSiblingIgnoringWhitespaceAndComments() if (prevSibling.canHaveSeparator() && (element.wantsSeparator() || prevSibling?.wantsSeparator() == true) ) { return createLineSeparatorByElement(element) } } } return null } private fun PsiElement?.canHaveSeparator() = this is KtFunction || this is KtClassInitializer || (this is KtProperty && !isLocal) || ((this is KtObjectDeclaration && this.isCompanion())) private fun PsiElement.wantsSeparator() = this is KtFunction || StringUtil.getLineBreakCount(text) > 0 private fun createLineSeparatorByElement(element: PsiElement): LineMarkerInfo<PsiElement> { val anchor = PsiTreeUtil.getDeepestFirst(element) val info = LineMarkerInfo(anchor, anchor.textRange) info.separatorColor = EditorColorsManager.getInstance().globalScheme.getColor(CodeInsightColors.METHOD_SEPARATORS_COLOR) info.separatorPlacement = SeparatorPlacement.TOP return info } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: LineMarkerInfos) { if (elements.isEmpty()) return if (KotlinLineMarkerOptions.options.none { option -> option.isEnabled }) return val first = elements.first() if (DumbService.getInstance(first.project).isDumb || !ProjectRootsUtil.isInProjectOrLibSource(first)) return val functions = hashSetOf<KtNamedFunction>() val properties = hashSetOf<KtNamedDeclaration>() val declarations = hashSetOf<KtNamedDeclaration>() for (leaf in elements) { ProgressManager.checkCanceled() if (leaf !is PsiIdentifier && leaf.firstChild != null) continue val element = leaf.parent as? KtNamedDeclaration ?: continue if (!declarations.add(element)) continue when (element) { is KtClass -> { collectInheritedClassMarker(element, result) collectHighlightingColorsMarkers(element, result) } is KtNamedFunction -> { functions.add(element) collectSuperDeclarationMarkers(element, result) } is KtProperty -> { properties.add(element) collectSuperDeclarationMarkers(element, result) } is KtParameter -> { if (element.hasValOrVar()) { properties.add(element) collectSuperDeclarationMarkers(element, result) } } } collectMultiplatformMarkers(element, result) } collectOverriddenFunctions(functions, result) collectOverriddenPropertyAccessors(properties, result) } } data class NavigationPopupDescriptor( val targets: Collection<NavigatablePsiElement>, @NlsContexts.PopupTitle val title: String, @NlsContexts.TabTitle val findUsagesTitle: String, val renderer: ListCellRenderer<in NavigatablePsiElement>, val updater: BackgroundUpdaterTask? = null ) { fun showPopup(e: MouseEvent) { PsiElementListNavigator.openTargets(e, targets.toTypedArray(), title, findUsagesTitle, renderer, updater) } } interface TestableLineMarkerNavigator { fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? } val SUBCLASSED_CLASS = MarkerType( "SUBCLASSED_CLASS", { getPsiClass(it)?.let(::getSubclassedClassTooltip) }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { getPsiClass(element)?.let { MarkerType.navigateToSubclassedClass(e, it, DeclarationByModuleRenderer()) } } }) val OVERRIDDEN_FUNCTION = object : MarkerType( "OVERRIDDEN_FUNCTION", { getPsiMethod(it)?.let(::getOverriddenMethodTooltip) }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToOverriddenMethodPopup(e, element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToOverriddenMethodPopup(null, element) } } } val OVERRIDDEN_PROPERTY = object : MarkerType( "OVERRIDDEN_PROPERTY", { it?.let { getOverriddenPropertyTooltip(it.parent as KtNamedDeclaration) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToPropertyOverriddenDeclarationsPopup(e, element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToPropertyOverriddenDeclarationsPopup(null, element) } } } val PsiElement.markerDeclaration get() = (this as? KtDeclaration) ?: (parent as? KtDeclaration) private val PLATFORM_ACTUAL = object : MarkerType( "PLATFORM_ACTUAL", { element -> element?.markerDeclaration?.let { getPlatformActualTooltip(it) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToActualDeclarationsPopup(element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? { return buildNavigateToActualDeclarationsPopup(element) } } } } private val EXPECTED_DECLARATION = object : MarkerType( "EXPECTED_DECLARATION", { element -> element?.markerDeclaration?.let { getExpectedDeclarationTooltip(it) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToExpectedDeclarationsPopup(element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? { return buildNavigateToExpectedDeclarationsPopup(element) } } } } private fun isImplementsAndNotOverrides( descriptor: CallableMemberDescriptor, overriddenMembers: Collection<CallableMemberDescriptor> ): Boolean = descriptor.modality != Modality.ABSTRACT && overriddenMembers.all { it.modality == Modality.ABSTRACT } private fun collectSuperDeclarationMarkers(declaration: KtDeclaration, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementingOption.isEnabled || KotlinLineMarkerOptions.overridingOption.isEnabled)) return assert(declaration is KtNamedFunction || declaration is KtProperty || declaration is KtParameter) declaration as KtNamedDeclaration // implied by assert if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return val resolveWithParents = resolveDeclarationWithParents(declaration) if (resolveWithParents.overriddenDescriptors.isEmpty()) return val implements = isImplementsAndNotOverrides(resolveWithParents.descriptor!!, resolveWithParents.overriddenDescriptors) val anchor = declaration.nameAnchor() // NOTE: Don't store descriptors in line markers because line markers are not deleted while editing other files and this can prevent // clearing the whole BindingTrace. val gutter = if (implements) KotlinLineMarkerOptions.implementingOption else KotlinLineMarkerOptions.overridingOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, SuperDeclarationMarkerTooltip, SuperDeclarationMarkerNavigationHandler(), GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, if (declaration is KtNamedFunction) KotlinBundle.message("highlighter.action.text.go.to.super.method") else KotlinBundle.message("highlighter.action.text.go.to.super.property"), IdeActions.ACTION_GOTO_SUPER ) result.add(lineMarkerInfo) } private fun collectInheritedClassMarker(element: KtClass, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) return if (!element.isInheritable()) { return } val lightClass = element.toLightClass() ?: element.toFakeLightClass() if (ClassInheritorsSearch.search(lightClass, false).findFirst() == null) return val anchor = element.nameIdentifier ?: element val gutter = if (element.isInterface()) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val icon = gutter.icon ?: return val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, icon, SUBCLASSED_CLASS.tooltip, SUBCLASSED_CLASS.navigationHandler, GutterIconRenderer.Alignment.RIGHT ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, if (element.isInterface()) KotlinBundle.message("highlighter.action.text.go.to.implementations") else KotlinBundle.message("highlighter.action.text.go.to.subclasses"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } private fun collectOverriddenPropertyAccessors( properties: Collection<KtNamedDeclaration>, result: LineMarkerInfos ) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) return val mappingToJava = HashMap<PsiElement, KtNamedDeclaration>() for (property in properties) { if (property.isOverridable()) { property.toPossiblyFakeLightMethods().forEach { mappingToJava[it] = property } mappingToJava[property] = property } } val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance<PsiMethod>()) for (property in getOverriddenDeclarations(mappingToJava, classes)) { ProgressManager.checkCanceled() val anchor = (property as? PsiNameIdentifierOwner)?.nameIdentifier ?: property val gutter = if (isImplemented(property)) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, OVERRIDDEN_PROPERTY.tooltip, OVERRIDDEN_PROPERTY.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.overridden.properties"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } } private val KtNamedDeclaration.expectOrActualAnchor get() = nameIdentifier ?: when (this) { is KtConstructor<*> -> getConstructorKeyword() ?: valueParameterList?.leftParenthesis is KtObjectDeclaration -> getObjectKeyword() else -> null } ?: this private fun collectMultiplatformMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { if (KotlinLineMarkerOptions.actualOption.isEnabled) { if (declaration.isExpectDeclaration()) { collectActualMarkers(declaration, result) return } } if (KotlinLineMarkerOptions.expectOption.isEnabled) { if (!declaration.isExpectDeclaration() && declaration.isEffectivelyActual()) { collectExpectedMarkers(declaration, result) return } } } private fun Document.areAnchorsOnOneLine( first: KtNamedDeclaration, second: KtNamedDeclaration? ): Boolean { if (second == null) return false val firstAnchor = first.expectOrActualAnchor val secondAnchor = second.expectOrActualAnchor return firstAnchor.startLine(this) == secondAnchor.startLine(this) } private fun KtNamedDeclaration.requiresNoMarkers( document: Document? = PsiDocumentManager.getInstance(project).getDocument(containingFile) ): Boolean { when (this) { is KtPrimaryConstructor -> return true is KtParameter, is KtEnumEntry -> { if (document?.areAnchorsOnOneLine(this, containingClassOrObject) == true) { return true } if (this is KtEnumEntry) { val enumEntries = containingClassOrObject?.body?.enumEntries.orEmpty() val previousEnumEntry = enumEntries.getOrNull(enumEntries.indexOf(this) - 1) if (document?.areAnchorsOnOneLine(this, previousEnumEntry) == true) { return true } } if (this is KtParameter && hasValOrVar()) { val parameters = containingClassOrObject?.primaryConstructorParameters.orEmpty() val previousParameter = parameters.getOrNull(parameters.indexOf(this) - 1) if (document?.areAnchorsOnOneLine(this, previousParameter) == true) { return true } } } } return false } internal fun KtDeclaration.findMarkerBoundDeclarations(): Sequence<KtNamedDeclaration> { if (this !is KtClass && this !is KtParameter) return emptySequence() val document = PsiDocumentManager.getInstance(project).getDocument(containingFile) fun <T : KtNamedDeclaration> Sequence<T>.takeBound(bound: KtNamedDeclaration) = takeWhile { document?.areAnchorsOnOneLine(bound, it) == true } return when (this) { is KtParameter -> { val propertyParameters = takeIf { hasValOrVar() }?.containingClassOrObject ?.primaryConstructorParameters ?: return emptySequence() propertyParameters.asSequence().dropWhile { it !== this }.drop(1).takeBound(this).filter { it.hasValOrVar() } } is KtEnumEntry -> { val enumEntries = containingClassOrObject?.body?.enumEntries ?: return emptySequence() enumEntries.asSequence().dropWhile { it !== this }.drop(1).takeBound(this) } is KtClass -> { val boundParameters = primaryConstructor?.valueParameters ?.asSequence() ?.takeBound(this) ?.filter { it.hasValOrVar() } .orEmpty() val boundEnumEntries = this.takeIf { isEnum() }?.body?.enumEntries?.asSequence()?.takeBound(this).orEmpty() boundParameters + boundEnumEntries } else -> emptySequence() } } private fun collectActualMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { val gutter = KotlinLineMarkerOptions.actualOption if (!gutter.isEnabled) return if (declaration.requiresNoMarkers()) return if (!declaration.hasAtLeastOneActual()) return val anchor = declaration.expectOrActualAnchor val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, PLATFORM_ACTUAL.tooltip, PLATFORM_ACTUAL.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.actual.declarations"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } private fun collectExpectedMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { if (!KotlinLineMarkerOptions.expectOption.isEnabled) return if (declaration.requiresNoMarkers()) return if (!declaration.hasMatchingExpected()) return val anchor = declaration.expectOrActualAnchor val gutter = KotlinLineMarkerOptions.expectOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, EXPECTED_DECLARATION.tooltip, EXPECTED_DECLARATION.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.expected.declaration"), null ) result.add(lineMarkerInfo) } private fun collectOverriddenFunctions(functions: Collection<KtNamedFunction>, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) { return } val mappingToJava = HashMap<PsiElement, KtNamedFunction>() for (function in functions) { if (function.isOverridable()) { val method = LightClassUtil.getLightClassMethod(function) ?: KtFakeLightMethod.get(function) if (method != null) { mappingToJava[method] = function } mappingToJava[function] = function } } val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance<PsiMethod>()) for (function in getOverriddenDeclarations(mappingToJava, classes)) { ProgressManager.checkCanceled() val anchor = function.nameAnchor() val gutter = if (isImplemented(function)) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, OVERRIDDEN_FUNCTION.tooltip, OVERRIDDEN_FUNCTION.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.overridden.methods"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } } private fun KtNamedDeclaration.nameAnchor(): PsiElement = nameIdentifier ?: PsiTreeUtil.getDeepestVisibleFirst(this) ?: this
apache-2.0
0c61bc3eb767787bc030201976ff4f66
38.818505
158
0.693301
5.30135
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/FromClosedRangeMigrationInspection.kt
1
5759
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.migration import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.configuration.MigrationInfo import org.jetbrains.kotlin.idea.configuration.isLanguageVersionUpdate import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.simpleNameExpressionVisitor import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.constants.TypedCompileTimeConstant import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class FromClosedRangeMigrationInspection : AbstractKotlinInspection(), MigrationFix, CleanupLocalInspectionTool { override fun isApplicable(migrationInfo: MigrationInfo): Boolean { return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_2, LanguageVersion.KOTLIN_1_3) } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = simpleNameExpressionVisitor(fun(simpleNameExpression) { val callExpression = simpleNameExpression.parent as? KtCallExpression ?: return if (simpleNameExpression.text != SHORT_NAME) return run { val versionAtLeast13 = simpleNameExpression.languageVersionSettings.languageVersion >= LanguageVersion.KOTLIN_1_3 if (!versionAtLeast13 && !isUnitTestMode()) { return } } val descriptor = simpleNameExpression.resolveMainReferenceToDescriptors().firstOrNull() ?: return val callableDescriptor = descriptor as? CallableDescriptor ?: return val resolvedToFqName = callableDescriptor.fqNameOrNull()?.asString() ?: return if (resolvedToFqName != INT_FROM_CLOSE_RANGE_FQNAME && resolvedToFqName != LONG_FROM_CLOSE_RANGE_FQNAME) { return } val stepParameter = callableDescriptor.valueParameters.getOrNull(2) ?: return if (stepParameter.name.asString() != "step") return val resolvedCall = callExpression.resolveToCall() ?: return val resolvedValueArgument = resolvedCall.valueArguments[stepParameter] as? ExpressionValueArgument ?: return val argumentExpression = resolvedValueArgument.valueArgument?.getArgumentExpression() ?: return val constant = ConstantExpressionEvaluator.getConstant(argumentExpression, argumentExpression.analyze(BodyResolveMode.PARTIAL)) if (constant != null) { val value = (constant as? TypedCompileTimeConstant<*>)?.constantValue?.value if (value != null) { if ((resolvedToFqName == INT_FROM_CLOSE_RANGE_FQNAME && Int.MIN_VALUE == value) || (resolvedToFqName == LONG_FROM_CLOSE_RANGE_FQNAME && Long.MIN_VALUE == value) ) { report(holder, simpleNameExpression, resolvedToFqName, isOnTheFly, isError = true) return } } // Don't report for constants other than MIN_VALUE return } report(holder, simpleNameExpression, resolvedToFqName, isOnTheFly, isError = false) }) private fun report( holder: ProblemsHolder, simpleNameExpression: KtSimpleNameExpression, resolvedToFqName: String, isOnTheFly: Boolean, isError: Boolean ) { val desc = when (resolvedToFqName) { INT_FROM_CLOSE_RANGE_FQNAME -> INT_FROM_CLOSE_RANGE_DESC LONG_FROM_CLOSE_RANGE_FQNAME -> LONG_FROM_CLOSE_RANGE_DESC else -> throw IllegalArgumentException("Can't process $resolvedToFqName") } val problemDescriptor = holder.manager.createProblemDescriptor( simpleNameExpression, simpleNameExpression, KotlinBundle.message("it.s.prohibited.to.call.0.with.min.value.step.since.1.3", desc), if (isError) ProblemHighlightType.ERROR else ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly ) holder.registerProblem(problemDescriptor) } companion object { private const val SHORT_NAME = "fromClosedRange" private const val INT_FROM_CLOSE_RANGE_FQNAME = "kotlin.ranges.IntProgression.Companion.fromClosedRange" private const val INT_FROM_CLOSE_RANGE_DESC = "IntProgression.fromClosedRange()" private const val LONG_FROM_CLOSE_RANGE_FQNAME = "kotlin.ranges.LongProgression.Companion.fromClosedRange" private const val LONG_FROM_CLOSE_RANGE_DESC = "LongProgression.fromClosedRange()" } }
apache-2.0
e4a758d9f4997f24730b86fff9b38a68
49.964602
158
0.716965
5.342301
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemsViewState.kt
1
1480
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.analysis.problemsView.toolWindow import com.intellij.ide.ui.UISettings import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.util.xmlb.annotations.XCollection import java.util.* import java.util.concurrent.ConcurrentHashMap open class ProblemsViewState : BaseState() { companion object { @JvmStatic fun getInstance(project: Project) = project.getService(ProblemsViewStateManager::class.java).state } var selectedTabId by string("") var proportion by property(0.5f) var autoscrollToSource by property(false) var showPreview by property(false) var showToolbar by property(true) var groupByToolId by property(false) var sortFoldersFirst by property(true) var sortBySeverity by property(true) var sortByName by property(false) @get:XCollection(style = XCollection.Style.v2) val hideBySeverity: MutableSet<Int> by property(Collections.newSetFromMap(ConcurrentHashMap())) { it.isEmpty() } } @State(name = "ProblemsViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))]) internal class ProblemsViewStateManager : SimplePersistentStateComponent<ProblemsViewState>(ProblemsViewState()) { override fun noStateLoaded() { state.autoscrollToSource = UISettings.instance.state.defaultAutoScrollToSource } }
apache-2.0
5a6127b43d6c72d7de96229ae436ba14
36.948718
140
0.789865
4.352941
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/AbstractDependencyAnalyzerAction.kt
1
1427
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.dependency.analyzer import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.registry.Registry abstract class AbstractDependencyAnalyzerAction : AnAction(), DumbAware { abstract fun getSystemId(e: AnActionEvent): ProjectSystemId? abstract fun setSelectedState(e: AnActionEvent, view: DependencyAnalyzerView) override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val systemId = getSystemId(e) ?: return val tab = DependencyAnalyzerEditorTab(project, systemId) setSelectedState(e, tab.view) UIComponentEditorTab.show(project, tab) } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = Registry.`is`("external.system.dependency.analyzer") } init { templatePresentation.icon = AllIcons.Actions.DependencyAnalyzer templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.action.name") } }
apache-2.0
99d42f4b1af4580fa7b02c234e4ecae4
42.272727
158
0.802383
4.694079
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/communication/Notification/NotificationActivity.kt
1
4170
package stan.androiddemo.communication.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.BitmapFactory import android.net.ConnectivityManager import android.os.Bundle import android.support.v4.content.LocalBroadcastManager import android.support.v7.app.AppCompatActivity import android.support.v7.app.NotificationCompat import android.widget.Toast import kotlinx.android.synthetic.main.activity_notifcation.* import stan.androiddemo.R class NotificationActivity : AppCompatActivity() { lateinit var intentFilter:IntentFilter lateinit var networkChangeReceiver:NetworkChangeReceiver lateinit var intentFilterLocal:IntentFilter lateinit var localReceive:LocalReceive lateinit var localBroadcastManager:LocalBroadcastManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_notifcation) intentFilter = IntentFilter() intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE") networkChangeReceiver = NetworkChangeReceiver() registerReceiver(networkChangeReceiver,intentFilter) localBroadcastManager = LocalBroadcastManager.getInstance(this) txt_send_notif.setOnClickListener { val intent = Intent("com.androiddemo.broadcast.CUSTOMBROADCAST") //sendBroadcast(intent) 这是标准广播 sendOrderedBroadcast(intent,null) //这是有序广播 //这种广播其他APP也可以收到,这样肯定不行 //可以使用本地广播 } intentFilterLocal = IntentFilter() intentFilterLocal.addAction("com.androiddemo.broadcast.LOCALBROADCAST") localReceive = LocalReceive() localBroadcastManager.registerReceiver(localReceive,intentFilterLocal) txt_send_notif_local.setOnClickListener { val intentLocal = Intent("com.androiddemo.broadcast.LOCALBROADCAST") localBroadcastManager.sendBroadcast(intentLocal) } btn_send_notif.setOnClickListener { val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val intent = Intent(this,PendingIntentActivity::class.java) val pi = PendingIntent.getActivity(this,0,intent,0) val notification = NotificationCompat.Builder(this).setContentTitle("This is the content title") .setContentText("This is the content text") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher)) .setContentIntent(pi) .setAutoCancel(true) .build() manager.notify(1,notification) } } override fun onDestroy() { super.onDestroy() unregisterReceiver(networkChangeReceiver) localBroadcastManager.unregisterReceiver(localReceive) } inner class NetworkChangeReceiver: BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { // Toast.makeText(p0,"network changes",Toast.LENGTH_LONG).show() val connectionManage = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectionManage.activeNetworkInfo //need add access network status if (networkInfo != null && networkInfo.isAvailable){ Toast.makeText(p0,"network is available",Toast.LENGTH_LONG).show() } else{ Toast.makeText(p0,"network is unavailable",Toast.LENGTH_LONG).show() } } //测试确实很OK } inner class LocalReceive:BroadcastReceiver(){ override fun onReceive(p0: Context?, p1: Intent?) { Toast.makeText(p0,"receive local broadcast",Toast.LENGTH_LONG).show() } } }
mit
0a3abb71076792a68198e1ca5f5d268e
32.752066
108
0.695397
5.182741
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/db/entity/Book.kt
1
1416
package com.orgzly.android.db.entity import androidx.room.* @Entity( tableName = "books", indices = [ Index("name", unique = true) ] ) data class Book constructor( @PrimaryKey(autoGenerate = true) val id: Long, val name: String, val title: String? = null, val mtime: Long? = null, @ColumnInfo(name = "is_dummy") val isDummy: Boolean = false, @ColumnInfo(name = "is_deleted") val isDeleted: Boolean? = false, val preface: String? = null, @ColumnInfo(name = "is_indented") val isIndented: Boolean? = false, @ColumnInfo(name = "used_encoding") val usedEncoding: String? = null, @ColumnInfo(name = "detected_encoding") val detectedEncoding: String? = null, @ColumnInfo(name = "selected_encoding") val selectedEncoding: String? = null, @ColumnInfo(name = "sync_status") val syncStatus: String? = null, // TODO: BookSyncStatus @Embedded(prefix = "last_action_") val lastAction: BookAction? = null, @ColumnInfo(name = "is_modified") val isModified: Boolean = false ) { override fun toString(): String { return "$name#$id" } companion object { @JvmStatic fun forName(name: String): Book { return Book(0, name) } } }
gpl-3.0
d8ed4c98732b9f7aa813cb1d408f4ca6
21.125
63
0.560734
4.176991
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/util/FloatExt.kt
1
751
package com.soywiz.kpspemu.util inline fun <T> Iterable<T>.sumByFloat(crossinline selector: (T) -> Float): Float { var out = 0f for (i in this) out += selector(i) return out } val Float.pspSign: Float get() = if (this == 0f || this == -0f) 0f else if ((this.toRawBits() ushr 31) != 0) -1f else +1f val Float.pspAbs: Float get() = Float.fromBits(this.toRawBits() and 0x80000000.toInt().inv()) val Float.pspSat0: Float get() = if (this == -0f) 0f else this.clampf(0f, 1f) val Float.pspSat1: Float get() = this.clampf(-1f, 1f) infix fun Float.pspAdd(that: Float): Float = if (this.isNaN() || that.isNaN()) Float.NaN else this + that infix fun Float.pspSub(that: Float): Float = if (this.isNaN() || that.isNaN()) Float.NaN else this - that
mit
45e404b42ae7af6d124cad00fca72c3a
49.066667
121
0.667111
2.945098
false
false
false
false
square/sqldelight
extensions/android-paging3/src/main/java/com/squareup/sqldelight/android/paging3/KeyedQueryPagingSource.kt
1
2187
package com.squareup.sqldelight.android.paging3 import androidx.paging.PagingState import com.squareup.sqldelight.Query import com.squareup.sqldelight.Transacter import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext internal class KeyedQueryPagingSource<Key : Any, RowType : Any>( private val queryProvider: (beginInclusive: Key, endExclusive: Key?) -> Query<RowType>, private val pageBoundariesProvider: (anchor: Key?, limit: Long) -> Query<Key>, private val transacter: Transacter, private val dispatcher: CoroutineDispatcher, ) : QueryPagingSource<Key, RowType>() { private var pageBoundaries: List<Key>? = null override val jumpingSupported: Boolean get() = false override fun getRefreshKey(state: PagingState<Key, RowType>): Key? { val boundaries = pageBoundaries ?: return null val last = state.pages.lastOrNull() ?: return null val keyIndexFromNext = last.nextKey?.let { boundaries.indexOf(it) - 1 } val keyIndexFromPrev = last.prevKey?.let { boundaries.indexOf(it) + 1 } val keyIndex = keyIndexFromNext ?: keyIndexFromPrev ?: return null return boundaries.getOrNull(keyIndex) } override suspend fun load(params: LoadParams<Key>): LoadResult<Key, RowType> { return withContext(dispatcher) { try { transacter.transactionWithResult { val boundaries = pageBoundaries ?: pageBoundariesProvider(params.key, params.loadSize.toLong()) .executeAsList() .also { pageBoundaries = it } val key = params.key ?: boundaries.first() require(key in boundaries) val keyIndex = boundaries.indexOf(key) val previousKey = boundaries.getOrNull(keyIndex - 1) val nextKey = boundaries.getOrNull(keyIndex + 1) val results = queryProvider(key, nextKey) .also { currentQuery = it } .executeAsList() LoadResult.Page( data = results, prevKey = previousKey, nextKey = nextKey, ) } } catch (e: Exception) { if (e is IllegalArgumentException) throw e LoadResult.Error(e) } } } }
apache-2.0
9eb01838561c8ca7215ed1abbf1b62b8
34.852459
89
0.671696
4.594538
false
false
false
false
mchernyavsky/kotlincheck
src/main/kotlin/io/kotlincheck/CounterexampleStorage.kt
1
2737
package io.kotlincheck import org.apache.commons.lang3.SerializationException import org.apache.commons.lang3.SerializationUtils import org.jetbrains.exposed.dao.EntityID import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.IntIdTable import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction import java.io.Serializable import java.sql.Blob import javax.sql.rowset.serial.SerialBlob object CounterexampleStorage { init { Database.connect("jdbc:h2:./build/counterexamples", driver = "org.h2.Driver") transaction { SchemaUtils.create(Counterexamples) } } fun <P> loadCounterexamples(propositionFullName: String): List<P> = transaction { try { Counterexample .find { Counterexamples.propositionName eq propositionFullName } .map { it.arguments } .map { it.binaryStream } .map { SerializationUtils.deserialize<P>(it) } } catch (e: ClassCastException) { Counterexamples.deleteWhere { Counterexamples.propositionName eq propositionFullName } listOf() } } fun saveCounterexample(propositionFullName: String, counterexample: Serializable) { try { val serialized = SerializationUtils.serialize(counterexample) transaction { Counterexamples.insert { it[propositionName] = propositionFullName it[arguments] = SerialBlob(serialized) } } } catch (e: SerializationException) { // ignore } } fun removeCounterexample(propositionFullName: String, counterexample: Serializable) { val serialized = SerializationUtils.serialize(counterexample) transaction { Counterexamples.deleteWhere { (Counterexamples.propositionName eq propositionFullName) and (Counterexamples.arguments eq SerialBlob(serialized)) } } } fun removeCounterexamples(propositionFullName: String) = transaction { Counterexamples.deleteWhere { Counterexamples.propositionName eq propositionFullName } } } object Counterexamples : IntIdTable() { val propositionName: Column<String> = varchar("propositionName", 128).index() val arguments: Column<Blob> = blob("arguments") } class Counterexample(id: EntityID<Int>) : IntEntity(id) { var propositionName: String by Counterexamples.propositionName var arguments: Blob by Counterexamples.arguments companion object : IntEntityClass<Counterexample>(Counterexamples) }
mit
74166357955d97bbbae160b98bfb43ec
34.545455
98
0.677019
4.784965
false
false
false
false
AdamMc331/CashCaretaker
analytics/src/main/java/com/adammcneilly/cashcaretaker/analytics/FirebaseAnalyticsTracker.kt
1
1539
package com.adammcneilly.cashcaretaker.analytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase internal class FirebaseAnalyticsTracker : AnalyticsTracker { private val firebase = Firebase.analytics override fun trackAccountAdded() { firebase.logEvent(EVENT_ACCOUNT_ADDED, null) } override fun trackAccountClicked() { firebase.logEvent(EVENT_ACCOUNT_CLICKED, null) } override fun trackAccountDeleted() { firebase.logEvent(EVENT_ACCOUNT_DELETED, null) } override fun trackTransactionAdded() { firebase.logEvent(EVENT_TRANSACTION_ADDED, null) } override fun trackTransactionDeleted() { firebase.logEvent(EVENT_TRANSACTION_DELETED, null) } override fun trackTransactionEdited() { firebase.logEvent(EVENT_TRANSACTION_EDITED, null) } override fun trackTransferAdded() { firebase.logEvent(EVENT_TRANSFER_ADDED, null) } companion object { private const val EVENT_ACCOUNT_ADDED = "user_added_account" private const val EVENT_ACCOUNT_CLICKED = "user_clicked_account" private const val EVENT_ACCOUNT_DELETED = "user_deleted_account" private const val EVENT_TRANSACTION_ADDED = "user_added_transaction" private const val EVENT_TRANSACTION_EDITED = "user_edited_transaction" private const val EVENT_TRANSACTION_DELETED = "user_deleted_transaction" private const val EVENT_TRANSFER_ADDED = "user_added_transfer" } }
mit
1777823781d0215a75f046314a8ae2e5
31.0625
80
0.712151
4.48688
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/api/remote/RemoteStoreIntegrationTest.kt
1
30756
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api.remote import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.libraries.pcc.chronicle.analysis.DefaultChronicleContext import com.google.android.libraries.pcc.chronicle.analysis.DefaultPolicySet import com.google.android.libraries.pcc.chronicle.analysis.impl.ChroniclePolicyEngine import com.google.android.libraries.pcc.chronicle.api.Chronicle import com.google.android.libraries.pcc.chronicle.api.Connection import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest import com.google.android.libraries.pcc.chronicle.api.DataType import com.google.android.libraries.pcc.chronicle.api.ManagedDataType import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy import com.google.android.libraries.pcc.chronicle.api.ProcessorNode import com.google.android.libraries.pcc.chronicle.api.ReadConnection import com.google.android.libraries.pcc.chronicle.api.StorageMedia import com.google.android.libraries.pcc.chronicle.api.WriteConnection import com.google.android.libraries.pcc.chronicle.api.error.PolicyViolation import com.google.android.libraries.pcc.chronicle.api.flags.FakeFlagsReader import com.google.android.libraries.pcc.chronicle.api.flags.Flags import com.google.android.libraries.pcc.chronicle.api.getConnectionOrThrow import com.google.android.libraries.pcc.chronicle.api.integration.DefaultChronicle import com.google.android.libraries.pcc.chronicle.api.integration.DefaultDataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.policy.DefaultPolicyConformanceCheck import com.google.android.libraries.pcc.chronicle.api.policy.Policy import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import com.google.android.libraries.pcc.chronicle.api.policy.UsageType import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.remote.client.AidlTransport import com.google.android.libraries.pcc.chronicle.api.remote.client.ChronicleServiceConnector import com.google.android.libraries.pcc.chronicle.api.remote.client.DefaultRemoteStoreClient import com.google.android.libraries.pcc.chronicle.api.remote.client.DefaultRemoteStreamClient import com.google.android.libraries.pcc.chronicle.api.remote.client.ManualChronicleServiceConnector import com.google.android.libraries.pcc.chronicle.api.remote.serialization.ProtoSerializer import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteStoreServer import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteStreamServer import com.google.android.libraries.pcc.chronicle.api.remote.testutil.RandomProtoGenerator import com.google.android.libraries.pcc.chronicle.api.remote.testutil.SIMPLE_PROTO_MESSAGE_DTD import com.google.android.libraries.pcc.chronicle.api.remote.testutil.SimpleProtoMessage import com.google.android.libraries.pcc.chronicle.api.storage.EntityMetadata import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity import com.google.android.libraries.pcc.chronicle.api.storage.toProtoTimestamp import com.google.android.libraries.pcc.chronicle.remote.RemoteRouter import com.google.android.libraries.pcc.chronicle.remote.handler.RemoteServerHandlerFactory import com.google.android.libraries.pcc.chronicle.remote.impl.ClientDetailsProviderImpl import com.google.android.libraries.pcc.chronicle.remote.impl.RemoteContextImpl import com.google.android.libraries.pcc.chronicle.remote.impl.RemotePolicyCheckerImpl import com.google.android.libraries.pcc.chronicle.storage.datacache.ManagedDataCache import com.google.android.libraries.pcc.chronicle.storage.datacache.impl.DataCacheStorageImpl import com.google.android.libraries.pcc.chronicle.storage.stream.EntityStream import com.google.android.libraries.pcc.chronicle.storage.stream.ManagedEntityStreamServer import com.google.android.libraries.pcc.chronicle.storage.stream.impl.EntityStreamProviderImpl import com.google.android.libraries.pcc.chronicle.util.TimeSource import com.google.common.truth.Truth.assertThat import java.time.Duration import java.time.Instant import kotlin.test.assertFailsWith import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.Test import org.junit.runner.RunWith /** * Integration test exercising client-server remote connections using full chronicle instances in * each endpoint and communicating with one-another over in-process gRPC. * * TODO(b/195135029): Create a JUnit rule to make constructing new e2e tests easier. */ @RunWith(AndroidJUnit4::class) class RemoteStoreIntegrationTest { private val protoGenerator = RandomProtoGenerator(System.currentTimeMillis()) private val serviceConnector = ManualChronicleServiceConnector() @Test fun clientHasValidPolicy_serverHasInvalidPolicy(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(INVALID_POLICY_MISSING_FIELDS), enableStoreServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(VALID_POLICY), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageWriter::class.java, SimpleProtoMessageReader::class.java) } // Populate the store from the server. val serverWriteConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageWriter>(processorNode) serverWriteConnection.writeMessage(protoGenerator.generateSimpleProtoMessage()) // Get connection from our client "process"'s Chronicle. // - Getting a connection should pass, since at this point the only policy check performed is // on the client. val clientReadConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>(processorNode, VALID_POLICY) // Use the connection. This step should fail because the server-side check performed when the // connection impl sends a grpc message won't see a policy which allows egress of the full // data. val error = assertFailsWith<RemoteError> { clientReadConnection.getMessages() } assertThat(error.metadata.errorType).isEqualTo(RemoteErrorMetadata.Type.POLICY_VIOLATION) } @Test fun clientHasInvalidPolicy_serverHasValidPolicy(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(VALID_POLICY), enableStoreServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(INVALID_POLICY_MISSING_FIELDS), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageWriter::class.java, SimpleProtoMessageReader::class.java) } // Populate the store from the server. val serverWriteConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageWriter>(processorNode) serverWriteConnection.writeMessage(protoGenerator.generateSimpleProtoMessage()) // Get connection from our client "process"'s Chronicle. // - Getting a connection should fail, since at this point we are checking policy at the // client. assertFailsWith<PolicyViolation> { client.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>( processorNode, INVALID_POLICY_MISSING_FIELDS ) } } @Test fun clientWrites_clientAndServerRead(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(VALID_POLICY), enableStoreServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(VALID_POLICY), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageWriter::class.java, SimpleProtoMessageReader::class.java) } // Get connections from our client "process"'s Chronicle val clientWriteConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessageWriter>(processorNode, VALID_POLICY) val clientReadConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>(processorNode, VALID_POLICY) // Get connection from our server "process"'s Chronicle val serverReadConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>(processorNode, VALID_POLICY) // Create some data. val messageA = protoGenerator.generateDistinctSimpleProtoMessage() val messageB = protoGenerator.generateDistinctSimpleProtoMessage(messageA) // Write from the client. clientWriteConnection.writeMessage(messageA) clientWriteConnection.writeMessage(messageB) // Verify that the client and server each have *both* written objects. assertThat(clientReadConnection.getMessages()).containsExactly(messageA, messageB) assertThat(serverReadConnection.getMessages()).containsExactly(messageA, messageB) } @Test fun serverWrites_clientAndServerRead(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(VALID_POLICY), enableStoreServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(VALID_POLICY), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageWriter::class.java, SimpleProtoMessageReader::class.java) } // Get connections from our server "process"'s Chronicle val serverWriteConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageWriter>(processorNode, VALID_POLICY) val serverReadConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>(processorNode, VALID_POLICY) // Get connection from our client "process"'s Chronicle val clientReadConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessageReader>(processorNode, VALID_POLICY) // Create some data. val messageA = protoGenerator.generateDistinctSimpleProtoMessage() val messageB = protoGenerator.generateDistinctSimpleProtoMessage(messageA) // Write from the server. serverWriteConnection.writeMessage(messageA) serverWriteConnection.writeMessage(messageB) // Verify that the client and server each have *both* written objects. assertThat(clientReadConnection.getMessages()).containsExactly(messageA, messageB) assertThat(serverReadConnection.getMessages()).containsExactly(messageA, messageB) } @OptIn(ExperimentalCoroutinesApi::class) // for CoroutineStart.ATOMIC @Test fun clientAndServerBothPublishAndSubscribe(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(VALID_POLICY), enableStreamServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(VALID_POLICY), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageSubscriber::class.java, SimpleProtoMessagePublisher::class.java) } // Get connections from our client "process"'s Chronicle val clientWriteConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessagePublisher>( processorNode, VALID_POLICY ) val clientReadConnection = client.chronicle.getConnectionOrThrow<SimpleProtoMessageSubscriber>( processorNode, VALID_POLICY ) // Get connections from our server "process"'s Chronicle val serverWriteConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessagePublisher>( processorNode, VALID_POLICY ) val serverReadConnection = server.chronicle.getConnectionOrThrow<SimpleProtoMessageSubscriber>( processorNode, VALID_POLICY ) // Create some data. val messageA = protoGenerator.generateDistinctSimpleProtoMessage() val messageB = protoGenerator.generateDistinctSimpleProtoMessage(messageA) val messagesReceivedByClient = mutableListOf<SimpleProtoMessage>() val messagesReceivedByServer = mutableListOf<SimpleProtoMessage>() val clientSubscription = launch(start = CoroutineStart.ATOMIC) { clientReadConnection.subscribe().take(2).collect { messagesReceivedByClient.add(it) } } val serverSubscription = launch(start = CoroutineStart.ATOMIC) { serverReadConnection.subscribe().take(2).collect { messagesReceivedByServer.add(it) } } withContext(Dispatchers.Default) { // Write from the server and the client. clientWriteConnection.publish(messageA) serverWriteConnection.publish(messageB) // Wait until both subscribers have seen both messages. clientSubscription.join() serverSubscription.join() // Verify that the client and server each received both objects. assertThat(messagesReceivedByClient).containsExactly(messageA, messageB).inOrder() assertThat(messagesReceivedByServer).containsExactly(messageA, messageB).inOrder() } } @Test fun serverCanServeBothStoreAndStreamConnectionsSimultaneously(): Unit = runBlocking { // Initialize our "processes". val server = ServerProcess(setOf(VALID_POLICY), enableStoreServer = true, enableStreamServer = true) serviceConnector.binder = server.router val client = ClientProcess(setOf(VALID_POLICY), serviceConnector) // Put together a simple processor node we can use to access both connection types. val processorNode = object : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> = setOf(SimpleProtoMessageSubscriber::class.java, SimpleProtoMessagePublisher::class.java) } // Get connections from our client "process"'s Chronicle client.chronicle.getConnectionOrThrow<SimpleProtoMessagePublisher>(processorNode, VALID_POLICY) client.chronicle.getConnectionOrThrow<SimpleProtoMessageSubscriber>(processorNode, VALID_POLICY) // Get connections from our server "process"'s Chronicle server.chronicle.getConnectionOrThrow<SimpleProtoMessagePublisher>(processorNode, VALID_POLICY) server.chronicle.getConnectionOrThrow<SimpleProtoMessageSubscriber>(processorNode, VALID_POLICY) } /** * Generates a new [SimpleProtoMessage] with distinct [SimpleProtoMessage.getStringField] values * from any of the [distinctFrom] values. */ private fun RandomProtoGenerator.generateDistinctSimpleProtoMessage( vararg distinctFrom: SimpleProtoMessage ): SimpleProtoMessage { val stringFieldValuesToAvoid = distinctFrom.map { it.stringField }.toSet() var message: SimpleProtoMessage do { message = generateSimpleProtoMessage() } while (message.stringField in stringFieldValuesToAvoid) return message } /** * Defines what amounts to a "Process" acting as a client in a Client-Server remote storage * scenario. * * @param policies set of [Policies][Policy] to support in the [chronicle] instance. */ class ClientProcess(policies: Set<Policy>, serviceConnector: ChronicleServiceConnector) { private val fakeTime = Instant.now() private val timeSource = TimeSource { fakeTime } private val configReader = FakeFlagsReader(Flags()) /** Client store which connects to the server running in the [ServerProcess]. */ private val remoteStoreClient = DefaultRemoteStoreClient( dataTypeName = SIMPLE_PROTO_MESSAGE_DTD.name, serializer = ProtoSerializer.createFrom(SimpleProtoMessage.getDefaultInstance()), transport = AidlTransport(serviceConnector) ) private val remoteStreamClient = DefaultRemoteStreamClient( dataTypeName = SIMPLE_PROTO_MESSAGE_DTD.name, serializer = ProtoSerializer.createFrom(SimpleProtoMessage.getDefaultInstance()), transport = AidlTransport(serviceConnector) ) /** * Connection provider instance using the [remoteStoreClient] to back the * [SimpleProtoMessageReader]/[SimpleProtoMessageWriter] interfaces. */ private val connectionProvider = object : ConnectionProvider { override val dataType = object : DataType { override val descriptor = SIMPLE_PROTO_MESSAGE_DTD override val managementStrategy = MANAGEMENT_STRATEGY override val connectionTypes = setOf( SimpleProtoMessageReader::class.java, SimpleProtoMessageWriter::class.java, SimpleProtoMessageSubscriber::class.java, SimpleProtoMessagePublisher::class.java ) } override fun getConnection( connectionRequest: ConnectionRequest<out Connection> ): Connection { return when (connectionRequest.connectionType) { SimpleProtoMessageReader::class.java -> object : SimpleProtoMessageReader { override suspend fun getMessages(): List<SimpleProtoMessage> { return remoteStoreClient .fetchAll(connectionRequest.policy) .map { it.entity } .toList() } } SimpleProtoMessageWriter::class.java -> object : SimpleProtoMessageWriter { override suspend fun writeMessage(message: SimpleProtoMessage) { val timestamp = timeSource.now().toProtoTimestamp() remoteStoreClient.create( connectionRequest.policy, listOf( WrappedEntity( EntityMetadata.newBuilder() .setId(message.toString()) .setCreated(timestamp) .setUpdated(timestamp) .build(), message ) ) ) } } SimpleProtoMessageSubscriber::class.java -> object : SimpleProtoMessageSubscriber { override fun subscribe(): Flow<SimpleProtoMessage> { return remoteStreamClient.subscribe(connectionRequest.policy).map { it.entity } } } SimpleProtoMessagePublisher::class.java -> object : SimpleProtoMessagePublisher { override suspend fun publish(message: SimpleProtoMessage) { remoteStreamClient.publish( connectionRequest.policy, listOf( WrappedEntity( EntityMetadata.newBuilder().setId(message.toString()).build(), message ) ) ) } } else -> throw IllegalArgumentException("not supported: $connectionRequest") } } } /** [Chronicle] instance "running" in the client "process". */ val chronicle: Chronicle = DefaultChronicle( chronicleContext = DefaultChronicleContext( setOf(connectionProvider), emptySet(), DefaultPolicySet(policies), DefaultDataTypeDescriptorSet(setOf(connectionProvider.dataType.descriptor)) ), policyEngine = ChroniclePolicyEngine(), config = DefaultChronicle.Config( DefaultChronicle.Config.PolicyMode.STRICT, DefaultPolicyConformanceCheck() ), flags = configReader ) } /** * Defines what amounts to a "Process" acting as a server in a Client-Server remote storage * scenario. Currently, remote connection servers are either Store or Stream servers, not both * simultaneously. This construct represents what we have in reality at this point in time, though * technically Chronicle can support having both simultaneously. * * @param policies set of [Policies][Policy] to support in the [chronicle] instance. * @param enableStoreServer use the internal [simpleProtoMessageStoreServer] when serving * connections. * @param enableStreamServer use the internal [simpleProtoMessageStreamServer] when serving * connections. */ class ServerProcess( private val policies: Set<Policy>, enableStoreServer: Boolean = false, enableStreamServer: Boolean = false ) { private val fakeTime = Instant.now() private val timeSource = TimeSource { fakeTime } private val dataCache = DataCacheStorageImpl(timeSource) private val configReader = FakeFlagsReader(Flags()) /** Actual store containing [SimpleProtoMessage] objects. */ private val managedDataCache = ManagedDataCache( entityClass = SimpleProtoMessage::class.java, cache = dataCache, maxSize = 100, ttl = MANAGEMENT_STRATEGY.ttl!!, dataTypeDescriptor = SIMPLE_PROTO_MESSAGE_DTD ) /** [RemoteStoreServer] instance to expose the [managedDataCache] to the client "process". */ private val simpleProtoMessageStoreServer = object : RemoteStoreServer<SimpleProtoMessage> { override val dataType = ManagedDataType( SIMPLE_PROTO_MESSAGE_DTD, managedDataCache.managementStrategy, setOf(SimpleProtoMessageReader::class.java, SimpleProtoMessageWriter::class.java) ) override val dataTypeDescriptor = SIMPLE_PROTO_MESSAGE_DTD override val serializer = ProtoSerializer.createFrom(SimpleProtoMessage.getDefaultInstance()) override fun getConnection( connectionRequest: ConnectionRequest<out Connection> ): Connection = when (connectionRequest.connectionType) { SimpleProtoMessageReader::class.java -> SimpleProtoMessageReaderImpl(managedDataCache) SimpleProtoMessageWriter::class.java -> SimpleProtoMessageWriterImpl(managedDataCache, timeSource) else -> throw IllegalArgumentException("not supported: $connectionRequest") } override suspend fun count(policy: Policy?): Int = throw NotImplementedError("") override fun fetchById( policy: Policy?, ids: List<String> ): Flow<List<WrappedEntity<SimpleProtoMessage>>> = flow { emit(ids.mapNotNull { managedDataCache.get(it) }) } override fun fetchAll(policy: Policy?): Flow<List<WrappedEntity<SimpleProtoMessage>>> = flow { emit(managedDataCache.all()) } override suspend fun create( policy: Policy?, wrappedEntities: List<WrappedEntity<SimpleProtoMessage>> ) { wrappedEntities.forEach { if (managedDataCache.get(it.entity.stringField) == null) { managedDataCache.put(it) } } } override suspend fun update( policy: Policy?, wrappedEntities: List<WrappedEntity<SimpleProtoMessage>> ) = wrappedEntities.forEach { managedDataCache.put(it) } override suspend fun deleteAll(policy: Policy?) = managedDataCache.removeAll() override suspend fun deleteById(policy: Policy?, ids: List<String>) = ids.forEach { managedDataCache.remove(it) } } private val entityStreamProvider = EntityStreamProviderImpl() /** * [RemoteStreamServer] instance to expose the [entityStreamProvider] to the client "process". */ private val simpleProtoMessageStreamServer: RemoteStreamServer<SimpleProtoMessage> = ManagedEntityStreamServer( SIMPLE_PROTO_MESSAGE_DTD, ProtoSerializer.createFrom(SimpleProtoMessage.getDefaultInstance()), entityStreamProvider, mapOf< Class<out Connection>, (ConnectionRequest<out Connection>, EntityStream<SimpleProtoMessage>) -> Connection >( SimpleProtoMessageSubscriber::class.java to { _, stream: EntityStream<SimpleProtoMessage> -> object : SimpleProtoMessageSubscriber { override fun subscribe(): Flow<SimpleProtoMessage> { return stream.subscribe().map { it.entity } } } }, SimpleProtoMessagePublisher::class.java to { _, stream: EntityStream<SimpleProtoMessage> -> object : SimpleProtoMessagePublisher { override suspend fun publish(message: SimpleProtoMessage) { stream.publish( WrappedEntity( EntityMetadata.newBuilder().setId(message.toString()).build(), message ) ) } } } ) ) val servers = buildSet { if (enableStoreServer) add(simpleProtoMessageStoreServer) if (enableStreamServer) add(simpleProtoMessageStreamServer) } /** [Chronicle] instance "running" in the server "process". */ val chronicle: Chronicle = DefaultChronicle( chronicleContext = DefaultChronicleContext( servers, emptySet(), DefaultPolicySet(policies), DefaultDataTypeDescriptorSet(servers.map { it.dataTypeDescriptor }.toSet()) ), policyEngine = ChroniclePolicyEngine(), config = DefaultChronicle.Config( DefaultChronicle.Config.PolicyMode.STRICT, DefaultPolicyConformanceCheck() ), flags = configReader ) val router: RemoteRouter = RemoteRouter( CoroutineScope(SupervisorJob()), RemoteContextImpl(servers), RemotePolicyCheckerImpl(chronicle, DefaultPolicySet(policies)), RemoteServerHandlerFactory(), ClientDetailsProviderImpl(ApplicationProvider.getApplicationContext()) ) } interface SimpleProtoMessageReader : ReadConnection { suspend fun getMessages(): List<SimpleProtoMessage> } class SimpleProtoMessageReaderImpl(val managedDataCache: ManagedDataCache<SimpleProtoMessage>) : SimpleProtoMessageReader { override suspend fun getMessages(): List<SimpleProtoMessage> { return managedDataCache.all().map { it.entity } } } interface SimpleProtoMessageWriter : WriteConnection { suspend fun writeMessage(message: SimpleProtoMessage) } class SimpleProtoMessageWriterImpl( val managedDataCache: ManagedDataCache<SimpleProtoMessage>, val timeSource: TimeSource ) : SimpleProtoMessageWriter { override suspend fun writeMessage(message: SimpleProtoMessage) { managedDataCache.put( WrappedEntity(EntityMetadata(message.stringField, "no-package", timeSource.now()), message) ) } } interface SimpleProtoMessageSubscriber : ReadConnection { fun subscribe(): Flow<SimpleProtoMessage> } interface SimpleProtoMessagePublisher : WriteConnection { suspend fun publish(message: SimpleProtoMessage) } companion object { private val MANAGEMENT_STRATEGY = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofDays(1) ) private val VALID_POLICY = policy("SimpleProtoMessagePolicy", "Read") { description = "Valid policy for egressing SimpleProtoMessages" target(SIMPLE_PROTO_MESSAGE_DTD, Duration.ofDays(2)) { retention(StorageMedium.RAM, false) "double_field" { rawUsage(UsageType.EGRESS) } "float_field" { rawUsage(UsageType.EGRESS) } "int_field" { rawUsage(UsageType.EGRESS) } "unsigned_int_field" { rawUsage(UsageType.EGRESS) } "signed_int_field" { rawUsage(UsageType.EGRESS) } "fixed_width_int_field" { rawUsage(UsageType.EGRESS) } "signed_fixed_width_int_field" { rawUsage(UsageType.EGRESS) } "long_field" { rawUsage(UsageType.EGRESS) } "unsigned_long_field" { rawUsage(UsageType.EGRESS) } "signed_long_field" { rawUsage(UsageType.EGRESS) } "fixed_width_long_field" { rawUsage(UsageType.EGRESS) } "signed_fixed_width_long_field" { rawUsage(UsageType.EGRESS) } "bool_field" { rawUsage(UsageType.EGRESS) } "string_field" { rawUsage(UsageType.EGRESS) } "enum_field" { rawUsage(UsageType.EGRESS) } } } private val INVALID_POLICY_MISSING_FIELDS = policy("SimpleProtoMessagePolicy", "Read") { description = "Valid policy for egressing SimpleProtoMessages" target(SIMPLE_PROTO_MESSAGE_DTD, Duration.ofDays(2)) { retention(StorageMedium.RAM, false) "bool_field" { rawUsage(UsageType.EGRESS) } "string_field" { rawUsage(UsageType.EGRESS) } "enum_field" { rawUsage(UsageType.EGRESS) } } } } }
apache-2.0
40a35e9fc0e74e368646f4b29b7cd0c8
42.07563
100
0.712641
4.895893
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/extensions/ApiAction.kt
1
8325
/* * 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 import jp.nephy.penicillin.core.exceptions.PenicillinException import jp.nephy.penicillin.core.i18n.LocalizedString import jp.nephy.penicillin.core.request.action.ApiAction import kotlinx.coroutines.* import mu.KotlinLogging /** * Awaits api execution and returns its result. * This function is suspend-function. * * @return Api result as [R]. * * @throws PenicillinException General Penicillin exceptions. * @throws CancellationException Thrown when coroutine scope is cancelled. */ @Throws(PenicillinException::class, CancellationException::class) suspend fun <R: Any> ApiAction<R>.execute(): R { return invoke() } /** * Awaits api execution and returns its result with timeout. * This function is suspend-function. * * @param timeoutInMillis Timeout value in millis. * * @return Api result as [R]. If the timeout exceeds, returns null. * * @throws PenicillinException General Penicillin exceptions. * @throws CancellationException Thrown when coroutine scope is cancelled. */ @Throws(PenicillinException::class, CancellationException::class) suspend fun <R: Any> ApiAction<R>.executeWithTimeout(timeoutInMillis: Long): R? { return withTimeoutOrNull(timeoutInMillis) { execute() } } /** * Awaits api execution and returns its result with user-defined or default timeout. * This function is suspend-function. * * @return Api result as [R]. If the timeout exceeds, returns null. * * @throws PenicillinException General Penicillin exceptions. * @throws CancellationException Thrown when coroutine scope is cancelled. */ @Throws(PenicillinException::class, CancellationException::class) suspend fun <R: Any> ApiAction<R>.executeWithTimeout(): R? { return executeWithTimeout(session.option.defaultTimeoutInMillis) } /** * Creates [Deferred] object for api execution. * * @return [Deferred] object for api execution. */ fun <R: Any> ApiAction<R>.executeAsync(): Deferred<R> { return session.async { execute() } } /** * Completes api execution and returns its result. * This operation is blocking. * * @return Api result as [R]. * * @throws PenicillinException General Penicillin exceptions. */ @Throws(PenicillinException::class) fun <R: Any> ApiAction<R>.complete(): R { return runBlocking(session.coroutineContext) { execute() } } /** * Completes api execution and returns its result with timeout. * This operation is blocking. * * @param timeoutInMillis Timeout value in millis. * * @return Api result as [R]. If the timeout exceeds, returns null. * * @throws PenicillinException General Penicillin exceptions. */ @Throws(PenicillinException::class) fun <R: Any> ApiAction<R>.completeWithTimeout(timeoutInMillis: Long): R? { return completeWithTimeout(timeoutInMillis) } /** * Completes api execution and returns its result with user-defined or default timeout. * This operation is blocking. * * @return Api result as [R]. If the timeout exceeds, returns null. * * @throws PenicillinException General Penicillin exceptions. */ @Throws(PenicillinException::class) fun <R: Any> ApiAction<R>.completeWithTimeout(): R? { return completeWithTimeout(session.option.defaultTimeoutInMillis) } private val defaultLogger = KotlinLogging.logger("Penicillin.Client") internal typealias ApiCallback<R> = suspend (response: R) -> Unit internal typealias ApiFallback = suspend (e: Throwable) -> Unit @PublishedApi internal val <R: Any> ApiAction<R>.defaultApiCallback: ApiCallback<R> get() = {} @PublishedApi internal val ApiAction<*>.defaultApiFallback: ApiFallback get() = { defaultLogger.error(it) { LocalizedString.ExceptionInAsyncBlock } } /** * Creates [Job] for api execution. * * @param onFailure Api fallback. * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queue(crossinline onFailure: ApiFallback, crossinline onSuccess: ApiCallback<R>): Job { return session.launch { runCatching { execute() }.onSuccess { onSuccess.invoke(it) }.onFailure { onFailure.invoke(it) } } } /** * Creates [Job] for api execution with default api fallback. * * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queue(crossinline onSuccess: ApiCallback<R>): Job { return queue(defaultApiFallback, onSuccess) } /** * Creates [Job] for api execution with default api fallback and default api callback. * * @return [Job] for api execution. */ fun <R: Any> ApiAction<R>.queue(): Job { return queue(defaultApiFallback, defaultApiCallback) } /** * Creates [Job] for api execution with timeout. * * @param timeoutInMillis Timeout value in millis. * @param onFailure Api fallback. * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queueWithTimeout(timeoutInMillis: Long, crossinline onFailure: ApiFallback, crossinline onSuccess: ApiCallback<R>): Job { return session.launch { runCatching { withTimeout(timeoutInMillis) { execute() } }.onSuccess { onSuccess.invoke(it) }.onFailure { onFailure.invoke(it) } } } /** * Creates [Job] for api execution with timeout and default api fallback. * * @param timeoutInMillis Timeout value. * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queueWithTimeout(timeoutInMillis: Long, crossinline onSuccess: ApiCallback<R>): Job { return queueWithTimeout(timeoutInMillis, defaultApiFallback, onSuccess) } /** * Creates [Job] for api execution with timeout and default api fallback, default api callback. * * @param timeoutInMillis Timeout value in millis. * * @return [Job] for api execution. */ fun <R: Any> ApiAction<R>.queueWithTimeout(timeoutInMillis: Long): Job { return queueWithTimeout(timeoutInMillis, defaultApiFallback, {}) } /** * Creates [Job] for api execution with user-defined or default timeout. * * @param onFailure Api fallback. * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queueWithTimeout(crossinline onFailure: ApiFallback, crossinline onSuccess: ApiCallback<R>): Job { return queueWithTimeout(session.option.defaultTimeoutInMillis, onFailure, onSuccess) } /** * Creates [Job] for api execution with user-defined or default timeout and default api fallback. * * @param onSuccess Api callback. * * @return [Job] for api execution. */ inline fun <R: Any> ApiAction<R>.queueWithTimeout(crossinline onSuccess: ApiCallback<R>): Job { return queueWithTimeout(defaultApiFallback, onSuccess) } /** * Creates [Job] for api execution with user-defined or default timeout, default api fallback and default api callback. * * @return [Job] for api execution. */ fun <R: Any> ApiAction<R>.queueWithTimeout(): Job { return queueWithTimeout(defaultApiFallback, defaultApiCallback) }
mit
e5737904e7868e46c58ed99e018360d9
30.296992
154
0.721321
4.109082
false
false
false
false
jayrave/falkon
falkon-mapper/src/main/kotlin/com/jayrave/falkon/mapper/lib/CompiledQueryExtn.kt
1
9691
package com.jayrave.falkon.mapper.lib import com.jayrave.falkon.engine.CompiledStatement import com.jayrave.falkon.engine.Source import com.jayrave.falkon.mapper.Column import com.jayrave.falkon.mapper.ReadOnlyColumn import com.jayrave.falkon.mapper.Realizer import com.jayrave.falkon.mapper.Table import java.util.* /** * Same as [extractFirstModel] but also closes [CompiledStatement] * @see extractFirstModel */ fun <T : Any> CompiledStatement<Source>.extractFirstModelAndClose( forTable: Table<T, *>, columnNameExtractor: ((Column<T, *>) -> String)): T? { return extractFirstModelAndClose( forTable.buildRealizer(), columnNameExtractor.castToUseWithRealizer() ) } /** * Same as [extractAllModels] but also closes [CompiledStatement] * @see extractAllModels */ fun <T : Any> CompiledStatement<Source>.extractAllModelsAndClose( forTable: Table<T, *>, toList: MutableList<T> = buildNewMutableList(), columnNameExtractor: ((Column<T, *>) -> String)): List<T> { return extractAllModelsAndClose( forTable.buildRealizer(), toList, columnNameExtractor.castToUseWithRealizer() ) } /** * Same as [extractModels] but also closes [CompiledStatement] * @see extractModels */ fun <T : Any> CompiledStatement<Source>.extractModelsAndClose( forTable: Table<T, *>, toList: MutableList<T> = buildNewMutableList(), maxNumberOfModelsToExtract: Int = Int.MAX_VALUE, columnNameExtractor: ((Column<T, *>) -> String)): List<T> { return extractModelsAndClose( forTable.buildRealizer(), toList, maxNumberOfModelsToExtract, columnNameExtractor.castToUseWithRealizer() ) } /** * Same as [extractModels] except that only the first model is extracted * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractFirstModelAndClose] * * @see extractFirstModelAndClose */ fun <T : Any> CompiledStatement<Source>.extractFirstModel( forTable: Table<T, *>, columnNameExtractor: ((Column<T, *>) -> String)): T? { return extractFirstModel( forTable.buildRealizer(), columnNameExtractor.castToUseWithRealizer() ) } /** * Same as [extractModels] except that all models are extracted * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractAllModelsAndClose] * * @see extractAllModelsAndClose */ fun <T : Any> CompiledStatement<Source>.extractAllModels( forTable: Table<T, *>, toList: MutableList<T> = buildNewMutableList(), columnNameExtractor: ((Column<T, *>) -> String)): List<T> { return extractAllModels( forTable.buildRealizer(), toList, columnNameExtractor.castToUseWithRealizer() ) } /** * Execute the [CompiledStatement] & extract an instance of [T] out of each row that is * returned. This is done through [Table.create] * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractModelsAndClose] * * @param [forTable] which manages the [T] & whose [Table.create] function is called * @param [toList] to which the created instances must be added. By default an [ArrayList] is used * @param [maxNumberOfModelsToExtract] at the most only these number of models will be extracted * @param [columnNameExtractor] used to extract the name that should be used to find the * appropriate column in [Source] that will created by executing this [CompiledStatement] * * @return is the same as [toList] * @see extractModelsAndClose */ fun <T : Any> CompiledStatement<Source>.extractModels( forTable: Table<T, *>, toList: MutableList<T> = buildNewMutableList(), maxNumberOfModelsToExtract: Int = Int.MAX_VALUE, columnNameExtractor: ((Column<T, *>) -> String)): List<T> { return extractModels( forTable.buildRealizer(), toList, maxNumberOfModelsToExtract, columnNameExtractor.castToUseWithRealizer() ) } /** * Same as [extractFirstModel] but also closes [CompiledStatement] * @see extractFirstModel */ fun <T : Any> CompiledStatement<Source>.extractFirstModelAndClose( realizer: Realizer<T>, columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): T? { return safeCloseAfterOp { extractFirstModel(realizer, columnNameExtractor) } } /** * Same as [extractAllModels] but also closes [CompiledStatement] * @see extractAllModels */ fun <T : Any> CompiledStatement<Source>.extractAllModelsAndClose( realizer: Realizer<T>, toList: MutableList<T> = buildNewMutableList(), columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): List<T> { return safeCloseAfterOp { extractAllModels(realizer, toList, columnNameExtractor) } } /** * Same as [extractModels] but also closes [CompiledStatement] * @see extractModels */ fun <T : Any> CompiledStatement<Source>.extractModelsAndClose( realizer: Realizer<T>, toList: MutableList<T> = buildNewMutableList(), maxNumberOfModelsToExtract: Int = Int.MAX_VALUE, columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): List<T> { return safeCloseAfterOp { extractModels(realizer, toList, maxNumberOfModelsToExtract, columnNameExtractor) } } /** * Same as [extractModels] except that only the first model is extracted * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractFirstModelAndClose] * * @see extractFirstModelAndClose */ fun <T : Any> CompiledStatement<Source>.extractFirstModel( realizer: Realizer<T>, columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): T? { val models = extractModels( realizer = realizer, toList = LinkedList(), maxNumberOfModelsToExtract = 1, columnNameExtractor = columnNameExtractor ) return models.firstOrNull() } /** * Same as [extractModels] except that all models are extracted * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractAllModelsAndClose] * * @see extractAllModelsAndClose */ fun <T : Any> CompiledStatement<Source>.extractAllModels( realizer: Realizer<T>, toList: MutableList<T> = buildNewMutableList(), columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): List<T> { return extractModels( realizer = realizer, toList = toList, columnNameExtractor = columnNameExtractor ) } /** * Execute the [CompiledStatement] & extract an instance of [T] out of each row that is * returned. This is done through [Realizer.realize] * * *NOTE:* [CompiledStatement] isn't closed after execution. If that is preferred, checkout * [extractModelsAndClose] * * @param [realizer] whose [Realizer.realize] function will be called to realize instance * @param [toList] to which the realized instances must be added. By default an [ArrayList] is used * @param [maxNumberOfModelsToExtract] at the most only these number of models will be extracted * @param [columnNameExtractor] used to extract the name that should be used to find the * appropriate column in [Source] that will created by executing this [CompiledStatement] * * @return is the same as [toList] * @see extractModelsAndClose */ fun <T : Any> CompiledStatement<Source>.extractModels( realizer: Realizer<T>, toList: MutableList<T> = buildNewMutableList(), maxNumberOfModelsToExtract: Int = Int.MAX_VALUE, columnNameExtractor: ((ReadOnlyColumn<*>) -> String)): List<T> { val source = execute() source.safeCloseAfterOp { val dataProducer = SourceBackedDataProducer(source) val columnIndexExtractor = buildColumnIndexExtractor(source, columnNameExtractor) while (source.moveToNext() && toList.size < maxNumberOfModelsToExtract) { toList.add(realizer.createInstanceFrom(dataProducer, columnIndexExtractor)) } return toList } } /** * By default [ArrayList] is used */ private fun <T> buildNewMutableList() = ArrayList<T>() /** * Builds a [Realizer] backed by [Table] */ private fun <T : Any> Table<T, *>.buildRealizer(): Realizer<T> = TableBackedRealizer(this) @Suppress("UNCHECKED_CAST") private fun <T : Any> ((Column<T, *>) -> String).castToUseWithRealizer(): ((ReadOnlyColumn<*>) -> String) = this as ((ReadOnlyColumn<*>) -> String) /** * Builds a column index extractor that looks up the index once & then caches it * for later use */ private fun buildColumnIndexExtractor( source: Source, columnNameExtractor: (ReadOnlyColumn<*>) -> String): (ReadOnlyColumn<*>) -> Int { val columnPositionMap = HashMap<ReadOnlyColumn<*>, Int>() return { column: ReadOnlyColumn<*> -> var index = columnPositionMap[column] // Check if the index is in cache if (index == null) { val columnName = columnNameExtractor.invoke(column) columnPositionMap[column] = source.getColumnIndex(columnName) // Put in cache index = columnPositionMap[column] } index!! } } /** * Used to build a instance of [T] */ private fun <T : Any> Realizer<T>.createInstanceFrom( dataProducer: SourceBackedDataProducer, columnIndexExtractor: ((ReadOnlyColumn<*>) -> Int)): T { return realize(object : Realizer.Value { override fun <C> of(column: ReadOnlyColumn<C>): C { // Update data producer to point to the current column dataProducer.setColumnIndex(columnIndexExtractor.invoke(column)) return column.computePropertyFrom(dataProducer) } }) }
apache-2.0
a8032a5260ece94fb42c473504a070c2
32.42069
99
0.692601
4.411015
false
false
false
false
square/kotlinpoet
kotlinpoet/src/main/java/com/squareup/kotlinpoet/Taggable.kt
1
5892
/* * Copyright (C) 2019 Square, 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.kotlinpoet import kotlin.reflect.KClass /** A type that can be tagged with extra metadata of the user's choice. */ public interface Taggable { /** Returns all tags. */ public val tags: Map<KClass<*>, Any> get() = emptyMap() /** Returns the tag attached with [type] as a key, or null if no tag is attached with that key. */ public fun <T : Any> tag(type: Class<T>): T? = tag(type.kotlin) /** Returns the tag attached with [type] as a key, or null if no tag is attached with that key. */ public fun <T : Any> tag(type: KClass<T>): T? { @Suppress("UNCHECKED_CAST") return tags[type] as T? } /** The builder analogue to [Taggable] types. */ public interface Builder<out T : Builder<T>> { /** Mutable map of the current tags this builder contains. */ public val tags: MutableMap<KClass<*>, Any> /** * Attaches [tag] to the request using [type] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [type]. * * Use this API to attach originating elements, debugging, or other application data to a spec * so that you may read it in other APIs or callbacks. */ public fun tag(type: Class<*>, tag: Any?): T = tag(type.kotlin, tag) /** * Attaches [tag] to the request using [type] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [type]. * * Use this API to attach originating elements, debugging, or other application data to a spec * so that you may read it in other APIs or callbacks. */ @Suppress("UNCHECKED_CAST") public fun tag(type: KClass<*>, tag: Any?): T = apply { if (tag == null) { this.tags.remove(type) } else { this.tags[type] = tag } } as T } } /** Returns the tag attached with [T] as a key, or null if no tag is attached with that key. */ public inline fun <reified T : Any> Taggable.tag(): T? = tag(T::class) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> AnnotationSpec.Builder.tag(tag: T?): AnnotationSpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> FileSpec.Builder.tag(tag: T?): FileSpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> FunSpec.Builder.tag(tag: T?): FunSpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> ParameterSpec.Builder.tag(tag: T?): ParameterSpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> PropertySpec.Builder.tag(tag: T?): PropertySpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> TypeAliasSpec.Builder.tag(tag: T?): TypeAliasSpec.Builder = tag(T::class, tag) /** * Attaches [tag] to the request using [T] as a key. Tags can be read from a * request using [Taggable.tag]. Use `null` to remove any existing tag assigned for * [T]. * * Use this API to attach debugging or other application data to a spec so that you may read it in * other APIs or callbacks. */ public inline fun <reified T : Any> TypeSpec.Builder.tag(tag: T?): TypeSpec.Builder = tag(T::class, tag) internal fun Taggable.Builder<*>.buildTagMap(): TagMap = TagMap(tags) @JvmInline internal value class TagMap private constructor(override val tags: Map<KClass<*>, Any>) : Taggable { companion object { operator fun invoke(tags: Map<KClass<*>, Any>): TagMap = TagMap(tags.toImmutableMap()) } }
apache-2.0
e4d2d780789ba58830791c8d980b9bff
36.291139
100
0.681432
3.715006
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/adapters/SelectAppAdapter.kt
1
1662
package com.androidvip.hebf.adapters import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.R import com.androidvip.hebf.goAway import com.androidvip.hebf.models.App class SelectAppAdapter(private val activity: Activity, private val apps: List<App>) : RecyclerView.Adapter<SelectAppAdapter.ViewHolder>() { var selectedApp: App? = null class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var label: TextView = v.findViewById(R.id.app_nome) var icon: ImageView = v.findViewById(R.id.icon) var checkBox: CheckBox = v.findViewById(R.id.force_stop_apps_check) init { setIsRecyclable(false) checkBox.goAway() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(activity).inflate(R.layout.list_item_small_app, parent, false) return ViewHolder(v).apply { setIsRecyclable(false) } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = apps[holder.adapterPosition] holder.checkBox.setOnCheckedChangeListener(null) holder.itemView.setOnClickListener { selectedApp = app } holder.label.text = app.label holder.icon.setImageDrawable(app.icon) } override fun getItemCount(): Int { return apps.size } }
apache-2.0
51c3341e5448da626ea261acdac757b0
29.796296
139
0.703971
4.316883
false
false
false
false
passsy/gradle-gitVersioner-plugin
gitversioner/src/main/java/com/pascalwelsch/gitversioner/GitVersionerPlugin.kt
1
4449
package com.pascalwelsch.gitversioner import org.gradle.api.Plugin import org.gradle.api.Project import java.util.Properties @Suppress("RedundantVisibilityModifier") public class GitVersionerPlugin : Plugin<Project> { override fun apply(project: Project) { val rootProject = project.rootProject if (project != rootProject) { throw IllegalStateException( "Register the 'com.pascalwelsch.gitversioner' plugin only once " + "in the root project build.gradle." ) } // add extension to root project, makes sense only once per project val gitVersionExtractor = ShellGitInfoExtractor(rootProject) val gitVersioner = rootProject.extensions.create( "gitVersioner", GitVersioner::class.java, gitVersionExtractor, project.logger ) project.task("gitVersion").apply { group = "Help" description = "Displays the version information extracted from git history" doLast { with(gitVersioner) { if (!gitVersioner.isGitProjectCorrectlyInitialized) { val why = if (gitVersioner.isHistoryShallowed) { "WARNING: Git history is incomplete (shallow clone)\n" + "The com.pascalwelsch.gitversioner gradle plugin requires the complete git history to calculate " + "the version. The history is shallowed, therefore the version code would be incorrect.\n" + "Default values versionName: 'undefined', versionCode: 1 are used instead.\n\n" + "Please fetch the complete history with:\n" + "\tgit fetch --unshallow" } else { "WARNING: git not initialized. Run:\n" + "\tgit init" } println( """ | |GitVersioner Plugin v$pluginVersion |------------------- |VersionCode: $versionCode |VersionName: $versionName | |baseBranch: $baseBranch | |$why """.replaceIndentByMargin() ) return@doLast } val baseBranchRange = (initialCommit?.take(7) ?: "") + "..${featureBranchOriginCommit?.take(7) ?: ""}" val featureBranchRange = (featureBranchOriginCommit?.take(7) ?: "") + "..${currentSha1Short ?: ""}" println( """ | |GitVersioner Plugin v$pluginVersion |------------------- |VersionCode: $versionCode |VersionName: $versionName | |baseBranch: $baseBranch |current branch: $branchName |current commit: $currentSha1Short | |baseBranch commits: $baseBranchCommitCount ($baseBranchRange) |featureBranch commits: $featureBranchCommitCount ($featureBranchRange) | |timeComponent: $timeComponent (yearFactor:$yearFactor) | |LocalChanges: ${localChanges.shortStats()} """.replaceIndentByMargin() ) } } } project.tasks.create("generateGitVersionName", GenerateGitVersionName::class.java).apply { this.gitVersioner = gitVersioner group = "Build" description = "analyzes the git history and creates a version name (generates machine readable output file)" } } val pluginVersion: String by lazy<String> { val props = Properties() props.load(GitVersionerPlugin::class.java.getResourceAsStream("/version.properties")) props.getProperty("version") } }
apache-2.0
6487f97331da3c5c8aef73fc0d6f6067
40.579439
135
0.478535
6.077869
false
false
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/GithubOrganization.kt
1
1281
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import org.openapitools.model.GithubOrganizationlinks import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param propertyClass * @param links * @param jenkinsOrganizationPipeline * @param name */ data class GithubOrganization( @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null, @field:Valid @Schema(example = "null", description = "") @field:JsonProperty("_links") val links: GithubOrganizationlinks? = null, @Schema(example = "null", description = "") @field:JsonProperty("jenkinsOrganizationPipeline") val jenkinsOrganizationPipeline: kotlin.Boolean? = null, @Schema(example = "null", description = "") @field:JsonProperty("name") val name: kotlin.String? = null ) { }
mit
4d3cbbc6b5fe4ad611e1347e700e0d6c
30.243902
111
0.765808
4.227723
false
false
false
false
siempredelao/Distance-From-Me-Android
app/src/test/java/gc/david/dfm/opensource/presentation/mapper/OpenSourceLibraryMapperTest.kt
1
2322
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm.opensource.presentation.mapper import gc.david.dfm.opensource.data.model.OpenSourceLibraryEntity import org.junit.Assert.assertEquals import org.junit.Test /** * Created by david on 26.01.17. */ class OpenSourceLibraryMapperTest { @Test fun `transforms open source library entity to open source library model`() { val libraryName = "fake name" val libraryAuthor = "fake author" val libraryVersion = "fake version" val libraryLink = "fake link" val libraryLicense = "fake license" val libraryYear = "fake year" val libraryDescription = "fake description" val openSourceLibraryEntity = OpenSourceLibraryEntity(libraryName, libraryAuthor, libraryVersion, libraryLink, libraryLicense, libraryYear, libraryDescription) val openSourceLibraryEntityList = mutableListOf(openSourceLibraryEntity) val openSourceLibraryModelList = OpenSourceLibraryMapper().transform(openSourceLibraryEntityList) assertEquals(1, openSourceLibraryModelList.size) val openSourceLibraryModel = openSourceLibraryModelList[0] assertEquals(libraryName, openSourceLibraryModel.name) assertEquals(libraryAuthor, openSourceLibraryModel.author) assertEquals(libraryVersion, openSourceLibraryModel.version) assertEquals(libraryLink, openSourceLibraryModel.link) assertEquals(libraryLicense, openSourceLibraryModel.license) assertEquals(libraryYear, openSourceLibraryModel.year) assertEquals(libraryDescription, openSourceLibraryModel.description) } }
apache-2.0
8f329b2fedd78eb54689e46fed17fcb0
37.716667
80
0.717916
5.171492
false
true
false
false
konachan700/Mew
software/MeWSync/app/src/main/java/com/mewhpm/mewsync/services/AuthService.kt
1
1438
package com.mewhpm.mewsync.services import android.app.IntentService import android.content.Intent import java.io.File import java.util.* class AuthService : IntentService(AuthService::class.java.simpleName) { companion object { const val AUTH_UPDATE_LOCAL_TOKEN = 1000 const val LOCAL_TIMEOUT: Long = 1000 * 60 * 5 const val AUTH_LOGIN = 1 const val AUTH_LOGOUT = 2 const val AUTH_VERIFY = 3 const val AUTH_OP_TYPE = "auth_op_type" const val AUTH_FIELD_PASSWORD = "pc" const val AUTH_RESULT_CODE = "result_code" const val AUTH_VERIFY_OK = 1 const val AUTH_VERIFY_ERROR = 2 // TODO: add setting field for this } var _hash = "" var _lastAccess: Long = 0 override fun onHandleIntent(intent: Intent?) { if (intent == null) return when (intent.getIntExtra(AUTH_OP_TYPE, 0)) { AUTH_UPDATE_LOCAL_TOKEN -> { } } } private fun generateTestFile() { val hashFromDisk = File(this.applicationContext.filesDir.absolutePath + File.separator + "data.mew").readText() } private fun sendVerify(result: Int) { val intentAnswer = Intent() intentAnswer.action = this::class.java.simpleName intentAnswer.addCategory(Intent.CATEGORY_DEFAULT) intentAnswer.putExtra(AUTH_RESULT_CODE, result) sendBroadcast(intentAnswer) } }
gpl-3.0
96fd41824a01170db234310b28cf4118
26.150943
119
0.635605
4.168116
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/gallery/CollageActivity.kt
1
2495
package com.example.android.eyebody.gallery import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.example.android.eyebody.R import android.view.Menu import android.view.MenuItem import com.kakao.kakaolink.KakaoLink import com.kakao.kakaolink.KakaoTalkLinkMessageBuilder import java.io.File class CollageActivity : AppCompatActivity() { var photoList: ArrayList<Photo> = ArrayList<Photo>() var selectedIndexList: ArrayList<Int> = ArrayList<Int>() var selectedPhotoList: ArrayList<Photo> = ArrayList<Photo>() lateinit var menu: Menu override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_collage) photoList = intent.getParcelableArrayListExtra("photoList") //ImageSelectFragment 생성 fragmentManager .beginTransaction() .add(R.id.fragment_container, ImageSelectFragment()) .commit() } override fun onBackPressed() { var count: Int = fragmentManager.backStackEntryCount if(count == 0){ //스택에 프래그먼트가 없으면 액티비티 뒤로가기 super.onBackPressed() } else { if(count == 1) //ImageSelectFragment로 돌아올 땐 캐시파일 삭제 clearApplicationCache(null) fragmentManager.popBackStack() //이전 프래그먼트 불러오기 } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_image_select, menu) this.menu = menu return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> { ShareKakao(baseContext).shareKakao() } } return super.onOptionsItemSelected(item) } override fun onDestroy() { super.onDestroy() clearApplicationCache(null) } fun clearApplicationCache(file: File?){ //캐시 파일 삭제 var dir: File if(file == null) dir = cacheDir else dir = file if(dir == null) return var children = dir.listFiles() try{ for(child in children){ if(child.isDirectory) clearApplicationCache(child) else child.delete() } } catch(e: Exception){ } } }
mit
1170ed0e9ceac86368e54730a9fc2b54
27.511905
68
0.626722
4.231449
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/support/MaterialImageLoader.kt
1
2545
package info.papdt.express.helper.support import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView class MaterialImageLoader private constructor(internal val imageView: ImageView) { internal val drawable: Drawable = imageView.drawable private var duration = DEFAULT_DURATION private var saturation: Float = 0.toFloat() private lateinit var animationSaturation: ValueAnimator private lateinit var animationContrast: ValueAnimator private lateinit var animationAlpha: ObjectAnimator fun getDuration(): Int { return duration } fun setDuration(duration: Int): MaterialImageLoader { this.duration = duration return this } fun start() { setup(duration) animationSaturation.start() animationContrast.start() animationAlpha.start() } fun cancel() { animationSaturation.cancel() animationContrast.cancel() animationAlpha.cancel() } private fun setContrast(contrast: Float): ColorMatrix { val scale = contrast + 1f val translate = (-.5f * scale + .5f) * 255f val array = floatArrayOf(scale, 0f, 0f, 0f, translate, 0f, scale, 0f, 0f, translate, 0f, 0f, scale, 0f, translate, 0f, 0f, 0f, 1f, 0f) return ColorMatrix(array) } private fun setup(duration: Int) { animationSaturation = ValueAnimator.ofFloat(0.2f, 1f) animationSaturation.duration = duration.toLong() animationSaturation.addUpdateListener { animation -> saturation = animation.animatedFraction } animationContrast = ValueAnimator.ofFloat(0f, 1f) animationContrast.duration = (duration * 3f / 4f).toLong() animationContrast.addUpdateListener { animation -> val colorMatrix = setContrast(animation.animatedFraction) colorMatrix.setSaturation(saturation) val colorFilter = ColorMatrixColorFilter(colorMatrix) drawable.colorFilter = colorFilter } animationAlpha = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0f, 1f) animationAlpha.duration = (duration / 2f).toLong() } companion object { private const val DEFAULT_DURATION = 3000 fun animate(imageView: ImageView): MaterialImageLoader { return MaterialImageLoader(imageView) } } }
gpl-3.0
76d450b0d9ebf21c44f02a84dd0c0db5
32.064935
142
0.693517
4.783835
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/article/PostContent.kt
1
11340
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.article import androidx.compose.foundation.Box import androidx.compose.foundation.Image import androidx.compose.foundation.ScrollableColumn import androidx.compose.foundation.Text import androidx.compose.foundation.contentColor import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredHeight import androidx.compose.foundation.layout.preferredSize import androidx.compose.foundation.layout.preferredWidth import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.FirstBaseline import androidx.compose.material.Colors import androidx.compose.material.EmphasisAmbient import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideEmphasis import androidx.compose.material.Surface import androidx.compose.material.Typography import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.DensityAmbient import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.ParagraphStyle import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.ui.tooling.preview.Preview import com.example.jetnews.data.posts.impl.post3 import com.example.jetnews.model.Markup import com.example.jetnews.model.MarkupType import com.example.jetnews.model.Metadata import com.example.jetnews.model.Paragraph import com.example.jetnews.model.ParagraphType import com.example.jetnews.model.Post import com.example.jetnews.ui.ThemedPreview private val defaultSpacerSize = 16.dp @Composable fun PostContent(post: Post, modifier: Modifier = Modifier) { ScrollableColumn( modifier = modifier.padding(horizontal = defaultSpacerSize) ) { Spacer(Modifier.preferredHeight(defaultSpacerSize)) PostHeaderImage(post) Text(text = post.title, style = MaterialTheme.typography.h4) Spacer(Modifier.preferredHeight(8.dp)) post.subtitle?.let { subtitle -> ProvideEmphasis(EmphasisAmbient.current.medium) { Text( text = subtitle, style = MaterialTheme.typography.body2, lineHeight = 20.sp ) } Spacer(Modifier.preferredHeight(defaultSpacerSize)) } PostMetadata(post.metadata) Spacer(Modifier.preferredHeight(24.dp)) PostContents(post.paragraphs) Spacer(Modifier.preferredHeight(48.dp)) } } @Composable private fun PostHeaderImage(post: Post) { post.image?.let { image -> val imageModifier = Modifier .heightIn(min = 180.dp) .fillMaxWidth() .clip(shape = MaterialTheme.shapes.medium) Image(image, imageModifier, contentScale = ContentScale.Crop) Spacer(Modifier.preferredHeight(defaultSpacerSize)) } } @Composable private fun PostMetadata(metadata: Metadata) { val typography = MaterialTheme.typography Row { Image( asset = Icons.Filled.AccountCircle, modifier = Modifier.preferredSize(40.dp), colorFilter = ColorFilter.tint(contentColor()), contentScale = ContentScale.Fit ) Spacer(Modifier.preferredWidth(8.dp)) Column { ProvideEmphasis(EmphasisAmbient.current.high) { Text( text = metadata.author.name, style = typography.caption, modifier = Modifier.padding(top = 4.dp) ) } ProvideEmphasis(EmphasisAmbient.current.medium) { Text( text = "${metadata.date} • ${metadata.readTimeMinutes} min read", style = typography.caption ) } } } } @Composable private fun PostContents(paragraphs: List<Paragraph>) { paragraphs.forEach { Paragraph(paragraph = it) } } @Composable private fun Paragraph(paragraph: Paragraph) { val (textStyle, paragraphStyle, trailingPadding) = paragraph.type.getTextAndParagraphStyle() val annotatedString = paragraphToAnnotatedString( paragraph, MaterialTheme.typography, MaterialTheme.colors.codeBlockBackground ) Box(modifier = Modifier.padding(bottom = trailingPadding)) { when (paragraph.type) { ParagraphType.Bullet -> BulletParagraph( text = annotatedString, textStyle = textStyle, paragraphStyle = paragraphStyle ) ParagraphType.CodeBlock -> CodeBlockParagraph( text = annotatedString, textStyle = textStyle, paragraphStyle = paragraphStyle ) ParagraphType.Header -> { Text( modifier = Modifier.padding(4.dp), text = annotatedString, style = textStyle.merge(paragraphStyle) ) } else -> Text( modifier = Modifier.padding(4.dp), text = annotatedString, style = textStyle ) } } } @Composable private fun CodeBlockParagraph( text: AnnotatedString, textStyle: TextStyle, paragraphStyle: ParagraphStyle ) { Surface( color = MaterialTheme.colors.codeBlockBackground, shape = MaterialTheme.shapes.small, modifier = Modifier.fillMaxWidth() ) { Text( modifier = Modifier.padding(16.dp), text = text, style = textStyle.merge(paragraphStyle) ) } } @Composable private fun BulletParagraph( text: AnnotatedString, textStyle: TextStyle, paragraphStyle: ParagraphStyle ) { Row { with(DensityAmbient.current) { // this box is acting as a character, so it's sized with font scaling (sp) Box( modifier = Modifier .preferredSize(8.sp.toDp(), 8.sp.toDp()) .alignWithSiblings { // Add an alignment "baseline" 1sp below the bottom of the circle 9.sp.toIntPx() }, backgroundColor = contentColor(), shape = CircleShape ) } Text( modifier = Modifier .weight(1f) .alignWithSiblings(FirstBaseline), text = text, style = textStyle.merge(paragraphStyle) ) } } private data class ParagraphStyling( val textStyle: TextStyle, val paragraphStyle: ParagraphStyle, val trailingPadding: Dp ) @Composable private fun ParagraphType.getTextAndParagraphStyle(): ParagraphStyling { val typography = MaterialTheme.typography var textStyle: TextStyle = typography.body1 var paragraphStyle = ParagraphStyle() var trailingPadding = 24.dp when (this) { ParagraphType.Caption -> textStyle = typography.body1 ParagraphType.Title -> textStyle = typography.h4 ParagraphType.Subhead -> { textStyle = typography.h6 trailingPadding = 16.dp } ParagraphType.Text -> { textStyle = typography.body1 paragraphStyle = paragraphStyle.copy(lineHeight = 28.sp) } ParagraphType.Header -> { textStyle = typography.h5 trailingPadding = 16.dp } ParagraphType.CodeBlock -> textStyle = typography.body1.copy( fontFamily = FontFamily.Monospace ) ParagraphType.Quote -> textStyle = typography.body1 ParagraphType.Bullet -> { paragraphStyle = ParagraphStyle(textIndent = TextIndent(firstLine = 8.sp)) } } return ParagraphStyling( textStyle, paragraphStyle, trailingPadding ) } private fun paragraphToAnnotatedString( paragraph: Paragraph, typography: Typography, codeBlockBackground: Color ): AnnotatedString { val styles: List<AnnotatedString.Range<SpanStyle>> = paragraph.markups .map { it.toAnnotatedStringItem(typography, codeBlockBackground) } return AnnotatedString(text = paragraph.text, spanStyles = styles) } fun Markup.toAnnotatedStringItem( typography: Typography, codeBlockBackground: Color ): AnnotatedString.Range<SpanStyle> { return when (this.type) { MarkupType.Italic -> { AnnotatedString.Range( typography.body1.copy(fontStyle = FontStyle.Italic).toSpanStyle(), start, end ) } MarkupType.Link -> { AnnotatedString.Range( typography.body1.copy(textDecoration = TextDecoration.Underline).toSpanStyle(), start, end ) } MarkupType.Bold -> { AnnotatedString.Range( typography.body1.copy(fontWeight = FontWeight.Bold).toSpanStyle(), start, end ) } MarkupType.Code -> { AnnotatedString.Range( typography.body1 .copy( background = codeBlockBackground, fontFamily = FontFamily.Monospace ).toSpanStyle(), start, end ) } } } private val Colors.codeBlockBackground: Color get() = onSurface.copy(alpha = .15f) @Preview("Post content") @Composable fun PreviewPost() { ThemedPreview { PostContent(post = post3) } } @Preview("Post content dark theme") @Composable fun PreviewPostDark() { ThemedPreview(darkTheme = true) { PostContent(post = post3) } }
apache-2.0
c2d8faf0bc45606d15bfaf487fd0fd0e
31.959302
96
0.646322
4.841161
false
false
false
false
edvin/tornadofx-idea-plugin
src/main/kotlin/no/tornado/tornadofx/idea/intentions/ExtractI18n.kt
1
3129
package no.tornado.tornadofx.idea.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import no.tornado.tornadofx.idea.dialog.ErrorDialog import no.tornado.tornadofx.idea.dialog.ExtractStringToResourceDialog import no.tornado.tornadofx.idea.translation.TranslationManager import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly /** * Intention on strings to extract string under cursor to a resource file based * on the Component's name. */ class ExtractI18n : PsiElementBaseIntentionAction() { private val translationManager = TranslationManager() override fun getText(): String = "Extract String into resources" override fun getFamilyName(): String = "Internationalization" override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean { return element.node.elementType == KtTokens.REGULAR_STRING_PART } override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val defaultValue = element.node.chars.toString() // Content of string val defaultKey = defaultValue .replace(Regex("([^A-Za-z]+)"), "_") .replace(Regex("_$"), "") // do not end keys with underscore .toLowerCaseAsciiOnly() val dialog: DialogWrapper = try { val clazz = getClass(element) ?: throw TranslationManager.FetchResourceFileException("Cannot find class.") val resourcePaths = translationManager.getResourceFiles(clazz) val resourcePathStrings = Array(resourcePaths.size) { translationManager.getResourcePath(project, resourcePaths[it]) } ExtractStringToResourceDialog(project, defaultKey, defaultValue, resourcePaths, resourcePathStrings) { key, value, resourceFile -> translationManager.addProperty(resourceFile, key, value) WriteCommandAction.runWriteCommandAction(project) { val factory = KtPsiFactory(project) val stringPsi = PsiTreeUtil.getParentOfType(element, KtStringTemplateExpression::class.java) ?: element stringPsi.replace(factory.createExpression("messages[\"$key\"]")) } } } catch (e: TranslationManager.FetchResourceFileException) { ErrorDialog(project, e.message) } ApplicationManager.getApplication().invokeLater { dialog.show() } } private fun getClass(element: PsiElement): KtClass? { return PsiTreeUtil.getParentOfType(element, KtClass::class.java) } }
apache-2.0
3049340f6fe71e840f04b6ae0cf59fd4
45.014706
142
0.721636
5.038647
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/ui/IconButtonScrim.kt
1
2364
/* * Copyright 2021 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 app.tivi.common.compose.ui import androidx.annotation.FloatRange import androidx.compose.animation.Crossfade import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import app.tivi.common.compose.theme.TiviTheme @Composable fun ScrimmedIconButton( showScrim: Boolean, onClick: () -> Unit, invertThemeOnScrim: Boolean = true, icon: @Composable () -> Unit ) { IconButton(onClick = onClick) { if (invertThemeOnScrim) { val isLight = MaterialTheme.colors.isLight Crossfade(targetState = showScrim) { show -> TiviTheme(useDarkColors = if (show) isLight else !isLight) { ScrimSurface(showScrim = show, icon = icon) } } } else { ScrimSurface(showScrim = showScrim, icon = icon) } } } @Composable private fun ScrimSurface( modifier: Modifier = Modifier, showScrim: Boolean = true, @FloatRange(from = 0.0, to = 1.0) alpha: Float = 0.3f, icon: @Composable () -> Unit ) { Surface( color = when { showScrim -> MaterialTheme.colors.surface.copy(alpha = alpha) else -> Color.Transparent }, contentColor = MaterialTheme.colors.onSurface, shape = MaterialTheme.shapes.small, modifier = modifier, content = { Box(Modifier.padding(4.dp)) { icon() } } ) }
apache-2.0
bd9e997104c57cb6b7b6ef0e38756cb9
30.52
76
0.669628
4.221429
false
false
false
false