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
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/PremiumEntryPreference.kt
1
2960
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.preference import android.content.Context import android.support.v4.app.FragmentActivity import android.support.v7.preference.Preference import android.util.AttributeSet import org.mariotaku.chameleon.ChameleonUtils import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.REQUEST_PURCHASE_EXTRA_FEATURES import de.vanita5.twittnuker.extension.findParent import de.vanita5.twittnuker.fragment.ExtraFeaturesIntroductionDialogFragment import de.vanita5.twittnuker.util.dagger.GeneralComponent import de.vanita5.twittnuker.util.premium.ExtraFeaturesService import javax.inject.Inject class PremiumEntryPreference(context: Context, attrs: AttributeSet) : Preference(context, attrs) { @Inject internal lateinit var extraFeaturesService: ExtraFeaturesService init { GeneralComponent.get(context).inject(this) val a = context.obtainStyledAttributes(attrs, R.styleable.PremiumEntryPreference) val requiredFeature: String = a.getString(R.styleable.PremiumEntryPreference_requiredFeature) a.recycle() isEnabled = extraFeaturesService.isSupported() setOnPreferenceClickListener { if (!extraFeaturesService.isEnabled(requiredFeature)) { val activity = ChameleonUtils.getActivity(context) if (activity is FragmentActivity) { ExtraFeaturesIntroductionDialogFragment.show(fm = activity.supportFragmentManager, feature = requiredFeature, source = "preference:${key}", requestCode = REQUEST_PURCHASE_EXTRA_FEATURES) } return@setOnPreferenceClickListener true } return@setOnPreferenceClickListener false } } override fun onAttached() { super.onAttached() if (!extraFeaturesService.isSupported()) { preferenceManager.preferenceScreen?.let { screen -> findParent(screen)?.removePreference(this) } } } }
gpl-3.0
c4668bf3798714436592967af2e46eda
40.125
102
0.716554
4.758842
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/networking/PaymentAnalyticsRequestFactory.kt
1
8113
package com.stripe.android.networking import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import com.stripe.android.core.injection.PUBLISHABLE_KEY import com.stripe.android.core.networking.AnalyticsRequest import com.stripe.android.core.networking.AnalyticsRequestFactory import com.stripe.android.core.utils.ContextUtils.packageInfo import com.stripe.android.model.PaymentMethodCode import com.stripe.android.model.Source import com.stripe.android.model.Token import com.stripe.android.payments.core.injection.PRODUCT_USAGE import javax.inject.Inject import javax.inject.Named import javax.inject.Provider /** * Factory for [AnalyticsRequest] objects. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class PaymentAnalyticsRequestFactory @VisibleForTesting internal constructor( packageManager: PackageManager?, packageInfo: PackageInfo?, packageName: String, publishableKeyProvider: Provider<String>, internal val defaultProductUsageTokens: Set<String> = emptySet() ) : AnalyticsRequestFactory( packageManager, packageInfo, packageName, publishableKeyProvider ) { @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) constructor( context: Context, publishableKey: String, defaultProductUsageTokens: Set<String> = emptySet() ) : this( context, { publishableKey }, defaultProductUsageTokens ) internal constructor( context: Context, publishableKeyProvider: Provider<String> ) : this( context.applicationContext.packageManager, context.applicationContext.packageInfo, context.applicationContext.packageName.orEmpty(), publishableKeyProvider, emptySet() ) @Inject internal constructor( context: Context, @Named(PUBLISHABLE_KEY) publishableKeyProvider: () -> String, @Named(PRODUCT_USAGE) defaultProductUsageTokens: Set<String> ) : this( context.applicationContext.packageManager, context.applicationContext.packageInfo, context.applicationContext.packageName.orEmpty(), publishableKeyProvider, defaultProductUsageTokens ) @JvmSynthetic internal fun create3ds2Challenge( event: PaymentAnalyticsEvent, uiTypeCode: String? ): AnalyticsRequest { return createRequest( event, threeDS2UiType = ThreeDS2UiType.fromUiTypeCode(uiTypeCode) ) } @JvmSynthetic internal fun createTokenCreation( productUsageTokens: Set<String>, tokenType: Token.Type ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.TokenCreate, productUsageTokens = productUsageTokens, tokenType = tokenType ) } @JvmSynthetic internal fun createPaymentMethodCreation( paymentMethodCode: PaymentMethodCode?, productUsageTokens: Set<String> ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.PaymentMethodCreate, sourceType = paymentMethodCode, productUsageTokens = productUsageTokens ) } @JvmSynthetic internal fun createSourceCreation( @Source.SourceType sourceType: String, productUsageTokens: Set<String> = emptySet() ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.SourceCreate, productUsageTokens = productUsageTokens, sourceType = sourceType ) } @JvmSynthetic internal fun createAddSource( productUsageTokens: Set<String> = emptySet(), @Source.SourceType sourceType: String ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.CustomerAddSource, productUsageTokens = productUsageTokens, sourceType = sourceType ) } @JvmSynthetic internal fun createDeleteSource( productUsageTokens: Set<String> ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.CustomerDeleteSource, productUsageTokens = productUsageTokens ) } @JvmSynthetic internal fun createAttachPaymentMethod( productUsageTokens: Set<String> ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.CustomerAttachPaymentMethod, productUsageTokens = productUsageTokens ) } @JvmSynthetic internal fun createDetachPaymentMethod( productUsageTokens: Set<String> ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.CustomerDetachPaymentMethod, productUsageTokens = productUsageTokens ) } @JvmSynthetic internal fun createPaymentIntentConfirmation( paymentMethodType: String? = null ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.PaymentIntentConfirm, sourceType = paymentMethodType ) } @JvmSynthetic internal fun createSetupIntentConfirmation( paymentMethodType: String? ): AnalyticsRequest { return createRequest( PaymentAnalyticsEvent.SetupIntentConfirm, sourceType = paymentMethodType ) } @JvmSynthetic internal fun createRequest( event: PaymentAnalyticsEvent, productUsageTokens: Set<String> = emptySet(), @Source.SourceType sourceType: String? = null, tokenType: Token.Type? = null, threeDS2UiType: ThreeDS2UiType? = null ): AnalyticsRequest { return createRequest( event, additionalParams( productUsageTokens = productUsageTokens, sourceType = sourceType, tokenType = tokenType, threeDS2UiType = threeDS2UiType ) ) } private fun additionalParams( productUsageTokens: Set<String> = emptySet(), @Source.SourceType sourceType: String? = null, tokenType: Token.Type? = null, threeDS2UiType: ThreeDS2UiType? = null ): Map<String, Any> { return defaultProductUsageTokens .plus(productUsageTokens) .takeUnless { it.isEmpty() }?.let { mapOf(FIELD_PRODUCT_USAGE to it.toList()) } .orEmpty() .plus(sourceType?.let { mapOf(FIELD_SOURCE_TYPE to it) }.orEmpty()) .plus(createTokenTypeParam(sourceType, tokenType)) .plus(threeDS2UiType?.let { mapOf(FIELD_3DS2_UI_TYPE to it.toString()) }.orEmpty()) } private fun createTokenTypeParam( @Source.SourceType sourceType: String? = null, tokenType: Token.Type? = null ): Map<String, String> { val value = when { tokenType != null -> tokenType.code // This is not a source event, so to match iOS we log a token without type // as type "unknown" sourceType == null -> "unknown" else -> null } return value?.let { mapOf(FIELD_TOKEN_TYPE to it) }.orEmpty() } internal enum class ThreeDS2UiType( private val code: String?, private val typeName: String ) { None(null, "none"), Text("01", "text"), SingleSelect("02", "single_select"), MultiSelect("03", "multi_select"), Oob("04", "oob"), Html("05", "html"); override fun toString(): String = typeName companion object { fun fromUiTypeCode(uiTypeCode: String?) = values().firstOrNull { it.code == uiTypeCode } ?: None } } internal companion object { internal const val FIELD_TOKEN_TYPE = "token_type" internal const val FIELD_PRODUCT_USAGE = "product_usage" internal const val FIELD_SOURCE_TYPE = "source_type" internal const val FIELD_3DS2_UI_TYPE = "3ds2_ui_type" } }
mit
273621da37bdd37a0418150d69cc4a85
30.568093
95
0.65167
5.470668
false
false
false
false
ivaneye/kt-jvm
src/com/ivaneye/ktjvm/model/MethodInfo.kt
1
693
package com.ivaneye.ktjvm.model import com.ivaneye.ktjvm.model.attr.Attribute import com.ivaneye.ktjvm.type.U2 /** * Created by wangyifan on 2017/5/17. */ class MethodInfo(val accFlag: U2, val nameIdx: U2, val descIdx: U2, val attrCount: U2, val attrs: Array<Attribute>, val classInfo: ClassInfo) { override fun toString(): String { var str = "" for(attr in attrs){ str += attr.toString() } return "MethodInfo(accFlag=${accFlag.toHexString()},name=${classInfo.cpInfos[nameIdx.toInt()]!!.value()}," + "desc=${classInfo.cpInfos[descIdx.toInt()]!!.value()},attrCount=${attrCount.toInt() },attrs=[$str])" } }
apache-2.0
3ca5948cf382599134d0d4fd2bf1a477
33.7
143
0.626263
3.628272
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/UsersCreateHandler.kt
1
1200
package au.com.codeka.warworlds.server.admin.handlers import au.com.codeka.warworlds.common.proto.AdminRole import au.com.codeka.warworlds.common.proto.AdminUser import au.com.codeka.warworlds.server.store.DataStore import com.google.common.collect.ImmutableMap import java.util.* /** * Handler for /admin/users/create, which is used to create new users. */ class UsersCreateHandler : AdminHandler() { public override fun get() { render("users/create.html", ImmutableMap.builder<String, Any>() .put("all_roles", AdminRole.values()) .build()) } public override fun post() { val emailAddr = request.getParameter("email_addr") val roles = ArrayList<AdminRole>() for (role in AdminRole.values()) { if (request.getParameter(role.toString()) != null) { roles.add(role) } } if (emailAddr == null || emailAddr.isEmpty()) { render("users/create.html", ImmutableMap.builder<String, Any>() .put("error", "Email address must not be empty.") .build()) return } DataStore.i.adminUsers().put(emailAddr, AdminUser( email_addr = emailAddr, roles = roles)) redirect("/admin/users") } }
mit
a2d2f2bb8b630dfb259cb95cef73fca7
30.605263
70
0.665
3.809524
false
false
false
false
Madzi/owide
src/main/kotlin/monaco/editor/ITextModel.kt
1
2036
package monaco.editor external interface ITextModel { fun findMatches(searchString: String, searchOnlyEditableRange: Boolean, isRegex: Boolean, matchCase: Boolean, wordSeparatos: String, captureMatches: Boolean, limitResultCount: Number = definedExternally): Any // FindMatch[] fun findNextMatch(searchString: String, searchStart: Any, isRegex: Boolean, matchCase: Boolean, wordSeparators: String, captureMatches: Boolean): Any // IPosition FindMatch fun findPreviousMatch(searchString: String, searchStart: Any, isRegex: Boolean, matchCase: Boolean, wordSeparators: String, captureMatches: Boolean): Any // IPosition FindMatch fun getAlternativeVersionId(): Number fun getEOL(): String fun getFullModelRange(): Any // Range fun getLineContent(lineNumber: Number): String fun getLineCount(): Number fun getLineFirstNonWhitespaceColumn(lineNumber: Number): Number fun getLineLastNonWhitespaceColumn(lineNumber: Number): Number fun getLineMaxColumn(lineNumber: Number): Number fun getLineMinColumn(lineNumber: Number): Number fun getLinesContent(): Array<String> fun getOffsetAt(position: Any): Number // IPosition fun getOptions(): Any // TextModelResolvedOptions fun getPositionAt(offset: Number): Any // Position fun getValue(eol: Any = definedExternally, preserveBOM: Boolean = definedExternally): String // EndOfLinePreference fun getValueInRange(range: Any, eol: Any = definedExternally): String // IRange, EndOfLinePreference fun getValueLength(eol: Any = definedExternally, preserveBOM: Boolean = definedExternally): Number // EndOfLinePreference fun getValueLengthInRange(range: Any): Number // IRange fun getVersionId(): Number fun isDisposed(): Boolean fun modifyPosition(position: Any, offset: Number): Any // IPosition Position fun setEOL(eol: Any) // EndOfLineSequence fun setValue(newValue: String) fun validatePosition(position: Any): Any // IPosition Position fun validateRange(range: Any): Any // IRange Range }
apache-2.0
d87c81622b2a0f1940fda66f5b4f9c46
64.709677
227
0.76277
4.813239
false
false
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/activity/ArtistRowAdapter.kt
1
7289
/* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2020 (C) Jozsef Varga */ package org.moire.ultrasonic.activity import android.view.LayoutInflater import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.PopupMenu import android.widget.RelativeLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView.SectionedAdapter import java.text.Collator import org.moire.ultrasonic.R import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isOffline import org.moire.ultrasonic.domain.Artist import org.moire.ultrasonic.domain.MusicDirectory import org.moire.ultrasonic.util.ImageLoader import org.moire.ultrasonic.util.Util /** * Creates a Row in a RecyclerView which contains the details of an Artist */ class ArtistRowAdapter( private var artistList: List<Artist>, private var folderName: String, private var shouldShowHeader: Boolean, val onArtistClick: (Artist) -> Unit, val onContextMenuClick: (MenuItem, Artist) -> Boolean, val onFolderClick: (view: View) -> Unit, private val imageLoader: ImageLoader ) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), SectionedAdapter { /** * Sets the data to be displayed in the RecyclerView */ fun setData(data: List<Artist>) { artistList = data.sortedWith(compareBy(Collator.getInstance()) { t -> t.name }) notifyDataSetChanged() } /** * Sets the name of the folder to be displayed n the Header (first) row */ fun setFolderName(name: String) { folderName = name notifyDataSetChanged() } /** * Holds the view properties of an Artist row */ class ArtistViewHolder( itemView: View ) : RecyclerView.ViewHolder(itemView) { var section: TextView = itemView.findViewById(R.id.row_section) var textView: TextView = itemView.findViewById(R.id.row_artist_name) var layout: RelativeLayout = itemView.findViewById(R.id.row_artist_layout) var coverArt: ImageView = itemView.findViewById(R.id.artist_coverart) var coverArtId: String? = null } /** * Holds the view properties of the Header row */ class HeaderViewHolder( itemView: View ) : RecyclerView.ViewHolder(itemView) { var folderName: TextView = itemView.findViewById(R.id.select_artist_folder_2) var layout: LinearLayout = itemView.findViewById(R.id.select_artist_folder) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): RecyclerView.ViewHolder { if (viewType == TYPE_ITEM) { val row = LayoutInflater.from(parent.context) .inflate(R.layout.artist_list_item, parent, false) return ArtistViewHolder(row) } val header = LayoutInflater.from(parent.context) .inflate(R.layout.select_artist_header, parent, false) return HeaderViewHolder(header) } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { if ((holder is ArtistViewHolder) && (holder.coverArtId != null)) { imageLoader.cancel(holder.coverArtId) } super.onViewRecycled(holder) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is ArtistViewHolder) { val listPosition = if (shouldShowHeader) position - 1 else position holder.textView.text = artistList[listPosition].name holder.section.text = getSectionForArtist(listPosition) holder.layout.setOnClickListener { onArtistClick(artistList[listPosition]) } holder.layout.setOnLongClickListener { view -> createPopupMenu(view, listPosition) } holder.coverArtId = artistList[listPosition].coverArt if (Util.getShouldShowArtistPicture(holder.coverArt.context)) { holder.coverArt.visibility = View.VISIBLE imageLoader.loadImage( holder.coverArt, MusicDirectory.Entry().apply { coverArt = holder.coverArtId }, false, 0, false, true, R.drawable.ic_contact_picture ) } else { holder.coverArt.visibility = View.GONE } } else if (holder is HeaderViewHolder) { holder.folderName.text = folderName holder.layout.setOnClickListener { onFolderClick(holder.layout) } } } override fun getItemCount() = if (shouldShowHeader) artistList.size + 1 else artistList.size override fun getItemViewType(position: Int): Int { return if (position == 0 && shouldShowHeader) TYPE_HEADER else TYPE_ITEM } override fun getSectionName(position: Int): String { var listPosition = if (shouldShowHeader) position - 1 else position // Show the first artist's initial in the popup when the list is // scrolled up to the "Select Folder" row if (listPosition < 0) listPosition = 0 return getSectionFromName(artistList[listPosition].name ?: " ") } private fun getSectionForArtist(artistPosition: Int): String { if (artistPosition == 0) return getSectionFromName(artistList[artistPosition].name ?: " ") val previousArtistSection = getSectionFromName( artistList[artistPosition - 1].name ?: " " ) val currentArtistSection = getSectionFromName( artistList[artistPosition].name ?: " " ) return if (previousArtistSection == currentArtistSection) "" else currentArtistSection } private fun getSectionFromName(name: String): String { var section = name.first().toUpperCase() if (!section.isLetter()) section = '#' return section.toString() } private fun createPopupMenu(view: View, position: Int): Boolean { val popup = PopupMenu(view.context, view) val inflater: MenuInflater = popup.menuInflater inflater.inflate(R.menu.select_artist_context, popup.menu) val downloadMenuItem = popup.menu.findItem(R.id.artist_menu_download) downloadMenuItem?.isVisible = !isOffline(view.context) popup.setOnMenuItemClickListener { menuItem -> onContextMenuClick(menuItem, artistList[position]) } popup.show() return true } companion object { private const val TYPE_HEADER = 0 private const val TYPE_ITEM = 1 } }
gpl-3.0
6677c32ddccc55a5980717c3b99eda8c
36.572165
96
0.681987
4.767168
false
false
false
false
colesadam/hill-lists
app/src/main/java/uk/colessoft/android/hilllist/domain/GeographImageDetail.kt
1
2829
package uk.colessoft.android.hilllist.domain class GeographImageDetail { /** * @return The title */ /** * @param title The title */ var title: String? = null /** * @return The description */ /** * @param description The description */ var description: String? = null /** * @return The link */ /** * @param link The link */ var link: String? = null /** * @return The author */ /** * @param author The author */ var author: String? = null /** * @return The category */ /** * @param category The category */ var category: String? = null /** * @return The guid */ /** * @param guid The guid */ var guid: String? = null /** * @return The source */ /** * @param source The source */ var source: String? = null /** * @return The date */ /** * @param date The date */ var date: Int = 0 /** * @return The imageTaken */ /** * @param imageTaken The imageTaken */ var imageTaken: String? = null /** * @return The lat */ /** * @param lat The lat */ var lat: String? = null /** * @return The _long */ /** * @param _long The long */ var long: String? = null /** * @return The thumb */ /** * @param thumb The thumb */ var thumb: String? = null /** * @return The thumbTag */ /** * @param thumbTag The thumbTag */ var thumbTag: String? = null /** * @return The licence */ /** * @param licence The licence */ var licence: String? = null /** * No args constructor for use in serialization */ constructor() {} /** * @param licence * @param link * @param date * @param imageTaken * @param guid * @param author * @param title * @param category * @param source * @param _long * @param description * @param thumbTag * @param thumb * @param lat */ constructor(title: String, description: String, link: String, author: String, category: String, guid: String, source: String, date: Int, imageTaken: String, lat: String, _long: String, thumb: String, thumbTag: String, licence: String) { this.title = title this.description = description this.link = link this.author = author this.category = category this.guid = guid this.source = source this.date = date this.imageTaken = imageTaken this.lat = lat this.long = _long this.thumb = thumb this.thumbTag = thumbTag this.licence = licence } }
mit
143bd27d13eb71ec172f63e5b2c28a40
18.929577
240
0.503358
4.2287
false
false
false
false
arsich/messenger
app/src/main/kotlin/ru/arsich/messenger/mvp/models/ChatRepository.kt
1
2932
package ru.arsich.messenger.mvp.models import com.vk.sdk.api.VKError import com.vk.sdk.api.VKRequest import com.vk.sdk.api.VKResponse import com.vk.sdk.api.model.VKApiGetMessagesResponse import com.vk.sdk.api.model.VKApiMessage import ru.arsich.messenger.vk.VKApiMessageHistory import java.lang.Exception class ChatRepository { companion object { val CHAT_PAGE_SIZE = 40 } private val messagesSubscribers: MutableList<RequestMessagesListener> = mutableListOf() fun addMessagesSubscriber(subscriber: RequestMessagesListener) { messagesSubscribers.add(subscriber) } fun removeMessagesSubscriber(subscriber: RequestMessagesListener) { messagesSubscribers.remove(subscriber) } // cache only last selected chat, no reload after orientation change private var lastChatId: Int = -1 private var lastMessages: MutableList<VKApiMessage> = ArrayList() fun requestMessages(chatId: Int, offset: Int = 0) { if (chatId != lastChatId) { // clear cache lastMessages.clear() lastChatId = chatId } if (offset < lastMessages.size) { // return date from cache sendMessagesToSubscribers(lastMessages.subList(offset, lastMessages.lastIndex)) return } val startMessageId = -1 val request = VKApiMessageHistory.get(chatId, offset, startMessageId, CHAT_PAGE_SIZE) request.attempts = 3 request.executeWithListener(object: VKRequest.VKRequestListener() { override fun onComplete(response: VKResponse?) { if (response != null) { val result = response.parsedModel as VKApiGetMessagesResponse val list = result.items.toList() lastMessages.addAll(list) sendMessagesToSubscribers(list) } } override fun onError(error: VKError?) { error?.let { if (it.httpError != null) { sendErrorToSubscribers(it.httpError) } else if (it.apiError != null) { sendErrorToSubscribers(Exception(it.apiError.errorMessage)) } else { sendErrorToSubscribers(Exception(it.errorMessage)) } } } }) } private fun sendMessagesToSubscribers(messages: List<VKApiMessage>) { for (subscriber in messagesSubscribers) { subscriber.onMessagesReceived(messages) } } private fun sendErrorToSubscribers(error: Exception) { for (subscriber in messagesSubscribers) { subscriber.onMessagesError(error) } } interface RequestMessagesListener { fun onMessagesReceived(messages: List<VKApiMessage>) fun onMessagesError(error: Exception) } }
mit
f7793cd2e66590d142df8c6283f130bd
32.329545
93
0.621078
5.090278
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/subscribers/Show.kt
1
2286
package com.twitter.meil_mitu.twitter4hk.api.lists.subscribers import com.twitter.meil_mitu.twitter4hk.AbsGet import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.ResponseData import com.twitter.meil_mitu.twitter4hk.converter.IUserConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class Show<TUser> : AbsGet<ResponseData<TUser>> { protected val json: IUserConverter<TUser> var listId: Long? by longParam("list_id") var userId: Long? by longParam("user_id") var screenName: String? by stringParam("screen_name") var slug: String? by stringParam("slug") var ownerScreenName: String? by stringParam("owner_screen_name") var ownerId: Long? by longParam("owner_id") var includeEntities: Boolean? by booleanParam("include_entities") var skipStatus: Boolean? by booleanParam("skip_status") override val url = "https://api.twitter.com/1.1/lists/subscribers/show.json" override val allowOauthType = OauthType.oauth1 or OauthType.oauth2 override val isAuthorization = true constructor( oauth: AbsOauth, json: IUserConverter<TUser>, listId: Long, userId: Long) : super(oauth) { this.json = json this.listId = listId this.userId = userId } constructor( oauth: AbsOauth, json: IUserConverter<TUser>, listId: Long, screenName: String) : super(oauth) { this.json = json this.listId = listId this.screenName = screenName } constructor( oauth: AbsOauth, json: IUserConverter<TUser>, slug: String, userId: Long) : super(oauth) { this.json = json this.slug = slug this.userId = userId } constructor( oauth: AbsOauth, json: IUserConverter<TUser>, slug: String, screenName: String) : super(oauth) { this.json = json this.slug = slug this.screenName = screenName } @Throws(Twitter4HKException::class) override fun call(): ResponseData<TUser> { return json.toUserResponseData(oauth.get(this)) } }
mit
22d5039f262c8c9b749e67843b267aac
32.130435
80
0.647857
4.264925
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/CustomizationDeserializer.kt
1
6747
package com.habitrpg.android.habitica.utils import android.annotation.SuppressLint import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.Customization import io.realm.Realm import io.realm.RealmList import java.lang.reflect.Type import java.text.SimpleDateFormat class CustomizationDeserializer : JsonDeserializer<List<Customization>> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): List<Customization> { val jsonObject = json.asJsonObject val customizations = RealmList<Customization>() val realm = Realm.getDefaultInstance() val existingCustomizations = realm.copyFromRealm(realm.where(Customization::class.java).findAll()) if (jsonObject.has("shirt")) { for (customization in existingCustomizations) { if (jsonObject.has(customization.type)) { var nestedObject = jsonObject.get(customization.type).asJsonObject if (customization.category != null) { if (nestedObject.has(customization.category)) { nestedObject = nestedObject.get(customization.category).asJsonObject } else { continue } } if (nestedObject.has(customization.identifier)) { customizations.add(this.parseCustomization(customization, customization.type, customization.category, customization.identifier, nestedObject.get(customization.identifier).asJsonObject)) nestedObject.remove(customization.identifier) } } } for (type in listOf("shirt", "skin", "chair")) { for ((key, value) in jsonObject.get(type).asJsonObject.entrySet()) { customizations.add(this.parseCustomization(null, type, null, key, value.asJsonObject)) } } for ((key, value) in jsonObject.get("hair").asJsonObject.entrySet()) { for ((key1, value1) in value.asJsonObject.entrySet()) { customizations.add(this.parseCustomization(null, "hair", key, key1, value1.asJsonObject)) } } } else { for (customization in existingCustomizations) { if (jsonObject.has(customization.customizationSet)) { val nestedObject = jsonObject.get(customization.customizationSet).asJsonObject if (nestedObject.has(customization.identifier)) { customizations.add(this.parseBackground(customization, customization.customizationSet ?: "", customization.identifier, nestedObject.get(customization.identifier).asJsonObject)) nestedObject.remove(customization.identifier) } } } for ((key, value) in jsonObject.entrySet()) { for ((key1, value1) in value.asJsonObject.entrySet()) { customizations.add(this.parseBackground(null, key, key1, value1.asJsonObject)) } } } realm.close() return customizations } private fun parseCustomization(existingCustomizaion: Customization?, type: String?, category: String?, key: String?, entry: JsonObject): Customization { var customization = existingCustomizaion if (customization == null) { customization = Customization() customization.identifier = key customization.type = type if (category != null) { customization.category = category } } if (entry.has("price")) { customization.price = entry.get("price").asInt } if (entry.has("set")) { val setInfo = entry.get("set").asJsonObject customization.customizationSet = setInfo.get("key").asString if (setInfo.has("setPrice")) { customization.setPrice = setInfo.get("setPrice").asInt } if (setInfo.has("text")) { customization.customizationSetName = setInfo.get("text").asString } @SuppressLint("SimpleDateFormat") val format = SimpleDateFormat("yyyy-MM-dd") try { if (setInfo.has("availableFrom")) { customization.availableFrom = format.parse(setInfo.get("availableFrom").asString) } if (setInfo.has("availableUntil")) { customization.availableUntil = format.parse(setInfo.get("availableUntil").asString) } } catch (e: Exception) { RxErrorHandler.reportError(e) } } return customization } private fun parseBackground(existingCustomization: Customization?, setName: String, key: String?, entry: JsonObject): Customization { var customization = existingCustomization if (customization == null) { customization = Customization() customization.customizationSet = setName val readableSetName = setName.substring(13, 17) + "." + setName.substring(11, 13) customization.customizationSetName = readableSetName customization.type = "background" customization.identifier = key } when (setName) { "incentiveBackgrounds" -> { customization.customizationSetName = "Login Incentive" customization.price = 0 customization.setPrice = 0 customization.isBuyable = false } "timeTravelBackgrounds" -> { customization.customizationSetName = "Time Travel Backgrounds" customization.price = 1 customization.setPrice = 0 customization.isBuyable = false } else -> { customization.price = 7 customization.setPrice = 15 } } customization.text = entry.get("text").asString customization.notes = entry.asJsonObject.get("notes").asString return customization } }
gpl-3.0
fa275fc0a42c76f9c3a9a13d162040fd
42.682119
209
0.584111
5.679293
false
false
false
false
androidx/androidx
fragment/fragment-lint/src/test/java/androidx/fragment/lint/BackPressedDispatcherCallbackDetectorTest.kt
3
8210
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UnstableApiUsage") package androidx.fragment.lint import androidx.fragment.lint.stubs.BACK_CALLBACK_STUBS import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.TestFile import com.android.tools.lint.checks.infrastructure.TestLintResult import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Issue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class BackPressedDispatcherCallbackDetectorTest : LintDetectorTest() { override fun getDetector(): Detector = UnsafeFragmentLifecycleObserverDetector() override fun getIssues(): MutableList<Issue> = mutableListOf(UnsafeFragmentLifecycleObserverDetector.BACK_PRESSED_ISSUE) private fun check(vararg files: TestFile): TestLintResult { return lint().files(*files, *BACK_CALLBACK_STUBS) .run() } @Test fun pass() { check( kotlin( """ package com.example import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback import com.example.test.Foo class TestFragment : Fragment { override fun onCreateView() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(getViewLifecycleOwner(), OnBackPressedCallback {}) } override fun onViewCreated() { test() val foo = Foo() foo.addCallback(this) foo.callback(this) } private fun test() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(getViewLifecycleOwner(), OnBackPressedCallback {}) test() } } """ ), kotlin( """ package com.example.test import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class Foo { fun addCallback(fragment: Fragment) { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(LifecycleOwner(), OnBackPressedCallback {}) } fun callback(fragment: Fragment) {} } """ ) ) .expectClean() } @Test fun inMethodFails() { check( kotlin( """ package com.example import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class TestFragment : Fragment { override fun onCreateView() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(this, OnBackPressedCallback {}) } } """ ) ) .expect( """ src/com/example/TestFragment.kt:12: Error: Use viewLifecycleOwner as the LifecycleOwner. [FragmentBackPressedCallback] dispatcher.addCallback(this, OnBackPressedCallback {}) ~~~~ 1 errors, 0 warnings """ ) .checkFix( null, kotlin( """ package com.example import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class TestFragment : Fragment { override fun onCreateView() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(viewLifecycleOwner, OnBackPressedCallback {}) } } """ ) ) } @Test fun helperMethodFails() { check( kotlin( """ package com.example import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class TestFragment : Fragment { override fun onCreateView() { test() } private fun test() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(this, OnBackPressedCallback {}) } } """ ) ) .expect( """ src/com/example/TestFragment.kt:16: Error: Use viewLifecycleOwner as the LifecycleOwner. [FragmentBackPressedCallback] dispatcher.addCallback(this, OnBackPressedCallback {}) ~~~~ 1 errors, 0 warnings """ ) .checkFix( null, kotlin( """ package com.example import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class TestFragment : Fragment { override fun onCreateView() { test() } private fun test() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(viewLifecycleOwner, OnBackPressedCallback {}) } } """ ) ) } @Test fun externalCallFails() { check( kotlin( """ package com.example import androidx.fragment.app.Fragment import com.example.test.Foo class TestFragment : Fragment { override fun onCreateView() { test() } private fun test() { val foo = Foo() foo.addCallback(this) } } """ ), kotlin( """ package com.example.test import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class Foo { fun addCallback(fragment: Fragment) { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(fragment, OnBackPressedCallback {}) } } """ ) ) .expect( """ src/com/example/test/Foo.kt:11: Error: Unsafe call to addCallback with Fragment instance as LifecycleOwner from TestFragment.onCreateView. [FragmentBackPressedCallback] dispatcher.addCallback(fragment, OnBackPressedCallback {}) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """ ) } @Test fun externalHelperMethodFails() { check( kotlin( """ package com.example import androidx.fragment.app.Fragment import com.example.test.Foo class TestFragment : Fragment { override fun onCreateView() { test() } private fun test() { val foo = Foo() foo.addCallback(this) } } """ ), kotlin( """ package com.example.test import androidx.fragment.app.Fragment import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedCallback class Foo { private lateinit val fragment: Fragment fun addCallback(fragment: Fragment) { this.fragment = fragment callback() } private fun callback() { val dispatcher = OnBackPressedDispatcher() dispatcher.addCallback(fragment, OnBackPressedCallback {}) } } """ ) ) .expect( """ src/com/example/test/Foo.kt:18: Error: Unsafe call to addCallback with Fragment instance as LifecycleOwner from TestFragment.onCreateView. [FragmentBackPressedCallback] dispatcher.addCallback(fragment, OnBackPressedCallback {}) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 errors, 0 warnings """ ) } }
apache-2.0
52b4f7f55871f88c017df88e0e58d9c6
24.899054
168
0.626066
5.259449
false
true
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/MutableLoadStateCollection.kt
3
1505
/* * 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.paging import androidx.paging.LoadState.NotLoading internal class MutableLoadStateCollection { var refresh: LoadState = NotLoading.Incomplete var prepend: LoadState = NotLoading.Incomplete var append: LoadState = NotLoading.Incomplete fun snapshot() = LoadStates( refresh = refresh, prepend = prepend, append = append, ) fun get(loadType: LoadType) = when (loadType) { LoadType.REFRESH -> refresh LoadType.APPEND -> append LoadType.PREPEND -> prepend } fun set(type: LoadType, state: LoadState) = when (type) { LoadType.REFRESH -> refresh = state LoadType.APPEND -> append = state LoadType.PREPEND -> prepend = state } fun set(states: LoadStates) { refresh = states.refresh append = states.append prepend = states.prepend } }
apache-2.0
fa6d5483fae87137f1bbb45b7c9f470b
29.734694
75
0.683721
4.574468
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/database/table/NoteTable.kt
1
7485
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.database.table import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import org.andstatus.app.data.DbUtils import org.andstatus.app.data.DownloadStatus /** * Table for both public and private notes * i.e. for tweets, dents, notices * and also for "direct messages", "direct dents" etc. */ object NoteTable : BaseColumns { val TABLE_NAME: String = "note" // Table columns are below: /* * {@link BaseColumns#_ID} is primary key in this database * No, we can not rename the {@link BaseColumns#_ID}, it should always be "_id". * See <a href="http://stackoverflow.com/questions/3359414/android-column-id-does-not-exist">Android column '_id' does not exist?</a> */ /** * ID of the originating (source) system ("Social Network": twitter.com, identi.ca, ... ) where the row was created */ val ORIGIN_ID: String = OriginTable.ORIGIN_ID /** * ID in the originating system * The id is not unique for this table, because we have IDs from different systems in one column * and IDs from different systems may overlap. */ val NOTE_OID: String = "note_oid" /** * See [DownloadStatus]. Defaults to [DownloadStatus.UNKNOWN] */ val NOTE_STATUS: String = "note_status" /** Conversation ID, internal to AndStatus */ val CONVERSATION_ID: String = "conversation_id" /** ID of the conversation in the originating system (if the system supports this) */ val CONVERSATION_OID: String = "conversation_oid" /** * A link to the representation of the resource. Currently this is simply URL to the HTML * representation of the resource (its "permalink") */ val URL: String = "url" /** A simple, human-readable, plain-text name for the Note */ val NAME: String = "note_name" /** A natural language summarization of the object. * Used as a Content Warning (CW) if [.SENSITIVE] flag is set. */ val SUMMARY: String = "summary" /** Content of the note */ val CONTENT: String = "content" /** Name and Content text, prepared for easy searching in a database */ val CONTENT_TO_SEARCH: String = "content_to_search" /** * String generally describing Client's software used to post this note * It's like "User Agent" string in the browsers?!: "via ..." * (This is "source" field in tweets) */ val VIA: String = "via" /** * If not null: Link to the #_ID in this table */ val IN_REPLY_TO_NOTE_ID: String = "in_reply_to_note_id" /** * Date and time when the note was created or updated in the originating system. * We store it as long milliseconds. */ val UPDATED_DATE: String = "note_updated_date" /** Date and time when the Note was first LOADED into this database * or if it was not LOADED yet, when the row was inserted into this database */ val INS_DATE: String = "note_ins_date" /** [org.andstatus.app.net.social.Visibility] */ val VISIBILITY: String = "public" // TODO: rename /** Indicates that some users may wish to apply discretion about viewing its content, whether due to nudity, * violence, or any other likely aspects that viewers may be sensitive to. * See [Activity Streams extensions](https://www.w3.org/wiki/Activity_Streams_extensions#as:sensitive_property) */ val SENSITIVE: String = "sensitive" /** Some of my accounts favorited this note */ val FAVORITED: String = "favorited" /** The Note is reblogged by some of my actors * In some sense REBLOGGED is like FAVORITED. * Main difference: visibility. REBLOGGED are shown for all followers in their Home timelines. */ val REBLOGGED: String = "reblogged" val LIKES_COUNT: String = "favorite_count" // TODO: rename val REBLOGS_COUNT: String = "reblog_count" // TODO: rename val REPLIES_COUNT: String = "reply_count" // TODO: rename. To be calculated locally?! val ATTACHMENTS_COUNT: String = "attachments_count" // Columns, which duplicate other existing info. Here to speed up data retrieval val AUTHOR_ID: String = "note_author_id" /** * If not null: to which Sender this note is a reply = Actor._ID * This field is not necessary but speeds up IN_REPLY_TO_NAME calculation */ val IN_REPLY_TO_ACTOR_ID: String = "in_reply_to_actor_id" // Derived columns (they are not stored in this table but are result of joins and aliasing) /** Alias for the primary key */ val NOTE_ID: String = "note_id" fun create(db: SQLiteDatabase) { DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + ORIGIN_ID + " INTEGER NOT NULL," + NOTE_OID + " TEXT NOT NULL," + NOTE_STATUS + " INTEGER NOT NULL DEFAULT 0," + CONVERSATION_ID + " INTEGER NOT NULL DEFAULT 0" + "," + CONVERSATION_OID + " TEXT," + URL + " TEXT," + NAME + " TEXT," + SUMMARY + " TEXT," + CONTENT + " TEXT," + CONTENT_TO_SEARCH + " TEXT," + VIA + " TEXT," + AUTHOR_ID + " INTEGER NOT NULL DEFAULT 0," + IN_REPLY_TO_NOTE_ID + " INTEGER," + IN_REPLY_TO_ACTOR_ID + " INTEGER," + VISIBILITY + " INTEGER NOT NULL DEFAULT 0," + SENSITIVE + " INTEGER NOT NULL DEFAULT 0," + FAVORITED + " INTEGER NOT NULL DEFAULT 0," + REBLOGGED + " INTEGER NOT NULL DEFAULT 0," + LIKES_COUNT + " INTEGER NOT NULL DEFAULT 0," + REBLOGS_COUNT + " INTEGER NOT NULL DEFAULT 0," + REPLIES_COUNT + " INTEGER NOT NULL DEFAULT 0," + ATTACHMENTS_COUNT + " INTEGER NOT NULL DEFAULT 0," + INS_DATE + " INTEGER NOT NULL," + UPDATED_DATE + " INTEGER NOT NULL DEFAULT 0" + ")") DbUtils.execSQL(db, "CREATE UNIQUE INDEX idx_note_origin ON " + TABLE_NAME + " (" + ORIGIN_ID + ", " + NOTE_OID + ")" ) // Index not null rows only, see https://www.sqlite.org/partialindex.html DbUtils.execSQL(db, "CREATE INDEX idx_note_in_reply_to_note_id ON " + TABLE_NAME + " (" + IN_REPLY_TO_NOTE_ID + ")" ) DbUtils.execSQL(db, "CREATE INDEX idx_note_conversation_id ON " + TABLE_NAME + " (" + CONVERSATION_ID + ")" ) DbUtils.execSQL(db, "CREATE INDEX idx_conversation_oid ON " + TABLE_NAME + " (" + ORIGIN_ID + ", " + CONVERSATION_OID + ")" ) } }
apache-2.0
06b39c4f8106965d9e497bc9a47a80db
40.126374
137
0.608818
4.121696
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/external/HaskellExternalAnnotator.kt
1
7081
package org.jetbrains.haskell.external import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.ExternalAnnotator import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nullable import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.module.ModuleUtilCore import org.json.simple.JSONArray import java.io.File import org.jetbrains.haskell.util.copyFile import org.json.simple.JSONObject import org.jetbrains.haskell.util.LineColPosition import com.intellij.openapi.vfs.LocalFileSystem import java.util.HashSet import sun.nio.cs.StandardCharsets import java.io.ByteArrayInputStream import org.jetbrains.haskell.util.getRelativePath import com.intellij.openapi.application.ModalityState import java.util.regex.Pattern import java.util.ArrayList import org.jetbrains.haskell.config.HaskellSettings public class HaskellExternalAnnotator() : ExternalAnnotator<PsiFile, List<ErrorMessage>>() { override fun collectInformation(file: PsiFile): PsiFile { return file } fun copyContent(basePath: VirtualFile, destination: File) { if (!destination.exists()) { destination.mkdir() } val localFileSystem = LocalFileSystem.getInstance()!! val destinationFiles = HashSet(destination.list()!!.toList()) for (child in basePath.getChildren()!!) { destinationFiles.remove(child.getName()) if (child.getName().equals(".idea")) { continue } if (child.getName().equals("dist")) { continue } if (child.getName().equals(".buildwrapper")) { continue } val destinationFile = File(destination, child.getName()) if (child.isDirectory()) { copyContent(child, destinationFile) } else { val childTime = child.getModificationStamp() val document = FileDocumentManager.getInstance().getCachedDocument(child) if (document != null) { val stream = ByteArrayInputStream(document.getText().toByteArray(child.getCharset())); copyFile(stream, destinationFile) } else { val destinationTime = localFileSystem.findFileByIoFile(destinationFile)?.getModificationStamp() if (destinationTime == null || childTime > destinationTime) { copyFile(child.getInputStream()!!, destinationFile) } } } } for (file in destinationFiles) { if (file.endsWith(".hs")) { File(destination, file).delete() } } } fun getResultFromGhcModi(psiFile: PsiFile, baseDir: VirtualFile, file: VirtualFile): List<ErrorMessage> { ApplicationManager.getApplication()!!.invokeAndWait(object : Runnable { override fun run() { FileDocumentManager.getInstance().saveAllDocuments() } }, ModalityState.any()) val ghcModi = psiFile.getProject().getComponent(javaClass<GhcModi>())!! val relativePath = getRelativePath(baseDir.getPath(), file.getPath()) val result = ghcModi.runCommand("check $relativePath") val errors = ArrayList<ErrorMessage>() for (resultLine in result) { val matcher = Pattern.compile("(.*):(\\d*):(\\d*):(.*)").matcher(resultLine) if (matcher.find()) { val path = matcher.group(1)!! val line = Integer.parseInt(matcher.group(2)!!) val col = Integer.parseInt(matcher.group(3)!!) val msg = matcher.group(4)!!.replace("\u0000", "\n") val severity = if (msg.startsWith("Warning")) { ErrorMessage.Severity.Warning } else { ErrorMessage.Severity.Error } if (relativePath == path) { errors.add(ErrorMessage(msg, path, severity, line, col, line, col)) } } } return errors } fun getResultFromBuidWrapper(psiFile: PsiFile, moduleContent: VirtualFile, file: VirtualFile): List<ErrorMessage> { ApplicationManager.getApplication()!!.invokeAndWait(object : Runnable { override fun run() { FileDocumentManager.getInstance().saveAllDocuments() } }, ModalityState.any()) copyContent(moduleContent, File(moduleContent.getCanonicalPath()!!, ".buildwrapper")) val out = BuildWrapper.init(psiFile).build1(file) if (out != null) { val errors = out.get(1) as JSONArray return errors.map { ErrorMessage.fromJson(it!!) } } return listOf() } fun getProjectBaseDir(psiFile: PsiFile): VirtualFile? { return psiFile.getProject().getBaseDir() } override fun doAnnotate(psiFile: PsiFile?): List<ErrorMessage> { val file = psiFile!!.getVirtualFile() if (file == null) { return listOf() } val baseDir = getProjectBaseDir(psiFile) if (baseDir == null) { return listOf() } if (!(HaskellSettings.getInstance().getState().useGhcMod!!)) { return listOf(); } if (!file.isInLocalFileSystem()) { return listOf() } return getResultFromGhcModi(psiFile, baseDir, file) } override fun apply(file: PsiFile, annotationResult: List<ErrorMessage>?, holder: AnnotationHolder) { for (error in annotationResult!!) { val start = LineColPosition(error.line, error.column).getOffset(file) val end = LineColPosition(error.eLine, error.eColumn).getOffset(file) val element = file.findElementAt(start) if (element != null) { when (error.severity) { ErrorMessage.Severity.Error -> holder.createErrorAnnotation(element, error.text); ErrorMessage.Severity.Warning -> holder.createWarningAnnotation(element, error.text); } } else { when (error.severity) { ErrorMessage.Severity.Error -> holder.createErrorAnnotation(TextRange(start, end), error.text); ErrorMessage.Severity.Warning -> holder.createWarningAnnotation(TextRange(start, end), error.text); } } } } }
apache-2.0
026e201e9180ec820baf82e3993c1531
36.664894
119
0.603587
5.260773
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/org/smileLee/cyls/qqbot/TreeNode.kt
1
1258
package org.smileLee.cyls.qqbot import sun.dc.path.PathException class TreeNode<T : QQBot<T>> { interface RunnerForJava<T : QQBot<T>> { fun run(str: String, qqBot: T) } val name: String val runner: (String, T) -> Unit val children = HashMap<String, TreeNode<T>>() //used in kotlin constructor(name: String, parent: TreeNode<T>, runner: (String, T) -> Unit) { this.name = name this.runner = runner parent.children.put(name, this) } constructor(name: String, runner: (String, T) -> Unit) { this.name = name this.runner = runner } //used in java constructor(name: String, parent: TreeNode<T>?, runner: RunnerForJava<T>) { this.name = name this.runner = { str, qqBot -> runner.run(str, qqBot) } parent?.children?.put(name, this) } constructor(name: String, runner: RunnerForJava<T>) { this.name = name this.runner = { str, cyls -> runner.run(str, cyls) } } fun findPath(path: List<String>, index: Int = 0): TreeNode<T> = if (index == path.size) this else children[path[index]]?.findPath(path, index + 1) ?: throw PathException() fun run(message: String, qqBot: T) = runner(message, qqBot) }
mit
f0d981674ce4da60b22a9a7e733daac3
27.590909
96
0.604928
3.427793
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/InformationActivity.kt
1
5240
package de.tum.`in`.tumcampusapp.component.ui.overview import android.content.ClipData import android.content.ClipboardManager import android.content.Intent import android.content.Intent.ACTION_VIEW import android.content.pm.PackageManager.NameNotFoundException import android.net.Uri import android.os.Bundle import android.preference.PreferenceManager import android.text.format.DateUtils import android.view.View import android.view.ViewGroup import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import androidx.core.content.pm.PackageInfoCompat import de.psdev.licensesdialog.LicensesDialog import de.tum.`in`.tumcampusapp.BuildConfig import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import kotlinx.android.synthetic.main.activity_information.* /** * Provides information about this app and all contributors */ class InformationActivity : BaseActivity(R.layout.activity_information) { private val rowParams = TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.displayDebugInfo() button_facebook.setOnClickListener { openFacebook() } button_github.setOnClickListener { startActivity(Intent(ACTION_VIEW, Uri.parse(getString(R.string.github_link)))) } button_privacy.setOnClickListener { startActivity(Intent(ACTION_VIEW, Uri.parse(getString(R.string.url_privacy_policy)))) } button_licenses.setOnClickListener { LicensesDialog.Builder(this) .setNotices(R.raw.notices) .setShowFullLicenseText(false) .setIncludeOwnLicense(true) .build() .show() } } /** * Open the Facebook app or view page in a browser if Facebook is not installed. */ private fun openFacebook() { try { packageManager.getPackageInfo("com.facebook.katana", 0) val intent = Intent(ACTION_VIEW, Uri.parse(getString(R.string.facebook_link_app))) startActivity(intent) } catch (e: Exception) { // Don't make any assumptions about another app, just start the browser instead val default = Intent(ACTION_VIEW, Uri.parse(getString(R.string.facebook_link))) startActivity(default) } } private fun displayDebugInfo() { // Setup showing of debug information val sp = PreferenceManager.getDefaultSharedPreferences(this) try { val packageInfo = packageManager.getPackageInfo(packageName, 0) this.addDebugRow(debugInfos, "App version", packageInfo.versionName) } catch (ignore: NameNotFoundException) { } this.addDebugRow(debugInfos, "TUM ID", sp.getString(Const.LRZ_ID, "")) val token = sp.getString(Const.ACCESS_TOKEN, "") if (token == "") { this.addDebugRow(debugInfos, "TUM access token", "") } else { this.addDebugRow(debugInfos, "TUM access token", token?.substring(0, 5) + "...") } this.addDebugRow(debugInfos, "Bug reports", sp.getBoolean(Const.BUG_REPORTS, false).toString() + " ") this.addDebugRow(debugInfos, "REG ID", Utils.getSetting(this, Const.FCM_REG_ID, "")) this.addDebugRow(debugInfos, "REG transmission", DateUtils.getRelativeDateTimeString(this, Utils.getSettingLong(this, Const.FCM_REG_ID_LAST_TRANSMISSION, 0), DateUtils.MINUTE_IN_MILLIS, DateUtils.DAY_IN_MILLIS * 2, 0).toString()) try { val packageInfo = packageManager.getPackageInfo(packageName, 0) this.addDebugRow(debugInfos, "Version code", PackageInfoCompat.getLongVersionCode(packageInfo).toString()) } catch (ignore: NameNotFoundException) { } this.addDebugRow(debugInfos, "Build configuration", BuildConfig.DEBUG.toString()) debugInfos.visibility = View.VISIBLE } private fun addDebugRow(tableLayout: TableLayout, label: String, value: String?) { val tableRow = TableRow(this) tableRow.layoutParams = rowParams val labelTextView = TextView(this).apply { text = label layoutParams = rowParams val padding = resources.getDimensionPixelSize(R.dimen.material_small_padding) setPadding(0, 0, padding, 0) } tableRow.addView(labelTextView) val valueTextView = TextView(this).apply { text = value layoutParams = rowParams isClickable = true setOnLongClickListener { val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(label, value) clipboard.setPrimaryClip(clip) true } } tableRow.addView(valueTextView) tableLayout.addView(tableRow) } }
gpl-3.0
e1a6acc83647e6f2f47eb8ee3204bc75
38.104478
123
0.665458
4.767971
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/ChatMessagesCardViewHolder.kt
1
1810
package de.tum.`in`.tumcampusapp.component.ui.chat import android.view.View import android.widget.TextView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder import kotlinx.android.synthetic.main.card_chat_messages.view.* class ChatMessagesCardViewHolder( itemView: View, interactionListener: CardInteractionListener ) : CardViewHolder(itemView, interactionListener) { @Suppress("UNUSED_PARAMETER") fun bind(roomName: String, roomId: Int, roomIdStr: String, unreadMessages: List<ChatMessage>) { with(itemView) { chatRoomNameTextView.text = if (unreadMessages.size > 5) { context.getString(R.string.card_message_title, roomName, unreadMessages.size) } else { roomName } if (contentContainerLayout.childCount == 0) { // We have not yet inflated the chat messages unreadMessages.asSequence() .map { message -> val memberName = message.member.displayName context.getString(R.string.card_message_line, memberName, message.text) } .map { messageText -> TextView(context, null, R.style.CardBody).apply { text = messageText } } .toList() .forEach { textView -> contentContainerLayout.addView(textView) } } } } }
gpl-3.0
65c3fb08c7d3cc1eac2b0cb17eadb0ae
40.159091
99
0.571823
5.216138
false
false
false
false
firebase/snippets-android
mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt
1
5503
package com.google.firebase.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.tasks.OnFailureListener import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.face.FirebaseVisionFace import com.google.firebase.ml.vision.face.FirebaseVisionFaceContour import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark class FaceDetectionActivity : AppCompatActivity() { private fun detectFaces(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionFaceDetectorOptions.Builder() .setClassificationMode(FirebaseVisionFaceDetectorOptions.ACCURATE) .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) .setMinFaceSize(0.15f) .enableTracking() .build() // [END set_detector_options] // [START get_detector] val detector = FirebaseVision.getInstance() .getVisionFaceDetector(options) // [END get_detector] // [START fml_run_detector] val result = detector.detectInImage(image) .addOnSuccessListener { faces -> // Task completed successfully // [START_EXCLUDE] // [START get_face_info] for (face in faces) { val bounds = face.boundingBox val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees // If landmark detection was enabled (mouth, ears, eyes, cheeks, and // nose available): val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR) leftEar?.let { val leftEarPos = leftEar.position } // If classification was enabled: if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { val smileProb = face.smilingProbability } if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { val rightEyeOpenProb = face.rightEyeOpenProbability } // If face tracking was enabled: if (face.trackingId != FirebaseVisionFace.INVALID_ID) { val id = face.trackingId } } // [END get_face_info] // [END_EXCLUDE] } .addOnFailureListener { e -> // Task failed with an exception // ... } // [END fml_run_detector] } private fun faceOptionsExamples() { // [START mlkit_face_options_examples] // High-accuracy landmark detection and face classification val highAccuracyOpts = FirebaseVisionFaceDetectorOptions.Builder() .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE) .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) .build() // Real-time contour detection of multiple faces val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder() .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS) .build() // [END mlkit_face_options_examples] } private fun processFaceList(faces: List<FirebaseVisionFace>) { // [START mlkit_face_list] for (face in faces) { val bounds = face.boundingBox val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees // If landmark detection was enabled (mouth, ears, eyes, cheeks, and // nose available): val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR) leftEar?.let { val leftEarPos = leftEar.position } // If contour detection was enabled: val leftEyeContour = face.getContour(FirebaseVisionFaceContour.LEFT_EYE).points val upperLipBottomContour = face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).points // If classification was enabled: if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { val smileProb = face.smilingProbability } if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { val rightEyeOpenProb = face.rightEyeOpenProbability } // If face tracking was enabled: if (face.trackingId != FirebaseVisionFace.INVALID_ID) { val id = face.trackingId } } // [END mlkit_face_list] } }
apache-2.0
8c2b87e6586e96d0d7d32e0f499d11f1
44.858333
106
0.597856
5.609582
false
false
false
false
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/impl/mappers/CharMapper.kt
1
940
package sqlbuilder.impl.mappers import sqlbuilder.mapping.BiMapper import sqlbuilder.mapping.ToObjectMappingParameters import sqlbuilder.mapping.ToSQLMappingParameters import java.sql.Types /** * @author Laurent Van der Linden. */ class CharMapper : BiMapper { override fun toObject(params: ToObjectMappingParameters): Char? { val string = params.resultSet.getString(params.index) if (string != null && string.isNotEmpty()) return string[0] return null } override fun toSQL(params: ToSQLMappingParameters) { if (params.value == null) { params.preparedStatement.setNull(params.index, Types.VARCHAR) } else { params.preparedStatement.setString(params.index, params.value.toString()) } } override fun handles(targetType: Class<*>): Boolean { return targetType == Char::class.java || java.lang.Character::class.java == targetType } }
apache-2.0
097a74b365526d902ef66216be8ec11d
30.366667
94
0.693617
4.563107
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/notifications/NotificationTimeCheckerImpl.kt
2
1174
package org.stepic.droid.notifications import java.util.Calendar import javax.inject.Inject class NotificationTimeCheckerImpl @Inject constructor( private var startHour: Int, private var endHour: Int) : NotificationTimeChecker { private val invertAnswer: Boolean init { if (endHour < 0 || startHour < 0) { throw IllegalArgumentException("interval bounds cannot be negative") } if (endHour > 23 || startHour > 23) { throw IllegalArgumentException("interval bounds cannot be greater than 23") } if (endHour >= startHour) { invertAnswer = false } else { startHour = startHour.xor(endHour) endHour = startHour.xor(endHour) startHour = startHour.xor(endHour) invertAnswer = true } } override fun isNight(nowMillis: Long): Boolean { val calendar = Calendar.getInstance() calendar.timeInMillis = nowMillis val nowHourInt = calendar.get(Calendar.HOUR_OF_DAY) val result: Boolean = nowHourInt in startHour until endHour return result.xor(invertAnswer) } }
apache-2.0
cb2df6b70e6233bd717e81ff99c9be26
28.35
87
0.632027
4.932773
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/onboarding/ui/activity/OnboardingCourseListsActivity.kt
1
4829
package org.stepik.android.view.onboarding.ui.activity import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_onboarding_course_lists.* import kotlinx.android.synthetic.main.item_onboarding.view.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.activities.MainFeedActivity import org.stepik.android.domain.onboarding.analytic.OnboardingOpenedAnalyticEvent import org.stepik.android.domain.onboarding.analytic.OnboardingCourseListSelectedAnalyticEvent import org.stepik.android.domain.onboarding.analytic.OnboardingCompletedAnalyticEvent import org.stepik.android.domain.onboarding.analytic.OnboardingClosedAnalyticEvent import org.stepik.android.domain.onboarding.analytic.OnboardingBackToGoalsAnalyticEvent import org.stepik.android.view.onboarding.model.OnboardingCourseList import org.stepik.android.view.onboarding.model.OnboardingGoal import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import javax.inject.Inject class OnboardingCourseListsActivity : AppCompatActivity(R.layout.activity_onboarding_course_lists) { companion object { private const val EXTRA_ONBOARDING_GOAL = "onboarding_goal" fun createIntent(context: Context, onboardingGoal: OnboardingGoal): Intent = Intent(context, OnboardingCourseListsActivity::class.java) .putExtra(EXTRA_ONBOARDING_GOAL, onboardingGoal) init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } } private val onboardingGoal by lazy { intent.getParcelableExtra<OnboardingGoal>(EXTRA_ONBOARDING_GOAL) } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper private val courseListsAdapter: DefaultDelegateAdapter<OnboardingCourseList> = DefaultDelegateAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App.component().inject(this) analytic.report(OnboardingOpenedAnalyticEvent(screen = 2)) courseListsHeader.text = onboardingGoal.title courseListsAdapter += createCourseListsAdapterDelegate { onboardingCourseList -> sharedPreferenceHelper.personalizedCourseList = onboardingCourseList.id analytic.report(OnboardingCourseListSelectedAnalyticEvent(onboardingCourseList.title, onboardingCourseList.id)) analytic.report(OnboardingCompletedAnalyticEvent) closeOnboarding() } courseListsAdapter.items = onboardingGoal.courseLists courseListsRecycler.layoutManager = LinearLayoutManager(this) courseListsRecycler.adapter = courseListsAdapter backAction.setOnClickListener { onBackPressed() } dismissButton.setOnClickListener { analytic.report(OnboardingClosedAnalyticEvent(screen = 2)) closeOnboarding() } } override fun onBackPressed() { analytic.report(OnboardingBackToGoalsAnalyticEvent) super.onBackPressed() } private fun createCourseListsAdapterDelegate(onItemClicked: (OnboardingCourseList) -> Unit) = adapterDelegate<OnboardingCourseList, OnboardingCourseList>(layoutResId = R.layout.item_onboarding) { val itemContainer = itemView.itemContainer val itemIcon = itemView.itemIcon val itemTitle = itemView.itemTitle itemView.setOnClickListener { item?.let(onItemClicked) } onBind { data -> itemIcon.text = data.icon itemTitle.text = data.title itemIcon.setBackgroundResource(R.drawable.onboarding_goal_yellow_green_gradient) if (data.isFeatured) { itemContainer.setBackgroundResource(R.drawable.onboarding_featured_background) } } } private fun closeOnboarding() { sharedPreferenceHelper.afterOnboardingPassed() sharedPreferenceHelper.setPersonalizedOnboardingWasShown() val isLogged = sharedPreferenceHelper.authResponseFromStore != null if (isLogged) { screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX) } else { screenManager.showLaunchScreen(this) } finish() } }
apache-2.0
d1a95a7d7b5c85055369ad977589687f
41.368421
123
0.746946
5.419753
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt
1
3898
package eu.kanade.tachiyomi.ui.base.controller import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler /** * A controller that displays a dialog window, floating on top of its activity's window. * This is a wrapper over [Dialog] object like [android.app.DialogFragment]. * * Implementations should override this class and implement [.onCreateDialog] to create a custom dialog, such as an [android.app.AlertDialog] */ abstract class DialogController : Controller { protected var dialog: Dialog? = null private set private var dismissed = false /** * Convenience constructor for use when no arguments are needed. */ protected constructor() : super(null) /** * Constructor that takes arguments that need to be retained across restarts. * * @param args Any arguments that need to be retained. */ protected constructor(args: Bundle?) : super(args) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { dialog = onCreateDialog(savedViewState) dialog!!.setOwnerActivity(activity!!) dialog!!.setOnDismissListener { dismissDialog() } if (savedViewState != null) { val dialogState = savedViewState.getBundle(SAVED_DIALOG_STATE_TAG) if (dialogState != null) { dialog!!.onRestoreInstanceState(dialogState) } } return View(activity) // stub view } override fun onSaveViewState(view: View, outState: Bundle) { super.onSaveViewState(view, outState) val dialogState = dialog!!.onSaveInstanceState() outState.putBundle(SAVED_DIALOG_STATE_TAG, dialogState) } override fun onAttach(view: View) { super.onAttach(view) dialog!!.show() } override fun onDetach(view: View) { super.onDetach(view) dialog!!.hide() } override fun onDestroyView(view: View) { super.onDestroyView(view) dialog!!.setOnDismissListener(null) dialog!!.dismiss() dialog = null } /** * Display the dialog, create a transaction and pushing the controller. * @param router The router on which the transaction will be applied */ open fun showDialog(router: Router) { showDialog(router, null) } /** * Display the dialog, create a transaction and pushing the controller. * @param router The router on which the transaction will be applied * @param tag The tag for this controller */ fun showDialog(router: Router, tag: String?) { dismissed = false router.pushController( RouterTransaction.with(this) .pushChangeHandler(SimpleSwapChangeHandler(false)) .popChangeHandler(SimpleSwapChangeHandler(false)) .tag(tag), ) } /** * Dismiss the dialog and pop this controller */ fun dismissDialog() { if (dismissed) { return } router.popController(this) dismissed = true } /** * Build your own custom Dialog container such as an [android.app.AlertDialog] * * @param savedViewState A bundle for the view's state, which would have been created in [.onSaveViewState] or `null` if no saved state exists. * @return Return a new Dialog instance to be displayed by the Controller */ protected abstract fun onCreateDialog(savedViewState: Bundle?): Dialog companion object { private const val SAVED_DIALOG_STATE_TAG = "android:savedDialogState" } }
apache-2.0
6a6a33bd4eec7d0e7c4a4a659c6ff17c
31.756303
147
0.667522
4.997436
false
false
false
false
Heiner1/AndroidAPS
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt
1
804
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase import org.junit.Assert import org.junit.Test class DanaRsPacketHistoryBolusTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } if (it is DanaRSPacketHistoryBolus) { it.rxBus = rxBus } } } @Test fun runTest() { val packet = DanaRSPacketHistoryBolus(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__BOLUS", packet.friendlyName) } }
agpl-3.0
b988d1ced95b169acfc318fd4b46eb5f
28.814815
89
0.665423
5.289474
false
true
false
false
ahant-pabi/field-validator
src/test/kotlin/com/github/ahant/validator/validation/Address.kt
1
1003
package com.github.ahant.validator.validation import com.github.ahant.validator.annotation.FieldInfo import com.github.ahant.validator.validation.FieldValidatorType.STRING import com.github.ahant.validator.validation.FieldValidatorType.ZIP import com.github.ahant.validator.validation.util.CountryCode /** * Created by ahant on 7/16/2016. */ class Address { @FieldInfo(validatorType = STRING, optional = false) var addressLine1: String? = null @FieldInfo(optional = true, validatorType = STRING) var addressLine2: String? = null @FieldInfo(validatorType = STRING, optional = false) var city: String? = null @FieldInfo(validatorType = STRING, optional = false) var state: String? = null @FieldInfo(validatorType = STRING, optional = false) var country = "India" @FieldInfo(validatorType = ZIP, optional = false) var zip: String? = null @FieldInfo(validatorType = ZIP, countryCode = CountryCode.US, optional = false) var usZip: String? = null }
apache-2.0
e7ff61a767705f622e522702382bbc80
37.576923
83
0.735793
4.093878
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt
3
7832
// 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.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.openapi.util.TextRange import com.intellij.patterns.ElementPattern import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.MemberDescriptor import org.jetbrains.kotlin.idea.completion.handlers.WithExpressionPrefixInsertHandler import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor import kotlin.math.max class LookupElementsCollector( private val onFlush: () -> Unit, private val prefixMatcher: PrefixMatcher, private val completionParameters: CompletionParameters, resultSet: CompletionResultSet, sorter: CompletionSorter, private val filter: ((LookupElement) -> Boolean)?, private val allowExpectDeclarations: Boolean ) { var bestMatchingDegree = Int.MIN_VALUE private set private val elements = ArrayList<LookupElement>() private val resultSet = resultSet.withPrefixMatcher(prefixMatcher).withRelevanceSorter(sorter) private val postProcessors = ArrayList<(LookupElement) -> LookupElement>() private val processedCallables = HashSet<CallableDescriptor>() var isResultEmpty: Boolean = true private set fun flushToResultSet() { if (elements.isNotEmpty()) { onFlush() resultSet.addAllElements(elements) elements.clear() isResultEmpty = false } } fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) { postProcessors.add(processor) } fun addDescriptorElements( descriptors: Iterable<DeclarationDescriptor>, lookupElementFactory: AbstractLookupElementFactory, notImported: Boolean = false, withReceiverCast: Boolean = false, prohibitDuplicates: Boolean = false ) { for (descriptor in descriptors) { addDescriptorElements(descriptor, lookupElementFactory, notImported, withReceiverCast, prohibitDuplicates) } } fun addDescriptorElements( descriptor: DeclarationDescriptor, lookupElementFactory: AbstractLookupElementFactory, notImported: Boolean = false, withReceiverCast: Boolean = false, prohibitDuplicates: Boolean = false ) { if (prohibitDuplicates && descriptor is CallableDescriptor && unwrapIfImportedFromObject(descriptor) in processedCallables) return var lookupElements = lookupElementFactory.createStandardLookupElementsForDescriptor(descriptor, useReceiverTypes = true) if (withReceiverCast) { lookupElements = lookupElements.map { it.withReceiverCast() } } addElements(lookupElements, notImported) if (prohibitDuplicates && descriptor is CallableDescriptor) processedCallables.add(unwrapIfImportedFromObject(descriptor)) } fun addElement(element: LookupElement, notImported: Boolean = false) { if (!prefixMatcher.prefixMatches(element)) { return } if (!allowExpectDeclarations) { val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor if ((descriptor as? MemberDescriptor)?.isExpect == true) return } if (notImported) { element.putUserData(NOT_IMPORTED_KEY, Unit) if (isResultEmpty && elements.isEmpty()) { /* without these checks we may get duplicated items */ addElement(element.suppressAutoInsertion()) } else { addElement(element) } return } val decorated = JustTypingLookupElementDecorator(element, completionParameters) var result: LookupElement = decorated for (postProcessor in postProcessors) { result = postProcessor(result) } val declarationLookupObject = result.`object` as? DeclarationLookupObject if (declarationLookupObject != null) { result = DeclarationLookupObjectLookupElementDecorator(result, declarationLookupObject) } if (filter?.invoke(result) != false) { elements.add(result) } val matchingDegree = RealPrefixMatchingWeigher.getBestMatchingDegree(result, prefixMatcher) bestMatchingDegree = max(bestMatchingDegree, matchingDegree) } fun addElements(elements: Iterable<LookupElement>, notImported: Boolean = false) { elements.forEach { addElement(it, notImported) } } fun restartCompletionOnPrefixChange(prefixCondition: ElementPattern<String>) { resultSet.restartCompletionOnPrefixChange(prefixCondition) } } private class JustTypingLookupElementDecorator(element: LookupElement, private val completionParameters: CompletionParameters) : LookupElementDecorator<LookupElement>(element) { // used to avoid insertion of spaces before/after ',', '=' on just typing private fun isJustTyping(context: InsertionContext, element: LookupElement): Boolean { if (!completionParameters.isAutoPopup) return false val insertedText = context.document.getText(TextRange(context.startOffset, context.tailOffset)) return insertedText == element.getUserDataDeep(KotlinCompletionCharFilter.JUST_TYPING_PREFIX) } override fun getDecoratorInsertHandler(): InsertHandler<LookupElementDecorator<LookupElement>> = InsertHandler { context, decorator -> delegate.handleInsert(context) if (context.shouldAddCompletionChar() && !isJustTyping(context, this)) { when (context.completionChar) { ',' -> WithTailInsertHandler.COMMA.postHandleInsert(context, delegate) '=' -> WithTailInsertHandler.EQ.postHandleInsert(context, delegate) '!' -> { WithExpressionPrefixInsertHandler("!").postHandleInsert(context) context.setAddCompletionChar(false) } } } val (typeArgs, exprOffset) = argList ?: return@InsertHandler val beforeCaret = context.file.findElementAt(exprOffset) ?: return@InsertHandler val callExpr = when (val beforeCaretExpr = beforeCaret.prevSibling) { is KtCallExpression -> beforeCaretExpr is KtDotQualifiedExpression -> beforeCaretExpr.collectDescendantsOfType<KtCallExpression>().lastOrNull() else -> null } ?: return@InsertHandler InsertExplicitTypeArgumentsIntention.applyTo(callExpr, typeArgs, true) } } private class DeclarationLookupObjectLookupElementDecorator( element: LookupElement, private val declarationLookupObject: DeclarationLookupObject ) : LookupElementDecorator<LookupElement>(element) { override fun getPsiElement() = declarationLookupObject.psiElement } private fun unwrapIfImportedFromObject(descriptor: CallableDescriptor): CallableDescriptor = if (descriptor is ImportedFromObjectCallableDescriptor<*>) descriptor.callableFromObject else descriptor
apache-2.0
b3db73a27cbeb0053d38eb71840c3c12
40.882353
158
0.72523
5.622398
false
false
false
false
PolymerLabs/arcs
java/arcs/core/storage/driver/testutil/SlowRamDisk.kt
1
3326
package arcs.core.storage.driver.testutil import arcs.core.storage.Driver import arcs.core.storage.DriverProvider import arcs.core.storage.StorageKey import arcs.core.storage.driver.volatiles.VolatileDriverImpl import arcs.core.storage.driver.volatiles.VolatileEntry import arcs.core.storage.driver.volatiles.VolatileMemory import arcs.core.storage.driver.volatiles.VolatileMemoryImpl import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.type.Type import kotlin.reflect.KClass /** * [DriverProvider] implementation which registers itself as capable of handling * [RamDiskStorageKey]s, but uses a [SlowVolatileMemory] bound to the instance, rather than a * global static [VolatileMemory] (the way it is done for [RamDiskDriverProvider]). * * Provide a [waitOp] callback to be able to control when an operation is allowed to finish. */ class SlowRamDiskDriverProvider( waitOp: suspend (SlowVolatileMemory.MemoryOp, StorageKey?) -> Unit ) : DriverProvider { val memory = SlowVolatileMemory(waitOp) override fun willSupport(storageKey: StorageKey) = storageKey is RamDiskStorageKey override suspend fun <Data : Any> getDriver( storageKey: StorageKey, dataClass: KClass<Data>, type: Type ): Driver<Data> = VolatileDriverImpl.create(storageKey, dataClass, memory) override suspend fun removeAllEntities() = Unit override suspend fun removeEntitiesCreatedBetween( startTimeMillis: Long, endTimeMillis: Long ) = Unit } /** * Essentially the same as [VolatileMemoryImpl], except that [waitOp] is used before the operations * exposed by [VolatileMemory] (implemented by [VolatileMemoryImpl]) are called - allowing the * developer to suspend the calling coroutine until they are ready for the operation to proceed. */ @Suppress("UNCHECKED_CAST") class SlowVolatileMemory( private val waitOp: suspend (MemoryOp, StorageKey?) -> Unit ) : VolatileMemory { private val delegate = VolatileMemoryImpl() override val token: String get() = delegate.token override suspend fun contains(key: StorageKey): Boolean { waitOp(MemoryOp.Contains, key) return delegate.contains(key) } override suspend fun <Data : Any> get(key: StorageKey): VolatileEntry<Data>? { waitOp(MemoryOp.Get, key) return delegate.get(key) } override suspend fun <Data : Any> set( key: StorageKey, value: VolatileEntry<Data> ): VolatileEntry<Data>? { waitOp(MemoryOp.Set, key) return delegate.set(key, value) } override suspend fun <Data : Any> update( key: StorageKey, updater: (VolatileEntry<Data>?) -> VolatileEntry<Data> ): Pair<Boolean, VolatileEntry<Data>> { waitOp(MemoryOp.Update, key) return delegate.update(key, updater) } override fun countEntities(): Long = delegate.countEntities() override suspend fun clear() { waitOp(MemoryOp.Clear, null) delegate.clear() } override suspend fun addListener(listener: (StorageKey, Any?) -> Unit) { delegate.addListener(listener) } override suspend fun removeListener(listener: (StorageKey, Any?) -> Unit) { delegate.removeListener(listener) } /** * Type of operation which was performed. Passed to the delaySource callback associated with a * [SlowVolatileMemory]. */ enum class MemoryOp { Contains, Get, Set, Update, Clear } }
bsd-3-clause
23c36fdd21ec541eda0b2800e082a70c
30.980769
99
0.743235
4.280566
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/mailstore/SaveMessageDataCreator.kt
2
2169
package com.fsck.k9.mailstore import com.fsck.k9.crypto.EncryptionExtractor import com.fsck.k9.mail.Message import com.fsck.k9.mail.MessageDownloadState import com.fsck.k9.message.extractors.AttachmentCounter import com.fsck.k9.message.extractors.MessageFulltextCreator import com.fsck.k9.message.extractors.MessagePreviewCreator class SaveMessageDataCreator( private val encryptionExtractor: EncryptionExtractor, private val messagePreviewCreator: MessagePreviewCreator, private val messageFulltextCreator: MessageFulltextCreator, private val attachmentCounter: AttachmentCounter ) { fun createSaveMessageData( message: Message, downloadState: MessageDownloadState, subject: String? = null ): SaveMessageData { val now = System.currentTimeMillis() val date = message.sentDate?.time ?: now val internalDate = message.internalDate?.time ?: now val displaySubject = subject ?: message.subject val encryptionResult = encryptionExtractor.extractEncryption(message) return if (encryptionResult != null) { SaveMessageData( message = message, subject = displaySubject, date = date, internalDate = internalDate, downloadState = downloadState, attachmentCount = encryptionResult.attachmentCount, previewResult = encryptionResult.previewResult, textForSearchIndex = encryptionResult.textForSearchIndex, encryptionType = encryptionResult.encryptionType ) } else { SaveMessageData( message = message, subject = displaySubject, date = date, internalDate = internalDate, downloadState = downloadState, attachmentCount = attachmentCounter.getAttachmentCount(message), previewResult = messagePreviewCreator.createPreview(message), textForSearchIndex = messageFulltextCreator.createFulltext(message), encryptionType = null ) } } }
apache-2.0
580e9285d3d98a25979cb19ac24e922b
39.924528
84
0.661595
5.619171
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/platform/testRunningUtils.kt
1
5060
// 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.platform import com.intellij.openapi.module.Module import com.intellij.openapi.util.Key import com.intellij.psi.util.ParameterizedCachedValue import com.intellij.psi.util.ParameterizedCachedValueProvider import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.core.util.AvailabilityProvider import org.jetbrains.kotlin.idea.core.util.isClassAvailableInModule import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor.Companion.getTestStateIcon import org.jetbrains.kotlin.idea.util.string.joinWithEscape import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.has import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind import org.jetbrains.kotlin.platform.js.JsPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatform import org.jetbrains.kotlin.platform.konan.NativePlatform import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import javax.swing.Icon private val TEST_FQ_NAME = FqName("kotlin.test.Test") private val IGNORE_FQ_NAME = FqName("kotlin.test.Ignore") private val GENERIC_KOTLIN_TEST_AVAILABLE_KEY = Key<ParameterizedCachedValue<Boolean, Module>>("GENERIC_KOTLIN_TEST_AVAILABLE") private val GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITHOUT_TEST_SCOPE: ParameterizedCachedValueProvider<Boolean, Module> = GenericKotlinTestAvailabilityProvider(includeTests = false) private val GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITH_TEST_SCOPE = GenericKotlinTestAvailabilityProvider(true) private class GenericKotlinTestAvailabilityProvider(includeTests: Boolean) : AvailabilityProvider( includeTests, fqNames = setOf(TEST_FQ_NAME.asString()), javaClassLookup = true, // `kotlin.test.Test` could be a typealias aliasLookup = true, // `kotlin.test.Test` could be expected/actual annotation class kotlinFullClassLookup = true ) fun getGenericTestIcon( declaration: KtNamedDeclaration, descriptorProvider: () -> DeclarationDescriptor?, initialLocations: () -> List<String>? ): Icon? { val locations = initialLocations()?.toMutableList() ?: return null // fast check if `kotlin.test.Test` is available in a module scope declaration.isClassAvailableInModule( GENERIC_KOTLIN_TEST_AVAILABLE_KEY, GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITHOUT_TEST_SCOPE, GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITH_TEST_SCOPE )?.takeUnless { it }?.let { return null } val clazz = when (declaration) { is KtClassOrObject -> declaration is KtNamedFunction -> declaration.containingClassOrObject ?: return null else -> return null } val descriptor = descriptorProvider() ?: return null if (!descriptor.isKotlinTestDeclaration()) return null locations += clazz.parentsWithSelf.filterIsInstance<KtNamedDeclaration>() .mapNotNull { it.name } .toList().asReversed() val testName = (declaration as? KtNamedFunction)?.name if (testName != null) { locations += "$testName" } val prefix = if (testName != null) "test://" else "suite://" val url = prefix + locations.joinWithEscape('.') return getTestStateIcon(listOf("java:$url", url), declaration) } private tailrec fun DeclarationDescriptor.isIgnored(): Boolean { if (annotations.any { it.fqName == IGNORE_FQ_NAME }) { return true } val containingClass = containingDeclaration as? ClassDescriptor ?: return false return containingClass.isIgnored() } fun DeclarationDescriptor.isKotlinTestDeclaration(): Boolean { if (isIgnored()) { return false } if (annotations.any { it.fqName == TEST_FQ_NAME }) { return true } val classDescriptor = this as? ClassDescriptorWithResolutionScopes ?: return false return classDescriptor.declaredCallableMembers.any { it.isKotlinTestDeclaration() } } internal fun IdePlatformKind.isCompatibleWith(platform: TargetPlatform): Boolean { return when (this) { is JvmIdePlatformKind -> platform.has(JvmPlatform::class) is NativeIdePlatformKind -> platform.has(NativePlatform::class) is JsIdePlatformKind -> platform.has(JsPlatform::class) is CommonIdePlatformKind -> true else -> false } }
apache-2.0
5849c8ac6a6cb241deae059f756b2413
41.889831
182
0.770751
4.646465
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/datatypes/VimList.kt
1
1603
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.datatypes import com.maddyhome.idea.vim.ex.ExException data class VimList(val values: MutableList<VimDataType>) : VimDataType() { operator fun get(index: Int): VimDataType = this.values[index] override fun asDouble(): Double { throw ExException("E745: Using a List as a Number") } override fun asString(): String { throw ExException("E730: Using a List as a String") } override fun toVimNumber(): VimInt { throw ExException("E745: Using a List as a Number") } override fun toString(): String { val result = StringBuffer("[") result.append(values.joinToString(separator = ", ") { if (it is VimString) "'$it'" else it.toString() }) result.append("]") return result.toString() } override fun asBoolean(): Boolean { throw ExException("E745: Using a List as a Number") } override fun deepCopy(level: Int): VimDataType { return if (level > 0) { VimList(values.map { it.deepCopy(level - 1) }.toMutableList()) } else { this } } override fun lockVar(depth: Int) { this.isLocked = true if (depth > 1) { for (value in values) { value.lockVar(depth - 1) } } } override fun unlockVar(depth: Int) { this.isLocked = false if (depth > 1) { for (value in values) { value.unlockVar(depth - 1) } } } }
mit
bb2140bac0f510d9fbcc862d2f8cb424
23.661538
108
0.641298
3.834928
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/widgets/NestedCoordinatorLayout.kt
1
7250
package org.wordpress.android.widgets import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.View import androidx.annotation.AttrRes import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.NestedScrollingChild3 import androidx.core.view.NestedScrollingChildHelper import org.wordpress.android.R // Coordinator Layout that can be nested inside another Coordinator Layout and propagate // its scroll state to it // https://stackoverflow.com/a/37660246/569430 class NestedCoordinatorLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes @SuppressLint("PrivateResource") defStyleAttr: Int = R.attr.coordinatorLayoutStyle ) : CoordinatorLayout(context, attrs, defStyleAttr), NestedScrollingChild3 { private val helper = NestedScrollingChildHelper(this) init { isNestedScrollingEnabled = true } override fun isNestedScrollingEnabled(): Boolean = helper.isNestedScrollingEnabled override fun setNestedScrollingEnabled(enabled: Boolean) { helper.isNestedScrollingEnabled = enabled } override fun hasNestedScrollingParent(type: Int): Boolean = helper.hasNestedScrollingParent(type) override fun hasNestedScrollingParent(): Boolean = helper.hasNestedScrollingParent() override fun onStartNestedScroll(child: View, target: View, axes: Int, type: Int): Boolean { val superResult = super.onStartNestedScroll(child, target, axes, type) return startNestedScroll(axes, type) || superResult } override fun onStartNestedScroll(child: View, target: View, axes: Int): Boolean { val superResult = super.onStartNestedScroll(child, target, axes) return startNestedScroll(axes) || superResult } override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { val superConsumed = intArrayOf(0, 0) super.onNestedPreScroll(target, dx, dy, superConsumed, type) val thisConsumed = intArrayOf(0, 0) dispatchNestedPreScroll(dx, dy, consumed, null, type) consumed[0] = superConsumed[0] + thisConsumed[0] consumed[1] = superConsumed[1] + thisConsumed[1] } override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray) { val superConsumed = intArrayOf(0, 0) super.onNestedPreScroll(target, dx, dy, superConsumed) val thisConsumed = intArrayOf(0, 0) dispatchNestedPreScroll(dx, dy, consumed, null) consumed[0] = superConsumed[0] + thisConsumed[0] consumed[1] = superConsumed[1] + thisConsumed[1] } override fun onNestedScroll( target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null, type) super.onNestedScroll( target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed ) } override fun onNestedScroll( target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int ) { super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type) dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null, type) } override fun onNestedScroll( target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int ) { super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed) dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null) } override fun onStopNestedScroll(target: View, type: Int) { super.onStopNestedScroll(target, type) stopNestedScroll(type) } override fun onStopNestedScroll(target: View) { super.onStopNestedScroll(target) stopNestedScroll() } override fun onNestedPreFling(target: View, velocityX: Float, velocityY: Float): Boolean { val superResult = super.onNestedPreFling(target, velocityX, velocityY) return dispatchNestedPreFling(velocityX, velocityY) || superResult } override fun onNestedFling( target: View, velocityX: Float, velocityY: Float, consumed: Boolean ): Boolean { val superResult = super.onNestedFling(target, velocityX, velocityY, consumed) return dispatchNestedFling(velocityX, velocityY, consumed) || superResult } override fun startNestedScroll(axes: Int, type: Int): Boolean = helper.startNestedScroll(axes, type) override fun startNestedScroll(axes: Int): Boolean = helper.startNestedScroll(axes) override fun stopNestedScroll(type: Int) { helper.stopNestedScroll(type) } override fun stopNestedScroll() { helper.stopNestedScroll() } override fun dispatchNestedScroll( dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, offsetInWindow: IntArray?, type: Int, consumed: IntArray ) { helper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type, consumed ) } override fun dispatchNestedScroll( dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, offsetInWindow: IntArray?, type: Int ): Boolean = helper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type ) override fun dispatchNestedScroll( dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, offsetInWindow: IntArray? ): Boolean = helper.dispatchNestedScroll( dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow ) override fun dispatchNestedPreScroll( dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?, type: Int ): Boolean = helper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type) override fun dispatchNestedPreScroll( dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray? ): Boolean = helper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow) override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean = helper.dispatchNestedPreFling(velocityX, velocityY) override fun dispatchNestedFling( velocityX: Float, velocityY: Float, consumed: Boolean ): Boolean = helper.dispatchNestedFling(velocityX, velocityY, consumed) }
gpl-2.0
9c108b0f3feed9a2c841bf221434c2d2
31.511211
99
0.653655
5.227109
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/qrcodeauth/QRCodeAuthActivity.kt
1
1209
package org.wordpress.android.ui.qrcodeauth import android.content.Context import android.content.Intent import android.os.Bundle import dagger.hilt.android.AndroidEntryPoint import org.wordpress.android.databinding.QrcodeauthActivityBinding import org.wordpress.android.ui.LocaleAwareActivity @AndroidEntryPoint class QRCodeAuthActivity : LocaleAwareActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) with(QrcodeauthActivityBinding.inflate(layoutInflater)) { setContentView(root) } } companion object { @JvmStatic fun start(context: Context) { context.startActivity(newIntent(context)) } @JvmStatic fun newIntent(context: Context, uri: String? = null, fromDeeplink: Boolean = false): Intent { val intent = Intent(context, QRCodeAuthActivity::class.java).apply { putExtra(DEEP_LINK_URI_KEY, uri) putExtra(IS_DEEP_LINK_KEY, fromDeeplink) } return intent } const val IS_DEEP_LINK_KEY = "is_deep_link_key" const val DEEP_LINK_URI_KEY = "deep_link_uri_key" } }
gpl-2.0
e2309f26ca66f9e358368fd3a7696e63
30.815789
101
0.673284
4.511194
false
false
false
false
team401/SnakeSkin
SnakeSkin-REV/src/main/kotlin/org/snakeskin/dsl/RevHardwareExtensions.kt
1
4181
package org.snakeskin.dsl import com.revrobotics.CANSparkMax import com.revrobotics.CANSparkMaxLowLevel import org.snakeskin.component.Hardware import org.snakeskin.component.ISparkMaxDevice import org.snakeskin.component.SparkMaxOutputVoltageReadingMode import org.snakeskin.component.impl.HardwareSparkMaxDevice import org.snakeskin.component.impl.NullSparkMaxDevice import org.snakeskin.runtime.SnakeskinPlatform import org.snakeskin.runtime.SnakeskinRuntime /** * Creates a new SPARK MAX device object in brushed mode. * @param hardwareId THe CAN ID of the SPARK MAX * @param encoderCpr Counts per rev of attached quadrature encoder, or 0 if no encoder is attached * @param voltageReadingMode The mode to read output voltage from the SPARK MAX * @param useAlternateEncoderPinout Whether or not to use the "alternate encoder" pinout * @param mockProducer Function which returns a mock object representing the device, used for emulating hardware */ inline fun Hardware.createBrushedSparkMax( hardwareId: Int, encoderCpr: Int = 0, voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem, useAlternateEncoderPinout: Boolean = false, mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") } ) = when (SnakeskinRuntime.platform) { SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax( hardwareId, CANSparkMaxLowLevel.MotorType.kBrushed ), voltageReadingMode, useAlternateEncoderPinout, encoderCpr) else -> mockProducer() } /** * Creates a new SPARK MAX device object in brushless mode, using the internal encoder. * @param hardwareId THe CAN ID of the SPARK MAX * @param voltageReadingMode The mode to read output voltage from the SPARK MAX * @param mockProducer Function which returns a mock object representing the device, used for emulating hardware */ inline fun Hardware.createBrushlessSparkMax( hardwareId: Int, voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem, mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") } ) = when (SnakeskinRuntime.platform) { SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax( hardwareId, CANSparkMaxLowLevel.MotorType.kBrushless ), voltageReadingMode, false) else -> mockProducer() } /** * Creates a new SPARK MAX device object in brushless mode, using an external encoder in the "alternate pinout". * @param hardwareId THe CAN ID of the SPARK MAX * @param encoderCpr Counts per rev of attached quadrature encoder * @param voltageReadingMode The mode to read output voltage from the SPARK MAX * @param mockProducer Function which returns a mock object representing the device, used for emulating hardware */ inline fun Hardware.createBrushlessSparkMaxWithEncoder( hardwareId: Int, encoderCpr: Int, voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem, mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") } ) = when (SnakeskinRuntime.platform) { SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax( hardwareId, CANSparkMaxLowLevel.MotorType.kBrushless ), voltageReadingMode, true, encoderCpr) else -> mockProducer() } /** * Allows access to hardware device functions of a SPARK MAX device * @param sparkMaxDevice The SPARK MAX device object * @param action The action to run on the hardware. If the runtime is not hardware, the action will not be run */ inline fun useHardware(sparkMaxDevice: ISparkMaxDevice, action: CANSparkMax.() -> Unit) { if (sparkMaxDevice is HardwareSparkMaxDevice) { action(sparkMaxDevice.device) } }
gpl-3.0
6a32f3d2541321063bef2a7abdea1bb8
48.2
120
0.771107
5.105006
false
false
false
false
knes1/kotao
src/main/kotlin/io/github/knes1/kotao/brew/WebServer.kt
1
2898
package io.github.knes1.kotao.brew import io.vertx.core.AbstractVerticle import io.vertx.core.Future import io.vertx.ext.web.Router import io.vertx.ext.web.handler.StaticHandler import io.vertx.ext.web.handler.sockjs.BridgeOptions import io.vertx.ext.web.handler.sockjs.SockJSHandler import io.vertx.kotlin.ext.web.handler.sockjs.PermittedOptions import java.io.File import java.nio.charset.Charset /** * Web server serving the generated content. It also listens on "updates" vertx event bus address for messages to * update the fronted. Any such messages is passed via injected SockJS to the browser which then reloads the page. * * Web server is implemented as vertx verticle. * * @author knesek * Created on: 5/26/17 */ class WebServer( val webRoot: String ) : AbstractVerticle() { override fun start() { val server = vertx.createHttpServer() val router = Router.router(vertx) val sockJSHandler = SockJSHandler.create(vertx) val options = BridgeOptions().addOutboundPermitted(PermittedOptions("updates")) sockJSHandler.bridge(options) // Handler for Kotao administrative static files and scripts router.route("/_kotao/static/*").handler(StaticHandler.create()) // Handler for Kotao event bus used for pushing updates router.route("/_kotao/eventbus/*").handler(sockJSHandler) // Injection handler that intercepts html files and injects Kotlin admin scripts, // otherwise it delegates to static handler router.get("/*").handler { val response = it.response() if (it.request().uri().endsWith("/")) { it.reroute(it.request().uri() + "index.html") return@handler } val file = File(webRoot + it.request().uri()) if (file.isDirectory) { it.reroute(it.request().uri() + "index.html") return@handler } if (!it.request().uri().endsWith("html")) { it.next() return@handler } if (!file.exists()) { it.next() return@handler } it.vertx().executeBlocking({ future: Future<String> -> val contents = file.readText(Charset.forName("UTF-8")) val injected = contents.replace("<body>", """<body> <script src="/_kotao/static/sockjs.min.js"></script> <script src='/_kotao/static/vertx-eventbus.js'></script> <script src='/_kotao/static/spin.min.js'></script> <script src='/_kotao/static/kotao.js'></script> """ ) future.complete(injected) }, { asyncResult -> if (asyncResult.succeeded()) { response.end(asyncResult.result(), "UTF-8") } else { // In case of any kind of failure resulting from our injection logic, we just delegate // to static handler to handle it. it.next() } }) } // Static serving files from the output. Read only flag set to false to prevent caching. router.route("/*").handler(StaticHandler.create(webRoot).setFilesReadOnly(false)) server.requestHandler { router.accept(it) }.listen(8080) } }
mit
742e84c01a38b42bc0755c68ef71fe2c
30.172043
114
0.695307
3.51699
false
false
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/settings/state/MLServerCompletionSettings.kt
2
7344
package org.jetbrains.completion.full.line.settings.state import com.intellij.lang.Language import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.util.registry.Registry import org.jetbrains.completion.full.line.language.* import org.jetbrains.completion.full.line.models.ModelType @State( name = "MLServerCompletionSettings", storages = [Storage("MLServerCompletionSettings.xml", deprecated = true), Storage("full.line.xml")] ) class MLServerCompletionSettings : PersistentStateComponent<GeneralState> { private var state = GeneralState() // ----------------------------- Methods for state persisting ------------------------------ // override fun initializeComponent() { loadEvaluationConfig() } override fun loadState(state: GeneralState) { this.state.langStates.forEach { state.langStates.putIfAbsent(it.key, it.value) } this.state = state } companion object { fun isExtended() = Registry.get("full.line.expand.settings").asBoolean() fun getInstance(): MLServerCompletionSettings { return service() } val availableLanguages: List<Language> get() = FullLineLanguageSupporter.supportedLanguages() } // ----------------------------------- State getters --------------------------------------- // override fun getState() = state fun getLangState(language: Language): LangState = getLangStateSafe(language) ?: throw IllegalArgumentException("Language ${language.displayName} is not supported") private fun getLangStateSafe(language: Language): LangState? = state.langStates[language.id] ?: language.baseLanguage?.let { state.langStates[it.id] } // ------------------------------ Common settings getters ---------------------------------- // fun isEnabled(): Boolean = state.enable fun isGreyTextMode(): Boolean = state.useGrayText fun enableStringsWalking(language: Language): Boolean = getLangState(language).stringsWalking fun showScore(language: Language): Boolean = getLangState(language).showScore fun topN(): Int? = if (state.useTopN) state.topN else null fun groupTopN(language: Language): Int? = getModelState(language).let { if (it.useGroupTopN) it.groupTopN else null } fun checkRedCode(language: Language): Boolean = getLangState(language).redCodePolicy != RedCodePolicy.SHOW fun hideRedCode(language: Language): Boolean = getLangState(language).redCodePolicy == RedCodePolicy.FILTER @Suppress("REDUNDANT_ELSE_IN_WHEN") fun getModelState(langState: LangState, type: ModelType = state.modelType): ModelState { return when (type) { ModelType.Cloud -> langState.cloudModelState ModelType.Local -> langState.localModelState else -> throw IllegalArgumentException("Got unexpected modelType `${type}`.") } } fun getModelState(language: Language, modelType: ModelType): ModelState = getModelState(getLangState(language), modelType) fun getModelMode(): ModelType = state.modelType fun getModelState(language: Language): ModelState = getModelState(getLangState(language)) // --------------------------- Language-specific settings getters -------------------------- // fun isLanguageSupported(language: Language): Boolean = getLangStateSafe(language) != null // Check if completion enabled for current language or if the current language is based on supported fun isEnabled(language: Language): Boolean { // TODO: add correct handle for not specified language. Hotfix in 0.2.1 return try { getLangState(language).enabled && isEnabled() } catch (e: Exception) { false } } private fun loadEvaluationConfig() { val isTesting = System.getenv("flcc_evaluating") ?: return if (!isTesting.toBoolean()) return // General settings System.getenv("flcc_enable")?.toBoolean()?.let { state.enable = it } System.getenv("flcc_topN")?.toInt()?.let { state.useTopN = true state.topN = it } System.getenv("flcc_useGrayText")?.toBoolean()?.let { state.useGrayText = it } System.getenv("flcc_modelType")?.let { state.modelType = ModelType.valueOf(it) } // Registries System.getenv("flcc_max_latency")?.let { Registry.get("full.line.server.host.max.latency").setValue(it.toInt()) } System.getenv("flcc_only_proposals")?.let { Registry.get("full.line.only.proposals").setValue(it.toBoolean()) } System.getenv("flcc_multi_token_only")?.let { Registry.get("full.line.multi.token.everywhere").setValue(it.toBoolean()) } System.getenv("flcc_caching")?.let { Registry.get("full.line.enable.caching").setValue(it.toBoolean()) } // Language-specific settings val langId = System.getenv("flcc_language") ?: return val langState = state.langStates .mapKeys { (k, _) -> k.toLowerCase() } .getValue(langId) System.getenv("flcc_enabled")?.toBoolean()?.let { langState.enabled = it } System.getenv("flcc_onlyFullLines")?.toBoolean()?.let { langState.onlyFullLines = it } System.getenv("flcc_stringsWalking")?.toBoolean()?.let { langState.stringsWalking = it } System.getenv("flcc_showScore")?.toBoolean()?.let { langState.showScore = it } System.getenv("flcc_redCodePolicy")?.let { langState.redCodePolicy = RedCodePolicy.valueOf(it) } System.getenv("flcc_groupAnswers")?.toBoolean()?.let { langState.groupAnswers = it } // Lang-registries @Suppress("UnresolvedPluginConfigReference") System.getenv("flcc_host")?.let { Registry.get("full.line.server.host.${langId.toLowerCase()}").setValue(it) Registry.get("full.line.server.host.psi.${langId.toLowerCase()}").setValue(it) } // Beam search configuration val modelState = getModelState(langState) System.getenv("flcc_numIterations")?.toInt()?.let { modelState.numIterations = it } System.getenv("flcc_beamSize")?.toInt()?.let { modelState.beamSize = it } System.getenv("flcc_diversityGroups")?.toInt()?.let { modelState.diversityGroups = it } System.getenv("flcc_diversityStrength")?.toDouble()?.let { modelState.diversityStrength = it } System.getenv("flcc_lenPow")?.toDouble()?.let { modelState.lenPow = it } System.getenv("flcc_lenBase")?.toDouble()?.let { modelState.lenBase = it } System.getenv("flcc_groupTopN")?.toInt()?.let { modelState.useGroupTopN = true modelState.groupTopN = it } System.getenv("flcc_customContextLength")?.toInt()?.let { modelState.useCustomContextLength = true modelState.customContextLength = it } System.getenv("flcc_minimumPrefixDist")?.toDouble()?.let { modelState.minimumPrefixDist = it } System.getenv("flcc_minimumEditDist")?.toDouble()?.let { modelState.minimumEditDist = it } System.getenv("flcc_keepKinds")?.let { modelState.keepKinds = it.removePrefix("[").removeSuffix("]") .split(",").asSequence() .onEach { it.trim() }.filter { it.isNotBlank() } .map { KeepKind.valueOf(it) }.toMutableSet() } System.getenv("flcc_psiBased")?.toBoolean()?.let { modelState.psiBased = it } } }
apache-2.0
22bb1ea79715cd377bc1ac3c45421779
40.491525
138
0.674564
4.5
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/providers/ModuleBookmarkProvider.kt
9
1992
// 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.ide.bookmark.providers import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkProvider import com.intellij.ide.projectView.impl.ModuleGroupUrl import com.intellij.ide.projectView.impl.ModuleUrl import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.util.text.StringUtil internal class ModuleBookmarkProvider(private val project: Project) : BookmarkProvider { override fun getWeight() = 200 override fun getProject() = project internal val moduleManager get() = if (project.isDisposed) null else ModuleManager.getInstance(project) internal val projectSettingsService get() = if (project.isDisposed) null else ProjectSettingsService.getInstance(project) override fun compare(bookmark1: Bookmark, bookmark2: Bookmark): Int { bookmark1 as ModuleBookmark bookmark2 as ModuleBookmark if (bookmark1.isGroup && !bookmark2.isGroup) return -1 if (!bookmark1.isGroup && bookmark2.isGroup) return +1 return StringUtil.naturalCompare(bookmark1.name, bookmark2.name) } override fun createBookmark(map: MutableMap<String, String>) = map["group"]?.let { ModuleBookmark(this, it, true) } ?: map["module"]?.let { ModuleBookmark(this, it, false) } private fun createGroupBookmark(name: String?) = name?.let { ModuleBookmark(this, it, true) } private fun createModuleBookmark(name: String?) = name?.let { ModuleBookmark(this, it, false) } override fun createBookmark(context: Any?): ModuleBookmark? = when (context) { is ModuleGroupUrl -> createGroupBookmark(context.url) is ModuleUrl -> createModuleBookmark(context.url) is Module -> createModuleBookmark(context.name) else -> null } }
apache-2.0
fa8764033652f483cbb1e13b22763eef
46.428571
158
0.771586
4.330435
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/WorkspaceModuleImporter.kt
2
13869
// 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.idea.maven.importing.workspaceModel import com.intellij.openapi.module.ModuleTypeId import com.intellij.openapi.module.impl.ModuleManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.containers.addIfNotNull import com.intellij.workspaceModel.ide.impl.FileInDirectorySourceNames import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.idea.maven.importing.MavenImportUtil import org.jetbrains.idea.maven.importing.StandardMavenModuleType import org.jetbrains.idea.maven.importing.tree.MavenModuleImportData import org.jetbrains.idea.maven.importing.tree.MavenTreeModuleImportData import org.jetbrains.idea.maven.importing.tree.dependency.* import org.jetbrains.idea.maven.model.MavenArtifact import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenImportingSettings import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.utils.MavenLog internal class WorkspaceModuleImporter( private val project: Project, private val importData: MavenTreeModuleImportData, private val virtualFileUrlManager: VirtualFileUrlManager, private val builder: MutableEntityStorage, private val existingEntitySourceNames: FileInDirectorySourceNames, private val importingSettings: MavenImportingSettings, private val folderImportingContext: WorkspaceFolderImporter.FolderImportingContext, private val stats: WorkspaceImportStats ) { private val externalSource = ExternalProjectSystemRegistry.getInstance().getSourceById(EXTERNAL_SOURCE_ID) fun importModule(): ModuleEntity { val baseModuleDir = virtualFileUrlManager.fromPath(importData.mavenProject.directory) val moduleName = importData.moduleData.moduleName val moduleLibrarySource = JpsEntitySourceFactory.createEntitySourceForModule(project, baseModuleDir, externalSource, existingEntitySourceNames, moduleName + ModuleManagerEx.IML_EXTENSION) val dependencies = collectDependencies(moduleName, importData.dependencies, moduleLibrarySource) val moduleEntity = createModuleEntity(moduleName, importData.mavenProject, importData.moduleData.type, dependencies, moduleLibrarySource) configureModuleEntity(importData, moduleEntity, folderImportingContext) return moduleEntity } private fun reuseOrCreateProjectLibrarySource(libraryName: String): EntitySource { return JpsEntitySourceFactory.createEntitySourceForProjectLibrary(project, externalSource, existingEntitySourceNames, libraryName) } private fun createModuleEntity(moduleName: String, mavenProject: MavenProject, mavenModuleType: StandardMavenModuleType, dependencies: List<ModuleDependencyItem>, entitySource: EntitySource): ModuleEntity { val moduleEntity = builder.addModuleEntity(moduleName, dependencies, entitySource, ModuleTypeId.JAVA_MODULE) val externalSystemModuleOptionsEntity = ExternalSystemModuleOptionsEntity(entitySource) { ExternalSystemData(moduleEntity, mavenProject.file.path, mavenModuleType).write(this) } builder.addEntity(externalSystemModuleOptionsEntity) return moduleEntity } private fun configureModuleEntity(importData: MavenModuleImportData, moduleEntity: ModuleEntity, folderImportingContext: WorkspaceFolderImporter.FolderImportingContext) { val folderImporter = WorkspaceFolderImporter(builder, virtualFileUrlManager, importingSettings, folderImportingContext) val importFolderHolder = folderImporter.createContentRoots(importData.mavenProject, importData.moduleData.type, moduleEntity, stats) importJavaSettings(moduleEntity, importData, importFolderHolder) } private fun collectDependencies(moduleName: String, dependencies: List<Any>, moduleLibrarySource: EntitySource): List<ModuleDependencyItem> { val result = ArrayList<ModuleDependencyItem>(2 + dependencies.size) result.add(ModuleDependencyItem.InheritedSdkDependency) result.add(ModuleDependencyItem.ModuleSourceDependency) for (dependency in dependencies) { val created = when (dependency) { is SystemDependency -> createSystemDependency(moduleName, dependency.artifact) { moduleLibrarySource } is LibraryDependency -> createLibraryDependency(dependency.artifact) { reuseOrCreateProjectLibrarySource(dependency.artifact.libraryName) } is AttachedJarDependency -> createLibraryDependency(dependency.artifact, toScope(dependency.scope), { dependency.rootPaths.map { (url, type) -> LibraryRoot(virtualFileUrlManager.fromUrl(pathToUrl(url)), type) } }, { reuseOrCreateProjectLibrarySource(dependency.artifact) }) is ModuleDependency -> ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(dependency.artifact), false, toScope(dependency.scope), dependency.isTestJar) is BaseDependency -> createLibraryDependency(dependency.artifact) { reuseOrCreateProjectLibrarySource(dependency.artifact.libraryName) } else -> null } result.addIfNotNull(created) } return result } private fun pathToUrl(it: String) = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, it) + JarFileSystem.JAR_SEPARATOR private fun toScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope = when (scope) { DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED else -> ModuleDependencyItem.DependencyScope.COMPILE } private fun createSystemDependency(moduleName: String, artifact: MavenArtifact, sourceProvider: () -> EntitySource): ModuleDependencyItem.Exportable.LibraryDependency { assert(MavenConstants.SCOPE_SYSTEM == artifact.scope) val libraryId = LibraryId(artifact.libraryName, LibraryTableId.ModuleLibraryTableId(moduleId = ModuleId(moduleName))) addLibraryEntity(libraryId, { val classes = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null) listOf(LibraryRoot(virtualFileUrlManager.fromUrl(classes), LibraryRootTypeId.COMPILED)) }, sourceProvider) return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, artifact.dependencyScope) } private fun createLibraryDependency(artifact: MavenArtifact, sourceProvider: () -> EntitySource): ModuleDependencyItem.Exportable.LibraryDependency { assert(MavenConstants.SCOPE_SYSTEM != artifact.scope) val libraryRootsProvider = { val classes = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null) val sources = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar") val javadoc = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar") listOf( LibraryRoot(virtualFileUrlManager.fromUrl(classes), LibraryRootTypeId.COMPILED), LibraryRoot(virtualFileUrlManager.fromUrl(sources), LibraryRootTypeId.SOURCES), LibraryRoot(virtualFileUrlManager.fromUrl(javadoc), JAVADOC_TYPE), ) } return createLibraryDependency(artifact.libraryName, artifact.dependencyScope, libraryRootsProvider, sourceProvider) } private fun createLibraryDependency( libraryName: String, scope: ModuleDependencyItem.DependencyScope, libraryRootsProvider: () -> List<LibraryRoot>, sourceProvider: () -> EntitySource ): ModuleDependencyItem.Exportable.LibraryDependency { val libraryId = LibraryId(libraryName, LibraryTableId.ProjectLibraryTableId) addLibraryEntity(libraryId, libraryRootsProvider, sourceProvider) return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, scope) } private fun addLibraryEntity( libraryId: LibraryId, libraryRootsProvider: () -> List<LibraryRoot>, // lazy provider to avoid roots creation for already added libraries sourceProvider: () -> EntitySource) { if (libraryId in builder) return builder.addLibraryEntity(libraryId.name, libraryId.tableId, libraryRootsProvider(), emptyList(), sourceProvider()) } private val MavenArtifact.dependencyScope: ModuleDependencyItem.DependencyScope get() = when (scope) { MavenConstants.SCOPE_RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME MavenConstants.SCOPE_TEST -> ModuleDependencyItem.DependencyScope.TEST MavenConstants.SCOPE_PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED else -> ModuleDependencyItem.DependencyScope.COMPILE } private fun importJavaSettings(moduleEntity: ModuleEntity, importData: MavenModuleImportData, importFolderHolder: WorkspaceFolderImporter.CachedProjectFolders) { val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel } var inheritCompilerOutput = true var compilerOutputUrl: VirtualFileUrl? = null var compilerOutputUrlForTests: VirtualFileUrl? = null val moduleType = importData.moduleData.type if (moduleType.containsCode && importingSettings.isUseMavenOutput) { inheritCompilerOutput = false if (moduleType.containsMain) { compilerOutputUrl = virtualFileUrlManager.fromPath(importFolderHolder.outputPath) } if (moduleType.containsTest) { compilerOutputUrlForTests = virtualFileUrlManager.fromPath(importFolderHolder.testOutputPath) } } builder.addJavaModuleSettingsEntity(inheritCompilerOutput, false, compilerOutputUrl, compilerOutputUrlForTests, languageLevel.name, moduleEntity, moduleEntity.entitySource) } companion object { val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC") val EXTERNAL_SOURCE_ID get() = ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID } class ExternalSystemData(val moduleEntity: ModuleEntity, val mavenProjectFilePath: String, val mavenModuleType: StandardMavenModuleType) { fun write(entity: ExternalSystemModuleOptionsEntity.Builder) { entity.externalSystemModuleVersion = VERSION entity.module = moduleEntity entity.externalSystem = EXTERNAL_SOURCE_ID // Can't use 'entity.linkedProjectPath' since it implies directory (and used to set working dir for Run Configurations). entity.linkedProjectId = FileUtil.toSystemIndependentName(mavenProjectFilePath) entity.externalSystemModuleType = mavenModuleType.name } companion object { const val VERSION = "223-2" fun isFromLegacyImport(entity: ExternalSystemModuleOptionsEntity): Boolean { return entity.externalSystem == EXTERNAL_SOURCE_ID && entity.externalSystemModuleVersion == null } fun tryRead(entity: ExternalSystemModuleOptionsEntity): ExternalSystemData? { if (entity.externalSystem != EXTERNAL_SOURCE_ID || entity.externalSystemModuleVersion != VERSION) return null val id = entity.linkedProjectId if (id == null) { MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.linkedProjectId must not be null") return null } val mavenProjectFilePath = FileUtil.toSystemIndependentName(id) val typeName = entity.externalSystemModuleType if (typeName == null) { MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.externalSystemModuleType must not be null") return null } val moduleType = try { StandardMavenModuleType.valueOf(typeName) } catch (e: Exception) { MavenLog.LOG.debug(e) return null } return ExternalSystemData(entity.module, mavenProjectFilePath, moduleType) } } } }
apache-2.0
7e8234e26e9d6eb3f8f3aaac16b7c5fe
49.072202
140
0.70654
6.379485
false
false
false
false
jk1/intellij-community
platform/configuration-store-impl/src/CompoundStreamProvider.kt
4
1497
package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.util.containers.ConcurrentList import com.intellij.util.containers.ContainerUtil import java.io.InputStream class CompoundStreamProvider : StreamProvider { val providers: ConcurrentList<StreamProvider> = ContainerUtil.createConcurrentList<StreamProvider>() override val enabled: Boolean get() = providers.any { it.enabled } override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = providers.any { it.isApplicable(fileSpec, roamingType) } override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean = providers.any { it.read(fileSpec, roamingType, consumer) } override fun processChildren(path: String, roamingType: RoamingType, filter: Function1<String, Boolean>, processor: Function3<String, InputStream, Boolean, Boolean>): Boolean { return providers.any { it.processChildren(path, roamingType, filter, processor) } } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { providers.forEach { if (it.isApplicable(fileSpec, roamingType)) { it.write(fileSpec, content, size, roamingType) } } } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean = providers.any { it.delete(fileSpec, roamingType) } }
apache-2.0
88ec9f10b5d7ee84c8c01c2c7068efd7
43.058824
167
0.718771
4.908197
false
false
false
false
jk1/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/CompletionLoggerImpl.kt
3
8389
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.completion import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.tracker.LookupElementPositionTracker import com.intellij.ide.plugins.PluginManager import com.intellij.stats.completion.events.* import com.intellij.stats.personalization.UserFactorsManager class CompletionFileLogger(private val installationUID: String, private val completionUID: String, private val eventLogger: CompletionEventLogger) : CompletionLogger() { private val elementToId = mutableMapOf<String, Int>() private fun registerElement(item: LookupElement): Int { val itemString = item.idString() val newId = elementToId.size elementToId[itemString] = newId return newId } private fun getElementId(item: LookupElement): Int? { val itemString = item.idString() return elementToId[itemString] } private fun getRecentlyAddedLookupItems(items: List<LookupElement>): List<LookupElement> { val newElements = items.filter { getElementId(it) == null } newElements.forEach { registerElement(it) } return newElements } private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl): List<LookupEntryInfo> { val relevanceObjects = lookup.getRelevanceObjects(this, false) return this.map { val id = getElementId(it)!! val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap() LookupEntryInfo(id, it.lookupString.length, relevanceMap) } } override fun completionStarted(lookup: LookupImpl, isExperimentPerformed: Boolean, experimentVersion: Int) { val lookupItems = lookup.items lookupItems.forEach { registerElement(it) } val relevanceObjects = lookup.getRelevanceObjects(lookupItems, false) val lookupEntryInfos = lookupItems.map { val id = getElementId(it)!! val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap() LookupEntryInfo(id, it.lookupString.length, relevanceMap) } val language = lookup.language() val ideVersion = PluginManager.BUILD_NUMBER ?: "ideVersion" val pluginVersion = calcPluginVersion() ?: "pluginVersion" val mlRankingVersion = "NONE" val userFactors = lookup.getUserData(UserFactorsManager.USER_FACTORS_KEY) ?: emptyMap() val event = CompletionStartedEvent( ideVersion, pluginVersion, mlRankingVersion, installationUID, completionUID, language?.displayName, isExperimentPerformed, experimentVersion, lookupEntryInfos, userFactors, selectedPosition = 0) event.isOneLineMode = lookup.editor.isOneLineMode event.fillCompletionParameters() eventLogger.log(event) } override fun customMessage(message: String) { val event = CustomMessageEvent(installationUID, completionUID, message) eventLogger.log(event) } override fun afterCharTyped(c: Char, lookup: LookupImpl) { val lookupItems = lookup.items val newItems = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = lookupItems.map { getElementId(it)!! } val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = TypeEvent(installationUID, completionUID, ids, newItems, currentPosition) event.fillCompletionParameters() eventLogger.log(event) } override fun downPressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList() val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = DownPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition) event.fillCompletionParameters() eventLogger.log(event) } override fun upPressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList() val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = UpPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition) event.fillCompletionParameters() eventLogger.log(event) } override fun completionCancelled() { val event = CompletionCancelledEvent(installationUID, completionUID) eventLogger.log(event) } override fun itemSelectedByTyping(lookup: LookupImpl) { val newCompletionElements = getRecentlyAddedLookupItems(lookup.items).toLookupInfos(lookup) val id = currentItemInfo(lookup).id val history = lookup.itemsHistory() val completionList = lookup.items.toLookupInfos(lookup) val event = TypedSelectEvent(installationUID, completionUID, newCompletionElements, id, completionList, history) event.fillCompletionParameters() eventLogger.log(event) } override fun itemSelectedCompletionFinished(lookup: LookupImpl) { val newCompletionItems = getRecentlyAddedLookupItems(lookup.items).toLookupInfos(lookup) val (index, id) = currentItemInfo(lookup) val history = lookup.itemsHistory() val completionList = lookup.items.toLookupInfos(lookup) val event = ExplicitSelectEvent(installationUID, completionUID, newCompletionItems, index, id, completionList, history) event.fillCompletionParameters() eventLogger.log(event) } private fun currentItemInfo(lookup: LookupImpl): CurrentElementInfo { val current = lookup.currentItem return if (current != null) { val index = lookup.items.indexOf(current) val id = getElementId(current)!! CurrentElementInfo(index, id) } else { CurrentElementInfo(-1, -1) } } private fun LookupImpl.itemsHistory(): Map<Int, ElementPositionHistory> { val positionTracker = LookupElementPositionTracker.getInstance() return items.map { getElementId(it)!! to positionTracker.positionsHistory(this, it).let { ElementPositionHistory(it) } }.toMap() } override fun afterBackspacePressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = lookupItems.map { getElementId(it)!! } val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = BackspaceEvent(installationUID, completionUID, ids, newInfos, currentPosition) event.fillCompletionParameters() eventLogger.log(event) } } private class CurrentElementInfo(val index: Int, val id: Int) { operator fun component1() = index operator fun component2() = id } private fun calcPluginVersion(): String? { val className = CompletionStartedEvent::class.java.name val id = PluginManager.getPluginByClassName(className) val plugin = PluginManager.getPlugin(id) return plugin?.version } private fun LookupStateLogData.fillCompletionParameters() { val params = CompletionUtil.getCurrentCompletionParameters() originalCompletionType = params?.completionType?.toString() ?: "" originalInvokationCount = params?.invocationCount ?: -1 }
apache-2.0
b234e3f73b1f2b0438e928c9d2364b97
36.963801
136
0.697223
5.16564
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/spa/SinglePageApplicationTest.kt
1
6866
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.http.spa import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.http.content.* import io.ktor.server.routing.* import io.ktor.server.testing.* import kotlin.test.* class SinglePageApplicationTest { @Test fun fullWithFilesTest() = testApplication { application { routing { singlePageApplication { filesPath = "jvm/test/io/ktor/server/http/spa" applicationRoute = "selected" defaultPage = "Empty3.kt" ignoreFiles { it.contains("Empty2.kt") } } } } client.get("/selected").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } client.get("/selected/a").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } client.get("/selected/Empty2.kt").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } client.get("/selected/Empty1.kt").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty1) } } @Test fun testPageGet() = testApplication { application { routing { singlePageApplication { filesPath = "jvm/test/io/ktor/server/http/spa" applicationRoute = "selected" defaultPage = "Empty3.kt" } } } client.get("/selected/Empty1.kt").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty1) } client.get("/selected").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } } @Test fun testIgnoreAllRoutes() = testApplication { application { routing { singlePageApplication { filesPath = "jvm/test/io/ktor/server/http/spa" defaultPage = "Empty3.kt" ignoreFiles { true } } } } client.get("/").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } client.get("/a").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } client.get("/Empty1.kt").let { assertEquals(it.status, HttpStatusCode.OK) assertEquals(it.bodyAsText().trimIndent(), empty3) } } @Test fun fullWithResourcesTest() = testApplication { application { routing { singlePageApplication { useResources = true filesPath = "io.ktor.server.http.spa" applicationRoute = "selected" defaultPage = "Empty3.class" ignoreFiles { it.contains("Empty2.class") } } } } assertEquals(client.get("/selected").status, HttpStatusCode.OK) assertEquals(client.get("/selected/a").status, HttpStatusCode.OK) assertEquals(client.get("/selected/Empty2.kt").status, HttpStatusCode.OK) assertEquals(client.get("/selected/Empty1.kt").status, HttpStatusCode.OK) } @Test fun testResources() = testApplication { application { routing { singlePageApplication { useResources = true filesPath = "io.ktor.server.http.spa" defaultPage = "SinglePageApplicationTest.class" } } } assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status) assertEquals(HttpStatusCode.OK, client.get("/SinglePageApplicationTest.class").status) assertEquals(HttpStatusCode.OK, client.get("/a").status) assertEquals(HttpStatusCode.OK, client.get("/").status) } @Test fun testIgnoreResourceRoutes() = testApplication { application { routing { singlePageApplication { useResources = true filesPath = "io.ktor.server.http.spa" defaultPage = "SinglePageApplicationTest.class" ignoreFiles { it.contains("Empty1.class") } ignoreFiles { it.endsWith("Empty2.class") } } } } assertEquals(HttpStatusCode.OK, client.get("/Empty3.class").status) assertEquals(HttpStatusCode.OK, client.get("/").status) assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status) assertEquals(HttpStatusCode.OK, client.get("/Empty2.class").status) } @Test fun testIgnoreAllResourceRoutes() = testApplication { application { routing { singlePageApplication { useResources = true filesPath = "io.ktor.server.http.spa" defaultPage = "SinglePageApplicationTest.class" ignoreFiles { true } } } } assertEquals(HttpStatusCode.OK, client.get("/SinglePageApplicationTest.class").status) assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status) assertEquals(HttpStatusCode.OK, client.get("/a").status) assertEquals(HttpStatusCode.OK, client.get("/").status) } @Test fun testShortcut() = testApplication { application { routing { singlePageApplication { angular("jvm/test/io/ktor/server/http/spa") } } } assertEquals(HttpStatusCode.OK, client.get("/Empty1.kt").status) } private val empty1 = """ /* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.http.spa // required for tests class Empty1 """.trimIndent() private val empty3 = """ /* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.http.spa // required for tests class Empty3 """.trimIndent() }
apache-2.0
1fd057cec4e982efacc7905de79de4ea
31.540284
127
0.554908
4.982583
false
true
false
false
ktorio/ktor
ktor-io/common/src/io/ktor/utils/io/ByteWriteChannel.kt
1
7115
package io.ktor.utils.io import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* /** * Channel for asynchronous writing of sequences of bytes. * This is a **single-writer channel**. * * Operations on this channel cannot be invoked concurrently, unless explicitly specified otherwise * in description. Exceptions are [close] and [flush]. */ public expect interface ByteWriteChannel { /** * Returns number of bytes that can be written without suspension. Write operations do no suspend and return * immediately when this number is at least the number of bytes requested for write. */ public val availableForWrite: Int /** * Returns `true` is channel has been closed and attempting to write to the channel will cause an exception. */ public val isClosedForWrite: Boolean /** * Returns `true` if channel flushes automatically all pending bytes after every write function call. * If `false` then flush only happens at manual [flush] invocation or when the buffer is full. */ public val autoFlush: Boolean /** * Number of bytes written to the channel. * It is not guaranteed to be atomic so could be updated in the middle of write operation. */ public val totalBytesWritten: Long /** * A closure causes exception or `null` if closed successfully or not yet closed */ public val closedCause: Throwable? /** * Writes as much as possible and only suspends if buffer is full */ public suspend fun writeAvailable(src: ByteArray, offset: Int, length: Int): Int public suspend fun writeAvailable(src: ChunkBuffer): Int /** * Writes all [src] bytes and suspends until all bytes written. Causes flush if buffer filled up or when [autoFlush] * Crashes if channel get closed while writing. */ public suspend fun writeFully(src: ByteArray, offset: Int, length: Int) public suspend fun writeFully(src: Buffer) public suspend fun writeFully(memory: Memory, startIndex: Int, endIndex: Int) @Suppress("DEPRECATION") @Deprecated("Use write { } instead.") public suspend fun writeSuspendSession(visitor: suspend WriterSuspendSession.() -> Unit) /** * Writes a [packet] fully or fails if channel get closed before the whole packet has been written */ public suspend fun writePacket(packet: ByteReadPacket) /** * Writes long number and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeLong(l: Long) /** * Writes int number and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeInt(i: Int) /** * Writes short number and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeShort(s: Short) /** * Writes byte and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeByte(b: Byte) /** * Writes double number and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeDouble(d: Double) /** * Writes float number and suspends until written. * Crashes if channel get closed while writing. */ public suspend fun writeFloat(f: Float) /** * Invokes [block] when at least 1 byte is available for write. */ public suspend fun awaitFreeSpace() /** * Closes this channel with an optional exceptional [cause]. * It flushes all pending write bytes (via [flush]). * This is an idempotent operation -- repeated invocations of this function have no effect and return `false`. * * A channel that was closed without a [cause], is considered to be _closed normally_. * A channel that was closed with non-null [cause] is called a _failed channel_. Attempts to read or * write on a failed channel throw this cause exception. * * After invocation of this operation [isClosedForWrite] starts returning `true` and * all subsequent write operations throw [ClosedWriteChannelException] or the specified [cause]. * However, [isClosedForRead][ByteReadChannel.isClosedForRead] on the side of [ByteReadChannel] * starts returning `true` only after all written bytes have been read. * * Please note that if the channel has been closed with cause and it has been provided by [reader] or [writer] * coroutine then the corresponding coroutine will be cancelled with [cause]. If no [cause] provided then no * cancellation will be propagated. */ public fun close(cause: Throwable?): Boolean /** * Flushes all pending write bytes making them available for read. * * This function is thread-safe and can be invoked in any thread at any time. * It does nothing when invoked on a closed channel. */ public fun flush() } public suspend fun ByteWriteChannel.writeAvailable(src: ByteArray): Int = writeAvailable(src, 0, src.size) public suspend fun ByteWriteChannel.writeFully(src: ByteArray): Unit = writeFully(src, 0, src.size) public suspend fun ByteWriteChannel.writeShort(s: Int) { return writeShort((s and 0xffff).toShort()) } public suspend fun ByteWriteChannel.writeShort(s: Int, byteOrder: ByteOrder) { return writeShort((s and 0xffff).toShort(), byteOrder) } public suspend fun ByteWriteChannel.writeByte(b: Int) { return writeByte((b and 0xff).toByte()) } public suspend fun ByteWriteChannel.writeInt(i: Long) { return writeInt(i.toInt()) } public suspend fun ByteWriteChannel.writeInt(i: Long, byteOrder: ByteOrder) { return writeInt(i.toInt(), byteOrder) } /** * Closes this channel with no failure (successfully) */ public fun ByteWriteChannel.close(): Boolean = close(null) public suspend fun ByteWriteChannel.writeStringUtf8(s: CharSequence) { val packet = buildPacket { writeText(s) } return writePacket(packet) } public suspend fun ByteWriteChannel.writeStringUtf8(s: String) { val packet = buildPacket { writeText(s) } return writePacket(packet) } public suspend fun ByteWriteChannel.writeBoolean(b: Boolean) { return writeByte(if (b) 1 else 0) } /** * Writes UTF16 character */ public suspend fun ByteWriteChannel.writeChar(ch: Char) { return writeShort(ch.code) } public suspend inline fun ByteWriteChannel.writePacket(builder: BytePacketBuilder.() -> Unit) { return writePacket(buildPacket(builder)) } public suspend fun ByteWriteChannel.writePacketSuspend(builder: suspend BytePacketBuilder.() -> Unit) { return writePacket(buildPacket { builder() }) } /** * Indicates attempt to write on [isClosedForWrite][ByteWriteChannel.isClosedForWrite] channel * that was closed without a cause. A _failed_ channel rethrows the original [close][ByteWriteChannel.close] cause * exception on send attempts. */ public class ClosedWriteChannelException(message: String?) : CancellationException(message)
apache-2.0
4aba7e0f20808843eade401237d17a35
33.371981
120
0.705552
4.629148
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/Codecs.kt
1
9214
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* private val URL_ALPHABET = ((('a'..'z') + ('A'..'Z') + ('0'..'9')).map { it.code.toByte() }).toSet() private val URL_ALPHABET_CHARS = ((('a'..'z') + ('A'..'Z') + ('0'..'9'))).toSet() private val HEX_ALPHABET = (('a'..'f') + ('A'..'F') + ('0'..'9')).toSet() /** * https://tools.ietf.org/html/rfc3986#section-2 */ private val URL_PROTOCOL_PART = setOf( ':', '/', '?', '#', '[', ']', '@', // general '!', '$', '&', '\'', '(', ')', '*', ',', ';', '=', // sub-components '-', '.', '_', '~', '+' // unreserved ).map { it.code.toByte() } /** * from `pchar` in https://tools.ietf.org/html/rfc3986#section-2 */ private val VALID_PATH_PART = setOf( ':', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', '-', '.', '_', '~' ) /** * Characters allowed in attributes according: https://datatracker.ietf.org/doc/html/rfc5987 * attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" */ internal val ATTRIBUTE_CHARACTERS: Set<Char> = URL_ALPHABET_CHARS + setOf( '!', '#', '$', '&', '+', '-', '.', '^', '_', '`', '|', '~' ) /** * Characters allowed in url according to https://tools.ietf.org/html/rfc3986#section-2.3 */ private val SPECIAL_SYMBOLS = listOf('-', '.', '_', '~').map { it.code.toByte() } /** * Encode url part as specified in * https://tools.ietf.org/html/rfc3986#section-2 */ public fun String.encodeURLQueryComponent( encodeFull: Boolean = false, spaceToPlus: Boolean = false, charset: Charset = Charsets.UTF_8 ): String = buildString { val content = charset.newEncoder().encode(this@encodeURLQueryComponent) content.forEach { when { it == ' '.code.toByte() -> if (spaceToPlus) append('+') else append("%20") it in URL_ALPHABET || (!encodeFull && it in URL_PROTOCOL_PART) -> append(it.toInt().toChar()) else -> append(it.percentEncode()) } } } /** * Encodes URL path. It escapes all illegal or ambiguous characters keeping all "/" symbols. */ public fun String.encodeURLPath(): String = encodeURLPath(encodeSlash = false) /** * Encodes URL path segment. It escapes all illegal or ambiguous characters */ public fun String.encodeURLPathPart(): String = encodeURLPath(encodeSlash = true) internal fun String.encodeURLPath(encodeSlash: Boolean): String = buildString { val charset = Charsets.UTF_8 var index = 0 while (index < [email protected]) { val current = this@encodeURLPath[index] if ((!encodeSlash && current == '/') || current in URL_ALPHABET_CHARS || current in VALID_PATH_PART) { append(current) index++ continue } if (current == '%' && index + 2 < [email protected] && this@encodeURLPath[index + 1] in HEX_ALPHABET && this@encodeURLPath[index + 2] in HEX_ALPHABET ) { append(current) append(this@encodeURLPath[index + 1]) append(this@encodeURLPath[index + 2]) index += 3 continue } val symbolSize = if (current.isSurrogate()) 2 else 1 // we need to call newEncoder() for every symbol, otherwise it won't work charset.newEncoder().encode(this@encodeURLPath, index, index + symbolSize).forEach { append(it.percentEncode()) } index += symbolSize } } /** * Encode [this] in percent encoding specified here: * https://tools.ietf.org/html/rfc5849#section-3.6 */ public fun String.encodeOAuth(): String = encodeURLParameter() /** * Encode [this] as query parameter key. */ public fun String.encodeURLParameter( spaceToPlus: Boolean = false ): String = buildString { val content = Charsets.UTF_8.newEncoder().encode(this@encodeURLParameter) content.forEach { when { it in URL_ALPHABET || it in SPECIAL_SYMBOLS -> append(it.toInt().toChar()) spaceToPlus && it == ' '.code.toByte() -> append('+') else -> append(it.percentEncode()) } } } internal fun String.percentEncode(allowedSet: Set<Char>): String { val encodedCount = count { it !in allowedSet } if (encodedCount == 0) return this val resultSize = length + encodedCount * 2 val result = CharArray(resultSize) var writeIndex = 0 for (index in 0 until length) { val current = this[index] if (current in allowedSet) { result[writeIndex++] = current } else { val code = current.code result[writeIndex++] = '%' result[writeIndex++] = hexDigitToChar(code shr 4) result[writeIndex++] = hexDigitToChar(code and 0xf) } } return result.concatToString() } /** * Encode [this] as query parameter value. */ internal fun String.encodeURLParameterValue(): String = encodeURLParameter(spaceToPlus = true) /** * Decode URL query component */ public fun String.decodeURLQueryComponent( start: Int = 0, end: Int = length, plusIsSpace: Boolean = false, charset: Charset = Charsets.UTF_8 ): String = decodeScan(start, end, plusIsSpace, charset) /** * Decode percent encoded URL part within the specified range [[start], [end]). * This function is not intended to decode urlencoded forms so it doesn't decode plus character to space. */ public fun String.decodeURLPart( start: Int = 0, end: Int = length, charset: Charset = Charsets.UTF_8 ): String = decodeScan(start, end, false, charset) private fun String.decodeScan(start: Int, end: Int, plusIsSpace: Boolean, charset: Charset): String { for (index in start until end) { val ch = this[index] if (ch == '%' || (plusIsSpace && ch == '+')) { return decodeImpl(start, end, index, plusIsSpace, charset) } } return if (start == 0 && end == length) toString() else substring(start, end) } private fun CharSequence.decodeImpl( start: Int, end: Int, prefixEnd: Int, plusIsSpace: Boolean, charset: Charset ): String { val length = end - start // if length is big, it probably means it is encoded val sbSize = if (length > 255) length / 3 else length val sb = StringBuilder(sbSize) if (prefixEnd > start) { sb.append(this, start, prefixEnd) } var index = prefixEnd // reuse ByteArray for hex decoding stripes var bytes: ByteArray? = null while (index < end) { val c = this[index] when { plusIsSpace && c == '+' -> { sb.append(' ') index++ } c == '%' -> { // if ByteArray was not needed before, create it with an estimate of remaining string be all hex if (bytes == null) { bytes = ByteArray((end - index) / 3) } // fill ByteArray with all the bytes, so Charset can decode text var count = 0 while (index < end && this[index] == '%') { if (index + 2 >= end) { throw URLDecodeException( "Incomplete trailing HEX escape: ${substring(index)}, in $this at $index" ) } val digit1 = charToHexDigit(this[index + 1]) val digit2 = charToHexDigit(this[index + 2]) if (digit1 == -1 || digit2 == -1) { throw URLDecodeException( "Wrong HEX escape: %${this[index + 1]}${this[index + 2]}, in $this, at $index" ) } bytes[count++] = (digit1 * 16 + digit2).toByte() index += 3 } // Decode chars from bytes and put into StringBuilder // Note: Tried using ByteBuffer and using enc.decode() – it's slower sb.append(String(bytes, offset = 0, length = count, charset = charset)) } else -> { sb.append(c) index++ } } } return sb.toString() } /** * URL decoder exception */ public class URLDecodeException(message: String) : Exception(message) private fun Byte.percentEncode(): String { val code = toInt() and 0xff val array = CharArray(3) array[0] = '%' array[1] = hexDigitToChar(code shr 4) array[2] = hexDigitToChar(code and 0xf) return array.concatToString() } private fun charToHexDigit(c2: Char) = when (c2) { in '0'..'9' -> c2 - '0' in 'A'..'F' -> c2 - 'A' + 10 in 'a'..'f' -> c2 - 'a' + 10 else -> -1 } private fun hexDigitToChar(digit: Int): Char = when (digit) { in 0..9 -> '0' + digit else -> 'A' + digit - 10 } private fun ByteReadPacket.forEach(block: (Byte) -> Unit) { takeWhile { buffer -> while (buffer.canRead()) { block(buffer.readByte()) } true } }
apache-2.0
ee842bc8dcd104604ccc6e1a1cc415e3
30.875433
118
0.556122
4.035042
false
false
false
false
helloworld1/FreeOTPPlus
token-data/src/main/java/org/fedorahosted/freeotp/data/OtpTokenDao.kt
1
2311
package org.fedorahosted.freeotp.data import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.RawQuery import androidx.room.Transaction import androidx.room.Update import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteQuery import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext @Dao interface OtpTokenDao { @Query("select * from otp_tokens order by ordinal") fun getAll(): Flow<List<OtpToken>> @Query("select * from otp_tokens where id = :id") fun get(id: Long): Flow<OtpToken?> @Query("select ordinal from otp_tokens order by ordinal desc limit 1") fun getLastOrdinal(): Long? @Query("delete from otp_tokens where id = :id") suspend fun deleteById(id: Long): Void @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(otpTokenList: List<OtpToken>) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(otpTokenList: OtpToken) @Update suspend fun update(otpTokenList: OtpToken) @Query("update otp_tokens set ordinal = :ordinal where id = :id") suspend fun updateOrdinal(id: Long, ordinal: Long) /** * This incrementCounter won't trigger Flow collect by using raw query * We do not want increment count triggering flow because it can refresh the token */ suspend fun incrementCounter(id: Long) { incrementCounterRaw( SimpleSQLiteQuery("update otp_tokens set counter = counter + 1 where id = ?", arrayOf(id)) ) } @RawQuery suspend fun incrementCounterRaw(query: SupportSQLiteQuery): Int @Transaction suspend fun movePairs(pairs : List<Pair<Long,Long>>){ for(pair in pairs.listIterator()) { withContext(Dispatchers.IO) { val token1 = get(pair.first).first() val token2 = get(pair.second).first() if (token1 == null || token2 == null) { return@withContext } updateOrdinal(pair.first, token2.ordinal) updateOrdinal(pair.second, token1.ordinal) } } } }
apache-2.0
bd93232e98489a2de9e79ed37c67d228
30.671233
89
0.676763
4.444231
false
false
false
false
weichen2046/IntellijPluginDevDemo
src/main/java/com/spreadst/devtools/demos/popup/OpenDemoPopupAction.kt
1
1859
package com.spreadst.devtools.demos.popup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import javax.swing.Icon import icons.Icons class OpenDemoPopupAction : AnAction("Demo Popup", "Open demo popup", null) { override fun actionPerformed(e: AnActionEvent?) { val title = "Popup Title" val values = getValues() val icons = getIcons() val popup = JBPopupFactory.getInstance().createListPopup(MyListPopupStep(title, values, icons)) popup.showCenteredInCurrentWindow(e!!.project!!) } private fun getValues(): List<String> { val values = ArrayList<String>() (0 until 26).mapTo(values) { ('A'.toInt() + it).toChar().toString() } return values } private fun getIcons(): List<Icon> { val icons = ArrayList<Icon>() (0 until 26).mapTo(icons) { Icons.DemoEditor } return icons } /** * http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/popups.html */ inner class MyListPopupStep(title: String, values: List<String>, icons: List<Icon>) : BaseListPopupStep<String>(title, values, icons) { private var selectedVal: String? = null override fun onChosen(selectedValue: String?, finalChoice: Boolean): PopupStep<*>? { selectedVal = selectedValue return super.onChosen(selectedValue, finalChoice) } override fun getFinalRunnable(): Runnable? { return Runnable { Messages.showMessageDialog("You selected $selectedVal", "Selected Value", Messages.getInformationIcon()) } } } }
apache-2.0
9c4d19e87b787cb3e3f6969036cb3c4e
35.470588
136
0.683701
4.458034
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/setting/ReaderSettingsSheet.kt
2
2635
package eu.kanade.tachiyomi.ui.reader.setting import android.animation.ValueAnimator import android.os.Bundle import com.google.android.material.tabs.TabLayout import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.widget.listener.SimpleTabSelectedListener import eu.kanade.tachiyomi.widget.sheet.TabbedBottomSheetDialog class ReaderSettingsSheet( private val activity: ReaderActivity, private val showColorFilterSettings: Boolean = false, ) : TabbedBottomSheetDialog(activity) { private val readingModeSettings = ReaderReadingModeSettings(activity) private val generalSettings = ReaderGeneralSettings(activity) private val colorFilterSettings = ReaderColorFilterSettings(activity) private val backgroundDimAnimator by lazy { val sheetBackgroundDim = window?.attributes?.dimAmount ?: 0.25f ValueAnimator.ofFloat(sheetBackgroundDim, 0f).also { valueAnimator -> valueAnimator.duration = 250 valueAnimator.addUpdateListener { window?.setDimAmount(it.animatedValue as Float) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) behavior.isFitToContents = false behavior.halfExpandedRatio = 0.25f val filterTabIndex = getTabViews().indexOf(colorFilterSettings) binding.tabs.addOnTabSelectedListener(object : SimpleTabSelectedListener() { override fun onTabSelected(tab: TabLayout.Tab?) { val isFilterTab = tab?.position == filterTabIndex // Remove dimmed backdrop so color filter changes can be previewed backgroundDimAnimator.run { if (isFilterTab) { if (animatedFraction < 1f) { start() } } else if (animatedFraction > 0f) { reverse() } } // Hide toolbars if (activity.menuVisible != !isFilterTab) { activity.setMenuVisibility(!isFilterTab) } } }) if (showColorFilterSettings) { binding.tabs.getTabAt(filterTabIndex)?.select() } } override fun getTabViews() = listOf( readingModeSettings, generalSettings, colorFilterSettings, ) override fun getTabTitles() = listOf( R.string.pref_category_reading_mode, R.string.pref_category_general, R.string.custom_filter, ) }
apache-2.0
2bee5e73b7bf71fa8f8f42c1770dfa1f
34.133333
84
0.637192
5.238569
false
false
false
false
dimagi/commcare-android
app/src/org/commcare/gis/MapboxLocationPickerViewModel.kt
1
3087
package org.commcare.gis import android.app.Application import android.location.Geocoder import android.location.Location import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.mapbox.mapboxsdk.geometry.LatLng import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.commcare.dalvik.R import org.commcare.util.LogTypes import org.commcare.utils.GeoUtils import org.commcare.utils.StringUtils import org.javarosa.core.services.Logger import java.lang.IllegalArgumentException import java.util.* /** * @author $|-|!˅@M */ class MapboxLocationPickerViewModel(application: Application): AndroidViewModel(application) { val placeName = MutableLiveData<String>() private var location = Location("XForm") fun reverseGeocode(latLng: LatLng) { viewModelScope.launch(Dispatchers.IO) { var addressString = "" val geocoder = Geocoder(getApplication(), Locale.getDefault()) val geoAddress = try { geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1) } catch (e: Exception) { if (e is IllegalArgumentException) { Logger.exception("Error while fetching location from geocoder", e) } null } geoAddress?.let { if (it.isNotEmpty()) { val addr = it[0] val builder = StringBuilder() for (i in 0..addr.maxAddressLineIndex) { builder.append(addr.getAddressLine(i)) .append("\n") } addressString = builder.toString() } } if (addressString.isEmpty()) { val builder = StringBuilder() builder.append(StringUtils.getStringSpannableRobust(getApplication(), R.string.latitude)) .append(": ") .append(GeoUtils.formatGps(latLng.latitude, "lat")) .append("\n") .append(StringUtils.getStringSpannableRobust(getApplication(), R.string.longitude)) .append(": ") .append(GeoUtils.formatGps(latLng.longitude, "lon")) .append("\n") .append(StringUtils.getStringSpannableRobust(getApplication(), R.string.altitude)) .append(": ") .append(String.format("%.2f", latLng.altitude)) addressString = builder.toString() } withContext(Dispatchers.Main) { location.latitude = latLng.latitude location.longitude = latLng.longitude location.altitude = latLng.altitude location.accuracy = 10.0f placeName.postValue(addressString) } } } fun getLocation() = location }
apache-2.0
939f98d6b5f0018e8223152aea010aae
38.564103
107
0.581983
5.275214
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/deft/api/Type.kt
2
1605
package org.jetbrains.deft abstract class Type<T : Obj, B : ObjBuilder<T>>(val base: Type<*, *>? = null) : Obj { var open: Boolean = false var abstract: Boolean = false var sealed: Boolean = false val inheritanceAllowed get() = open || sealed || abstract val superTypes: List<Type<*, *>> get() = base?.superTypes?.toMutableList()?.apply { add(base) } ?: emptyList() val ival: Class<T> get() = javaClass.enclosingClass as Class<T> val ivar: Class<B> get() = ival.classes.single { it.simpleName == "Builder" } as Class<B> open val packageName: String get() = ival.packageName open val name by lazy { if (ival.enclosingClass == null) ival.simpleName else { var topLevelClass: Class<*> = ival val outerNames = mutableListOf<String>() do { outerNames.add(topLevelClass.simpleName) topLevelClass = topLevelClass.enclosingClass ?: break } while (true) outerNames.reversed().joinToString(".") } } protected open fun loadBuilderFactory(): () -> B { val ivalClass = ival val packageName = ivalClass.packageName val simpleName = name.replace(".", "") val c = ivalClass.classLoader.loadClass("$packageName.${simpleName}Impl\$Builder") val ctor = c.constructors.find { it.parameterCount == 0 }!! return { ctor.newInstance() as B } } private val _builder: () -> B by lazy { loadBuilderFactory() } protected fun builder(): B = _builder() override fun toString(): String = name }
apache-2.0
cde1deae5d0c66ab283904a44ce45d69
31.77551
93
0.607477
4.470752
false
false
false
false
Pinkal7600/Todo
app/src/main/java/com/pinkal/todo/utils/views/indicator/CirclePageIndicator.kt
1
17645
/* * Copyright (C) 2011 Patrik Akerfeldt * Copyright (C) 2011 Jake Wharton * * 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.pinkal.todo.utils.views.indicator import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Paint.ANTI_ALIAS_FLAG import android.graphics.Paint.Style import android.os.Parcel import android.os.Parcelable import android.support.v4.view.MotionEventCompat import android.support.v4.view.ViewConfigurationCompat import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import android.widget.LinearLayout.HORIZONTAL import android.widget.LinearLayout.VERTICAL import com.pinkal.todo.R /** * Draws circles (one for each view). The current view position is filled and * others are only stroked. */ class CirclePageIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet = null!!, defStyle: Int = R.attr.vpiCirclePageIndicatorStyle) : View(context, attrs, defStyle), PageIndicator { private var mRadius: Float = 0.toFloat() private val mPaintPageFill = Paint(ANTI_ALIAS_FLAG) private val mPaintStroke = Paint(ANTI_ALIAS_FLAG) private val mPaintFill = Paint(ANTI_ALIAS_FLAG) private var mViewPager: ViewPager? = null private var mListener: ViewPager.OnPageChangeListener? = null private var mCurrentPage: Int = 0 private var mSnapPage: Int = 0 private var mPageOffset: Float = 0.toFloat() private var mScrollState: Int = 0 private var mOrientation: Int = 0 private var mCentered: Boolean = false private var mSnap: Boolean = false private val mTouchSlop: Int private var mLastMotionX = -1f private var mActivePointerId = INVALID_POINTER private var mIsDragging: Boolean = false init { // if (isInEditMode) return //Load defaults from resources val res = resources val defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color) val defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color) val defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation) val defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color) val defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width) val defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius) val defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered) val defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap) //Retrieve styles attributes val a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0) mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered) mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation) mPaintPageFill.style = Style.FILL mPaintPageFill.color = a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor) mPaintStroke.style = Style.STROKE mPaintStroke.color = a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor) mPaintStroke.strokeWidth = a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth) mPaintFill.style = Style.FILL mPaintFill.color = a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor) mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius) mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap) val background = a.getDrawable(R.styleable.CirclePageIndicator_android_background) if (background != null) { setBackgroundDrawable(background) } a.recycle() val configuration = ViewConfiguration.get(context) mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration) } var isCentered: Boolean get() = mCentered set(centered) { mCentered = centered invalidate() } var pageColor: Int get() = mPaintPageFill.color set(pageColor) { mPaintPageFill.color = pageColor invalidate() } var fillColor: Int get() = mPaintFill.color set(fillColor) { mPaintFill.color = fillColor invalidate() } var orientation: Int get() = mOrientation set(orientation) = when (orientation) { HORIZONTAL, VERTICAL -> { mOrientation = orientation requestLayout() } else -> throw IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.") } var strokeColor: Int get() = mPaintStroke.color set(strokeColor) { mPaintStroke.color = strokeColor invalidate() } var strokeWidth: Float get() = mPaintStroke.strokeWidth set(strokeWidth) { mPaintStroke.strokeWidth = strokeWidth invalidate() } var radius: Float get() = mRadius set(radius) { mRadius = radius invalidate() } var isSnap: Boolean get() = mSnap set(snap) { mSnap = snap invalidate() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (mViewPager == null) { return } val count = mViewPager!!.adapter.count if (count == 0) { return } if (mCurrentPage >= count) { setCurrentItem(count - 1) return } val longSize: Int val longPaddingBefore: Int val longPaddingAfter: Int val shortPaddingBefore: Int if (mOrientation == HORIZONTAL) { longSize = width longPaddingBefore = paddingLeft longPaddingAfter = paddingRight shortPaddingBefore = paddingTop } else { longSize = height longPaddingBefore = paddingTop longPaddingAfter = paddingBottom shortPaddingBefore = paddingLeft } val threeRadius = mRadius * 3 val shortOffset = shortPaddingBefore + mRadius var longOffset = longPaddingBefore + mRadius if (mCentered) { longOffset += (longSize - longPaddingBefore - longPaddingAfter) / 2.0f - count * threeRadius / 2.0f } var dX: Float var dY: Float var pageFillRadius = mRadius if (mPaintStroke.strokeWidth > 0) { pageFillRadius -= mPaintStroke.strokeWidth / 2.0f } //Draw stroked circles for (iLoop in 0..count - 1) { val drawLong = longOffset + iLoop * threeRadius if (mOrientation == HORIZONTAL) { dX = drawLong dY = shortOffset } else { dX = shortOffset dY = drawLong } // Only paint fill if not completely transparent if (mPaintPageFill.alpha > 0) { canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill) } // Only paint stroke if a stroke width was non-zero if (pageFillRadius != mRadius) { canvas.drawCircle(dX, dY, mRadius, mPaintStroke) } } //Draw the filled circle according to the current scroll var cx = (if (mSnap) mSnapPage else mCurrentPage) * threeRadius if (!mSnap) { cx += mPageOffset * threeRadius } if (mOrientation == HORIZONTAL) { dX = longOffset + cx dY = shortOffset } else { dX = shortOffset dY = longOffset + cx } canvas.drawCircle(dX, dY, mRadius, mPaintFill) } override fun onTouchEvent(ev: MotionEvent): Boolean { if (super.onTouchEvent(ev)) { return true } if (mViewPager == null || mViewPager!!.adapter.count == 0) { return false } val action = ev.action and MotionEventCompat.ACTION_MASK when (action) { MotionEvent.ACTION_DOWN -> { mActivePointerId = MotionEventCompat.getPointerId(ev, 0) mLastMotionX = ev.x } MotionEvent.ACTION_MOVE -> { val activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId) val x = MotionEventCompat.getX(ev, activePointerIndex) val deltaX = x - mLastMotionX if (!mIsDragging) { if (Math.abs(deltaX) > mTouchSlop) { mIsDragging = true } } if (mIsDragging) { mLastMotionX = x if (mViewPager!!.isFakeDragging || mViewPager!!.beginFakeDrag()) { mViewPager!!.fakeDragBy(deltaX) } } } MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> { if (!mIsDragging) { val count = mViewPager!!.adapter.count val width = width val halfWidth = width / 2f val sixthWidth = width / 6f if (mCurrentPage > 0 && ev.x < halfWidth - sixthWidth) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager!!.currentItem = mCurrentPage - 1 } return true } else if (mCurrentPage < count - 1 && ev.x > halfWidth + sixthWidth) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager!!.currentItem = mCurrentPage + 1 } return true } } mIsDragging = false mActivePointerId = INVALID_POINTER if (mViewPager!!.isFakeDragging) mViewPager!!.endFakeDrag() } MotionEventCompat.ACTION_POINTER_DOWN -> { val index = MotionEventCompat.getActionIndex(ev) mLastMotionX = MotionEventCompat.getX(ev, index) mActivePointerId = MotionEventCompat.getPointerId(ev, index) } MotionEventCompat.ACTION_POINTER_UP -> { val pointerIndex = MotionEventCompat.getActionIndex(ev) val pointerId = MotionEventCompat.getPointerId(ev, pointerIndex) if (pointerId == mActivePointerId) { val newPointerIndex = if (pointerIndex == 0) 1 else 0 mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex) } mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)) } } return true } override fun setViewPager(view: ViewPager) { if (mViewPager === view) { return } if (mViewPager != null) { mViewPager!!.setOnPageChangeListener(null) } if (view.adapter == null) { throw IllegalStateException("ViewPager does not have adapter instance.") } mViewPager = view mViewPager!!.setOnPageChangeListener(this) invalidate() } override fun setViewPager(view: ViewPager, initialPosition: Int) { setViewPager(view) setCurrentItem(initialPosition) } override fun setCurrentItem(item: Int) { if (mViewPager == null) { throw IllegalStateException("ViewPager has not been bound.") } mViewPager!!.currentItem = item mCurrentPage = item invalidate() } override fun notifyDataSetChanged() { invalidate() } override fun onPageScrollStateChanged(state: Int) { mScrollState = state if (mListener != null) { mListener!!.onPageScrollStateChanged(state) } } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { mCurrentPage = position mPageOffset = positionOffset invalidate() if (mListener != null) { mListener!!.onPageScrolled(position, positionOffset, positionOffsetPixels) } } override fun onPageSelected(position: Int) { if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) { mCurrentPage = position mSnapPage = position invalidate() } if (mListener != null) { mListener!!.onPageSelected(position) } } override fun setOnPageChangeListener(listener: ViewPager.OnPageChangeListener) { mListener = listener } /* * (non-Javadoc) * * @see android.view.View#onMeasure(int, int) */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (mOrientation == HORIZONTAL) { setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec)) } else { setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec)) } } /** * Determines the width of this view * @param measureSpec * * A measureSpec packed into an int * * * @return The width of the view, honoring constraints from measureSpec */ private fun measureLong(measureSpec: Int): Int { var result: Int val specMode = View.MeasureSpec.getMode(measureSpec) val specSize = View.MeasureSpec.getSize(measureSpec) if (specMode == View.MeasureSpec.EXACTLY || mViewPager == null) { //We were told how big to be result = specSize } else { //Calculate the width according the views count val count = mViewPager!!.adapter.count result = (paddingLeft.toFloat() + paddingRight.toFloat() + count.toFloat() * 2f * mRadius + (count - 1) * mRadius + 1f).toInt() //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == View.MeasureSpec.AT_MOST) { result = Math.min(result, specSize) } } return result } /** * Determines the height of this view * @param measureSpec * * A measureSpec packed into an int * * * @return The height of the view, honoring constraints from measureSpec */ private fun measureShort(measureSpec: Int): Int { var result: Int val specMode = View.MeasureSpec.getMode(measureSpec) val specSize = View.MeasureSpec.getSize(measureSpec) if (specMode == View.MeasureSpec.EXACTLY) { //We were told how big to be result = specSize } else { //Measure the height result = (2 * mRadius + paddingTop.toFloat() + paddingBottom.toFloat() + 1f).toInt() //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == View.MeasureSpec.AT_MOST) { result = Math.min(result, specSize) } } return result } public override fun onRestoreInstanceState(state: Parcelable) { val savedState = state as SavedState super.onRestoreInstanceState(savedState.superState) mCurrentPage = savedState.currentPage mSnapPage = savedState.currentPage requestLayout() } public override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() val savedState = SavedState(superState) savedState.currentPage = mCurrentPage return savedState } internal class SavedState : View.BaseSavedState { var currentPage: Int = 0 constructor(superState: Parcelable) : super(superState) {} private constructor(`in`: Parcel) : super(`in`) { currentPage = `in`.readInt() } override fun writeToParcel(dest: Parcel, flags: Int) { super.writeToParcel(dest, flags) dest.writeInt(currentPage) } companion object { val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> { override fun createFromParcel(`in`: Parcel): SavedState { return SavedState(`in`) } override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) } } } } companion object { private val INVALID_POINTER = -1 } }
apache-2.0
082a64239f5eab6f4f4f3d76cbe5e9e0
33.734252
115
0.599433
5.225052
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/test/src/org/intellij/plugins/markdown/parser/FrontMatterParserTest.kt
8
1402
package org.intellij.plugins.markdown.parser import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.psi.impl.DebugUtil import com.intellij.testFramework.LightPlatformCodeInsightTestCase import com.intellij.testFramework.RegistryKeyRule import junit.framework.TestCase import org.intellij.plugins.markdown.MarkdownTestingUtil import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.File @RunWith(JUnit4::class) class FrontMatterParserTest: LightPlatformCodeInsightTestCase() { @Rule @JvmField val rule = RegistryKeyRule("markdown.experimental.frontmatter.support.enable", true) @Test fun `test header block`() = doTest() private fun doTest() { val testName = getTestName(true) configureByFile("$testName.md") val psi = DebugUtil.psiToString(file, true, false) val expectedContentPath = File(testDataPath, "$testName.txt") val expected = FileUtil.loadFile(expectedContentPath, CharsetToolkit.UTF8, true) TestCase.assertEquals(expected, psi) } override fun getTestName(lowercaseFirstLetter: Boolean): String { val name = super.getTestName(lowercaseFirstLetter) return name.trimStart().replace(' ', '_') } override fun getTestDataPath(): String { return "${MarkdownTestingUtil.TEST_DATA_PATH}/parser/frontmatter/" } }
apache-2.0
2ae3fa13641c6c3c6a578ede2512d18b
32.380952
86
0.779601
4.340557
false
true
false
false
phylame/jem
jem-formats/src/main/kotlin/jem/format/epub/opf/Spine.kt
1
2151
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.format.epub.opf import jclp.text.ifNotEmpty import jclp.xml.attribute import jclp.xml.endTag import jclp.xml.startTag import jem.format.epub.Taggable import org.xmlpull.v1.XmlSerializer import java.util.* class ItemRef(val idref: String, var linear: Boolean, var properties: String, id: String = "") : Taggable(id) { override fun renderTo(xml: XmlSerializer) { with(xml) { startTag("itemref") attribute("idref", idref) if (!linear) attribute("linear", "no") properties.ifNotEmpty { attribute("properties", it) } attr.forEach { attribute(it.key, it.value) } id.ifNotEmpty { attribute("id", it) } endTag() } } } class Spine(var toc: String = "", id: String = "") : Taggable(id) { private val refs = LinkedList<ItemRef>() operator fun plusAssign(ref: ItemRef) { refs += ref } operator fun minusAssign(ref: ItemRef) { refs -= ref } fun addRef(idref: String, linear: Boolean = true, properties: String = "", id: String = "") = ItemRef(idref, linear, properties, id).also { refs += it } override fun renderTo(xml: XmlSerializer) { with(xml) { startTag("spine") toc.ifNotEmpty { attribute("toc", it) } attr.forEach { attribute(it.key, it.value) } id.ifNotEmpty { attribute("id", it) } refs.forEach { it.renderTo(this) } endTag() } } }
apache-2.0
ae8261dac17a98245e4dcae9a5435a13
31.104478
111
0.630404
3.854839
false
false
false
false
evoasm/evoasm
src/evoasm/x64/ProgramSet.kt
1
8699
package evoasm.x64 import kasm.Address import kasm.CodeModel import kasm.NativeBuffer import kasm.address import kasm.x64.Assembler import java.util.logging.Logger class CompiledNumberProgram<T: Number> internal constructor(program: Program, interpreter: Interpreter, val programSetInput: NumberProgramSetInput<T>, val programSetOutput: NumberProgramSetOutput<T>) { val buffer = NativeBuffer(1024) companion object { val LOGGER = Logger.getLogger(CompiledNumberProgram::class.java.name) } init { compile(program, interpreter) } private fun compile(program: Program, interpreter: Interpreter) { Assembler(buffer).apply { emitStackFrame { programSetInput.emitLoad(this) program.forEach { val interpreterInstruction = interpreter.getInstruction(it) interpreterInstruction!!.instruction.encode(buffer, interpreterInstruction.instructionParameters) } programSetOutput.emitStore(this) } } } fun run(vararg arguments: T) : T { arguments.forEachIndexed {index, argument -> programSetInput[0, index] = argument } LOGGER.finer(buffer.toByteString()) buffer.setExecutable(true) LOGGER.fine("executing compiled program") buffer.execute() return programSetOutput[0, 0] } } class Program(val size: Int) { private val code = UShortArray(size) operator fun set(index: Int, opcode: InterpreterOpcode) { code[index] = opcode.code } inline fun forEach(action: (InterpreterOpcode) -> Unit) { for (i in 0 until size) { action(this[i]) } } inline fun forEachIndexed(action: (InterpreterOpcode, Int) -> Unit) { for (i in 0 until size) { action(this[i], i) } } operator fun get(index: Int): InterpreterOpcode { return InterpreterOpcode(code[index]) } } class ProgramSet(val programCount: Int, val programSize: Int, val threadCount: Int) { constructor(size: Int, programSize: Int) : this(size, programSize, 1) internal val programSizeWithEnd = programSize + 1 internal val perThreadProgramCount = programCount / threadCount private val perThreadInstructionCountWithHalt = perThreadProgramCount * programSizeWithEnd + 1 val instructionCount = programCount * programSizeWithEnd private val instructionCountWithHalts = instructionCount + threadCount private val codeBuffer = NativeBuffer(instructionCountWithHalts.toLong() * UShort.SIZE_BYTES, CodeModel.LARGE) internal val byteBuffer = codeBuffer.byteBuffer private val shortBuffer = byteBuffer.asShortBuffer() val address: Address = codeBuffer.address internal var initialized : Boolean = false fun getAddress(threadIndex: Int): Address { val offset = (threadIndex * perThreadInstructionCountWithHalt * Short.SIZE_BYTES).toULong() val address = codeBuffer.address + offset LOGGER.finest("address: $address, offset: $offset, threadIndex: $threadIndex, bufferSize: ${codeBuffer.byteBuffer.capacity()}") return address } init { require(programCount % threadCount == 0) } companion object { val LOGGER = Logger.getLogger(ProgramSet::class.java.name) } internal fun initialize(haltOpcode: InterpreterOpcode, endOpcode: InterpreterOpcode) { check(!initialized) {"cannot reuse program set"} initialized = true // shortBuffer.put(0, startOpcode.code.toShort()) require(perThreadInstructionCountWithHalt * threadCount == instructionCountWithHalts) { "${perThreadInstructionCountWithHalt * threadCount} == ${instructionCountWithHalts}" } for(threadIndex in 0 until threadCount) { for (threadProgramIndex in 0 until perThreadProgramCount) { val offset = calculateOffset(threadIndex, threadProgramIndex, programSize) require(offset == threadIndex * perThreadInstructionCountWithHalt + threadProgramIndex * programSizeWithEnd + programSize) shortBuffer.put(offset, endOpcode.code.toShort()) } val haltOffset = threadIndex * perThreadInstructionCountWithHalt + perThreadInstructionCountWithHalt - 1 LOGGER.finer("setting halt at $haltOffset"); shortBuffer.put(haltOffset, haltOpcode.code.toShort()) } } fun toString(interpreter: Interpreter): String { val builder = StringBuilder() for(i in 0 until instructionCountWithHalts) { val interpreterOpcode = InterpreterOpcode(shortBuffer.get(i).toUShort()) val programIndex = i / programSizeWithEnd val instructionIndex = i % programSizeWithEnd val threadIndex = i / perThreadInstructionCountWithHalt val perThreadProgramIndex = i % perThreadInstructionCountWithHalt val instructionName = if(interpreterOpcode == interpreter.getHaltOpcode()) { "HALT" } else if(interpreterOpcode == interpreter.getEndOpcode()) { "END" } else { interpreter.getInstruction(interpreterOpcode).toString() } builder.append("$threadIndex:$perThreadProgramIndex:$instructionIndex:$i:$instructionName\t\n") } forEach { interpreterOpcode: InterpreterOpcode, threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int, instructionOffset: Int -> } return builder.toString() } operator fun set(programIndex: Int, instructionIndex: Int, opcode: InterpreterOpcode) { val offset = calculateOffset(programIndex, instructionIndex) shortBuffer.put(offset, opcode.code.toShort()) } private inline fun forEach(action: (InterpreterOpcode, Int, Int, Int, Int) -> Unit) { for(threadIndex in 0 until threadCount) { for (perThreadProgramIndex in 0 until perThreadProgramCount) { for (instructionIndex in 0 until programSize) { val instructionOffset = calculateOffset(threadIndex, perThreadProgramIndex, instructionIndex); val interpreterOpcode = InterpreterOpcode(shortBuffer.get(instructionOffset).toUShort()) action(interpreterOpcode, threadIndex, perThreadProgramIndex, instructionIndex, instructionOffset) } } } } internal inline fun transform(action: (InterpreterOpcode, Int, Int, Int) -> InterpreterOpcode) { forEach { interpreterOpcode: InterpreterOpcode, threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int, instructionOffset: Int -> shortBuffer.put(instructionOffset, action(interpreterOpcode, threadIndex, perThreadProgramIndex, instructionIndex).code.toShort()) } } operator fun get(programIndex: Int, instructionIndex: Int): InterpreterOpcode { val offset = calculateOffset(programIndex, instructionIndex) return InterpreterOpcode(shortBuffer.get(offset).toUShort()) } private fun calculateOffset(threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int): Int { return (threadIndex * perThreadInstructionCountWithHalt + perThreadProgramIndex * programSizeWithEnd + instructionIndex) } private fun calculateOffset(programIndex: Int, instructionIndex: Int): Int { val threadIndex = programIndex / perThreadProgramCount val threadProgramIndex = programIndex % perThreadProgramCount return calculateOffset(threadIndex, threadProgramIndex, instructionIndex) } fun copyProgramTo(programIndex: Int, program: Program) { val programOffset = calculateOffset(programIndex, 0) for (i in 0 until programSize) { val instructionOffset = programOffset + i program[i] = InterpreterOpcode(shortBuffer.get(instructionOffset).toUShort()) } } internal inline fun copyProgram(fromProgramIndex: Int, toProgramIndex: Int, transformer: (InterpreterOpcode, Int) -> InterpreterOpcode = { io, o -> io}) { val fromOffset = calculateOffset(fromProgramIndex, 0) val toOffset = calculateOffset(toProgramIndex, 0) for (i in 0 until programSizeWithEnd) { val relativeOffset = i val interpreterInstruction = InterpreterOpcode(shortBuffer.get(fromOffset + relativeOffset).toUShort()) shortBuffer.put(toOffset + relativeOffset, transformer(interpreterInstruction, i).code.toShort()) } } }
agpl-3.0
9ebde33b364f239d4a5633da53a6ba30
40.428571
201
0.677434
5.554917
false
false
false
false
android/location-samples
SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/receiver/SleepReceiver.kt
2
3906
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.sleepsamplekotlin.receiver import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import com.android.example.sleepsamplekotlin.MainApplication import com.android.example.sleepsamplekotlin.data.SleepRepository import com.android.example.sleepsamplekotlin.data.db.SleepClassifyEventEntity import com.android.example.sleepsamplekotlin.data.db.SleepSegmentEventEntity import com.google.android.gms.location.SleepClassifyEvent import com.google.android.gms.location.SleepSegmentEvent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch /** * Saves Sleep Events to Database. */ class SleepReceiver : BroadcastReceiver() { // Used to launch coroutines (non-blocking way to insert data). private val scope: CoroutineScope = MainScope() override fun onReceive(context: Context, intent: Intent) { Log.d(TAG, "onReceive(): $intent") val repository: SleepRepository = (context.applicationContext as MainApplication).repository if (SleepSegmentEvent.hasEvents(intent)) { val sleepSegmentEvents: List<SleepSegmentEvent> = SleepSegmentEvent.extractEvents(intent) Log.d(TAG, "SleepSegmentEvent List: $sleepSegmentEvents") addSleepSegmentEventsToDatabase(repository, sleepSegmentEvents) } else if (SleepClassifyEvent.hasEvents(intent)) { val sleepClassifyEvents: List<SleepClassifyEvent> = SleepClassifyEvent.extractEvents(intent) Log.d(TAG, "SleepClassifyEvent List: $sleepClassifyEvents") addSleepClassifyEventsToDatabase(repository, sleepClassifyEvents) } } private fun addSleepSegmentEventsToDatabase( repository: SleepRepository, sleepSegmentEvents: List<SleepSegmentEvent> ) { if (sleepSegmentEvents.isNotEmpty()) { scope.launch { val convertedToEntityVersion: List<SleepSegmentEventEntity> = sleepSegmentEvents.map { SleepSegmentEventEntity.from(it) } repository.insertSleepSegments(convertedToEntityVersion) } } } private fun addSleepClassifyEventsToDatabase( repository: SleepRepository, sleepClassifyEvents: List<SleepClassifyEvent> ) { if (sleepClassifyEvents.isNotEmpty()) { scope.launch { val convertedToEntityVersion: List<SleepClassifyEventEntity> = sleepClassifyEvents.map { SleepClassifyEventEntity.from(it) } repository.insertSleepClassifyEvents(convertedToEntityVersion) } } } companion object { const val TAG = "SleepReceiver" fun createSleepReceiverPendingIntent(context: Context): PendingIntent { val sleepIntent = Intent(context, SleepReceiver::class.java) return PendingIntent.getBroadcast( context, 0, sleepIntent, PendingIntent.FLAG_CANCEL_CURRENT ) } } }
apache-2.0
13e927e35447a28395b92482bb759f62
37.673267
100
0.687916
5.257066
false
false
false
false
Pagejects/pagejects-core
src/main/kotlin/net/pagejects/core/forms/FormFieldsExt.kt
1
1942
package net.pagejects.core.forms import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import net.pagejects.core.annotation.FormField import org.apache.commons.beanutils.PropertyUtils import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty import kotlin.reflect.jvm.javaField import kotlin.reflect.memberProperties private val cache = CacheBuilder.from(System.getProperty("pagejects.cache", "maximumSize=200,expireAfterWrite=1h")). build(CacheLoader.from<KClass<*>, Sequence<FormFieldProperty>> { if (it == null) { throw KotlinNullPointerException() } val propertyDescriptors = PropertyUtils.getPropertyDescriptors(it.java).associateBy { it.name } it.memberProperties.asSequence().map { it to propertyDescriptors[it.name] }.filter { it.second != null }.map { it.first to it.second!! }.map { var list = it.second.readMethod.annotations list += (it.first.javaField?.annotations ?: emptyArray<Annotation>()) list += it.second.writeMethod.annotations val field = list.asSequence().filter { it is FormField }.map { it as FormField }.firstOrNull() FormFieldProperty( name = it.first.name, type = it.second.propertyType, getter = it.second.readMethod, setter = it.second.writeMethod, __formField = field ) }.filter { it.__formField != null } }) /** * This extension return all mutable properties (see [KMutableProperty]) that annotated by @[FormField]. * * @author Andrey Paslavsky * @since 0.1 */ val KClass<*>.formFields: Sequence<FormFieldProperty> get() = cache[this]
apache-2.0
cb1e5e81312ec249c86a5ac34e8f0d4e
38.653061
116
0.604531
5.005155
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/copy/CopyKotlinDeclarationsHandler.kt
3
20245
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.copy import com.intellij.ide.util.EditorHelper import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.* import com.intellij.psi.* import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler import com.intellij.refactoring.copy.CopyHandlerDelegateBase import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.core.util.toPsiDirectory import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.createKotlinFile import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.sourceRoot import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.utils.ifEmpty class CopyKotlinDeclarationsHandler : CopyHandlerDelegateBase() { companion object { private val commandName get() = RefactoringBundle.message("copy.handler.copy.files.directories") @set:TestOnly var Project.newName: String? by UserDataProperty(Key.create("NEW_NAME")) private fun PsiElement.getCopyableElement() = parentsWithSelf.firstOrNull { it is KtFile || (it is KtNamedDeclaration && it.parent is KtFile) } as? KtElement private fun PsiElement.getDeclarationsToCopy(): List<KtElement> = when (val declarationOrFile = getCopyableElement()) { is KtFile -> declarationOrFile.declarations.filterIsInstance<KtNamedDeclaration>().ifEmpty { listOf(declarationOrFile) } is KtNamedDeclaration -> listOf(declarationOrFile) else -> emptyList() } } private val copyFilesHandler by lazy { CopyFilesOrDirectoriesHandler() } private fun getSourceFiles(elements: Array<out PsiElement>): Array<PsiFileSystemItem>? { return elements .map { it.containingFile ?: it as? PsiFileSystemItem ?: return null } .toTypedArray() } private fun canCopyFiles(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean { val sourceFiles = getSourceFiles(elements) ?: return false if (!sourceFiles.any { it is KtFile }) return false return copyFilesHandler.canCopy(sourceFiles, fromUpdate) } private fun canCopyDeclarations(elements: Array<out PsiElement>): Boolean { val containingFile = elements .flatMap { it.getDeclarationsToCopy().ifEmpty { return false } } .distinctBy { it.containingFile } .singleOrNull() ?.containingFile ?: return false return containingFile.sourceRoot != null } override fun canCopy(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean { return canCopyDeclarations(elements) || canCopyFiles(elements, fromUpdate) } enum class ExistingFilePolicy { APPEND, OVERWRITE, SKIP } private fun getOrCreateTargetFile( originalFile: KtFile, targetDirectory: PsiDirectory, targetFileName: String ): KtFile? { val existingFile = targetDirectory.findFile(targetFileName) if (existingFile == originalFile) return null if (existingFile != null) when (getFilePolicy(existingFile, targetFileName, targetDirectory)) { ExistingFilePolicy.APPEND -> { } ExistingFilePolicy.OVERWRITE -> runWriteAction { existingFile.delete() } ExistingFilePolicy.SKIP -> return null } return runWriteAction { if (existingFile != null && existingFile.isValid) { existingFile as KtFile } else { createKotlinFile(targetFileName, targetDirectory) } } } private fun getFilePolicy( existingFile: PsiFile?, targetFileName: String, targetDirectory: PsiDirectory ): ExistingFilePolicy { val message = KotlinBundle.message( "text.file.0.already.exists.in.1", targetFileName, targetDirectory.virtualFile.path ) return if (existingFile !is KtFile) { if (isUnitTestMode()) return ExistingFilePolicy.OVERWRITE val answer = Messages.showOkCancelDialog( message, commandName, KotlinBundle.message("action.text.overwrite"), KotlinBundle.message("action.text.cancel"), Messages.getQuestionIcon() ) if (answer == Messages.OK) ExistingFilePolicy.OVERWRITE else ExistingFilePolicy.SKIP } else { if (isUnitTestMode()) return ExistingFilePolicy.APPEND val answer = Messages.showYesNoCancelDialog( message, commandName, KotlinBundle.message("action.text.append"), KotlinBundle.message("action.text.overwrite"), KotlinBundle.message("action.text.cancel"), Messages.getQuestionIcon() ) when (answer) { Messages.YES -> ExistingFilePolicy.APPEND Messages.NO -> ExistingFilePolicy.OVERWRITE else -> ExistingFilePolicy.SKIP } } } private data class TargetData( val openInEditor: Boolean, val newName: String, val targetDirWrapper: AutocreatingPsiDirectoryWrapper, val targetSourceRoot: VirtualFile? ) private data class SourceData( val project: Project, val singleElementToCopy: KtElement?, val elementsToCopy: List<KtElement>, val originalFile: KtFile, val initialTargetDirectory: PsiDirectory ) private fun getTargetDataForUnitTest(sourceData: SourceData): TargetData? { with(sourceData) { val targetSourceRoot: VirtualFile = initialTargetDirectory.sourceRoot ?: return null val newName: String = project.newName ?: singleElementToCopy?.name ?: originalFile.name if (singleElementToCopy != null && newName.isEmpty()) return null return TargetData( openInEditor = false, newName = newName, targetDirWrapper = initialTargetDirectory.toDirectoryWrapper(), targetSourceRoot = targetSourceRoot ) } } private fun getTargetDataForUX(sourceData: SourceData): TargetData? { val openInEditor: Boolean val newName: String? val targetDirWrapper: AutocreatingPsiDirectoryWrapper? val targetSourceRoot: VirtualFile? val singleNamedSourceElement = sourceData.singleElementToCopy as? KtNamedDeclaration if (singleNamedSourceElement !== null) { val dialog = CopyKotlinDeclarationDialog(singleNamedSourceElement, sourceData.initialTargetDirectory, sourceData.project) dialog.title = commandName if (!dialog.showAndGet()) return null openInEditor = dialog.openInEditor newName = dialog.newName targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper() targetSourceRoot = dialog.targetSourceRoot } else { val dialog = CopyFilesOrDirectoriesDialog( arrayOf(sourceData.originalFile), sourceData.initialTargetDirectory, sourceData.project, /*doClone = */false ) if (!dialog.showAndGet()) return null openInEditor = dialog.openInEditor() newName = dialog.newName targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper() targetSourceRoot = dialog.targetDirectory?.sourceRoot } targetDirWrapper ?: return null newName ?: return null if (sourceData.singleElementToCopy != null && newName.isEmpty()) return null return TargetData( openInEditor = openInEditor, newName = newName, targetDirWrapper = targetDirWrapper, targetSourceRoot = targetSourceRoot ) } private fun collectInternalUsages(sourceData: SourceData, targetData: TargetData) = runReadAction { val targetPackageName = targetData.targetDirWrapper.getPackageName() val changeInfo = ContainerChangeInfo( ContainerInfo.Package(sourceData.originalFile.packageFqName), ContainerInfo.Package(FqName(targetPackageName)) ) sourceData.elementsToCopy.flatMapTo(LinkedHashSet()) { elementToCopy -> elementToCopy.getInternalReferencesToUpdateOnPackageNameChange(changeInfo).filter { val referencedElement = (it as? MoveRenameUsageInfo)?.referencedElement referencedElement == null || !elementToCopy.isAncestor(referencedElement) } } } private fun trackedCopyFiles(sourceFiles: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?): Set<VirtualFile> { if (!copyFilesHandler.canCopy(sourceFiles)) return emptySet() val mapper = object : VirtualFileListener { val filesCopied = mutableSetOf<VirtualFile>() override fun fileCopied(event: VirtualFileCopyEvent) { filesCopied.add(event.file) } override fun fileCreated(event: VirtualFileEvent) { filesCopied.add(event.file) } } with(VirtualFileManager.getInstance()) { try { addVirtualFileListener(mapper) copyFilesHandler.doCopy(sourceFiles, initialTargetDirectory) } finally { removeVirtualFileListener(mapper) } } return mapper.filesCopied } private fun doCopyFiles(filesToCopy: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?) { if (filesToCopy.isEmpty()) return val project = filesToCopy[0].project val psiManager = PsiManager.getInstance(project) project.executeCommand(commandName) { val copiedFiles = trackedCopyFiles(filesToCopy, initialTargetDirectory) copiedFiles.forEach { copiedFile -> val targetKtFile = psiManager.findFile(copiedFile) as? KtFile if (targetKtFile !== null) { runWriteAction { if (!targetKtFile.packageMatchesDirectoryOrImplicit()) { targetKtFile.containingDirectory?.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let { targetDirectoryFqName -> targetKtFile.packageFqName = targetDirectoryFqName } } performDelayedRefactoringRequests(project) } } } } } override fun doCopy(elements: Array<out PsiElement>, defaultTargetDirectory: PsiDirectory?) { if (elements.isEmpty()) return if (!canCopyDeclarations(elements)) { getSourceFiles(elements)?.let { return doCopyFiles(it, defaultTargetDirectory) } } val elementsToCopy = elements.mapNotNull { it.getCopyableElement() } if (elementsToCopy.isEmpty()) return val singleElementToCopy = elementsToCopy.singleOrNull() val originalFile = elementsToCopy.first().containingFile as KtFile val initialTargetDirectory = defaultTargetDirectory ?: originalFile.containingDirectory ?: return val project = initialTargetDirectory.project val sourceData = SourceData( project = project, singleElementToCopy = singleElementToCopy, elementsToCopy = elementsToCopy, originalFile = originalFile, initialTargetDirectory = initialTargetDirectory ) val targetData = if (isUnitTestMode()) getTargetDataForUnitTest(sourceData) else getTargetDataForUX(sourceData) targetData ?: return val internalUsages = collectInternalUsages(sourceData, targetData) markInternalUsages(internalUsages) val conflicts = collectConflicts(sourceData, targetData, internalUsages) project.checkConflictsInteractively(conflicts) { try { project.executeCommand(commandName) { doRefactor(sourceData, targetData) } } finally { cleanUpInternalUsages(internalUsages) } } } private data class RefactoringResult( val targetFile: PsiFile, val copiedDeclaration: KtNamedDeclaration?, val restoredInternalUsages: List<UsageInfo>? = null ) private fun getTargetFileName(sourceData: SourceData, targetData: TargetData) = if (targetData.newName.contains(".")) targetData.newName else targetData.newName + "." + sourceData.originalFile.virtualFile.extension private fun doRefactor(sourceData: SourceData, targetData: TargetData) { var refactoringResult: RefactoringResult? = null try { val targetDirectory = runWriteAction { targetData.targetDirWrapper.getOrCreateDirectory(sourceData.initialTargetDirectory) } val targetFileName = getTargetFileName(sourceData, targetData) val isSingleDeclarationInFile = sourceData.singleElementToCopy is KtNamedDeclaration && sourceData.originalFile.declarations.singleOrNull() == sourceData.singleElementToCopy val fileToCopy = when { sourceData.singleElementToCopy is KtFile -> sourceData.singleElementToCopy isSingleDeclarationInFile -> sourceData.originalFile else -> null } refactoringResult = if (fileToCopy !== null) { doRefactoringOnFile(fileToCopy, sourceData, targetDirectory, targetFileName, isSingleDeclarationInFile) } else { val targetFile = getOrCreateTargetFile(sourceData.originalFile, targetDirectory, targetFileName) ?: throw IncorrectOperationException("Could not create target file.") doRefactoringOnElement(sourceData, targetFile) } refactoringResult.copiedDeclaration?.let<KtNamedDeclaration, Unit> { newDeclaration -> if (targetData.newName == newDeclaration.name) return@let val selfReferences = ReferencesSearch.search(newDeclaration, LocalSearchScope(newDeclaration)).findAll() runWriteAction { selfReferences.forEach { it.handleElementRename(targetData.newName) } newDeclaration.setName(targetData.newName) } } if (targetData.openInEditor) { EditorHelper.openInEditor(refactoringResult.targetFile) } } catch (e: IncorrectOperationException) { Messages.showMessageDialog(sourceData.project, e.message, RefactoringBundle.message("error.title"), Messages.getErrorIcon()) } finally { refactoringResult?.restoredInternalUsages?.let { cleanUpInternalUsages(it) } } } private fun doRefactoringOnFile( fileToCopy: KtFile, sourceData: SourceData, targetDirectory: PsiDirectory, targetFileName: String, isSingleDeclarationInFile: Boolean ): RefactoringResult { val targetFile = runWriteAction { // implicit package prefix may change after copy val targetDirectoryFqName = targetDirectory.getFqNameWithImplicitPrefix() val copiedFile = targetDirectory.copyFileFrom(targetFileName, fileToCopy) if (copiedFile is KtFile && fileToCopy.packageMatchesDirectoryOrImplicit()) { targetDirectoryFqName?.quoteIfNeeded()?.let { copiedFile.packageFqName = it } } performDelayedRefactoringRequests(sourceData.project) copiedFile } val copiedDeclaration = if (isSingleDeclarationInFile && targetFile is KtFile) { targetFile.declarations.singleOrNull() as? KtNamedDeclaration } else null return RefactoringResult(targetFile, copiedDeclaration) } private fun doRefactoringOnElement( sourceData: SourceData, targetFile: KtFile ): RefactoringResult { val restoredInternalUsages = ArrayList<UsageInfo>() val oldToNewElementsMapping = HashMap<PsiElement, PsiElement>() runWriteAction { val newElements = sourceData.elementsToCopy.map { targetFile.add(it.copy()) as KtNamedDeclaration } sourceData.elementsToCopy.zip(newElements).toMap(oldToNewElementsMapping) oldToNewElementsMapping[sourceData.originalFile] = targetFile for (newElement in oldToNewElementsMapping.values) { restoredInternalUsages += restoreInternalUsages(newElement as KtElement, oldToNewElementsMapping, forcedRestore = true) postProcessMoveUsages(restoredInternalUsages, oldToNewElementsMapping) } performDelayedRefactoringRequests(sourceData.project) } val copiedDeclaration = oldToNewElementsMapping.values.filterIsInstance<KtNamedDeclaration>().singleOrNull() return RefactoringResult(targetFile, copiedDeclaration, restoredInternalUsages) } private fun collectConflicts( sourceData: SourceData, targetData: TargetData, internalUsages: HashSet<UsageInfo> ): MultiMap<PsiElement, String> { if (isUnitTestMode() && BaseRefactoringProcessor.ConflictsInTestsException.isTestIgnore()) return MultiMap.empty() val targetSourceRootPsi = targetData.targetSourceRoot?.toPsiDirectory(sourceData.project) ?: return MultiMap.empty() if (sourceData.project != sourceData.originalFile.project) return MultiMap.empty() val conflictChecker = MoveConflictChecker( sourceData.project, sourceData.elementsToCopy, KotlinDirectoryMoveTarget(FqName.ROOT, targetSourceRootPsi.virtualFile), sourceData.originalFile ) return MultiMap<PsiElement, String>().also { conflictChecker.checkModuleConflictsInDeclarations(internalUsages, it) conflictChecker.checkVisibilityInDeclarations(it) } } override fun doClone(element: PsiElement) { } }
apache-2.0
9f571e418bf3c88567098d0a0fa71372
40.485656
140
0.672117
6.034277
false
false
false
false
Werb/MoreType
library/src/main/kotlin/com/werb/library/MoreViewHolder.kt
1
2146
package com.werb.library import android.view.View import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.werb.library.action.MoreClickListener import kotlinx.android.extensions.LayoutContainer /** * [MoreViewHolder] Base ViewHolder implement Action fun * Created by wanbo on 2017/7/2. */ abstract class MoreViewHolder<T : Any>(val values: MutableMap<String, Any> = mutableMapOf(), override val containerView: View) : ViewHolder(containerView), LayoutContainer { val injectValueMap = mutableMapOf<String, Any>() internal var clickListener: MoreClickListener? = null fun getItemView(): View = itemView fun addOnTouchListener(viewId: Int) { clickListener?.let { val _this = it itemView.findViewById<View>(viewId).setOnTouchListener { v, event -> _this.onItemTouch(v, event, layoutPosition) } } } fun addOnTouchListener(view: View) { clickListener?.let { val _this = it view.setOnTouchListener { v, event -> _this.onItemTouch(v, event, layoutPosition) } } } fun addOnClickListener(viewId: Int) { itemView.findViewById<View>(viewId).setOnClickListener { clickListener?.onItemClick(it, layoutPosition) } } fun addOnClickListener(view: View) { view.setOnClickListener { clickListener?.onItemClick(it, layoutPosition) } } fun addOnLongClickListener(viewId: Int) { clickListener?.let { it -> val _this = it itemView.findViewById<View>(viewId).setOnLongClickListener { _this.onItemLongClick(it, layoutPosition) } } } fun addOnLongClickListener(view: View) { clickListener?.let { it -> val _this = it view.setOnLongClickListener { _this.onItemLongClick(view, layoutPosition) } } } /** [bindData] bind data with T */ abstract fun bindData(data: T, payloads: List<Any> = arrayListOf()) /** [unBindData] unbind and release resources*/ open fun unBindData() {} }
apache-2.0
2423d4dec28688ed26b2b5643c102842
29.239437
173
0.634669
4.844244
false
false
false
false
google/intellij-community
plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt
1
8370
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.fir.analysis.providers.trackers import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest import org.jetbrains.kotlin.idea.util.sourceRoots import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory import org.junit.Assert import java.io.File class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() { override fun getTestDataDirectory(): File = error("Should not be called") fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText("main.kt", "fun main() = 10") ) } val moduleB = createModuleInTmpDir("b") val moduleC = createModuleInTmpDir("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10") Assert.assertTrue( "Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatDeleteSymbolInBodyDoesNotLeadToOutOfBlockChange() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText( "main.kt", "fun main() {\n" + "//abc\n" + "}" ) ) } val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) val singleFunction = ktFile.declarations.single() as KtNamedFunction val comment = PsiTreeUtil.findChildOfType(singleFunction.bodyBlockExpression!!, PsiComment::class.java)!! editor.caretModel.moveToOffset(comment.textRange.endOffset) backspace() PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments() Assert.assertFalse( "Out of block modification count for module A with out of block should not change after deleting, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertEquals("fun main() {\n" + "//ab\n" + "}", ktFile.text) } fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() { val moduleA = createModuleInTmpDir("a") val moduleB = createModuleInTmpDir("b") val moduleC = createModuleInTmpDir("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) runWriteAction { moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt") } Assert.assertTrue( "Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatNonPhysicalFileChangeNotCausingBOOM() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText("main.kt", "fun main() {}") ) } val moduleB = createModuleInTmpDir("b") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val projectWithModificationTracker = ProjectWithModificationTracker(project) runWriteAction { val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c") nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}")) } Assert.assertFalse( "Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}", projectWithModificationTracker.changed() ) } private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) { val file = "${sourceRoots.first().url}/$fileName" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) val singleFunction = ktFile.declarations.single() as KtNamedFunction editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset) type("hello") PsiDocumentManager.getInstance(project).commitAllDocuments() Assert.assertEquals(textAfterTyping, ktFile.text) } abstract class WithModificationTracker(private val modificationTracker: ModificationTracker) { private val initialModificationCount = modificationTracker.modificationCount val modificationCount: Long get() = modificationTracker.modificationCount fun changed(): Boolean = modificationTracker.modificationCount != initialModificationCount } private class ModuleWithModificationTracker(module: Module) : WithModificationTracker( module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project) ) private class ProjectWithModificationTracker(project: Project) : WithModificationTracker( project.createProjectWideOutOfBlockModificationTracker() ) }
apache-2.0
b518bb0d82f510b6f57edfdca2cc3991
45.505556
182
0.708722
5.944602
false
false
false
false
youdonghai/intellij-community
platform/script-debugger/debugger-ui/src/LineBreakpointManager.kt
1
9460
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.util.SmartList import com.intellij.util.containers.putValue import com.intellij.util.containers.remove import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.breakpoints.XLineBreakpoint import gnu.trove.THashMap import gnu.trove.THashSet import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.all import org.jetbrains.concurrency.nullPromise import org.jetbrains.concurrency.resolvedPromise import java.util.concurrent.atomic.AtomicBoolean private val IDE_TO_VM_BREAKPOINTS_KEY = Key.create<THashMap<XLineBreakpoint<*>, MutableList<Breakpoint>>>("ideToVmBreakpoints") abstract class LineBreakpointManager(internal val debugProcess: DebugProcessImpl<*>) { protected val vmToIdeBreakpoints = THashMap<Breakpoint, MutableList<XLineBreakpoint<*>>>() private val runToLocationBreakpoints = THashSet<Breakpoint>() private val lock = Object() open fun isAnyFirstLineBreakpoint(breakpoint: Breakpoint) = false private val breakpointResolvedListenerAdded = AtomicBoolean() fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>) { val target = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.get(breakpoint) } if (target == null) { setBreakpoint(vm, breakpoint, debugProcess.getLocationsForBreakpoint(vm, breakpoint)) } else { val breakpointManager = vm.breakpointManager for (vmBreakpoint in target) { if (!vmBreakpoint.enabled) { vmBreakpoint.enabled = true breakpointManager.flush(vmBreakpoint) .rejected { debugProcess.session.updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, it.message) } } } } } fun removeBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, temporary: Boolean): Promise<*> { val disable = temporary && debugProcess.mainVm!!.breakpointManager.getMuteMode() !== BreakpointManager.MUTE_MODE.NONE beforeBreakpointRemoved(breakpoint, disable) return doRemoveBreakpoint(vm, breakpoint, disable) } protected open fun beforeBreakpointRemoved(breakpoint: XLineBreakpoint<*>, disable: Boolean) { } fun doRemoveBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, disable: Boolean = false): Promise<*> { var vmBreakpoints: Collection<Breakpoint> = emptySet() synchronized (lock) { if (disable) { val list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.get(breakpoint) ?: return nullPromise() val iterator = list.iterator() vmBreakpoints = list while (iterator.hasNext()) { val vmBreakpoint = iterator.next() if ((vmToIdeBreakpoints.get(vmBreakpoint)?.size ?: -1) > 1) { // we must not disable vm breakpoint - it is used for another ide breakpoints iterator.remove() } } } else { vmBreakpoints = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.remove(breakpoint) ?: return nullPromise() for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.remove(vmBreakpoint, breakpoint) if (vmToIdeBreakpoints.containsKey(vmBreakpoint)) { // we must not remove vm breakpoint - it is used for another ide breakpoints return nullPromise() } } } } if (vmBreakpoints.isEmpty()) { return nullPromise() } val breakpointManager = vm.breakpointManager val promises = SmartList<Promise<*>>() if (disable) { for (vmBreakpoint in vmBreakpoints) { vmBreakpoint.enabled = false promises.add(breakpointManager.flush(vmBreakpoint)) } } else { for (vmBreakpoint in vmBreakpoints) { promises.add(breakpointManager.remove(vmBreakpoint)) } } return all(promises) } fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, locations: List<Location>, promiseRef: Ref<Promise<out Breakpoint>>? = null) { if (locations.isEmpty()) { return } val vmBreakpoints = SmartList<Breakpoint>() for (location in locations) { doSetBreakpoint(vm, breakpoint, location, false, promiseRef)?.let { vmBreakpoints.add(it) } } synchronized (lock) { var list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm) if (list == null) { list = vm.putUserDataIfAbsent(IDE_TO_VM_BREAKPOINTS_KEY, THashMap()) } list.put(breakpoint, vmBreakpoints) for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.putValue(vmBreakpoint, breakpoint) } } } protected fun doSetBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>?, location: Location, isTemporary: Boolean, promiseRef: Ref<Promise<out Breakpoint>>? = null): Breakpoint? { if (breakpointResolvedListenerAdded.compareAndSet(false, true)) { vm.breakpointManager.addBreakpointListener(object : BreakpointListener { override fun resolved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints[breakpoint] }?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_verified_breakpoint, null) } } } override fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?) { if (isAnyFirstLineBreakpoint(breakpoint)) { return } if (synchronized (lock) { runToLocationBreakpoints.remove(breakpoint) }) { debugProcess.session.reportError("Cannot run to cursor: $errorMessage") return } synchronized (lock) { vmToIdeBreakpoints.get(breakpoint) } ?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage) } } } override fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints.remove(breakpoint)?.let { for (ideBreakpoint in it) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.remove(ideBreakpoint, breakpoint) } it } } ?.let { for (ideBreakpoint in it) { setBreakpoint(vm, ideBreakpoint, debugProcess.getLocationsForBreakpoint(vm, ideBreakpoint)) } } } }) } val breakpointManager = vm.breakpointManager val target = createTarget(breakpoint, breakpointManager, location, isTemporary) checkDuplicates(target, location, breakpointManager)?.let { promiseRef?.set(resolvedPromise(it)) return it } return breakpointManager.setBreakpoint(target, location.line, location.column, location.url, breakpoint?.conditionExpression?.expression, promiseRef = promiseRef) } protected abstract fun createTarget(breakpoint: XLineBreakpoint<*>?, breakpointManager: BreakpointManager, location: Location, isTemporary: Boolean): BreakpointTarget protected open fun checkDuplicates(newTarget: BreakpointTarget, location: Location, breakpointManager: BreakpointManager): Breakpoint? = null fun runToLocation(position: XSourcePosition, vm: Vm) { val addedBreakpoints = doRunToLocation(position) if (addedBreakpoints.isEmpty()) { return } synchronized (lock) { runToLocationBreakpoints.addAll(addedBreakpoints) } debugProcess.resume(vm) } protected abstract fun doRunToLocation(position: XSourcePosition): List<Breakpoint> fun isRunToCursorBreakpoint(breakpoint: Breakpoint) = synchronized (runToLocationBreakpoints) { runToLocationBreakpoints.contains(breakpoint) } fun updateAllBreakpoints(vm: Vm) { val array = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.keys?.toTypedArray() } ?: return for (breakpoint in array) { removeBreakpoint(vm, breakpoint, false) setBreakpoint(vm, breakpoint) } } fun removeAllBreakpoints(vm: Vm): Promise<*> { synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.clear() vmToIdeBreakpoints.clear() runToLocationBreakpoints.clear() } return vm.breakpointManager.removeAll() } fun clearRunToLocationBreakpoints(vm: Vm) { val breakpoints = synchronized (lock) { if (runToLocationBreakpoints.isEmpty) { return@clearRunToLocationBreakpoints } val breakpoints = runToLocationBreakpoints.toArray<Breakpoint>(arrayOfNulls<Breakpoint>(runToLocationBreakpoints.size)) runToLocationBreakpoints.clear() breakpoints } val breakpointManager = vm.breakpointManager for (breakpoint in breakpoints) { breakpointManager.remove(breakpoint) } } }
apache-2.0
5ba0007b061f05f0f0af90b9696ccc50
37.149194
179
0.691543
4.91684
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/kotlin.searching/src/org/jetbrains/kotlin/idea/searching/usages/KotlinK2UsageTypeProvider.kt
1
3766
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.searching.usages import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.idea.base.searching.usages.KotlinUsageTypeProvider import org.jetbrains.kotlin.idea.base.searching.usages.UsageTypeEnum import org.jetbrains.kotlin.idea.base.searching.usages.UsageTypeEnum.* import org.jetbrains.kotlin.idea.references.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.util.OperatorNameConventions internal class KotlinK2UsageTypeProvider : KotlinUsageTypeProvider() { override fun getUsageTypeEnumByReference(refExpr: KtReferenceExpression): UsageTypeEnum? { val reference = refExpr.mainReference check(reference is KtSimpleReference<*>) { "Reference should be KtSimpleReference but not ${reference::class}" } fun KtAnalysisSession.getFunctionUsageType(functionSymbol: KtFunctionLikeSymbol): UsageTypeEnum? { when (reference) { is KtArrayAccessReference -> return when ((functionSymbol as KtFunctionSymbol).name) { OperatorNameConventions.GET -> IMPLICIT_GET OperatorNameConventions.SET -> IMPLICIT_SET else -> error("Expected get or set operator but resolved to unexpected symbol {functionSymbol.render()}") } is KtInvokeFunctionReference -> return IMPLICIT_INVOKE is KtConstructorDelegationReference -> return null } return when { refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry> { typeReference } != null -> SUPER_TYPE functionSymbol is KtConstructorSymbol && refExpr.getParentOfTypeAndBranch<KtAnnotationEntry> { typeReference } != null -> ANNOTATION with(refExpr.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }) { this?.calleeExpression is KtSimpleNameExpression } -> if (functionSymbol is KtConstructorSymbol) CLASS_NEW_OPERATOR else FUNCTION_CALL refExpr.getParentOfTypeAndBranch<KtBinaryExpression> { operationReference } != null || refExpr.getParentOfTypeAndBranch<KtUnaryExpression> { operationReference } != null || refExpr.getParentOfTypeAndBranch<KtWhenConditionInRange> { operationReference } != null -> FUNCTION_CALL else -> null } } return analyzeWithReadAction(refExpr) { when (val targetElement = reference.resolveToSymbol()) { is KtClassifierSymbol -> when (targetElement) { is KtClassOrObjectSymbol -> when (targetElement.classKind) { KtClassKind.COMPANION_OBJECT -> COMPANION_OBJECT_ACCESS KtClassKind.OBJECT -> getVariableUsageType(refExpr) else -> getClassUsageType(refExpr) } else -> getClassUsageType(refExpr) } is KtPackageSymbol -> //TODO FIR Implement package symbol type if (targetElement is PsiPackage) getPackageUsageType(refExpr) else getClassUsageType(refExpr) is KtVariableLikeSymbol -> getVariableUsageType(refExpr) is KtFunctionLikeSymbol -> getFunctionUsageType(targetElement) else -> null } } } }
apache-2.0
dedbe3302d7402c1864778eba427eb56
53.57971
293
0.670207
6.084006
false
false
false
false
vhromada/Catalog
core/src/test/kotlin/com/github/vhromada/catalog/utils/MusicUtils.kt
1
13586
package com.github.vhromada.catalog.utils import com.github.vhromada.catalog.common.entity.Time import com.github.vhromada.catalog.domain.filter.MusicFilter import com.github.vhromada.catalog.domain.io.MusicStatistics import com.github.vhromada.catalog.entity.ChangeMusicRequest import com.github.vhromada.catalog.entity.Music import com.github.vhromada.catalog.filter.NameFilter import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.SoftAssertions.assertSoftly import javax.persistence.EntityManager /** * Updates music fields. * * @return updated music */ fun com.github.vhromada.catalog.domain.Music.updated(): com.github.vhromada.catalog.domain.Music { name = "Name" normalizedName = "Name" wikiEn = "enWiki" wikiCz = "czWiki" mediaCount = 1 note = "Note" return this } /** * Updates music fields. * * @return updated music */ fun Music.updated(): Music { return copy( name = "Name", wikiEn = "enWiki", wikiCz = "czWiki", mediaCount = 1, note = "Note" ) } /** * A class represents utility class for music. * * @author Vladimir Hromada */ object MusicUtils { /** * Count of music */ const val MUSIC_COUNT = 3 /** * Multiplier for media count */ private const val MEDIA_COUNT_MULTIPLIER = 10 /** * Returns list of music. * * @return list of music */ fun getDomainMusicList(): List<com.github.vhromada.catalog.domain.Music> { val musicList = mutableListOf<com.github.vhromada.catalog.domain.Music>() for (i in 1..MUSIC_COUNT) { musicList.add(getDomainMusic(index = i)) } return musicList } /** * Returns list of music. * * @return list of music */ fun getMusicList(): List<Music> { val musicList = mutableListOf<Music>() for (i in 1..MUSIC_COUNT) { musicList.add(getMusic(index = i)) } return musicList } /** * Returns music for index. * * @param index index * @return music for index */ fun getDomainMusic(index: Int): com.github.vhromada.catalog.domain.Music { val name = "Music $index name" val music = com.github.vhromada.catalog.domain.Music( id = index, uuid = getUuid(index = index), name = name, normalizedName = name, wikiEn = if (index != 1) "Music $index English Wikipedia" else null, wikiCz = if (index != 1) "Music $index Czech Wikipedia" else null, mediaCount = index * MEDIA_COUNT_MULTIPLIER, note = if (index == 2) "Music $index note" else null, songs = SongUtils.getDomainSongs(music = index) ).fillAudit(audit = AuditUtils.getAudit()) music.songs.forEach { it.music = music } return music } /** * Returns UUID for index. * * @param index index * @return UUID for index */ private fun getUuid(index: Int): String { return when (index) { 1 -> "9c9f53ce-5576-4d18-8470-5863dbb49c46" 2 -> "21d837eb-258e-4170-b27d-b81c880e9260" 3 -> "66fc3034-223a-486e-8c03-c3f71a733ca9" else -> throw IllegalArgumentException("Bad index") } } /** * Returns music. * * @param entityManager entity manager * @param id music ID * @return music */ fun getDomainMusic(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Music? { return entityManager.find(com.github.vhromada.catalog.domain.Music::class.java, id) } /** * Returns music for index. * * @param index index * @return music for index */ fun getMusic(index: Int): Music { return Music( uuid = getUuid(index = index), name = "Music $index name", wikiEn = if (index != 1) "Music $index English Wikipedia" else null, wikiCz = if (index != 1) "Music $index Czech Wikipedia" else null, mediaCount = index * MEDIA_COUNT_MULTIPLIER, note = if (index == 2) "Music $index note" else null, songsCount = SongUtils.SONGS_PER_MUSIC_COUNT, length = SongUtils.getSongs(music = index).sumOf { it.length } ) } /** * Returns statistics for music. * * @return statistics for music */ fun getDomainStatistics(): MusicStatistics { return MusicStatistics(count = MUSIC_COUNT.toLong(), mediaCount = 60L) } /** * Returns statistics for music. * * @return statistics for music */ fun getStatistics(): com.github.vhromada.catalog.entity.MusicStatistics { return com.github.vhromada.catalog.entity.MusicStatistics(count = MUSIC_COUNT, songsCount = SongUtils.SONGS_COUNT, mediaCount = 60, length = Time(length = 666).toString()) } /** * Returns count of music. * * @param entityManager entity manager * @return count of music */ fun getMusicCount(entityManager: EntityManager): Int { return entityManager.createQuery("SELECT COUNT(m.id) FROM Music m", java.lang.Long::class.java).singleResult.toInt() } /** * Returns music. * * @param id ID * @return music */ fun newDomainMusic(id: Int?): com.github.vhromada.catalog.domain.Music { return com.github.vhromada.catalog.domain.Music( id = id, uuid = TestConstants.UUID, name = "", normalizedName = "", wikiEn = null, wikiCz = null, mediaCount = 0, note = null, songs = mutableListOf() ).updated() } /** * Returns music. * * @return music */ fun newMusic(): Music { return Music( uuid = TestConstants.UUID, name = "", wikiEn = null, wikiCz = null, mediaCount = 0, note = null, songsCount = 0, length = 0 ).updated() } /** * Returns request for changing music. * * @return request for changing music */ fun newRequest(): ChangeMusicRequest { return ChangeMusicRequest( name = "Name", wikiEn = "enWiki", wikiCz = "czWiki", mediaCount = 1, note = "Note" ) } /** * Asserts list of music deep equals. * * @param expected expected list of music * @param actual actual list of music */ fun assertDomainMusicDeepEquals(expected: List<com.github.vhromada.catalog.domain.Music>, actual: List<com.github.vhromada.catalog.domain.Music>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertMusicDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts music deep equals. * * @param expected expected music * @param actual actual music * @param checkSongs true if songs should be checked */ fun assertMusicDeepEquals(expected: com.github.vhromada.catalog.domain.Music?, actual: com.github.vhromada.catalog.domain.Music?, checkSongs: Boolean = true) { if (expected == null) { assertThat(actual).isNull() } else { assertThat(actual).isNotNull assertSoftly { it.assertThat(actual!!.id).isEqualTo(expected.id) it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.normalizedName).isEqualTo(expected.normalizedName) it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn) it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) it.assertThat(actual.note).isEqualTo(expected.note) } AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!) if (checkSongs) { SongUtils.assertDomainSongsDeepEquals(expected = expected.songs, actual = actual.songs) } } } /** * Asserts list of music deep equals. * * @param expected expected list of music * @param actual actual list of music */ fun assertMusicDeepEquals(expected: List<com.github.vhromada.catalog.domain.Music>, actual: List<Music>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertMusicDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts music deep equals. * * @param expected expected music * @param actual actual music */ fun assertMusicDeepEquals(expected: com.github.vhromada.catalog.domain.Music, actual: Music) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn) it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.songsCount).isEqualTo(expected.songs.size) it.assertThat(actual.length).isEqualTo(expected.songs.sumOf { song -> song.length }) } } /** * Asserts list of music deep equals. * * @param expected expected list of music * @param actual actual list of music */ fun assertMusicListDeepEquals(expected: List<Music>, actual: List<Music>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertMusicDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts music deep equals. * * @param expected expected music * @param actual actual music */ fun assertMusicDeepEquals(expected: Music, actual: Music) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn) it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.songsCount).isEqualTo(expected.songsCount) it.assertThat(actual.length).isEqualTo(expected.length) } } /** * Asserts request and music deep equals. * * @param expected expected request for changing music * @param actual actual music * @param uuid UUID */ fun assertRequestDeepEquals(expected: ChangeMusicRequest, actual: com.github.vhromada.catalog.domain.Music, uuid: String) { assertSoftly { it.assertThat(actual.id).isNull() it.assertThat(actual.uuid).isEqualTo(uuid) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.normalizedName).isEqualTo(expected.name) it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn) it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.songs).isEmpty() it.assertThat(actual.createdUser).isNull() it.assertThat(actual.createdTime).isNull() it.assertThat(actual.updatedUser).isNull() it.assertThat(actual.updatedTime).isNull() } } /** * Asserts filter deep equals. * * @param expected expected filter * @param actual actual filter */ fun assertFilterDeepEquals(expected: NameFilter, actual: MusicFilter) { assertThat(actual.name).isEqualTo(expected.name) } /** * Asserts statistics for musics deep equals. * * @param expected expected statistics for musics * @param actual actual statistics for musics */ fun assertStatisticsDeepEquals(expected: MusicStatistics, actual: MusicStatistics) { assertSoftly { it.assertThat(actual.count).isEqualTo(expected.count) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) } } /** * Asserts statistics for musics deep equals. * * @param expected expected statistics for musics * @param actual actual statistics for musics */ fun assertStatisticsDeepEquals(expected: com.github.vhromada.catalog.entity.MusicStatistics, actual: com.github.vhromada.catalog.entity.MusicStatistics) { assertSoftly { it.assertThat(actual.count).isEqualTo(expected.count) it.assertThat(actual.songsCount).isEqualTo(expected.songsCount) it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount) it.assertThat(actual.length).isEqualTo(expected.length) } } }
mit
62795cee9f5fd10bed65fc8c6babb045
31.975728
179
0.609525
4.451507
false
false
false
false
JetBrains/intellij-community
platform/feedback/src/com/intellij/feedback/productivityMetric/dialog/ProductivityFeedbackDialog.kt
1
8133
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.feedback.productivityMetric.dialog import com.intellij.feedback.FeedbackRequestData import com.intellij.feedback.common.FEEDBACK_REPORT_ID_KEY import com.intellij.feedback.common.FeedbackRequestType import com.intellij.feedback.common.dialog.COMMON_FEEDBACK_SYSTEM_INFO_VERSION import com.intellij.feedback.common.dialog.CommonFeedbackSystemInfoData import com.intellij.feedback.common.dialog.showFeedbackSystemInfoDialog import com.intellij.feedback.common.feedbackAgreement import com.intellij.feedback.new_ui.CancelFeedbackNotification import com.intellij.feedback.productivityMetric.bundle.ProductivityFeedbackBundle import com.intellij.feedback.submitFeedback import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import kotlinx.serialization.json.* import javax.swing.Action import javax.swing.JComponent import javax.swing.SwingConstants class ProductivityFeedbackDialog( private val project: Project?, private val forTest: Boolean ) : DialogWrapper(project) { /** Increase the additional number when feedback format is changed */ private val FEEDBACK_JSON_VERSION = COMMON_FEEDBACK_SYSTEM_INFO_VERSION private val FEEDBACK_REPORT_ID_VALUE = "productivity_metric_feedback" private val FEEDBACK_PRIVACY_CONSENT_TYPE_VALUE = "productivity_metric_feedback_consent" private val systemInfoData: Lazy<CommonFeedbackSystemInfoData> = lazy { CommonFeedbackSystemInfoData.getCurrentData() } private val digitRegexp: Regex = Regex("\\d") private val applicationName: String = run { val fullAppName: String = ApplicationInfoEx.getInstanceEx().fullApplicationName val range: IntRange? = digitRegexp.find(fullAppName)?.range if (range != null) { fullAppName.substring(0, range.first).trim() } else { fullAppName } } private val propertyGraph = PropertyGraph() private val productivityProperty = propertyGraph.property(0) private val proficiencyProperty = propertyGraph.property(0) private val usingExperience = propertyGraph.property("") private val jsonConverter = Json { prettyPrint = true } init { init() title = ProductivityFeedbackBundle.message("dialog.top.title") isResizable = false } override fun doOKAction() { super.doOKAction() val feedbackData = FeedbackRequestData(FEEDBACK_REPORT_ID_VALUE, createCollectedDataJsonString(), FEEDBACK_PRIVACY_CONSENT_TYPE_VALUE) submitFeedback(project, feedbackData, { }, { }, if (forTest) FeedbackRequestType.TEST_REQUEST else FeedbackRequestType.PRODUCTION_REQUEST) } override fun doCancelAction() { super.doCancelAction() CancelFeedbackNotification().notify(project) } private fun createCollectedDataJsonString(): JsonObject { val collectedData = buildJsonObject { put(FEEDBACK_REPORT_ID_KEY, FEEDBACK_REPORT_ID_VALUE) put("format_version", FEEDBACK_JSON_VERSION) put("productivity_influence", productivityProperty.get()) put("proficiency_level", proficiencyProperty.get()) put("using_experience", usingExperience.get()) put("system_info", jsonConverter.encodeToJsonElement(systemInfoData.value)) } return collectedData } override fun createCenterPanel(): JComponent { val productivitySegmentedButtonPanel = panel { row { label(ProductivityFeedbackBundle.message("dialog.segmentedButton.1.label", applicationName)) .customize(Gaps(top = IntelliJSpacingConfiguration().verticalComponentGap)) .bold() }.bottomGap(BottomGap.SMALL).topGap(TopGap.MEDIUM) row { segmentedButton(List(9) { it + 1 }) { it.toString() } .apply { maxButtonsCount(9) }.customize(Gaps(top = IntelliJSpacingConfiguration().verticalComponentGap)) .whenItemSelected { productivityProperty.set(it) } .align(Align.FILL) } row { label(ProductivityFeedbackBundle.message("dialog.segmentedButton.1.left.label")) .applyToComponent { font = ComponentPanelBuilder.getCommentFont(font) } .widthGroup("Group1") label(ProductivityFeedbackBundle.message("dialog.segmentedButton.1.middle.label")) .applyToComponent { font = ComponentPanelBuilder.getCommentFont(font) } .align(AlignX.CENTER) .resizableColumn() label(ProductivityFeedbackBundle.message("dialog.segmentedButton.1.right.label")) .applyToComponent { font = ComponentPanelBuilder.getCommentFont(font) horizontalAlignment = SwingConstants.RIGHT } .widthGroup("Group1") } } val proficiencySegmentedButtonPanel = panel { row { label(ProductivityFeedbackBundle.message("dialog.segmentedButton.2.label", applicationName)) .customize(Gaps(top = IntelliJSpacingConfiguration().verticalComponentGap)) .bold() }.bottomGap(BottomGap.SMALL).topGap(TopGap.MEDIUM) row { segmentedButton(List(9) { it + 1 }) { it.toString() } .apply { maxButtonsCount(9) }.customize(Gaps(top = IntelliJSpacingConfiguration().verticalComponentGap)) .whenItemSelected { proficiencyProperty.set(it) } .align(Align.FILL) } row { label(ProductivityFeedbackBundle.message("dialog.segmentedButton.2.left.label")) .applyToComponent { font = ComponentPanelBuilder.getCommentFont(font) } .widthGroup("Group2") .resizableColumn() label(ProductivityFeedbackBundle.message("dialog.segmentedButton.2.right.label")) .applyToComponent { font = ComponentPanelBuilder.getCommentFont(font) horizontalAlignment = SwingConstants.RIGHT } .widthGroup("Group2") } } val mainPanel = panel { row { label(ProductivityFeedbackBundle.message("dialog.title")) .applyToComponent { font = JBFont.h1() } } row { cell(productivitySegmentedButtonPanel) .align(Align.FILL) } row { cell(proficiencySegmentedButtonPanel) .align(Align.FILL) } row { label(ProductivityFeedbackBundle.message("dialog.combobox.label", applicationName)) .customize(Gaps(top = IntelliJSpacingConfiguration().verticalComponentGap)) .bold() }.bottomGap(BottomGap.SMALL).topGap(TopGap.MEDIUM) row { comboBox(List(8) { ProductivityFeedbackBundle.message("dialog.combobox.item.${it + 1}") }) .applyToComponent { usingExperience.set(selectedItem?.toString() ?: "null") columns(COLUMNS_MEDIUM) }.whenItemSelectedFromUi { usingExperience.set(it) } }.bottomGap(BottomGap.MEDIUM) row { feedbackAgreement(project) { showFeedbackSystemInfoDialog(project, systemInfoData.value) } }.bottomGap(BottomGap.SMALL) }.also { dialog -> dialog.border = JBEmptyBorder(JBUI.scale(15), JBUI.scale(10), JBUI.scale(0), JBUI.scale(10)) } return mainPanel } override fun createActions(): Array<Action> { return arrayOf(cancelAction, okAction) } override fun getOKAction(): Action { return object : OkAction() { init { putValue(NAME, ProductivityFeedbackBundle.message("dialog.ok.label")) } } } override fun getCancelAction(): Action { val cancelAction = super.getCancelAction() cancelAction.putValue(Action.NAME, ProductivityFeedbackBundle.message("dialog.cancel.label")) return cancelAction } }
apache-2.0
8f6eef0c452673bd84ad99b03c9e222f
37.549763
138
0.705767
4.815275
false
false
false
false
resilience4j/resilience4j
resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/retry/Retry.kt
4
2233
/* * * Copyright 2019: Brad Newman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package io.github.resilience4j.kotlin.retry import io.github.resilience4j.retry.Retry import kotlinx.coroutines.delay /** * Decorates and executes the given suspend function [block]. * * Between attempts, suspends based on the configured interval function. */ suspend fun <T> Retry.executeSuspendFunction(block: suspend () -> T): T { val retryContext = asyncContext<T>() while (true) { try { val result = block() val delayMs = retryContext.onResult(result) if (delayMs < 1) { retryContext.onComplete() return result } else { delay(delayMs) } } catch (e: Exception) { val delayMs = retryContext.onError(e) if (delayMs < 1) { throw e } else { delay(delayMs) } } } } /** * Decorates the given function [block] and returns it. * * Between attempts, suspends based on the configured interval function. */ fun <T> Retry.decorateSuspendFunction(block: suspend () -> T): suspend () -> T = { executeSuspendFunction(block) } /** * Decorates the given function [block] and returns it. * * Between attempts, suspends based on the configured interval function. */ fun <T> Retry.decorateFunction(block: () -> T): () -> T = { executeFunction(block) } /** * Decorates and executes the given function [block]. * * Between attempts, suspends based on the configured interval function. */ fun <T> Retry.executeFunction(block: () -> T): T { return this.executeCallable(block) }
apache-2.0
b73f2ce0c4bdf2ebb393feefa6088366
28
82
0.636811
4.127542
false
true
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/presentation/filter/FiltersPresenter.kt
2
2893
package org.stepik.android.presentation.filter import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject import org.stepic.droid.analytic.Analytic import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepic.droid.model.StepikFilter import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepik.android.domain.filter.analytic.ContenLanguageChangedAnalyticEvent import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.view.injection.catalog.FiltersBus import ru.nobird.android.presentation.base.PresenterBase import java.util.EnumSet import javax.inject.Inject class FiltersPresenter @Inject constructor( private val analytic: Analytic, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler, private val sharedPreferenceHelper: SharedPreferenceHelper, @FiltersBus private val filtersPublisher: PublishSubject<EnumSet<StepikFilter>> ) : PresenterBase<FiltersView>() { private var state: FiltersView.State = FiltersView.State.Idle set(value) { field = value view?.setState(value) } init { onNeedFilters() } override fun attachView(view: FiltersView) { super.attachView(view) view.setState(state) } private fun onNeedFilters(forceUpdate: Boolean = false) { if (state != FiltersView.State.Idle && !forceUpdate) return compositeDisposable += Single.fromCallable { sharedPreferenceHelper.filterForFeatured } .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { state = FiltersView.State.FiltersLoaded(it) }, onError = { state = FiltersView.State.Empty } ) } fun onFilterChanged(newAppliedFilters: EnumSet<StepikFilter>) { val newLanguage = newAppliedFilters.firstOrNull()?.language if (newLanguage != null) { analytic.report(ContenLanguageChangedAnalyticEvent(newLanguage, ContenLanguageChangedAnalyticEvent.Source.SETTINGS)) } compositeDisposable += Completable.fromCallable { sharedPreferenceHelper.saveFilterForFeatured(newAppliedFilters) } .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onComplete = { filtersPublisher.onNext(newAppliedFilters) onNeedFilters(forceUpdate = true) }, onError = emptyOnErrorStub ) } }
apache-2.0
2aa59e9271fa679a54d6420e074cfb92
33.86747
128
0.693052
5.175313
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/completion/SearchCompletionPopup.kt
1
4901
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.completion import com.intellij.ide.plugins.newui.SearchPopupCallback import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SearchTextField import com.intellij.ui.components.JBList import com.intellij.util.Consumer import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.api.query.SearchQueryCompletionModel import java.awt.Component import java.awt.Point import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.JList import javax.swing.SwingUtilities import javax.swing.event.CaretEvent import javax.swing.event.CaretListener import javax.swing.text.BadLocationException class SearchCompletionPopup( private val searchField: SearchTextField, private val completionModel: SearchQueryCompletionModel, private val popupListener: JBPopupListener ) : ComponentAdapter(), CaretListener { private var skipCaretEvent: Boolean = false private var searchPopupCallback: SearchPopupCallback? = null private var jbPopup: JBPopup? = null private var windowEvent: LightweightWindowEvent? = null private var dialogComponent: Component? = null var itemsList: JList<String>? = null @Suppress("DEPRECATION") fun createAndShow(callback: Consumer<in String>, renderer: ColoredListCellRenderer<in String>, async: Boolean) { if (callback is SearchPopupCallback) { searchPopupCallback = callback } val ipad = renderer.ipad ipad.right = getXOffset() ipad.left = ipad.right renderer.font = searchField.textEditor.font val completionData = mutableListOf<String>() if (!completionModel.values.isNullOrEmpty()) { completionData.addAll(completionModel.values) } else if (!completionModel.attributes.isNullOrEmpty()) { completionData.addAll(completionModel.attributes) } val list = JBList(completionData) val popup = JBPopupFactory.getInstance().createListPopupBuilder(list) .setMovable(false) .setResizable(false) .setRequestFocus(false) .setItemChosenCallback(callback) .setFont(searchField.textEditor.font) .setRenderer(renderer) .createPopup() itemsList = list jbPopup = popup windowEvent = LightweightWindowEvent(popup) skipCaretEvent = true popup.addListener(popupListener) searchField.textEditor.addCaretListener(this) dialogComponent = searchField.textEditor.rootPane.parent dialogComponent?.addComponentListener(this) if (async) { SwingUtilities.invokeLater { this.show() } } else { show() } } private fun getXOffset(): Int { val i = if (UIUtil.isUnderWin10LookAndFeel()) 5 else UIUtil.getListCellHPadding() return JBUI.scale(i) } private fun getPopupLocation(): Point { val location = try { val view = searchField.textEditor.modelToView(completionModel.caretPosition) Point(view.maxX.toInt(), view.maxY.toInt()) } catch (ignore: BadLocationException) { searchField.textEditor.caret.magicCaretPosition } SwingUtilities.convertPointToScreen(location, searchField.textEditor) location.x -= getXOffset() + JBUI.scale(2) location.y += 2 return location } private fun isValid(): Boolean { val popup = jbPopup return popup != null && popup.isVisible && popup.content.parent != null } private fun update() { skipCaretEvent = true jbPopup?.setLocation(getPopupLocation()) jbPopup?.pack(true, true) } private fun show() { if (jbPopup != null) { itemsList?.clearSelection() jbPopup?.showInScreenCoordinates(searchField.textEditor, getPopupLocation()) } } fun hide() { searchField.textEditor.removeCaretListener(this) dialogComponent?.removeComponentListener(this) dialogComponent = null jbPopup?.cancel() jbPopup = null } override fun caretUpdate(e: CaretEvent) { if (skipCaretEvent) { skipCaretEvent = false } else { hide() popupListener.onClosed(windowEvent!!) } } override fun componentMoved(e: ComponentEvent?) { if (jbPopup != null && isValid()) { update() } } override fun componentResized(e: ComponentEvent?) { componentMoved(e) } }
apache-2.0
59cfe3b6973a0431bf3bb5b40e9cad41
31.03268
116
0.678229
5.00102
false
false
false
false
allotria/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCustomCodeStyleSettings.kt
3
1182
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.settings import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CustomCodeStyleSettings import org.intellij.plugins.markdown.lang.MarkdownLanguage @Suppress("PropertyName") class MarkdownCustomCodeStyleSettings(settings: CodeStyleSettings) : CustomCodeStyleSettings(MarkdownLanguage.INSTANCE.id, settings) { //BLANK LINES @JvmField var MAX_LINES_AROUND_HEADER: Int = 1 @JvmField var MIN_LINES_AROUND_HEADER: Int = 1 @JvmField var MAX_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MIN_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MAX_LINES_BETWEEN_PARAGRAPHS: Int = 1 @JvmField var MIN_LINES_BETWEEN_PARAGRAPHS: Int = 1 //SPACES @JvmField var FORCE_ONE_SPACE_BETWEEN_WORDS: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_LIST_BULLET: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL: Boolean = true }
apache-2.0
d59725643f5b4bb0cce18fe56872692e
26.511628
140
0.765651
3.92691
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/internal/KeymapToCsvAction.kt
5
2539
// 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.internal import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.FileSaverDescriptor import com.intellij.openapi.keymap.KeymapManager class KeymapToCsvAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val allShortcuts = linkedMapOf<String, MutableMap<String, MutableList<String>>>() val seenModifierSets = mutableSetOf<String>() val columns = mutableListOf("", "shift", "ctrl", "alt", "meta") for (key in 'A'..'Z') { allShortcuts[key.toString()] = hashMapOf() } for (key in '0'..'9') { allShortcuts[key.toString()] = hashMapOf() } for (key in 1..12) { allShortcuts["F$key"] = hashMapOf() } val keymap = KeymapManager.getInstance().activeKeymap for (actionId in keymap.actionIdList) { val shortcuts = keymap.getShortcuts(actionId).filterIsInstance<KeyboardShortcut>() for (shortcut in shortcuts) { val keyStroke = shortcut.firstKeyStroke val str = keyStroke.toString() val keyName = str.substringAfterLast(' ', str) val modifiers = str.substringBeforeLast(' ').replace("pressed", "").trim() seenModifierSets += modifiers val forKey = allShortcuts.getOrPut(keyName) { hashMapOf() } val actionIds = forKey.getOrPut(modifiers) { mutableListOf() } actionIds.add(actionId) } } for (seenModifierSet in seenModifierSets) { if (seenModifierSet !in columns) { columns.add(seenModifierSet) } } val result = buildString { appendln("key," + columns.joinToString(",")) for ((key, shortcutsForKey) in allShortcuts) { append(key) for (column in columns) { append(",") val actionsForShortcut = shortcutsForKey[column] ?: emptyList<String>() append(actionsForShortcut.joinToString("|")) } appendln() } } val dialog = FileChooserFactory.getInstance().createSaveFileDialog( FileSaverDescriptor("Export Keymap to .csv", "Select file to save to:", "csv"), e.project) val virtualFileWrapper = dialog.save(null) virtualFileWrapper?.file?.writeText(result.replace("\n", "\r\n")) } }
apache-2.0
a1091c9091cb2f9f05bfd40166365dfb
37.484848
140
0.677432
4.533929
false
false
false
false
fluidsonic/fluid-json
annotation-processor/sources-jvm/utility/KotlinpoetTypeNames.kt
1
740
package io.fluidsonic.json.annotationprocessor import com.squareup.kotlinpoet.* internal object KotlinpoetTypeNames { val any = ANY val boolean = ClassName("kotlin", "Boolean") val byte = ClassName("kotlin", "Byte") val char = ClassName("kotlin", "Char") val double = ClassName("kotlin", "Double") val float = ClassName("kotlin", "Float") val int = ClassName("kotlin", "Int") val long = ClassName("kotlin", "Long") val short = ClassName("kotlin", "Short") val string = ClassName("kotlin", "String") val nullableAny = any.copy(nullable = true) val basic = setOf( boolean, byte, char, double, float, int, long, short ) } internal val TypeName.isPrimitive get() = KotlinpoetTypeNames.basic.contains(this)
apache-2.0
81008eecd326c5250b7d755b4daa585f
20.142857
49
0.694595
3.363636
false
false
false
false
rightfromleft/weather-app
data/src/main/java/com/rightfromleftsw/weather/data/executor/JobExecutor.kt
1
1755
package com.rightfromleftsw.weather.data.executor import com.rightfromleftsw.weather.domain.executor.ThreadExecutor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadFactory import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import javax.inject.Inject /** * Decorated [ThreadPoolExecutor] */ open class JobExecutor @Inject constructor(): ThreadExecutor { private val workQueue: LinkedBlockingQueue<Runnable> private val threadPoolExecutor: ThreadPoolExecutor private val threadFactory: ThreadFactory init { this.workQueue = LinkedBlockingQueue() this.threadFactory = JobThreadFactory() this.threadPoolExecutor = ThreadPoolExecutor(INITIAL_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME.toLong(), KEEP_ALIVE_TIME_UNIT, this.workQueue, this.threadFactory) } override fun execute(runnable: Runnable?) { if (runnable == null) { throw IllegalArgumentException("Runnable to execute cannot be null") } this.threadPoolExecutor.execute(runnable) } private class JobThreadFactory : ThreadFactory { private var counter = 0 override fun newThread(runnable: Runnable): Thread { return Thread(runnable, THREAD_NAME + counter++) } companion object { private val THREAD_NAME = "android_" } } companion object { private val INITIAL_POOL_SIZE = 3 private val MAX_POOL_SIZE = 5 // Sets the amount of time an idle thread waits before terminating private val KEEP_ALIVE_TIME = 10 // Sets the Time Unit to seconds private val KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS } }
mit
704c0eb9434ec550aba52055e06e96ef
29.275862
99
0.693447
5.086957
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PopupMenuListItemCellRenderer.kt
1
2597
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers import com.intellij.ide.ui.AntialiasingType import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.GraphicsUtil import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.TableColors import icons.PackageSearchIcons import java.awt.Component import javax.accessibility.AccessibleContext import javax.accessibility.AccessibleRole import javax.accessibility.AccessibleState import javax.accessibility.AccessibleStateSet import javax.swing.DefaultListCellRenderer import javax.swing.JLabel import javax.swing.JList internal class PopupMenuListItemCellRenderer<T>( private val selectedValue: T?, private val colors: TableColors, private val itemLabelRenderer: (T) -> String = { it.toString() } ) : DefaultListCellRenderer() { private val selectedIcon = PackageSearchIcons.Checkmark private val emptyIcon = EmptyIcon.create(selectedIcon.iconWidth) private var currentItemIsSelected = false override fun getListCellRendererComponent(list: JList<*>, value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { @Suppress("UNCHECKED_CAST") // It's ok to crash if this isn't true val item = value as T val itemLabel = itemLabelRenderer(item) + " " // The spaces are to compensate for the lack of padding in the label (yes, I know, it's a hack) val label = super.getListCellRendererComponent(list, itemLabel, index, isSelected, cellHasFocus) as JLabel label.font = list.font colors.applyTo(label, isSelected) currentItemIsSelected = item === selectedValue label.icon = if (currentItemIsSelected) selectedIcon else emptyIcon GraphicsUtil.setAntialiasingType(label, AntialiasingType.getAAHintForSwingComponent()) return label } override fun getAccessibleContext(): AccessibleContext { if (accessibleContext == null) { accessibleContext = AccessibleRenderer(currentItemIsSelected) } return accessibleContext } private inner class AccessibleRenderer( private val isSelected: Boolean ) : AccessibleJLabel() { override fun getAccessibleRole(): AccessibleRole = AccessibleRole.CHECK_BOX override fun getAccessibleStateSet(): AccessibleStateSet { val set = super.getAccessibleStateSet() if (isSelected) { set.add(AccessibleState.CHECKED) } return set } } }
apache-2.0
b50cf6bf35b2e883c29d6ff12867e69c
38.953846
149
0.735464
5.173307
false
false
false
false
leafclick/intellij-community
plugins/github/test/org/jetbrains/plugins/github/GithubUrlUtilTest.kt
1
7812
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github import com.intellij.openapi.util.Pair import junit.framework.TestCase import org.jetbrains.plugins.github.api.GHRepositoryPath import org.jetbrains.plugins.github.util.GithubUrlUtil.* import java.util.* class GithubUrlUtilTest : TestCase() { private class TestCase<T> { val tests: MutableList<Pair<String, T>> = ArrayList() fun add(`in`: String, out: T?) { tests.add(Pair.create(`in`, out)) } } private fun <T> runTestCase(tests: TestCase<T>, func: (String) -> T) { for (test in tests.tests) { assertEquals(test.getFirst(), test.getSecond(), func(test.getFirst())) } } fun testRemoveTrailingSlash() { val tests = TestCase<String>() tests.add("http://github.com/", "http://github.com") tests.add("http://github.com", "http://github.com") tests.add("http://github.com/user/repo/", "http://github.com/user/repo") tests.add("http://github.com/user/repo", "http://github.com/user/repo") runTestCase(tests) { `in` -> removeTrailingSlash(`in`) } } fun testRemoveProtocolPrefix() { val tests = TestCase<String>() tests.add("github.com/user/repo/", "github.com/user/repo/") tests.add("api.github.com/user/repo/", "api.github.com/user/repo/") tests.add("http://github.com/user/repo/", "github.com/user/repo/") tests.add("https://github.com/user/repo/", "github.com/user/repo/") tests.add("git://github.com/user/repo/", "github.com/user/repo/") tests.add("[email protected]:user/repo/", "github.com/user/repo/") tests.add("[email protected]:username/repo/", "github.com/username/repo/") tests.add("https://username:[email protected]/user/repo/", "github.com/user/repo/") tests.add("https://[email protected]/user/repo/", "github.com/user/repo/") tests.add("https://github.com:2233/user/repo/", "github.com:2233/user/repo/") tests.add("HTTP://GITHUB.com/user/repo/", "GITHUB.com/user/repo/") tests.add("HttP://GitHub.com/user/repo/", "GitHub.com/user/repo/") runTestCase(tests) { `in` -> removeProtocolPrefix(`in`) } } fun testRemovePort() { val tests = TestCase<String>() tests.add("github.com/user/repo/", "github.com/user/repo/") tests.add("github.com", "github.com") tests.add("github.com/", "github.com/") tests.add("github.com:80/user/repo/", "github.com/user/repo/") tests.add("github.com:80/user/repo", "github.com/user/repo") tests.add("github.com:80/user", "github.com/user") tests.add("github.com:80", "github.com") runTestCase(tests) { `in` -> removePort(`in`) } } fun testGetUserAndRepositoryFromRemoteUrl() { val tests = TestCase<GHRepositoryPath?>() tests.add("http://github.com/username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("https://github.com/username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("git://github.com/username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("[email protected]:username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("https://github.com/username/reponame", GHRepositoryPath("username", "reponame")) tests.add("https://github.com/username/reponame.git", GHRepositoryPath("username", "reponame")) tests.add("https://github.com/username/reponame.git/", GHRepositoryPath("username", "reponame")) tests.add("[email protected]:username/reponame.git/", GHRepositoryPath("username", "reponame")) tests.add("http://login:[email protected]/username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("HTTPS://GitHub.com/username/reponame/", GHRepositoryPath("username", "reponame")) tests.add("https://github.com/UserName/RepoName/", GHRepositoryPath("UserName", "RepoName")) tests.add("https://github.com/RepoName/", null) tests.add("[email protected]:user/", null) tests.add("https://user:[email protected]/", null) runTestCase(tests) { `in` -> getUserAndRepositoryFromRemoteUrl(`in`) } } fun testMakeGithubRepoFromRemoteUrl() { val tests = TestCase<String?>() tests.add("http://github.com/username/reponame/", "https://github.com/username/reponame") tests.add("https://github.com/username/reponame/", "https://github.com/username/reponame") tests.add("git://github.com/username/reponame/", "https://github.com/username/reponame") tests.add("[email protected]:username/reponame/", "https://github.com/username/reponame") tests.add("https://github.com/username/reponame", "https://github.com/username/reponame") tests.add("https://github.com/username/reponame.git", "https://github.com/username/reponame") tests.add("https://github.com/username/reponame.git/", "https://github.com/username/reponame") tests.add("[email protected]:username/reponame.git/", "https://github.com/username/reponame") tests.add("[email protected]:username/reponame/", "https://github.com/username/reponame") tests.add("http://login:[email protected]/username/reponame/", "https://github.com/username/reponame") tests.add("HTTPS://GitHub.com/username/reponame/", "https://github.com/username/reponame") tests.add("https://github.com/UserName/RepoName/", "https://github.com/UserName/RepoName") tests.add("https://github.com/RepoName/", null) tests.add("[email protected]:user/", null) tests.add("https://user:[email protected]/", null) runTestCase(tests) { `in` -> makeGithubRepoUrlFromRemoteUrl(`in`, "https://github.com") } } fun testGetHostFromUrl() { val tests = TestCase<String>() tests.add("github.com", "github.com") tests.add("api.github.com", "api.github.com") tests.add("github.com/", "github.com") tests.add("api.github.com/", "api.github.com") tests.add("github.com/user/repo/", "github.com") tests.add("api.github.com/user/repo/", "api.github.com") tests.add("http://github.com/user/repo/", "github.com") tests.add("https://github.com/user/repo/", "github.com") tests.add("git://github.com/user/repo/", "github.com") tests.add("[email protected]:user/repo/", "github.com") tests.add("[email protected]:username/repo/", "github.com") tests.add("https://username:[email protected]/user/repo/", "github.com") tests.add("https://[email protected]/user/repo/", "github.com") tests.add("https://github.com:2233/user/repo/", "github.com") tests.add("HTTP://GITHUB.com/user/repo/", "GITHUB.com") tests.add("HttP://GitHub.com/user/repo/", "GitHub.com") runTestCase(tests) { `in` -> getHostFromUrl(`in`) } } fun testGetApiUrl() { val tests = TestCase<String>() tests.add("github.com", "https://api.github.com") tests.add("https://github.com/", "https://api.github.com") tests.add("https://my.site.com/", "https://my.site.com/api/v3") tests.add("https://api.site.com/", "https://api.site.com/api/v3") tests.add("https://url.github.com/", "https://url.github.com/api/v3") tests.add("my.site.com/", "https://my.site.com/api/v3") tests.add("api.site.com/", "https://api.site.com/api/v3") tests.add("url.github.com/", "https://url.github.com/api/v3") tests.add("http://my.site.com/", "http://my.site.com/api/v3") tests.add("http://api.site.com/", "http://api.site.com/api/v3") tests.add("http://url.github.com/", "http://url.github.com/api/v3") tests.add("HTTP://GITHUB.com", "http://api.github.com") tests.add("HttP://GitHub.com/", "http://api.github.com") tests.add("https://ghe.com/suffix", "https://ghe.com/suffix/api/v3") tests.add("https://ghe.com/suFFix", "https://ghe.com/suFFix/api/v3") runTestCase(tests) { `in` -> getApiUrl(`in`) } } }
apache-2.0
cc44711d645d94e3d10e8e466ebabee5
42.4
140
0.668587
3.338462
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/superMembers.kt
3
700
open class Base { private val x: Long = 0 protected open fun foo(): Long = 1 } class Derived : Base() { private val x: String = "" override fun foo(): Long = 2 } fun <T> block(block: () -> T): T { return block() } fun main() { val b = Base() val d = Derived() //Breakpoint! val f = 0 } // EXPRESSION: block { d.foo() } // RESULT: 2: J // EXPRESSION: block { (d as Base).foo() } // RESULT: 2: J // EXPRESSION: block { b.foo() } // RESULT: 1: J // EXPRESSION: block { b.foo() } // RESULT: 1: J // EXPRESSION: block { b.x } // RESULT: 0: J // EXPRESSION: block { d.x } // RESULT: "": Ljava/lang/String; // EXPRESSION: block { (d as Base).x } // RESULT: 0: J
apache-2.0
9e31e9d68d5e357b8c9943b59605ac7d
16.097561
42
0.544286
2.904564
false
false
false
false
miketrewartha/positional
app/src/main/kotlin/io/trewartha/positional/ui/utils/CoordinatorLayoutExtensions.kt
1
1544
package io.trewartha.positional.ui.utils import android.view.View import androidx.annotation.StringRes import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.snackbar.Snackbar fun CoordinatorLayout.showSnackbar( @StringRes resId: Int, duration: Int = Snackbar.LENGTH_LONG, @StringRes actionResId: Int? = null, listener: ((View) -> Unit)? = null ) { var builder = Snackbar.make(this, resId, duration) if (actionResId != null) builder = builder.setAction(actionResId, listener) builder.show() } fun CoordinatorLayout.showSnackbar( text: String, duration: Int = Snackbar.LENGTH_LONG, actionText: String?, listener: ((View) -> Unit)? = null ) { var builder = Snackbar.make(this, text, duration) if (actionText != null) builder = builder.setAction(actionText, listener) builder.show() } fun CoordinatorLayout.showSnackbar( text: String, duration: Int = Snackbar.LENGTH_LONG, @StringRes actionResId: Int? = null, listener: ((View) -> Unit)? = null ) { var builder = Snackbar.make(this, text, duration) if (actionResId != null) builder = builder.setAction(actionResId, listener) builder.show() } fun CoordinatorLayout.showSnackbar( @StringRes resId: Int, duration: Int = Snackbar.LENGTH_LONG, actionText: String?, listener: ((View) -> Unit)? = null ) { var builder = Snackbar.make(this, resId, duration) if (actionText != null) builder = builder.setAction(actionText, listener) builder.show() }
mit
d12e274d80240d93dd7f0043934a93af
29.88
79
0.701425
3.948849
false
false
false
false
smmribeiro/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/SimplePropertiesInStorageTest.kt
2
6130
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.intellij.openapi.util.Ref import com.intellij.workspaceModel.storage.entities.ModifiableSampleEntity import com.intellij.workspaceModel.storage.entities.ModifiableSecondSampleEntity import com.intellij.workspaceModel.storage.entities.SampleEntity import com.intellij.workspaceModel.storage.entities.addSampleEntity import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.junit.Assert.* import org.junit.Before import org.junit.Test internal fun WorkspaceEntityStorage.singleSampleEntity() = entities(SampleEntity::class.java).single() class SimplePropertiesInStorageTest { private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = VirtualFileUrlManagerImpl() } @Test fun `add entity`() { val builder = createEmptyBuilder() val source = SampleEntitySource("test") val entity = builder.addSampleEntity("hello", source, true, mutableListOf("one", "two")) assertTrue(entity.booleanProperty) assertEquals("hello", entity.stringProperty) assertEquals(listOf("one", "two"), entity.stringListProperty) assertEquals(entity, builder.singleSampleEntity()) assertEquals(source, entity.entitySource) } @Test fun `remove entity`() { val builder = createEmptyBuilder() val entity = builder.addSampleEntity("hello") builder.removeEntity(entity) assertTrue(builder.entities(SampleEntity::class.java).toList().isEmpty()) } @Test fun `modify entity`() { val builder = createEmptyBuilder() val original = builder.addSampleEntity("hello") val modified = builder.modifyEntity(ModifiableSampleEntity::class.java, original) { stringProperty = "foo" stringListProperty = stringListProperty + "first" booleanProperty = true fileProperty = virtualFileManager.fromUrl("file:///xxx") } assertEquals("hello", original.stringProperty) assertEquals(emptyList<String>(), original.stringListProperty) assertEquals("foo", modified.stringProperty) assertEquals(listOf("first"), modified.stringListProperty) assertTrue(modified.booleanProperty) assertEquals("file:///xxx", modified.fileProperty.url) } @Test fun `builder from storage`() { val storage = createEmptyBuilder().apply { addSampleEntity("hello") }.toStorage() assertEquals("hello", storage.singleSampleEntity().stringProperty) val builder = createBuilderFrom(storage) assertEquals("hello", builder.singleSampleEntity().stringProperty) builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) { stringProperty = "good bye" } assertEquals("hello", storage.singleSampleEntity().stringProperty) assertEquals("good bye", builder.singleSampleEntity().stringProperty) } @Test fun `snapshot from builder`() { val builder = createEmptyBuilder() builder.addSampleEntity("hello") val snapshot = builder.toStorage() assertEquals("hello", builder.singleSampleEntity().stringProperty) assertEquals("hello", snapshot.singleSampleEntity().stringProperty) builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) { stringProperty = "good bye" } assertEquals("hello", snapshot.singleSampleEntity().stringProperty) assertEquals("good bye", builder.singleSampleEntity().stringProperty) } @Test fun `different entities with same properties`() { val builder = createEmptyBuilder() val foo1 = builder.addSampleEntity("foo1", virtualFileManager = virtualFileManager) val foo2 = builder.addSampleEntity("foo1", virtualFileManager = virtualFileManager) val bar = builder.addSampleEntity("bar", virtualFileManager = virtualFileManager) assertFalse(foo1 == foo2) assertTrue(foo1.hasEqualProperties(foo1)) assertTrue(foo1.hasEqualProperties(foo2)) assertFalse(foo1.hasEqualProperties(bar)) val builder2 = createEmptyBuilder() val foo1a = builder2.addSampleEntity("foo1", virtualFileManager = virtualFileManager) assertTrue(foo1.hasEqualProperties(foo1a)) val bar2 = builder.modifyEntity(ModifiableSampleEntity::class.java, bar) { stringProperty = "bar2" } assertTrue(bar == bar2) assertFalse(bar.hasEqualProperties(bar2)) val foo2a = builder.modifyEntity(ModifiableSampleEntity::class.java, foo2) { stringProperty = "foo2" } assertFalse(foo1.hasEqualProperties(foo2a)) } @Test fun `change source`() { val builder = createEmptyBuilder() val source1 = SampleEntitySource("1") val source2 = SampleEntitySource("2") val foo = builder.addSampleEntity("foo", source1) val foo2 = builder.changeSource(foo, source2) assertEquals(source1, foo.entitySource) assertEquals(source2, foo2.entitySource) assertEquals(source2, builder.singleSampleEntity().entitySource) assertEquals(foo2, builder.entitiesBySource { it == source2 }.values.flatMap { it.values.flatten() }.single()) assertTrue(builder.entitiesBySource { it == source1 }.values.all { it.isEmpty() }) } @Test(expected = IllegalStateException::class) fun `modifications are allowed inside special methods only`() { val thief = Ref.create<ModifiableSecondSampleEntity>() val builder = createEmptyBuilder() builder.addEntity(ModifiableSecondSampleEntity::class.java, SampleEntitySource("test")) { thief.set(this) intProperty = 10 } thief.get().intProperty = 30 } @Test(expected = IllegalStateException::class) fun `test trying to modify non-existing entity`() { val builder = createEmptyBuilder() val sampleEntity = builder.addSampleEntity("Prop") val anotherBuilder = createEmptyBuilder() anotherBuilder.modifyEntity(ModifiableSampleEntity::class.java, sampleEntity) { this.stringProperty = "Another prop" } } }
apache-2.0
14c5a00810cd9c36c1231e166154829d
37.553459
140
0.744209
4.967585
false
true
false
false
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/directory/detail/single/SingleDataSourceDirectoryDetailActivity.kt
1
5291
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * 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 org.pattonvillecs.pattonvilleapp.view.ui.directory.detail.single import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.SearchView import android.text.InputType import android.util.Log import android.view.Menu import android.view.View import android.view.inputmethod.EditorInfo import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.common.FlexibleItemDecoration import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager import kotlinx.android.synthetic.main.activity_directory_single_datasource_detail.* import org.jetbrains.anko.appcompat.v7.coroutines.onQueryTextListener import org.pattonvillecs.pattonvilleapp.R import org.pattonvillecs.pattonvilleapp.service.model.DataSource import org.pattonvillecs.pattonvilleapp.view.adapter.directory.FacultyAdapter import org.pattonvillecs.pattonvilleapp.view.ui.directory.detail.AbstractDirectoryDetailActivity import org.pattonvillecs.pattonvilleapp.viewmodel.directory.detail.single.SingleDataSourceDirectoryDetailActivityViewModel import org.pattonvillecs.pattonvilleapp.viewmodel.getViewModel /** * Created by Mitchell Skaggs on 12/10/2017. */ class SingleDataSourceDirectoryDetailActivity : AbstractDirectoryDetailActivity() { lateinit var viewModel: SingleDataSourceDirectoryDetailActivityViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_directory_single_datasource_detail) viewModel = getViewModel() viewModel.setDataSource(intent.getSerializableExtra("datasource") as DataSource) viewModel.directoryRepository = directoryRepository viewModel.title.observe(this::getLifecycle) { title = it } val facultyAdapter = FacultyAdapter(stableIds = true) faculty_recyclerview.adapter = facultyAdapter faculty_recyclerview.layoutManager = SmoothScrollLinearLayoutManager(this) faculty_recyclerview.addItemDecoration( FlexibleItemDecoration(this) .withDefaultDivider() .withDrawDividerOnLastItem(true)) fast_scroller.setViewsToUse( R.layout.small_fast_scroller_layout, R.id.fast_scroller_bubble, R.id.fast_scroller_handle) facultyAdapter.fastScroller = fast_scroller viewModel.facultyItems.observe(this::getLifecycle) { Log.i(TAG, "Visible from update!") progress_bar.visibility = View.VISIBLE facultyAdapter.updateDataSet(it) facultyAdapter.filterItems(100L) } viewModel.searchText.observe(this::getLifecycle) { facultyAdapter.setFilter(it.orEmpty()) if (facultyAdapter.hasFilter()) { Log.i(TAG, "Visible from search with text $it!") progress_bar.visibility = View.VISIBLE } facultyAdapter.filterItems(100L) } facultyAdapter.addListener(FlexibleAdapter.OnUpdateListener { Log.i(TAG, "Count=$it") progress_bar.visibility = View.GONE Log.i(TAG, "Gone!") }) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.search_icon_menu, menu) initSearchView(menu) return true } /** * Method to setup the search functionality of the list * * @param menu Menu object of current options menu */ private fun initSearchView(menu: Menu) { val searchItem = menu.findItem(R.id.menu_search) if (searchItem != null) { val searchView = searchItem.actionView as SearchView searchView.inputType = InputType.TYPE_TEXT_VARIATION_FILTER searchView.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_FULLSCREEN searchView.queryHint = getString(R.string.action_search) searchView.onQueryTextListener { onQueryTextChange { viewModel.setSearchText(it) true } } } } companion object { const val TAG: String = "SingleDataSourceDirecto" fun createIntent(context: Context, dataSource: DataSource): Intent = Intent(context, SingleDataSourceDirectoryDetailActivity::class.java).putExtra("datasource", dataSource) } }
gpl-3.0
36e6a412ef8004f522fa2ef05f6d22b1
39.7
123
0.706294
4.972744
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/controller/usecases/MaterialList.kt
1
6385
package com.cout970.modeler.controller.usecases import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.selection.SelectionTarget import com.cout970.modeler.api.model.selection.SelectionType import com.cout970.modeler.controller.tasks.* import com.cout970.modeler.core.config.colorToHex import com.cout970.modeler.core.model.material.ColoredMaterial import com.cout970.modeler.core.model.material.MaterialNone import com.cout970.modeler.core.model.material.MaterialRefNone import com.cout970.modeler.core.model.material.TexturedMaterial import com.cout970.modeler.core.model.objects import com.cout970.modeler.core.model.selection.Selection import com.cout970.modeler.core.project.IProgramState import com.cout970.modeler.core.project.ProjectManager import com.cout970.modeler.gui.GuiState import com.cout970.modeler.input.dialogs.FileDialogs import com.cout970.modeler.input.dialogs.MessageDialogs import com.cout970.modeler.util.asNullable import com.cout970.modeler.util.getOr import com.cout970.modeler.util.toResourcePath import com.cout970.vector.extensions.vec3Of import org.liquidengine.legui.component.Component import java.awt.Color import java.io.File /** * Created by cout970 on 2017/07/20. */ @UseCase("material.view.apply") private fun applyMaterial(component: Component, programState: IProgramState): ITask { val model = programState.model programState.modelSelection.ifNotNull { selection -> component.asNullable() .map { it.metadata["ref"] } .flatMap { it as? IMaterialRef } .map { ref -> val newModel = model.modifyObjects(selection.objects.toSet()) { _, obj -> obj.withMaterial(ref) } return TaskUpdateModel(oldModel = model, newModel = newModel) } } return TaskNone } @UseCase("material.view.load") private fun loadMaterial(component: Component, projectManager: ProjectManager): ITask { val ref = component.metadata["ref"] ?: return TaskNone val materialRef = ref as? IMaterialRef ?: return TaskNone return if (materialRef == MaterialRefNone) { importMaterial() } else { showLoadMaterialMenu(materialRef, projectManager) } } private fun showLoadMaterialMenu(ref: IMaterialRef, projectManager: ProjectManager): ITask = TaskAsync { returnFunc -> val path = FileDialogs.openFile( title = "Import Texture", description = "PNG texture (*.png)", filters = listOf("*.png") ) if (path != null) { val archive = File(path) val material = TexturedMaterial(archive.nameWithoutExtension, archive.toResourcePath(), ref.materialId) returnFunc(TaskUpdateMaterial( oldMaterial = projectManager.loadedMaterials[ref]!!, newMaterial = material )) } } @UseCase("material.view.import") private fun importMaterial(): ITask = TaskAsync { returnFunc -> val file = FileDialogs.openFile( title = "Import Texture", description = "PNG texture (*.png)", filters = listOf("*.png") ) if (file != null) { val archive = File(file) val material = TexturedMaterial(archive.nameWithoutExtension, archive.toResourcePath()) returnFunc(TaskImportMaterial(material)) } } @UseCase("material.new.colored") private fun newColoredMaterial(): ITask = TaskAsync { returnFunc -> val c = Color.getHSBColor(Math.random().toFloat(), 0.5f, 1.0f) val color = vec3Of(c.red / 255f, c.green / 255f, c.blue / 255f) val name = "Color #${colorToHex(color)}" returnFunc(TaskImportMaterial(ColoredMaterial(name, color))) } @UseCase("material.view.select") private fun selectMaterial(component: Component): ITask { return component.asNullable() .map { it.metadata["ref"] } .flatMap { it as? IMaterialRef } .map { TaskUpdateMaterialSelection(it) as ITask } .getOr(TaskNone) } @UseCase("material.view.duplicate") private fun duplicateMaterial(component: Component, access: IProgramState): ITask { return component.asNullable() .flatMap { it.metadata["ref"] } .flatMap { it as? IMaterialRef } .map { access.model.getMaterial(it) } .filterIsInstance<TexturedMaterial>() .map { TaskImportMaterial(it.copy(name = "${it.name} copy")) as ITask } .getOr(TaskNone) } @UseCase("material.view.remove") private fun removeMaterial(guiState: GuiState, projectManager: ProjectManager): ITask { val matRef = guiState.selectedMaterial val model = projectManager.model val material = model.getMaterial(matRef) if (material == MaterialNone) return TaskNone val used = model.objects.any { it.material == matRef } if (used) { //ask return TaskAsync { returnFunc -> val result = MessageDialogs.warningBoolean( title = "Remove material", message = "Are you sure you want to remove this material?", default = false ) if (result) { returnFunc(removeMaterialTask(model, matRef, material)) } } } return removeMaterialTask(model, matRef, material) } private fun removeMaterialTask(model: IModel, ref: IMaterialRef, material: IMaterial): ITask { val newModel = model.modifyObjects({ true }) { _, obj -> if (obj.material == ref) obj.withMaterial(MaterialRefNone) else obj } return TaskChain(listOf( TaskUpdateModel(oldModel = model, newModel = newModel), TaskRemoveMaterial(ref, material) )) } @UseCase("material.view.inverse_select") private fun selectByMaterial(guiState: GuiState, programState: IProgramState): ITask { val matRef = guiState.selectedMaterial val model = programState.model val objs = model.objectMap.entries .filter { it.value.material == matRef } .map { it.key } return TaskUpdateModelSelection( newSelection = Selection(SelectionTarget.MODEL, SelectionType.OBJECT, objs).asNullable(), oldSelection = programState.modelSelection ) }
gpl-3.0
4bb6808f9668cf2ed6fb0b8c234ac632
35.491429
118
0.676899
4.334691
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/JvmOverloadedRenameParameterBefore.kt
13
227
@JvmOverloads fun <caret>foo(a: Int, b: Int, c: Int = 1, d: Int = 2) { } fun test() { foo(a = 1, b = 2, c = 3, d = 4) foo(a = 1, b = 2, c = 3) foo(b = 1, c = 2, a = 3) foo(a = 1, b = 2) foo(b = 1, a = 2) }
apache-2.0
ed3beaeae7caf1bb0910655b20a74e0e
19.727273
70
0.400881
2.045045
false
true
false
false
leafclick/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectStatus.kt
1
5195
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.* import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectState.* import java.util.concurrent.atomic.AtomicReference import kotlin.math.max class ProjectStatus(private val debugName: String? = null) { private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport") private var state = AtomicReference(Synchronized(-1) as ProjectState) fun isDirty() = state.get() is Dirty fun isUpToDate() = when (state.get()) { is Modified, is Dirty -> false is Synchronized, is Reverted -> true } fun getModificationType() = when (val state = state.get()) { is Dirty -> state.type is Modified -> state.type is Synchronized, is Reverted -> null } fun markDirty(stamp: Long, type: ModificationType = INTERNAL): ProjectState { return update(Invalidate(stamp, type)) } fun markModified(stamp: Long, type: ModificationType = INTERNAL): ProjectState { return update(Modify(stamp, type)) } fun markReverted(stamp: Long): ProjectState { return update(Revert(stamp)) } fun markSynchronized(stamp: Long): ProjectState { return update(Synchronize(stamp)) } fun update(event: ProjectEvent): ProjectState { if (LOG.isDebugEnabled) { val debugPrefix = if (debugName == null) "" else "$debugName: " val eventName = event::class.simpleName val state = state.get() val stateName = state::class.java.simpleName LOG.debug("${debugPrefix}Event $eventName is happened at ${event.stamp}. Current state $stateName is changed at ${state.stamp}") } val newState = state.updateAndGet { currentState -> when (currentState) { is Synchronized -> when (event) { is Synchronize -> event.withFuture(currentState, ::Synchronized) is Invalidate -> event.ifFuture(currentState) { Dirty(it, event.type) } is Modify -> event.ifFuture(currentState) { Modified(it, event.type) } is Revert -> event.ifFuture(currentState, ::Reverted) } is Dirty -> when (event) { is Synchronize -> event.ifFuture(currentState, ::Synchronized) is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) } is Modify -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) } is Revert -> event.withFuture(currentState) { Dirty(it, currentState.type) } } is Modified -> when (event) { is Synchronize -> event.ifFuture(currentState, ::Synchronized) is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) } is Modify -> event.withFuture(currentState) { Modified(it, currentState.type.merge(event.type)) } is Revert -> event.ifFuture(currentState, ::Reverted) } is Reverted -> when (event) { is Synchronize -> event.ifFuture(currentState, ::Synchronized) is Invalidate -> event.withFuture(currentState) { Dirty(it, event.type) } is Modify -> event.ifFuture(currentState) { Modified(it, event.type) } is Revert -> event.withFuture(currentState, ::Reverted) } } } if (LOG.isDebugEnabled) { val debugPrefix = if (debugName == null) "" else "$debugName: " val eventName = event::class.simpleName val state = state.get() val stateName = state::class.java.simpleName LOG.debug("${debugPrefix}State is $stateName at ${state.stamp} after event $eventName that happen at ${event.stamp}.") } return newState } private fun ProjectEvent.withFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState { return action(max(stamp, state.stamp)) } private fun ProjectEvent.ifFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState { return if (stamp > state.stamp) action(stamp) else state } enum class ModificationType { EXTERNAL, INTERNAL; fun merge(other: ModificationType): ModificationType { return when (this) { INTERNAL -> INTERNAL EXTERNAL -> other } } } sealed class ProjectEvent(val stamp: Long) { class Synchronize(stamp: Long) : ProjectEvent(stamp) class Invalidate(stamp: Long, val type: ModificationType) : ProjectEvent(stamp) class Modify(stamp: Long, val type: ModificationType) : ProjectEvent(stamp) class Revert(stamp: Long) : ProjectEvent(stamp) } sealed class ProjectState(val stamp: Long) { class Synchronized(stamp: Long) : ProjectState(stamp) class Dirty(stamp: Long, val type: ModificationType) : ProjectState(stamp) class Modified(stamp: Long, val type: ModificationType) : ProjectState(stamp) class Reverted(stamp: Long) : ProjectState(stamp) } }
apache-2.0
befda11e939f39da05761bb2dc17941d
38.961538
140
0.689317
4.463058
false
false
false
false
kivensolo/UiUsingListView
library/network/src/main/java/com/zeke/network/interceptor/CommonParamsInterceptor.kt
1
7252
package com.zeke.network.interceptor import android.text.TextUtils import okhttp3.* import okio.Buffer import java.io.IOException /** * author:ZekeWang * date:2021/6/5 * description: * 公共接口参数网络配置拦截器 * 支持Params和Header全局添加 * 使用Builder模式(Kotlin) */ @Suppress("unused") class CommonParamsInterceptor private constructor() : Interceptor { // 添加到 URL 末尾,Get Post 方法都使用 var queryParamsMap: HashMap<String, String> = HashMap() // 添加到公共参数到消息体,适用 Post 请求 var postParamsMap: HashMap<String, String> = HashMap() // 公共 Headers 添加 var headerParamsMap: HashMap<String, String> = HashMap() // 消息头 集合形式,一次添加一行 var headerLinesList: MutableList<String> = ArrayList() override fun intercept(chain: Interceptor.Chain): Response { var request: Request = chain.request() val requestBuilder = request.newBuilder() val headerBuilder: Headers.Builder = request.headers().newBuilder() injectHeaderParams(headerBuilder, requestBuilder) injectQueryParmas(request, requestBuilder) injectPostBodyParmas(request, requestBuilder) request = requestBuilder.build() return chain.proceed(request) } /** * Post模式下添加Body参数 */ private fun injectPostBodyParmas(request: Request, requestBuilder: Request.Builder) { if (postParamsMap.isNotEmpty()) { if (canInjectIntoBody(request)) { val formBodyBuilder = FormBody.Builder() for ((key, value) in postParamsMap) { formBodyBuilder.add(key, value) } val formBody: RequestBody = formBodyBuilder.build() var postBodyString: String = bodyToString(request.body()) val prefex = if (postBodyString.isNotEmpty()) "&" else "" postBodyString += prefex + bodyToString(formBody) requestBuilder.post( RequestBody.create( MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString ) ) } } } /** * 添加消息头 */ private fun injectHeaderParams( headerBuilder: Headers.Builder, requestBuilder: Request.Builder ) { // 以 Entry 添加消息头 if (headerParamsMap.isNotEmpty()) { val iterator: Iterator<*> = headerParamsMap.entries.iterator() while (iterator.hasNext()) { val entry = iterator.next() as Map.Entry<*, *> headerBuilder.add(entry.key as String, entry.value as String) } requestBuilder.headers(headerBuilder.build()) } // 以 String 形式添加消息头 if (headerLinesList.isNotEmpty()) { for (line in headerLinesList) { headerBuilder.add(line) } requestBuilder.headers(headerBuilder.build()) } } //添加查询参数 Get|Post private fun injectQueryParmas(request: Request?, requestBuilder: Request.Builder) { if (queryParamsMap.isNotEmpty()) { injectParamsIntoUrl( request!!.url().newBuilder(), requestBuilder, queryParamsMap ) } } /** * 注入公共参数到Url中,储存在requestBuilder中 */ private fun injectParamsIntoUrl( httpUrlBuilder: HttpUrl.Builder, requestBuilder: Request.Builder, paramsMap: Map<String, String> ){ if (paramsMap.isNotEmpty()) { val iterator: Iterator<*> = paramsMap.entries.iterator() while (iterator.hasNext()) { val entry = iterator.next() as Map.Entry<*, *> httpUrlBuilder.addQueryParameter( entry.key as String, entry.value as String ) } requestBuilder.url(httpUrlBuilder.build()) } } /** * 确认是否是 post 请求 * @param request 发出的请求 * @return true 需要注入公共参数 */ private fun canInjectIntoBody(request: Request?): Boolean { if (request == null) { return false } if (!TextUtils.equals(request.method(), "POST")) { return false } val body = request.body() ?: return false val mediaType = body.contentType() ?: return false return TextUtils.equals(mediaType.subtype(), "x-www-form-urlencoded") } private fun bodyToString(request: RequestBody?): String { return try { val buffer = Buffer() request?.writeTo(buffer) buffer.readUtf8() } catch (e: IOException) { "did not work" } } // <editor-fold defaultstate="collapsed" desc="对外提供的Builder构造器"> class Builder { private var interceptor: CommonParamsInterceptor = CommonParamsInterceptor() // <editor-fold defaultstate="collapsed" desc="添加公共参数到 post 消息体"> fun addPostParam(key: String, value: String): Builder { interceptor.postParamsMap[key] = value return this } fun addPostParamsMap(paramsMap: Map<String, String>): Builder { interceptor.postParamsMap.putAll(paramsMap) return this } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="添加公共参数到消息头"> fun addHeaderParam(key: String?,value: String?): Builder { interceptor.headerParamsMap[key!!] = value!! return this } fun addHeaderParamsMap(headerParamsMap: Map<String, String>) : Builder { interceptor.headerParamsMap.putAll(headerParamsMap) return this } fun addHeaderLine(headerLine: String): Builder { val index = headerLine.indexOf(":") require(index != -1) { "Unexpected header: $headerLine" } interceptor.headerLinesList.add(headerLine) return this } fun addHeaderLinesList(headerLinesList: List<String>): Builder { for (headerLine in headerLinesList) { val index = headerLine.indexOf(":") require(index != -1) { "Unexpected header: $headerLine" } interceptor.headerLinesList.add(headerLine) } return this } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="添加公共参数到URL"> fun addQueryParam(key: String, value: String): Builder { interceptor.queryParamsMap[key] = value return this } fun addQueryParamsMap( queryParamsMap: Map<String, String>): Builder { interceptor.queryParamsMap.putAll(queryParamsMap) return this } // </editor-fold> fun build(): CommonParamsInterceptor { return interceptor } } // </editor-fold> }
gpl-2.0
56f56fa8d735d9af373a5161e8d820cf
31.43662
91
0.579618
4.790569
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasFqNameIndex.kt
1
1118
// 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.stubindex import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StubIndex import com.intellij.psi.stubs.StubIndexKey import org.jetbrains.kotlin.psi.KtTypeAlias class KotlinTopLevelTypeAliasFqNameIndex : StringStubIndexExtension<KtTypeAlias>() { override fun getKey(): StubIndexKey<String, KtTypeAlias> = KEY override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> = StubIndex.getElements<String, KtTypeAlias>( KEY, s, project, scope, KtTypeAlias::class.java ) companion object { val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelTypeAliasFqNameIndex::class.java) val INSTANCE = KotlinTopLevelTypeAliasFqNameIndex() @JvmStatic fun getInstance() = INSTANCE } }
apache-2.0
6c88a812af667067dd6715eca81fa23d
37.551724
158
0.754025
4.86087
false
false
false
false
siosio/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageUastVisitor.kt
2
18361
// 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.codeInspection.apiUsage import com.intellij.lang.java.JavaLanguage import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.uast.UastVisitorAdapter import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor /** * Non-recursive UAST visitor that detects usages of APIs in source code of UAST-supporting languages * and reports them via [ApiUsageProcessor] interface. */ @ApiStatus.Experimental open class ApiUsageUastVisitor(private val apiUsageProcessor: ApiUsageProcessor) : AbstractUastNonRecursiveVisitor() { companion object { @JvmStatic fun createPsiElementVisitor(apiUsageProcessor: ApiUsageProcessor): PsiElementVisitor = UastVisitorAdapter(ApiUsageUastVisitor(apiUsageProcessor), true) } override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean { if (maybeProcessReferenceInsideImportStatement(node)) { return true } if (maybeProcessJavaModuleReference(node)) { return true } if (isMethodReferenceOfCallExpression(node) || isNewArrayClassReference(node) || isMethodReferenceOfCallableReferenceExpression(node) || isSelectorOfQualifiedReference(node) ) { return true } if (isSuperOrThisCall(node)) { return true } val resolved = node.resolve() if (resolved is PsiMethod) { if (isClassReferenceInConstructorInvocation(node) || isClassReferenceInKotlinSuperClassConstructor(node)) { /* Suppose a code: ``` object : SomeClass(42) { } or new SomeClass(42) ``` with USimpleNameReferenceExpression pointing to `SomeClass`. We want ApiUsageProcessor to notice two events: 1) reference to `SomeClass` and 2) reference to `SomeClass(int)` constructor. But Kotlin UAST resolves this simple reference to the PSI constructor of the class SomeClass. So we resolve it manually to the class because the constructor will be handled separately in "visitObjectLiteralExpression" or "visitCallExpression". */ val resolvedClass = resolved.containingClass if (resolvedClass != null) { apiUsageProcessor.processReference(node, resolvedClass, null) } return true } } if (resolved is PsiModifierListOwner) { apiUsageProcessor.processReference(node, resolved, null) return true } if (resolved == null) { /* * KT-30522 UAST for Kotlin: reference to annotation parameter resolves to null. */ val psiReferences = node.sourcePsi?.references.orEmpty() for (psiReference in psiReferences) { val target = psiReference.resolve()?.toUElement()?.javaPsi as? PsiAnnotationMethod if (target != null) { apiUsageProcessor.processReference(node, target, null) return true } } } return true } override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean { if (maybeProcessReferenceInsideImportStatement(node)) { return true } if (node.sourcePsi is PsiMethodCallExpression || node.selector is UCallExpression) { //UAST for Java produces UQualifiedReferenceExpression for both PsiMethodCallExpression and PsiReferenceExpression inside it //UAST for Kotlin produces UQualifiedReferenceExpression with UCallExpression as selector return true } var resolved = node.resolve() if (resolved == null) { resolved = node.selector.tryResolve() } if (resolved is PsiModifierListOwner) { apiUsageProcessor.processReference(node.selector, resolved, node.receiver) } return true } private fun isKotlin(node: UElement): Boolean { val sourcePsi = node.sourcePsi ?: return false return sourcePsi.language.id.contains("kotlin", true) } override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean { /* * KT-31181: Kotlin UAST: UCallableReferenceExpression.referenceNameElement is always null. */ fun workaroundKotlinGetReferenceNameElement(node: UCallableReferenceExpression): UElement? { if (isKotlin(node)) { val sourcePsi = node.sourcePsi if (sourcePsi != null) { val children = sourcePsi.children if (children.size == 2) { return children[1].toUElement() } } } return null } val resolve = node.resolve() if (resolve is PsiModifierListOwner) { val sourceNode = node.referenceNameElement ?: workaroundKotlinGetReferenceNameElement(node) ?: node apiUsageProcessor.processReference(sourceNode, resolve, node.qualifierExpression) //todo support this for other JVM languages val javaMethodReference = node.sourcePsi as? PsiMethodReferenceExpression if (javaMethodReference != null) { //a reference to the functional interface will be added by compiler val resolved = PsiUtil.resolveGenericsClassInType(javaMethodReference.functionalInterfaceType).element if (resolved != null) { apiUsageProcessor.processReference(node, resolved, null) } } } return true } override fun visitCallExpression(node: UCallExpression): Boolean { if (node.sourcePsi is PsiExpressionStatement) { //UAST for Java generates UCallExpression for PsiExpressionStatement and PsiMethodCallExpression inside it. return true } val psiMethod = node.resolve() val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node if (psiMethod != null) { val containingClass = psiMethod.containingClass if (psiMethod.isConstructor) { if (containingClass != null) { apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, null) } } else { apiUsageProcessor.processReference(sourceNode, psiMethod, node.receiver) } return true } if (node.kind == UastCallKind.CONSTRUCTOR_CALL) { //Java does not resolve constructor for subclass constructor's "super()" statement // if the superclass has the default constructor, which is not declared in source code and lacks PsiMethod. val superClass = node.getContainingUClass()?.javaPsi?.superClass ?: return true apiUsageProcessor.processConstructorInvocation(sourceNode, superClass, null, null) return true } val classReference = node.classReference if (classReference != null) { val resolvedClass = classReference.resolve() as? PsiClass if (resolvedClass != null) { if (node.kind == UastCallKind.CONSTRUCTOR_CALL) { val emptyConstructor = resolvedClass.constructors.find { it.parameterList.isEmpty } apiUsageProcessor.processConstructorInvocation(sourceNode, resolvedClass, emptyConstructor, null) } else { apiUsageProcessor.processReference(sourceNode, resolvedClass, node.receiver) } } return true } return true } override fun visitObjectLiteralExpression(node: UObjectLiteralExpression): Boolean { val psiMethod = node.resolve() val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node.declaration.uastSuperTypes.firstOrNull() ?: node if (psiMethod != null) { val containingClass = psiMethod.containingClass if (psiMethod.isConstructor) { if (containingClass != null) { apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, node.declaration) } } } else { maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode, node.declaration) } return true } override fun visitElement(node: UElement): Boolean { if (node is UNamedExpression) { //IDEA-209279: UAstVisitor lacks a hook for UNamedExpression //KT-30522: Kotlin does not generate UNamedExpression for annotation's parameters. processNamedExpression(node) return true } return super.visitElement(node) } override fun visitClass(node: UClass): Boolean { val uastAnchor = node.uastAnchor if (uastAnchor == null || node is UAnonymousClass || node.javaPsi is PsiTypeParameter) { return true } maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(uastAnchor, node) return true } override fun visitMethod(node: UMethod): Boolean { if (node.isConstructor) { checkImplicitCallOfSuperEmptyConstructor(node) } else { checkMethodOverriding(node) } return true } override fun visitLambdaExpression(node: ULambdaExpression): Boolean { val explicitClassReference = (node.uastParent as? UCallExpression)?.classReference if (explicitClassReference == null) { //a reference to the functional interface will be added by compiler val resolved = PsiUtil.resolveGenericsClassInType(node.functionalInterfaceType).element if (resolved != null) { apiUsageProcessor.processReference(node, resolved, null) } } return true } private fun maybeProcessJavaModuleReference(node: UElement): Boolean { val sourcePsi = node.sourcePsi if (sourcePsi is PsiJavaModuleReferenceElement) { val reference = sourcePsi.reference val target = reference?.resolve() if (target != null) { apiUsageProcessor.processJavaModuleReference(reference, target) } return true } return false } private fun maybeProcessReferenceInsideImportStatement(node: UReferenceExpression): Boolean { if (isInsideImportStatement(node)) { if (isKotlin(node)) { /* UAST for Kotlin 1.3.30 import statements have bugs. KT-30546: some references resolve to nulls. KT-30957: simple references for members resolve incorrectly to class declaration, not to the member declaration Therefore, we have to fallback to base PSI for Kotlin references. */ val resolved = node.sourcePsi?.reference?.resolve() val target = (resolved?.toUElement()?.javaPsi ?: resolved) as? PsiModifierListOwner if (target != null) { apiUsageProcessor.processImportReference(node, target) } } else { val resolved = node.resolve() as? PsiModifierListOwner if (resolved != null) { apiUsageProcessor.processImportReference(node.referenceNameElement ?: node, resolved) } } return true } return false } private fun isInsideImportStatement(node: UElement): Boolean { val sourcePsi = node.sourcePsi if (sourcePsi != null && sourcePsi.language == JavaLanguage.INSTANCE) { return PsiTreeUtil.getParentOfType(sourcePsi, PsiImportStatementBase::class.java) != null } return sourcePsi.findContaining(UImportStatement::class.java) != null } private fun maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode: UElement, subclassDeclaration: UClass) { val instantiatedClass = subclassDeclaration.javaPsi.superClass ?: return val subclassHasExplicitConstructor = subclassDeclaration.methods.any { it.isConstructor } val emptyConstructor = instantiatedClass.constructors.find { it.parameterList.isEmpty } if (subclassDeclaration is UAnonymousClass || !subclassHasExplicitConstructor) { apiUsageProcessor.processConstructorInvocation(sourceNode, instantiatedClass, emptyConstructor, subclassDeclaration) } } private fun processNamedExpression(node: UNamedExpression) { val sourcePsi = node.sourcePsi val annotationMethod = sourcePsi?.reference?.resolve() as? PsiAnnotationMethod if (annotationMethod != null) { val sourceNode = (sourcePsi as? PsiNameValuePair)?.nameIdentifier?.toUElement() ?: node apiUsageProcessor.processReference(sourceNode, annotationMethod, null) } } private fun checkImplicitCallOfSuperEmptyConstructor(constructor: UMethod) { val containingUClass = constructor.getContainingUClass() ?: return val superClass = containingUClass.javaPsi.superClass ?: return val uastBody = constructor.uastBody val uastAnchor = constructor.uastAnchor if (uastAnchor != null && isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(uastBody)) { val emptyConstructor = superClass.constructors.find { it.parameterList.isEmpty } apiUsageProcessor.processConstructorInvocation(uastAnchor, superClass, emptyConstructor, null) } } private fun isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(constructorBody: UExpression?): Boolean { if (constructorBody == null || constructorBody is UBlockExpression && constructorBody.expressions.isEmpty()) { //Empty constructor body => implicit super() call. return true } val firstExpression = (constructorBody as? UBlockExpression)?.expressions?.firstOrNull() ?: constructorBody if (firstExpression !is UCallExpression) { //First expression is not super() => the super() is implicit. return true } if (firstExpression.valueArgumentCount > 0) { //Invocation of non-empty super(args) constructor. return false } val methodName = firstExpression.methodIdentifier?.name ?: firstExpression.methodName return methodName != "super" && methodName != "this" } private fun checkMethodOverriding(node: UMethod) { val method = node.javaPsi val superMethods = method.findSuperMethods(true) for (superMethod in superMethods) { apiUsageProcessor.processMethodOverriding(node, superMethod) } } /** * UAST for Kotlin generates UAST tree with "UnknownKotlinExpression (CONSTRUCTOR_CALLEE)" for the following expressions: * 1) an object literal expression: `object : BaseClass() { ... }` * 2) a super class constructor invocation `class Derived : BaseClass(42) { ... }` * * * ``` * UObjectLiteralExpression * UnknownKotlinExpression (CONSTRUCTOR_CALLEE) * UTypeReferenceExpression (BaseClass) * USimpleNameReferenceExpression (BaseClass) * ``` * * and * * ``` * UCallExpression (kind = CONSTRUCTOR_CALL) * UnknownKotlinExpression (CONSTRUCTOR_CALLEE) * UTypeReferenceExpression (BaseClass) * USimpleNameReferenceExpression (BaseClass) * ``` * * This method checks if the given simple reference points to the `BaseClass` part, * which is treated by Kotlin UAST as a reference to `BaseClass'` constructor, not to the `BaseClass` itself. */ private fun isClassReferenceInKotlinSuperClassConstructor(expression: USimpleNameReferenceExpression): Boolean { val parent1 = expression.uastParent val parent2 = parent1?.uastParent val parent3 = parent2?.uastParent return parent1 is UTypeReferenceExpression && parent2 != null && parent2.asLogString().contains("CONSTRUCTOR_CALLEE") && (parent3 is UObjectLiteralExpression || parent3 is UCallExpression && parent3.kind == UastCallKind.CONSTRUCTOR_CALL) } private fun isSelectorOfQualifiedReference(expression: USimpleNameReferenceExpression): Boolean { val qualifiedReference = expression.uastParent as? UQualifiedReferenceExpression ?: return false return haveSameSourceElement(expression, qualifiedReference.selector) } private fun isNewArrayClassReference(simpleReference: USimpleNameReferenceExpression): Boolean { val callExpression = simpleReference.uastParent as? UCallExpression ?: return false return callExpression.kind == UastCallKind.NEW_ARRAY_WITH_DIMENSIONS } private fun isSuperOrThisCall(simpleReference: USimpleNameReferenceExpression): Boolean { val callExpression = simpleReference.uastParent as? UCallExpression ?: return false return callExpression.kind == UastCallKind.CONSTRUCTOR_CALL && (callExpression.methodIdentifier?.name == "super" || callExpression.methodIdentifier?.name == "this") } private fun isClassReferenceInConstructorInvocation(simpleReference: USimpleNameReferenceExpression): Boolean { if (isSuperOrThisCall(simpleReference)) { return false } val callExpression = simpleReference.uastParent as? UCallExpression ?: return false if (callExpression.kind != UastCallKind.CONSTRUCTOR_CALL) { return false } val classReferenceNameElement = callExpression.classReference?.referenceNameElement if (classReferenceNameElement != null) { return haveSameSourceElement(classReferenceNameElement, simpleReference.referenceNameElement) } return callExpression.resolve()?.name == simpleReference.resolvedName } private fun isMethodReferenceOfCallExpression(expression: USimpleNameReferenceExpression): Boolean { val callExpression = expression.uastParent as? UCallExpression ?: return false if (callExpression.kind != UastCallKind.METHOD_CALL) { return false } val expressionNameElement = expression.referenceNameElement val methodIdentifier = callExpression.methodIdentifier return methodIdentifier != null && haveSameSourceElement(expressionNameElement, methodIdentifier) } private fun isMethodReferenceOfCallableReferenceExpression(expression: USimpleNameReferenceExpression): Boolean { val callableReferenceExpression = expression.uastParent as? UCallableReferenceExpression ?: return false if (haveSameSourceElement(callableReferenceExpression.referenceNameElement, expression)) { return true } return expression.identifier == callableReferenceExpression.callableName } private fun haveSameSourceElement(element1: UElement?, element2: UElement?): Boolean { if (element1 == null || element2 == null) return false val sourcePsi1 = element1.sourcePsi return sourcePsi1 != null && sourcePsi1 == element2.sourcePsi } }
apache-2.0
faed13dafbcd5bd2e76ca33223a95787
39.893096
140
0.718588
5.661733
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt
4
5042
// 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.createFromUsage.createClass import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeIntersector import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.ifEmpty import java.util.* object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory<KtUserType>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtUserType? { return diagnostic.psiElement.findParentOfType(strict = false) } override fun getPossibleClassKinds(element: KtUserType, diagnostic: Diagnostic): List<ClassKind> { val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return Collections.emptyList() val isQualifier = (element.parent as? KtUserType)?.let { it.qualifier == element } ?: false val typeReference = element.parent as? KtTypeReference val isUpperBound = typeReference?.getParentOfTypeAndBranch<KtTypeParameter> { extendsBound } != null || typeReference?.getParentOfTypeAndBranch<KtTypeConstraint> { boundTypeReference } != null return when (typeRefParent) { is KtSuperTypeEntry -> listOfNotNull( ClassKind.INTERFACE, if (typeRefParent.classExpected()) ClassKind.PLAIN_CLASS else null ) else -> ClassKind.values().filter { val noTypeArguments = element.typeArgumentsAsTypes.isEmpty() when (it) { ClassKind.OBJECT -> noTypeArguments && isQualifier ClassKind.ANNOTATION_CLASS -> noTypeArguments && !isQualifier && !isUpperBound ClassKind.ENUM_ENTRY -> false ClassKind.ENUM_CLASS -> noTypeArguments && !isUpperBound else -> true } } } } private fun KtSuperTypeEntry.classExpected(): Boolean { val containingClass = getStrictParentOfType<KtClass>() ?: return false return !containingClass.hasModifier(KtTokens.ANNOTATION_KEYWORD) && !containingClass.hasModifier(KtTokens.ENUM_KEYWORD) && !containingClass.hasModifier(KtTokens.INLINE_KEYWORD) } private fun getExpectedUpperBound(element: KtUserType, context: BindingContext): KotlinType? { val projection = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = projection.parent as? KtTypeArgumentList ?: return null val index = argumentList.arguments.indexOf(projection) val callElement = argumentList.parent as? KtCallElement ?: return null val resolvedCall = callElement.getResolvedCall(context) ?: return null val typeParameterDescriptor = resolvedCall.candidateDescriptor.typeParameters.getOrNull(index) ?: return null if (typeParameterDescriptor.upperBounds.isEmpty()) return null return TypeIntersector.getUpperBoundsAsType(typeParameterDescriptor) } override fun extractFixData(element: KtUserType, diagnostic: Diagnostic): ClassInfo? { val name = element.referenceExpression?.getReferencedName() ?: return null val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return null val (context, module) = element.analyzeAndGetResult() val qualifier = element.qualifier?.referenceExpression val qualifierDescriptor = qualifier?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, qualifier != null, qualifierDescriptor).ifEmpty { return null } val expectedUpperBound = getExpectedUpperBound(element, context) val anyType = module.builtIns.anyType return ClassInfo( name = name, targetParents = targetParents, expectedTypeInfo = expectedUpperBound?.let { TypeInfo.ByType(it, Variance.INVARIANT) } ?: TypeInfo.Empty, open = typeRefParent is KtSuperTypeEntry && typeRefParent.classExpected(), typeArguments = element.typeArgumentsAsTypes.map { if (it != null) TypeInfo(it, Variance.INVARIANT) else TypeInfo(anyType, Variance.INVARIANT) } ) } }
apache-2.0
1bb0e968ab14177fbdefb90bdeab0aee
51.520833
185
0.716977
5.492375
false
false
false
false
alisle/Penella
src/main/java/org/penella/index/bstree/SubjectPropertyObjectBSTreeIndex.kt
1
1404
package org.penella.index.bstree import org.penella.index.IndexType import org.penella.messages.IndexResultSet import org.penella.structures.triples.HashTriple import org.penella.structures.triples.TripleType /** * 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 11/29/16. */ class SubjectPropertyObjectBSTreeIndex() : BSTreeIndex(IndexType.SPO) { override fun add(triple: HashTriple) = addTriple(triple.hashSubject, triple.hashProperty, triple.hashObj) override fun get(first: TripleType, second: TripleType, firstValue: Long, secondValue: Long) : IndexResultSet = if(first == TripleType.SUBJECT && second == TripleType.PROPERTY) getResults(firstValue, secondValue) else throw IncorrectIndexRequest() override fun get(first: TripleType, value: Long ) : IndexResultSet = if(first == TripleType.SUBJECT) getResults(value) else throw IncorrectIndexRequest() }
apache-2.0
3081b351a9a677ba40b84bbda56ba83f
49.178571
252
0.773504
4.166172
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/ParagraphStyle.kt
3
15590
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.text.style.Hyphens import androidx.compose.ui.text.style.LineBreak import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDirection import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.text.style.lerp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.isUnspecified private val DefaultLineHeight = TextUnit.Unspecified /** * Paragraph styling configuration for a paragraph. The difference between [SpanStyle] and * `ParagraphStyle` is that, `ParagraphStyle` can be applied to a whole [Paragraph] while * [SpanStyle] can be applied at the character level. * Once a portion of the text is marked with a `ParagraphStyle`, that portion will be separated from * the remaining as if a line feed character was added. * * @sample androidx.compose.ui.text.samples.ParagraphStyleSample * @sample androidx.compose.ui.text.samples.ParagraphStyleAnnotatedStringsSample * * @param textAlign The alignment of the text within the lines of the paragraph. * @param textDirection The algorithm to be used to resolve the final text direction: * Left To Right or Right To Left. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * @param textIndent The indentation of the paragraph. * @param platformStyle Platform specific [ParagraphStyle] parameters. * @param lineHeightStyle the configuration for line height such as vertical alignment of the * line, whether to apply additional space as a result of line height to top of first line top and * bottom of last line. The configuration is applied only when a [lineHeight] is defined. * When null, [LineHeightStyle.Default] is used. * @param lineBreak The line breaking configuration for the text. * @param hyphens The configuration of hyphenation. * * @see Paragraph * @see AnnotatedString * @see SpanStyle * @see TextStyle */ @Immutable class ParagraphStyle @ExperimentalTextApi constructor( val textAlign: TextAlign? = null, val textDirection: TextDirection? = null, val lineHeight: TextUnit = TextUnit.Unspecified, val textIndent: TextIndent? = null, val platformStyle: PlatformParagraphStyle? = null, val lineHeightStyle: LineHeightStyle? = null, @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalTextApi @property:ExperimentalTextApi val lineBreak: LineBreak? = null, @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalTextApi @property:ExperimentalTextApi val hyphens: Hyphens? = null ) { /** * Paragraph styling configuration for a paragraph. The difference between [SpanStyle] and * `ParagraphStyle` is that, `ParagraphStyle` can be applied to a whole [Paragraph] while * [SpanStyle] can be applied at the character level. * Once a portion of the text is marked with a `ParagraphStyle`, that portion will be separated from * the remaining as if a line feed character was added. * * @sample androidx.compose.ui.text.samples.ParagraphStyleSample * @sample androidx.compose.ui.text.samples.ParagraphStyleAnnotatedStringsSample * * @param textAlign The alignment of the text within the lines of the paragraph. * @param textDirection The algorithm to be used to resolve the final text direction: * Left To Right or Right To Left. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * @param textIndent The indentation of the paragraph. * * @see Paragraph * @see AnnotatedString * @see SpanStyle * @see TextStyle */ constructor( textAlign: TextAlign? = null, textDirection: TextDirection? = null, lineHeight: TextUnit = TextUnit.Unspecified, textIndent: TextIndent? = null ) : this( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent, platformStyle = null, lineHeightStyle = null ) /** * Paragraph styling configuration for a paragraph. The difference between [SpanStyle] and * `ParagraphStyle` is that, `ParagraphStyle` can be applied to a whole [Paragraph] while * [SpanStyle] can be applied at the character level. * Once a portion of the text is marked with a `ParagraphStyle`, that portion will be separated from * the remaining as if a line feed character was added. * * @sample androidx.compose.ui.text.samples.ParagraphStyleSample * @sample androidx.compose.ui.text.samples.ParagraphStyleAnnotatedStringsSample * * @param textAlign The alignment of the text within the lines of the paragraph. * @param textDirection The algorithm to be used to resolve the final text direction: * Left To Right or Right To Left. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * @param textIndent The indentation of the paragraph. * @param platformStyle Platform specific [ParagraphStyle] parameters. * @param lineHeightStyle the configuration for line height such as vertical alignment of the * line, whether to apply additional space as a result of line height to top of first line top and * bottom of last line. The configuration is applied only when a [lineHeight] is defined. * When null, [LineHeightStyle.Default] is used. * * @see Paragraph * @see AnnotatedString * @see SpanStyle * @see TextStyle */ // TODO(b/245939557, b/246715337): Deprecate this when LineBreak and Hyphens are stable @OptIn(ExperimentalTextApi::class) constructor( textAlign: TextAlign? = null, textDirection: TextDirection? = null, lineHeight: TextUnit = TextUnit.Unspecified, textIndent: TextIndent? = null, platformStyle: PlatformParagraphStyle? = null, lineHeightStyle: LineHeightStyle? = null ) : this( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent, platformStyle = platformStyle, lineHeightStyle = lineHeightStyle, lineBreak = null, hyphens = null ) init { if (lineHeight != TextUnit.Unspecified) { // Since we are checking if it's negative, no need to convert Sp into Px at this point. check(lineHeight.value >= 0f) { "lineHeight can't be negative (${lineHeight.value})" } } } /** * Returns a new paragraph style that is a combination of this style and the given [other] * style. * * If the given paragraph style is null, returns this paragraph style. */ @OptIn(ExperimentalTextApi::class) @Stable fun merge(other: ParagraphStyle? = null): ParagraphStyle { if (other == null) return this return ParagraphStyle( lineHeight = if (other.lineHeight.isUnspecified) { this.lineHeight } else { other.lineHeight }, textIndent = other.textIndent ?: this.textIndent, textAlign = other.textAlign ?: this.textAlign, textDirection = other.textDirection ?: this.textDirection, platformStyle = mergePlatformStyle(other.platformStyle), lineHeightStyle = other.lineHeightStyle ?: this.lineHeightStyle, lineBreak = other.lineBreak ?: this.lineBreak, hyphens = other.hyphens ?: this.hyphens ) } private fun mergePlatformStyle(other: PlatformParagraphStyle?): PlatformParagraphStyle? { if (platformStyle == null) return other if (other == null) return platformStyle return platformStyle.merge(other) } /** * Plus operator overload that applies a [merge]. */ @Stable operator fun plus(other: ParagraphStyle): ParagraphStyle = this.merge(other) @OptIn(ExperimentalTextApi::class) fun copy( textAlign: TextAlign? = this.textAlign, textDirection: TextDirection? = this.textDirection, lineHeight: TextUnit = this.lineHeight, textIndent: TextIndent? = this.textIndent ): ParagraphStyle { return ParagraphStyle( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent, platformStyle = this.platformStyle, lineHeightStyle = this.lineHeightStyle, lineBreak = this.lineBreak, hyphens = this.hyphens ) } // TODO(b/246715337, b/245939557): Deprecate this when Hyphens and LineBreak are stable @OptIn(ExperimentalTextApi::class) fun copy( textAlign: TextAlign? = this.textAlign, textDirection: TextDirection? = this.textDirection, lineHeight: TextUnit = this.lineHeight, textIndent: TextIndent? = this.textIndent, platformStyle: PlatformParagraphStyle? = this.platformStyle, lineHeightStyle: LineHeightStyle? = this.lineHeightStyle ): ParagraphStyle { return ParagraphStyle( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent, platformStyle = platformStyle, lineHeightStyle = lineHeightStyle, lineBreak = this.lineBreak, hyphens = this.hyphens ) } @ExperimentalTextApi fun copy( textAlign: TextAlign? = this.textAlign, textDirection: TextDirection? = this.textDirection, lineHeight: TextUnit = this.lineHeight, textIndent: TextIndent? = this.textIndent, platformStyle: PlatformParagraphStyle? = this.platformStyle, lineHeightStyle: LineHeightStyle? = this.lineHeightStyle, lineBreak: LineBreak? = this.lineBreak, hyphens: Hyphens? = this.hyphens ): ParagraphStyle { return ParagraphStyle( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent, platformStyle = platformStyle, lineHeightStyle = lineHeightStyle, lineBreak = lineBreak, hyphens = hyphens ) } @OptIn(ExperimentalTextApi::class) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ParagraphStyle) return false if (textAlign != other.textAlign) return false if (textDirection != other.textDirection) return false if (lineHeight != other.lineHeight) return false if (textIndent != other.textIndent) return false if (platformStyle != other.platformStyle) return false if (lineHeightStyle != other.lineHeightStyle) return false if (lineBreak != other.lineBreak) return false if (hyphens != other.hyphens) return false return true } @OptIn(ExperimentalTextApi::class) override fun hashCode(): Int { var result = textAlign?.hashCode() ?: 0 result = 31 * result + (textDirection?.hashCode() ?: 0) result = 31 * result + lineHeight.hashCode() result = 31 * result + (textIndent?.hashCode() ?: 0) result = 31 * result + (platformStyle?.hashCode() ?: 0) result = 31 * result + (lineHeightStyle?.hashCode() ?: 0) result = 31 * result + (lineBreak?.hashCode() ?: 0) result = 31 * result + (hyphens?.hashCode() ?: 0) return result } @OptIn(ExperimentalTextApi::class) override fun toString(): String { return "ParagraphStyle(" + "textAlign=$textAlign, " + "textDirection=$textDirection, " + "lineHeight=$lineHeight, " + "textIndent=$textIndent, " + "platformStyle=$platformStyle, " + "lineHeightStyle=$lineHeightStyle, " + "lineBreak=$lineBreak, " + "hyphens=$hyphens" + ")" } } /** * Interpolate between two [ParagraphStyle]s. * * This will not work well if the styles don't set the same fields. * * The [fraction] argument represents position on the timeline, with 0.0 meaning * that the interpolation has not started, returning [start] (or something * equivalent to [start]), 1.0 meaning that the interpolation has finished, * returning [stop] (or something equivalent to [stop]), and values in between * meaning that the interpolation is at the relevant point on the timeline * between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and * 1.0, so negative values and values greater than 1.0 are valid. */ @OptIn(ExperimentalTextApi::class) @Stable fun lerp(start: ParagraphStyle, stop: ParagraphStyle, fraction: Float): ParagraphStyle { return ParagraphStyle( textAlign = lerpDiscrete(start.textAlign, stop.textAlign, fraction), textDirection = lerpDiscrete( start.textDirection, stop.textDirection, fraction ), lineHeight = lerpTextUnitInheritable(start.lineHeight, stop.lineHeight, fraction), textIndent = lerp( start.textIndent ?: TextIndent.None, stop.textIndent ?: TextIndent.None, fraction ), platformStyle = lerpPlatformStyle(start.platformStyle, stop.platformStyle, fraction), lineHeightStyle = lerpDiscrete( start.lineHeightStyle, stop.lineHeightStyle, fraction ), lineBreak = lerpDiscrete(start.lineBreak, stop.lineBreak, fraction), hyphens = lerpDiscrete(start.hyphens, stop.hyphens, fraction) ) } private fun lerpPlatformStyle( start: PlatformParagraphStyle?, stop: PlatformParagraphStyle?, fraction: Float ): PlatformParagraphStyle? { if (start == null && stop == null) return null val startNonNull = start ?: PlatformParagraphStyle.Default val stopNonNull = stop ?: PlatformParagraphStyle.Default return lerp(startNonNull, stopNonNull, fraction) } @OptIn(ExperimentalTextApi::class) internal fun resolveParagraphStyleDefaults( style: ParagraphStyle, direction: LayoutDirection ) = ParagraphStyle( textAlign = style.textAlign ?: TextAlign.Start, textDirection = resolveTextDirection(direction, style.textDirection), lineHeight = if (style.lineHeight.isUnspecified) DefaultLineHeight else style.lineHeight, textIndent = style.textIndent ?: TextIndent.None, platformStyle = style.platformStyle, lineHeightStyle = style.lineHeightStyle, lineBreak = style.lineBreak ?: LineBreak.Simple, hyphens = style.hyphens ?: Hyphens.None )
apache-2.0
4de2c3b78cc04f4109776855695db6fc
39.811518
104
0.678833
4.957075
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/drafts/DraftRepository.kt
1
3273
package org.thoughtcrime.securesms.conversation.drafts import android.content.Context import android.net.Uri import android.text.Spannable import android.text.SpannableString import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.components.mention.MentionAnnotation import org.thoughtcrime.securesms.database.DraftDatabase import org.thoughtcrime.securesms.database.DraftDatabase.Drafts import org.thoughtcrime.securesms.database.MentionUtil import org.thoughtcrime.securesms.database.MmsSmsColumns import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.database.ThreadDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.Base64 import org.thoughtcrime.securesms.util.concurrent.SerialMonoLifoExecutor import java.util.concurrent.Executor class DraftRepository( private val context: Context = ApplicationDependencies.getApplication(), private val threadDatabase: ThreadDatabase = SignalDatabase.threads, private val draftDatabase: DraftDatabase = SignalDatabase.drafts, private val saveDraftsExecutor: Executor = SerialMonoLifoExecutor(SignalExecutors.BOUNDED) ) { fun deleteVoiceNoteDraftData(draft: DraftDatabase.Draft?) { if (draft != null) { SignalExecutors.BOUNDED.execute { BlobProvider.getInstance().delete(context, Uri.parse(draft.value).buildUpon().clearQuery().build()) } } } fun saveDrafts(recipient: Recipient, threadId: Long, distributionType: Int, drafts: Drafts) { saveDraftsExecutor.execute { if (drafts.isNotEmpty()) { val actualThreadId = if (threadId == -1L) { threadDatabase.getOrCreateThreadIdFor(recipient, distributionType) } else { threadId } draftDatabase.replaceDrafts(actualThreadId, drafts) threadDatabase.updateSnippet(actualThreadId, drafts.getSnippet(context), drafts.uriSnippet, System.currentTimeMillis(), MmsSmsColumns.Types.BASE_DRAFT_TYPE, true) } else if (threadId > 0) { threadDatabase.update(threadId, false) draftDatabase.clearDrafts(threadId) } } } fun loadDrafts(threadId: Long): Single<DatabaseDraft> { return Single.fromCallable { val drafts: Drafts = draftDatabase.getDrafts(threadId) val mentionsDraft = drafts.getDraftOfType(DraftDatabase.Draft.MENTION) var updatedText: Spannable? = null if (mentionsDraft != null) { val text = drafts.getDraftOfType(DraftDatabase.Draft.TEXT)!!.value val mentions = MentionUtil.bodyRangeListToMentions(context, Base64.decodeOrThrow(mentionsDraft.value)) val updated = MentionUtil.updateBodyAndMentionsWithDisplayNames(context, text, mentions) updatedText = SpannableString(updated.body) MentionAnnotation.setMentionAnnotations(updatedText, updated.mentions) } DatabaseDraft(drafts, updatedText) }.subscribeOn(Schedulers.io()) } data class DatabaseDraft(val drafts: Drafts, val updatedText: CharSequence?) }
gpl-3.0
a5126cad1232a2c0d19823ebb73b7fac
42.065789
170
0.776658
4.642553
false
false
false
false
GunoH/intellij-community
plugins/full-line/python/src/org/jetbrains/completion/full/line/python/formatters/ArgumentListFormatter.kt
2
1378
package org.jetbrains.completion.full.line.python.formatters import com.intellij.psi.PsiElement import com.jetbrains.python.psi.PyArgumentList import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyExpression import org.jetbrains.completion.full.line.language.ElementFormatter class ArgumentListFormatter : ElementFormatter { override fun condition(element: PsiElement): Boolean = element is PyArgumentList override fun filter(element: PsiElement): Boolean? = element is PyArgumentList override fun format(element: PsiElement): String { element as PyArgumentList return if (element.arguments.isEmpty()) { if (element.parent is PyClass) { "" } else { element.text } } else { handlePyArgumentList(element.arguments, element.text.last() == ',', element.closingParen != null) } } companion object { fun handlePyArgumentList(arguments: Array<PyExpression>, lastComma: Boolean = false, closed: Boolean = true): String { val text = StringBuilder("(") arguments.forEach { text.append(it.text).append(", ") } if (!lastComma) { text.delete(text.length - 2, text.length) } else { text.delete(text.length - 1, text.length) } if (closed) { text.append(")") } return text.toString() } } }
apache-2.0
d3888747a625d9331a34723f4f8fcb09
27.708333
122
0.667634
4.30625
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityParentListImpl.kt
2
6272
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId 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 org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityParentListImpl(val dataSource: AttachedEntityParentListData) : AttachedEntityParentList, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: AttachedEntityParentListData?) : ModifiableWorkspaceEntityBase<AttachedEntityParentList, AttachedEntityParentListData>( result), AttachedEntityParentList.Builder { constructor() : this(AttachedEntityParentListData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntityParentList is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field AttachedEntityParentList#data 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 AttachedEntityParentList if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override fun getEntityClass(): Class<AttachedEntityParentList> = AttachedEntityParentList::class.java } } class AttachedEntityParentListData : WorkspaceEntityData<AttachedEntityParentList>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<AttachedEntityParentList> { val modifiable = AttachedEntityParentListImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): AttachedEntityParentList { return getCached(snapshot) { val entity = AttachedEntityParentListImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntityParentList::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return AttachedEntityParentList(data, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityParentListData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityParentListData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
a92e0489e4b20948f9e0972cf50cbc6b
31.666667
143
0.73581
5.487314
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/highlighter/HtmlCacheManager.kt
4
2413
package org.intellij.plugins.markdown.extensions.common.highlighter import com.intellij.diagnostic.LoadingState import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.Project import com.intellij.openapi.project.processOpenedProjects import com.intellij.util.application import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil import java.lang.ref.SoftReference import java.util.concurrent.ConcurrentHashMap @Service internal class HtmlCacheManager { private data class CachedHtmlResult(val html: SoftReference<String>, var expires: Long) { data class HtmlResult(val html: String, val expires: Long) fun resolve(): HtmlResult? { return html.get()?.let { HtmlResult(it, expires) } } } private val values = ConcurrentHashMap<String, CachedHtmlResult>() fun obtainCacheKey(content: String, language: String): String { return MarkdownUtil.md5(content, language) } fun obtainCachedHtml(key: String): String? { val entry = values[key] val resolved = entry?.resolve() if (resolved != null) { entry.expires += expiration return resolved.html } cleanup() return null } fun cacheHtml(key: String, html: String) { val expires = System.currentTimeMillis() + expiration values[key] = CachedHtmlResult(SoftReference(html), expires) } fun cleanup() { val time = System.currentTimeMillis() val expired = values.filter { it.value.expires < time }.keys for (key in expired) { values.remove(key) } } fun invalidate() { values.clear() } internal class InvalidateHtmlCacheLafListener: LafManagerListener { override fun lookAndFeelChanged(source: LafManager) { if (!LoadingState.APP_STARTED.isOccurred) { return } application.serviceIfCreated<HtmlCacheManager>()?.invalidate() processOpenedProjects { project -> project.serviceIfCreated<HtmlCacheManager>()?.invalidate() } } } companion object { private const val expiration = 5 * 60 * 1000 fun getInstance(project: Project? = null): HtmlCacheManager { return when (project) { null -> service() else -> project.service() } } } }
apache-2.0
1c25b8deb2ceec68c37c9f72253c1713
28.426829
91
0.715292
4.387273
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/column/ColumnBasedTableAction.kt
3
4918
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.actions.column import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.editor.tables.actions.TableActionKeys import org.intellij.plugins.markdown.lang.MarkdownLanguage import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable /** * Base class for actions operating on a single column. * * Implementations should override performAction and update methods which take current editor, table and column index. * * Could be invoked from two contexts: normally from the editor or from the table inlay toolbar. * In the latter case current column index, and it's parent table are taken from the event's data context (see [TableActionKeys]). * If table and column index are not found in even's data context, then we consider that action was invoked normally * (e.g. from search everywhere) and compute column index and table element based on the position of current caret. * * See [ColumnBasedTableAction.Companion.findTableAndIndex]. */ internal abstract class ColumnBasedTableAction: AnAction() { override fun actionPerformed(event: AnActionEvent) { val editor = event.getRequiredData(CommonDataKeys.EDITOR) val file = event.getRequiredData(CommonDataKeys.PSI_FILE) val offset = event.getRequiredData(CommonDataKeys.CARET).offset val document = editor.document val (table, columnIndex) = findTableAndIndex(event, file, document, offset) requireNotNull(table) requireNotNull(columnIndex) performAction(editor, table, columnIndex) } @Suppress("DuplicatedCode") override fun update(event: AnActionEvent) { val project = event.getData(CommonDataKeys.PROJECT) val editor = event.getData(CommonDataKeys.EDITOR) val file = event.getData(CommonDataKeys.PSI_FILE) val offset = event.getData(CommonDataKeys.CARET)?.offset if (project == null || editor == null || file == null || offset == null || !file.language.isMarkdownLanguage()) { event.presentation.isEnabledAndVisible = false return } val document = editor.document val (table, columnIndex) = findTableAndIndex(event, file, document, offset) event.presentation.isEnabledAndVisible = table != null && columnIndex != null update(event, table, columnIndex) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } protected abstract fun performAction(editor: Editor, table: MarkdownTable, columnIndex: Int) protected open fun update(event: AnActionEvent, table: MarkdownTable?, columnIndex: Int?) = Unit private fun findTableAndIndex(event: AnActionEvent, file: PsiFile, document: Document, offset: Int): Pair<MarkdownTable?, Int?> { return findTableAndIndex(event, file, document, offset, ::findTable, ::findColumnIndex) } protected open fun findTable(file: PsiFile, document: Document, offset: Int): MarkdownTable? { return TableUtils.findTable(file, offset) } protected open fun findColumnIndex(file: PsiFile, document: Document, offset: Int): Int? { return TableUtils.findCellIndex(file, offset) } companion object { fun findTableAndIndex( event: AnActionEvent, file: PsiFile, document: Document, offset: Int, tableGetter: (PsiFile, Document, Int) -> MarkdownTable?, columnIndexGetter: (PsiFile, Document, Int) -> Int? ): Pair<MarkdownTable?, Int?> { val tableFromEvent = event.getData(TableActionKeys.ELEMENT)?.get() as? MarkdownTable val indexFromEvent = event.getData(TableActionKeys.COLUMN_INDEX) if (tableFromEvent != null && indexFromEvent != null) { return tableFromEvent to indexFromEvent } val table = tableGetter(file, document, offset)?.takeIf { it.isValid } val index = columnIndexGetter(file, document, offset) return table to index } fun findTableAndIndex(event: AnActionEvent, file: PsiFile, document: Document, offset: Int): Pair<MarkdownTable?, Int?> { return findTableAndIndex( event, file, document, offset, tableGetter = { file, document, offset -> TableUtils.findTable(file, offset) }, columnIndexGetter = { file, document, offset -> TableUtils.findCellIndex(file, offset) } ) } } }
apache-2.0
edf60b656dc334616dae90db8b514a2b
43.306306
158
0.740748
4.652791
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/hasNull6.kt
2
183
fun bar(i: Int, x: String?) { var str: String? = null <caret>if (i == 1) { str = null } else if (i == 2) { str = "2" } else { str = x } }
apache-2.0
d5283f1c3235c97f2e2f88ac7cb1b260
15.636364
29
0.377049
2.859375
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/CallFromPublicInlineFactory.kt
4
3502
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.util.parentOfTypes import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.jetbrains.kotlin.utils.addToStdlib.safeAs object CallFromPublicInlineFactory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val fixes = mutableListOf<IntentionAction>() val element = diagnostic.psiElement.safeAs<KtExpression>() ?: return fixes val (containingDeclaration, containingDeclarationName) = element.containingDeclaration() ?: return fixes when (diagnostic.factory) { Errors.NON_PUBLIC_CALL_FROM_PUBLIC_INLINE, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.warningFactory, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.errorFactory -> { val (declaration, declarationName, declarationVisibility) = element.referenceDeclaration() ?: return fixes fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, declarationVisibility)) fixes.add(ChangeVisibilityFix(declaration, declarationName, KtTokens.PUBLIC_KEYWORD)) if (!containingDeclaration.hasReifiedTypeParameter()) { fixes.add(RemoveModifierFix(containingDeclaration, KtTokens.INLINE_KEYWORD, isRedundant = false)) } } Errors.SUPER_CALL_FROM_PUBLIC_INLINE.warningFactory, Errors.SUPER_CALL_FROM_PUBLIC_INLINE.errorFactory -> { fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, KtTokens.INTERNAL_KEYWORD)) fixes.add(ChangeVisibilityFix(containingDeclaration, containingDeclarationName, KtTokens.PRIVATE_KEYWORD)) if (!containingDeclaration.hasReifiedTypeParameter()) { fixes.add(RemoveModifierFix(containingDeclaration, KtTokens.INLINE_KEYWORD, isRedundant = false)) } } } return fixes } private fun KtExpression.containingDeclaration(): Pair<KtCallableDeclaration, String>? { val declaration = parentOfTypes(KtNamedFunction::class, KtProperty::class) ?.safeAs<KtCallableDeclaration>() ?.takeIf { it.hasModifier(KtTokens.INLINE_KEYWORD) } ?: return null val name = declaration.name ?: return null return declaration to name } private fun KtExpression.referenceDeclaration(): Triple<KtDeclaration, String, KtModifierKeywordToken>? { val declaration = safeAs<KtNameReferenceExpression>()?.mainReference?.resolve().safeAs<KtDeclaration>() ?: return null val name = declaration.name ?: return null val visibility = declaration.visibilityModifierType() ?: return null return Triple(declaration, name, visibility) } private fun KtCallableDeclaration.hasReifiedTypeParameter() = typeParameters.any { it.hasModifier(KtTokens.REIFIED_KEYWORD) } }
apache-2.0
2cfd5cd46534bc92fd03055598dfd8f2
58.355932
158
0.728441
5.379416
false
false
false
false
GunoH/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/whole/HighlightWholeProjectPerformanceTest.kt
4
8143
// 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.perf.whole import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.perf.suite.DefaultProfile import org.jetbrains.kotlin.idea.perf.suite.EmptyProfile import org.jetbrains.kotlin.idea.perf.suite.suite import org.jetbrains.kotlin.idea.perf.util.* import org.jetbrains.kotlin.idea.performance.tests.utils.logMessage import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor import org.jetbrains.kotlin.idea.performance.tests.utils.relativePath import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners import org.junit.runner.RunWith import java.io.File import java.nio.file.Files @RunWith(JUnit3RunnerWithInners::class) class HighlightWholeProjectPerformanceTest : UsefulTestCase() { override fun setUp() { val allowedErrorDescription = setOf( "Unknown artifact type: war", "Unknown artifact type: exploded-war" ) ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(testRootDisposable) { errorDescription -> val description = errorDescription.description if (description !in allowedErrorDescription) { throw RuntimeException(description) } else { logMessage { "project loading error: '$description' at '${errorDescription.elementName}'" } } } } fun testHighlightAllKtFilesInProject() { val emptyProfile = System.getProperty("emptyProfile", "false")!!.toBoolean() val percentOfFiles = System.getProperty("files.percentOfFiles", "10")!!.toInt() val maxFilesPerPart = System.getProperty("files.maxFilesPerPart", "300")!!.toInt() val minFileSize = System.getProperty("files.minFileSize", "300")!!.toInt() val warmUpIterations = System.getProperty("iterations.warmup", "1")!!.toInt() val numberOfIterations = System.getProperty("iterations.number", "10")!!.toInt() val clearPsiCaches = System.getProperty("caches.clearPsi", "true")!!.toBoolean() val projectSpecs = projectSpecs() logMessage { "projectSpecs: $projectSpecs" } for (projectSpec in projectSpecs) { val projectName = projectSpec.name val projectPath = projectSpec.path val suiteName = listOfNotNull("allKtFilesIn", "emptyProfile".takeIf { emptyProfile }, projectName) .joinToString(separator = "-") suite(suiteName = suiteName) { app { ExpressionsOfTypeProcessor.prodMode() warmUpProject() with(config) { warmup = warmUpIterations iterations = numberOfIterations fastIterations = true } try { project(ExternalProject.autoOpenProject(projectPath), refresh = true) { profile(if (emptyProfile) EmptyProfile else DefaultProfile) val ktFiles = mutableSetOf<VirtualFile>() project.runReadActionInSmartMode { val projectFileIndex = ProjectFileIndex.getInstance(project) val modules = mutableSetOf<Module>() val ktFileProcessor = { ktFile: VirtualFile -> if (projectFileIndex.isInSourceContent(ktFile)) { ktFiles.add(ktFile) } true } FileTypeIndex.processFiles( KotlinFileType.INSTANCE, ktFileProcessor, GlobalSearchScope.projectScope(project) ) modules } logStatValue("number of kt files", ktFiles.size) val filesToProcess = limitedFiles( ktFiles, percentOfFiles = percentOfFiles, maxFilesPerPart = maxFilesPerPart, minFileSize = minFileSize ) logStatValue("limited number of kt files", filesToProcess.size) filesToProcess.forEach { logMessage { "${project.relativePath(it)} fileSize: ${Files.size(it.toNioPath())}" } } filesToProcess.forEachIndexed { idx, file -> logMessage { "${idx + 1} / ${filesToProcess.size} : ${project.relativePath(file)} fileSize: ${Files.size(file.toNioPath())}" } try { fixture(file).use { measure<List<HighlightInfo>>(it.fileName, clearCaches = clearPsiCaches) { test = { it.highlight() } } } } catch (e: Exception) { // nothing as it is already caught by perfTest } } } } catch (e: Exception) { e.printStackTrace() // nothing as it is already caught by perfTest } } } } } private fun limitedFiles( ktFiles: Collection<VirtualFile>, percentOfFiles: Int, maxFilesPerPart: Int, minFileSize: Int ): Collection<VirtualFile> { val sortedBySize = ktFiles .filter { Files.size(it.toNioPath()) > minFileSize } .map { it to Files.size(it.toNioPath()) }.sortedByDescending { it.second } val numberOfFiles = minOf((sortedBySize.size * percentOfFiles) / 100, maxFilesPerPart) val topFiles = sortedBySize.take(numberOfFiles).map { it.first } val midFiles = sortedBySize.take(sortedBySize.size / 2 + numberOfFiles / 2).takeLast(numberOfFiles).map { it.first } val lastFiles = sortedBySize.takeLast(numberOfFiles).map { it.first } return LinkedHashSet(topFiles + midFiles + lastFiles) } private fun projectSpecs(): List<ProjectSpec> { val projects = System.getProperty("performanceProjects") val specs = projects?.split(",")?.map { val idx = it.indexOf("=") if (idx <= 0) ProjectSpec(it, "../$it") else ProjectSpec(it.substring(0, idx), it.substring(idx + 1)) } ?: emptyList() specs.forEach { val path = File(it.path) check(path.exists() && path.isDirectory) { "Project `${it.name}` path ${path.absolutePath} does not exist or it is not a directory" } } return specs.takeIf { it.isNotEmpty() } ?: error("No projects specified, use `-DperformanceProjects=projectName`") } private data class ProjectSpec(val name: String, val path: String) }
apache-2.0
fd2ced97956bbf8bba62257fe3ed9f37
46.619883
158
0.552253
5.783381
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/PropertyUsageReplacementStrategy.kt
2
1230
// 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.codeInliner import org.jetbrains.kotlin.idea.references.ReferenceAccess import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtReferenceExpression class PropertyUsageReplacementStrategy(readReplacement: CodeToInline?, writeReplacement: CodeToInline?) : UsageReplacementStrategy { private val readReplacementStrategy = readReplacement?.let { CallableUsageReplacementStrategy(it, inlineSetter = false) } private val writeReplacementStrategy = writeReplacement?.let { CallableUsageReplacementStrategy(it, inlineSetter = true) } override fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? { return when (usage.readWriteAccess(useResolveForReadWrite = true)) { ReferenceAccess.READ -> readReplacementStrategy?.createReplacer(usage) ReferenceAccess.WRITE -> writeReplacementStrategy?.createReplacer(usage) ReferenceAccess.READ_WRITE -> null } } }
apache-2.0
80d03c468c3c6f432a7d20df11203bda
46.346154
158
0.765854
5.25641
false
false
false
false
xmartlabs/bigbang
core/src/main/java/com/xmartlabs/bigbang/core/module/PicassoModule.kt
2
1598
package com.xmartlabs.bigbang.core.module import android.content.Context import com.squareup.picasso.OkHttp3Downloader import com.squareup.picasso.Picasso import com.xmartlabs.bigbang.core.log.LoggerTree import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import timber.log.Timber import java.util.HashMap import javax.inject.Named import javax.inject.Singleton @Module open class PicassoModule { companion object { private const val LOGGER_KEY_URL = "url" private const val LOGGER_KEY_MESSAGE = "message" } @Provides @Singleton open fun providePicasso(picassoBuilder: Picasso.Builder): Picasso { val providePicasso = picassoBuilder.build() try { Picasso.setSingletonInstance(providePicasso) } catch (illegalStateException: IllegalStateException) { Timber.w(illegalStateException) } return providePicasso } @Provides @Singleton open fun providePicassoBuilder(loggerTree: LoggerTree, context: Context, downloader: OkHttp3Downloader) = Picasso.Builder(context) .downloader(downloader) .listener(getPicassoListener(loggerTree)) private fun getPicassoListener(loggerTree: LoggerTree) = Picasso.Listener { _, uri, exception -> val data = HashMap<String, String>() uri?.let { data.put(LOGGER_KEY_URL, it.toString()) } data.put(LOGGER_KEY_MESSAGE, "Picasso image load failed") loggerTree.log(data, exception) } @Provides @Singleton open fun provideOkHttpDownloader(@Named(OkHttpModule.Companion.CLIENT_PICASSO) client: OkHttpClient) = OkHttp3Downloader(client) }
apache-2.0
a8036ea42f5180a7b65b222a77937d46
29.730769
107
0.754693
4.205263
false
false
false
false
7449/Album
material/src/main/java/com/gallery/ui/material/finder/MaterialFinderAdapter.kt
1
4930
package com.gallery.ui.material.finder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.BaseAdapter import android.widget.FrameLayout import androidx.appcompat.widget.AppCompatTextView import androidx.appcompat.widget.ListPopupWindow import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import com.gallery.compat.activity.GalleryCompatActivity import com.gallery.compat.finder.GalleryFinderAdapter import com.gallery.core.entity.ScanEntity import com.gallery.ui.material.args.MaterialGalleryBundle import com.gallery.ui.material.databinding.MaterialGalleryItemFinderBinding class MaterialFinderAdapter( private val activity: GalleryCompatActivity, private val viewAnchor: View, private val uiGalleryBundle: MaterialGalleryBundle, private val finderListener: GalleryFinderAdapter.AdapterFinderListener ) : GalleryFinderAdapter, AdapterView.OnItemClickListener { private val finderAdapter: FinderAdapter = FinderAdapter(uiGalleryBundle) { finderEntity, container -> finderListener.onGalleryFinderThumbnails(finderEntity, container) } private val popupWindow: ListPopupWindow = ListPopupWindow(activity).apply { this.anchorView = viewAnchor this.width = uiGalleryBundle.listPopupWidth this.horizontalOffset = uiGalleryBundle.listPopupHorizontalOffset this.verticalOffset = uiGalleryBundle.listPopupVerticalOffset this.isModal = true this.setOnItemClickListener(this@MaterialFinderAdapter) this.setAdapter(finderAdapter) } init { activity.lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (source.lifecycle.currentState == Lifecycle.State.DESTROYED) { activity.lifecycle.removeObserver(this) if (popupWindow.isShowing) { popupWindow.dismiss() } } } }) } override fun show() { popupWindow.show() popupWindow.listView?.setBackgroundColor(uiGalleryBundle.finderItemBackground) } override fun hide() { popupWindow.dismiss() } override fun finderUpdate(finderList: ArrayList<ScanEntity>) { finderAdapter.updateFinder(finderList) } override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { finderListener.onGalleryAdapterItemClick(view, position, finderAdapter.getItem(position)) } private class FinderAdapter( private val uiGalleryBundle: MaterialGalleryBundle, private val displayFinder: (finderEntity: ScanEntity, container: FrameLayout) -> Unit ) : BaseAdapter() { private val list: ArrayList<ScanEntity> = arrayListOf() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val finderEntity: ScanEntity = getItem(position) val rootView: View = convertView ?: MaterialGalleryItemFinderBinding.inflate( LayoutInflater.from(parent.context), parent, false ).apply { this.root.tag = ViewHolder(this) }.root val viewHolder: ViewHolder = rootView.tag as ViewHolder viewHolder.appCompatTextView.setTextColor(uiGalleryBundle.finderItemTextColor) viewHolder.appCompatTextView.text = "%s".format(finderEntity.bucketDisplayName) viewHolder.appCompatTextViewCount.setTextColor(uiGalleryBundle.finderItemTextCountColor) viewHolder.appCompatTextViewCount.text = "%s".format(finderEntity.count.toString()) displayFinder.invoke(finderEntity, viewHolder.frameLayout) return rootView } override fun getItem(position: Int): ScanEntity = list[position] override fun getItemId(position: Int): Long = position.toLong() override fun getCount(): Int = list.size fun updateFinder(entities: ArrayList<ScanEntity>) { list.clear() list.addAll(entities) notifyDataSetChanged() } private class ViewHolder(viewBinding: MaterialGalleryItemFinderBinding) { val frameLayout: FrameLayout = viewBinding.ivGalleryFinderIcon val appCompatTextView: AppCompatTextView = viewBinding.tvGalleryFinderName val appCompatTextViewCount: AppCompatTextView = viewBinding.tvGalleryFinderFileCount } } }
mpl-2.0
30e8b709773b63d7c8e1bbf26bbda9d1
41.263158
100
0.675659
5.576923
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/favicon_grabber/src/main/kotlin/ch/rmy/favicongrabber/grabbers/ManifestGrabber.kt
1
2423
package ch.rmy.favicongrabber.grabbers import ch.rmy.favicongrabber.models.IconResult import ch.rmy.favicongrabber.models.ManifestRoot import ch.rmy.favicongrabber.utils.HTMLUtil import ch.rmy.favicongrabber.utils.HttpUtil import ch.rmy.favicongrabber.utils.createComparator import com.google.gson.Gson import com.google.gson.JsonParseException import com.google.gson.JsonSyntaxException import okhttp3.HttpUrl class ManifestGrabber( private val httpUtil: HttpUtil, ) : Grabber { override suspend fun grabIconsFrom(pageUrl: HttpUrl, preferredSize: Int): List<IconResult> { val pageContent = httpUtil.downloadIntoString(pageUrl) ?: return emptyList() val iconUrls = getManifestIcons(pageUrl, pageContent) ?.sortedWith( createComparator(preferredSize) { size } ) ?.mapNotNull { icon -> pageUrl.resolve(icon.src) } ?: return emptyList() val results = mutableListOf<IconResult>() for (iconUrl in iconUrls) { val file = httpUtil.downloadIntoFile(iconUrl) if (file != null) { results.add(IconResult(file)) if (results.size >= PREFERRED_NUMBER_OF_RESULTS) { break } } } return results } private fun getManifestIcons(pageUrl: HttpUrl, pageContent: String) = HTMLUtil.findLinkTags(pageContent, MANIFEST_REL_VALUES) .firstOrNull() ?.href ?.let(pageUrl::resolve) ?.let(httpUtil::downloadIntoString) ?.let(::parseManifest) ?.icons ?.filter { icon -> icon.type !in UNSUPPORTED_ICON_TYPES && icon.purpose !in UNSUPPORTED_ICON_PURPOSES } companion object { private val MANIFEST_REL_VALUES = setOf("manifest") private val UNSUPPORTED_ICON_TYPES = setOf("image/svg+xml") private val UNSUPPORTED_ICON_PURPOSES = setOf("monochrome") private const val PREFERRED_NUMBER_OF_RESULTS = 2 private fun parseManifest(manifestString: String): ManifestRoot? = try { Gson().fromJson(manifestString, ManifestRoot::class.java) } catch (e: JsonSyntaxException) { null } catch (e: JsonParseException) { null } } }
mit
bf94360db654b3b04951a9e5ecc12aba
34.115942
98
0.610813
4.732422
false
false
false
false
sky-map-team/stardroid
app/src/main/java/com/google/android/stardroid/touch/Flinger.kt
1
2294
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.touch import android.util.Log import com.google.android.stardroid.util.MiscUtil.getTag import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit /** * Given a flung motion event, this class pumps new Motion events out * to simulate an underlying object with some inertia. */ class Flinger(private val listener: (Float, Float) -> Unit) { private val updatesPerSecond = 20 private val timeIntervalMillis = 1000 / updatesPerSecond private val executor: ScheduledExecutorService private var flingTask: ScheduledFuture<*>? = null fun fling(velocityX: Float, velocityY: Float) { Log.d(TAG, "Doing the fling") class PositionUpdater(private var myVelocityX: Float, private var myVelocityY: Float) : Runnable { private val decelFactor = 1.1f private val TOL = 10f override fun run() { if (myVelocityX * myVelocityX + myVelocityY * myVelocityY < TOL) { stop() } listener( myVelocityX / updatesPerSecond, myVelocityY / updatesPerSecond ) myVelocityX /= decelFactor myVelocityY /= decelFactor } } flingTask = executor.scheduleAtFixedRate( PositionUpdater(velocityX, velocityY), 0, timeIntervalMillis.toLong(), TimeUnit.MILLISECONDS ) } /** * Brings the flinger to a dead stop. */ fun stop() { flingTask?.cancel(true) Log.d(TAG, "Fling stopped") } companion object { private val TAG = getTag(Flinger::class.java) } init { executor = Executors.newScheduledThreadPool(1) } }
apache-2.0
d9a9bdb7ed27e693313a5893ad4b9572
31.323944
91
0.707062
4.352941
false
false
false
false
atlarge-research/opendc-simulator
opendc-model-odc/jpa/src/main/kotlin/com/atlarge/opendc/model/odc/integration/jpa/schema/MachineState.kt
1
2540
/* * MIT License * * Copyright (c) 2017 atlarge-research * * 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. */ package com.atlarge.opendc.model.odc.integration.jpa.schema import com.atlarge.opendc.simulator.Instant import com.atlarge.opendc.simulator.instrumentation.lerp import javax.persistence.Entity /** * The state of a [Machine]. * * @property id The unique identifier of the state. * @property machine The machine of the state. * @property experiment The experiment the machine is running in. * @property time The current moment in time. * @property temperature The temperature of the machine. * @property memoryUsage The memory usage of the machine. * @property load The load of the machine. * @author Fabian Mastenbroek ([email protected]) */ @Entity data class MachineState( val id: Int?, val machine: Machine, val experiment: Experiment, val time: Instant, val temperature: Double, val memoryUsage: Int, val load: Double ) { companion object { /** * A linear interpolator for [MachineState] instances. */ val Interpolator: (Double, MachineState, MachineState) -> MachineState = { f, a, b -> a.copy( id = null, time = lerp(a.time, b.time, f), temperature = lerp(a.temperature, b.temperature, f), memoryUsage = lerp(a.memoryUsage, b.memoryUsage, f), load = lerp(a.load, b.load, f) ) } } }
mit
0c1c0ad46d51e0317d2870a4585bbff7
36.352941
93
0.696457
4.2978
false
false
false
false
syrop/Wiktor-Navigator
navigator/src/main/kotlin/pl/org/seva/navigator/navigation/NavigationFragment.kt
1
11251
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.navigation import android.Manifest import android.annotation.SuppressLint import android.app.Dialog import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.preference.PreferenceManager import android.provider.Settings import android.view.* import android.webkit.WebView import android.widget.Button import androidx.core.content.ContextCompat import androidx.core.content.edit import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.fr_navigation.* import pl.org.seva.navigator.R import pl.org.seva.navigator.contact.* import pl.org.seva.navigator.main.data.fb.fbWriter import pl.org.seva.navigator.main.* import pl.org.seva.navigator.main.data.db.contactDao import pl.org.seva.navigator.main.extension.* import pl.org.seva.navigator.main.data.* import pl.org.seva.navigator.main.init.APP_VERSION import pl.org.seva.navigator.main.init.instance import pl.org.seva.navigator.profile.* class NavigationFragment : Fragment(R.layout.fr_navigation) { private val versionName by instance<String>(APP_VERSION) private var isLocationPermissionGranted = false private var dialog: Dialog? = null private var snackbar: Snackbar? = null private lateinit var mapHolder: MapHolder private val navigatorModel by viewModel<NavigatorViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) @SuppressLint("CommitPrefEdits") fun persistCameraPositionAndZoom() = PreferenceManager.getDefaultSharedPreferences(context).edit { putFloat(ZOOM_PROPERTY, mapHolder.zoom) putFloat(LATITUDE_PROPERTY, mapHolder.lastCameraPosition.latitude.toFloat()) putFloat(LONGITUDE_PROPERTY, mapHolder.lastCameraPosition.longitude.toFloat()) } fun ifLocationPermissionGranted(f: () -> Unit) = checkLocationPermission(onGranted = f, onDenied = {}) fun onAddContactClicked() { mapHolder.stopWatchingPeer() if (!isLocationPermissionGranted) { checkLocationPermission() } else if (isLoggedIn) { nav(R.id.action_navigationFragment_to_contactsFragment) } else { showLoginSnackbar() } } fun deleteProfile() { mapHolder.stopWatchingPeer() contacts.clear() contactDao.deleteAll() setShortcuts() fbWriter.deleteMe() logout() } mapHolder = createMapHolder { init(savedInstanceState, root, navigatorModel.contact.value, prefs) checkLocationPermission = ::ifLocationPermissionGranted persistCameraPositionAndZoom = ::persistCameraPositionAndZoom } add_contact_fab.setOnClickListener { onAddContactClicked() } checkLocationPermission() activityRecognition.stateLiveData.observe(this) { state -> when (state) { ActivityRecognitionObservable.STATIONARY -> hud_stationary.visibility = View.VISIBLE ActivityRecognitionObservable.MOVING -> hud_stationary.visibility = View.GONE } } navigatorModel.contact.observe(this) { contact -> mapHolder.contact = contact contact persist prefs } navigatorModel.deleteProfile.observe(this) { result -> if (result) { deleteProfile() navigatorModel.deleteProfile.value = false } } } override fun onDestroy() { super.onDestroy() peerObservable.clearPeerListeners() } override fun onResume() { super.onResume() checkLocationPermission( onGranted = { snackbar?.dismiss() if (!isLoggedIn) { showLoginSnackbar() } }, onDenied = {}) requireActivity().invalidateOptionsMenu() } private inline fun checkLocationPermission( onGranted: () -> Unit = ::onLocationPermissionGranted, onDenied: () -> Unit = ::requestLocationPermission) = if (ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { isLocationPermissionGranted = true onGranted.invoke() } else { onDenied.invoke() } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) = menuInflater.inflate(R.menu.navigation, menu) override fun onPrepareOptionsMenu(menu: Menu) { menu.findItem(R.id.action_help).isVisible = !isLocationPermissionGranted || !isLoggedIn menu.findItem(R.id.action_logout).isVisible = isLoggedIn menu.findItem(R.id.action_delete_user).isVisible = isLoggedIn } override fun onOptionsItemSelected(item: MenuItem): Boolean { fun help(caption: Int, file: String, action: () -> Unit): Boolean { dialog = Dialog(requireContext()).apply { setContentView(R.layout.dialog_help) val web = findViewById<WebView>(R.id.web) web.settings.defaultTextEncodingName = UTF_8 findViewById<Button>(R.id.action_button).setText(caption) val content = requireActivity().assets.open(file).readString() .replace(APP_VERSION_PLACEHOLDER, versionName) .replace(APP_NAME_PLACEHOLDER, getString(R.string.app_name)) web.loadDataWithBaseURL(ASSET_DIR, content, PLAIN_TEXT, UTF_8, null) findViewById<View>(R.id.action_button).setOnClickListener { action() dismiss() } show() } return true } fun showLocationPermissionHelp() = help( R.string.dialog_settings_button, HELP_LOCATION_PERMISSION_EN, action = ::onSettingsClicked) fun showLoginHelp() = help(R.string.dialog_login_button, HELP_LOGIN_EN, action = ::login) return when (item.itemId) { R.id.action_logout -> logout() R.id.action_delete_user -> nav(R.id.action_navigationFragment_to_deleteProfileFragment) R.id.action_help -> if (!isLocationPermissionGranted) showLocationPermissionHelp() else if (!isLoggedIn) { showLoginHelp() } else true R.id.action_settings -> nav(R.id.action_navigationFragment_to_settingsFragmentContainer) R.id.action_credits -> nav(R.id.action_navigationFragment_to_creditsFragment) else -> super.onOptionsItemSelected(item) } } private fun onSettingsClicked() { dialog?.dismiss() val intent = Intent() intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS val uri = Uri.fromParts("package", requireActivity().packageName, null) intent.data = uri startActivity(intent) } private fun requestLocationPermission() { fun showLocationPermissionSnackbar() { snackbar = Snackbar.make( coordinator, R.string.snackbar_permission_request_denied, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.snackbar_retry) { requestLocationPermission() } .apply { show() } } requestPermissions( Permissions.DEFAULT_PERMISSION_REQUEST_ID, arrayOf(Permissions.PermissionRequest( Manifest.permission.ACCESS_FINE_LOCATION, onGranted = ::onLocationPermissionGranted, onDenied = ::showLocationPermissionSnackbar))) } @SuppressLint("MissingPermission") private fun onLocationPermissionGranted() { requireActivity().invalidateOptionsMenu() mapHolder.locationPermissionGranted() if (isLoggedIn) { (requireActivity().application as NavigatorApplication).startService() } } private fun showLoginSnackbar() { snackbar = Snackbar.make( coordinator, R.string.snackbar_please_log_in, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.snackbar_login) { login() } .apply { show() } } override fun onRequestPermissionsResult( requestCode: Int, requests: Array<String>, grantResults: IntArray) = permissions.onRequestPermissionsResult(requestCode, requests, grantResults) private fun login() { dialog?.dismiss() requireActivity().loginActivity(LoginActivity.LOGIN) } private fun logout(): Boolean { null persist prefs mapHolder.stopWatchingPeer() requireActivity().loginActivity(LoginActivity.LOGOUT) return true } override fun onSaveInstanceState(outState: Bundle) { outState.putParcelable(SAVED_PEER_LOCATION, mapHolder.peerLocation) super.onSaveInstanceState(outState) } companion object { private const val UTF_8 = "UTF-8" private const val ASSET_DIR = "file:///android_asset/" private const val PLAIN_TEXT = "text/html" private const val APP_VERSION_PLACEHOLDER = "[app_version]" private const val APP_NAME_PLACEHOLDER = "[app_name]" private const val HELP_LOCATION_PERMISSION_EN = "help_location_permission_en.html" private const val HELP_LOGIN_EN = "help_login_en.html" const val SAVED_PEER_LOCATION = "saved_peer_location" const val ZOOM_PROPERTY = "navigation_map_zoom" const val LATITUDE_PROPERTY = "navigation_map_latitude" const val LONGITUDE_PROPERTY = "navigation_map_longitude" const val DEFAULT_ZOOM = 7.5f } }
gpl-3.0
208a54b3948504527ea369dfdb1a28a8
36.882155
101
0.633633
5.065736
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/usecase/NoteRefile.kt
1
1123
package com.orgzly.android.usecase import com.orgzly.android.data.DataRepository import com.orgzly.android.ui.NotePlace class NoteRefile(val noteIds: Set<Long>, val target: NotePlace) : UseCase() { override fun run(dataRepository: DataRepository): UseCaseResult { checkIfValidTarget(dataRepository, target) dataRepository.refileNotes(noteIds, target) val firstRefilledNote = dataRepository.getFirstNote(noteIds) return UseCaseResult( modifiesLocalData = true, triggersSync = SYNC_DATA_MODIFIED, userData = firstRefilledNote ) } /** * Make sure there is no overlap - notes can't be refiled under themselves */ private fun checkIfValidTarget(dataRepository: DataRepository, notePlace: NotePlace) { if (notePlace.noteId != 0L) { val sourceNotes = dataRepository.getNotesAndSubtrees(noteIds) if (sourceNotes.map { it.id }.contains(notePlace.noteId)) { throw TargetInNotesSubtree() } } } class TargetInNotesSubtree : Throwable() }
gpl-3.0
ca1d77e607cc1cf8a6f2282d4f9631fb
31.114286
90
0.661621
4.583673
false
false
false
false
samthor/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/connection/VmConnection.kt
9
3710
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.connection import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import com.intellij.util.io.socketConnection.ConnectionState import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.util.io.socketConnection.SocketConnectionListener import org.jetbrains.annotations.TestOnly import org.jetbrains.debugger.DebugEventListener import org.jetbrains.debugger.Vm import org.jetbrains.util.concurrency.AsyncPromise import org.jetbrains.util.concurrency.Promise import org.jetbrains.util.concurrency.ResolvedPromise import org.jetbrains.util.concurrency.isPending import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkListener public abstract class VmConnection<T : Vm> : Disposable, BrowserConnection { private val state = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED)) private val dispatcher = EventDispatcher.create(javaClass<DebugEventListener>()) private val connectionDispatcher = EventDispatcher.create(javaClass<SocketConnectionListener>()) public volatile var vm: T? = null protected set private val opened = AsyncPromise<Any?>() private val closed = AtomicBoolean() override fun getState() = state.get() public fun addDebugListener(listener: DebugEventListener) { dispatcher.addListener(listener) } @TestOnly public fun opened(): Promise<*> = opened override fun executeOnStart(runnable: Runnable) { opened.done { runnable.run() } } protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) { val newState = ConnectionState(status, message, messageLinkListener) val oldState = state.getAndSet(newState) if (oldState == null || oldState.getStatus() != status) { if (status == ConnectionStatus.CONNECTION_FAILED) { opened.setError(newState.getMessage()) } connectionDispatcher.getMulticaster().statusChanged(status) } } override fun addListener(listener: SocketConnectionListener) { connectionDispatcher.addListener(listener) } protected val debugEventListener: DebugEventListener get() = dispatcher.getMulticaster() protected open fun startProcessing() { opened.setResult(null) } public fun close(message: String?, status: ConnectionStatus) { if (!closed.compareAndSet(false, true)) { return } if (opened.isPending) { opened.setError("closed") } setState(status, message) Disposer.dispose(this, false) } override fun dispose() { vm = null } public open fun detachAndClose(): Promise<*> { if (opened.isPending) { opened.setError("detached and closed") } val currentVm = vm val callback: Promise<*> if (currentVm == null) { callback = ResolvedPromise() } else { vm = null callback = currentVm.attachStateManager.detach() } close(null, ConnectionStatus.DISCONNECTED) return callback } }
apache-2.0
db39dbd7601d9fb45769e75c716127a8
31.552632
125
0.74717
4.620174
false
false
false
false
Adven27/Exam
exam-ws/src/main/java/io/github/adven27/concordion/extensions/exam/ws/RestCommands.kt
1
22215
package io.github.adven27.concordion.extensions.exam.ws import io.github.adven27.concordion.extensions.exam.core.ContentTypeConfig import io.github.adven27.concordion.extensions.exam.core.ContentVerifier import io.github.adven27.concordion.extensions.exam.core.ExamExtension.Companion.contentTypeConfig import io.github.adven27.concordion.extensions.exam.core.commands.ExamCommand import io.github.adven27.concordion.extensions.exam.core.commands.ExamVerifyCommand import io.github.adven27.concordion.extensions.exam.core.content import io.github.adven27.concordion.extensions.exam.core.errorMessage import io.github.adven27.concordion.extensions.exam.core.handlebars.matchers.PLACEHOLDER_TYPE import io.github.adven27.concordion.extensions.exam.core.html.Html import io.github.adven27.concordion.extensions.exam.core.html.NAME import io.github.adven27.concordion.extensions.exam.core.html.RowParserEval import io.github.adven27.concordion.extensions.exam.core.html.badge import io.github.adven27.concordion.extensions.exam.core.html.code import io.github.adven27.concordion.extensions.exam.core.html.codeHighlight import io.github.adven27.concordion.extensions.exam.core.html.div import io.github.adven27.concordion.extensions.exam.core.html.html import io.github.adven27.concordion.extensions.exam.core.html.li import io.github.adven27.concordion.extensions.exam.core.html.pill import io.github.adven27.concordion.extensions.exam.core.html.span import io.github.adven27.concordion.extensions.exam.core.html.table import io.github.adven27.concordion.extensions.exam.core.html.tag import io.github.adven27.concordion.extensions.exam.core.html.td import io.github.adven27.concordion.extensions.exam.core.html.th import io.github.adven27.concordion.extensions.exam.core.html.thead import io.github.adven27.concordion.extensions.exam.core.html.tr import io.github.adven27.concordion.extensions.exam.core.html.ul import io.github.adven27.concordion.extensions.exam.core.prettyJson import io.github.adven27.concordion.extensions.exam.core.prettyXml import io.github.adven27.concordion.extensions.exam.core.resolveForContentType import io.github.adven27.concordion.extensions.exam.core.resolveJson import io.github.adven27.concordion.extensions.exam.core.resolveNoType import io.github.adven27.concordion.extensions.exam.core.resolveValues import io.github.adven27.concordion.extensions.exam.core.resolveXml import io.github.adven27.concordion.extensions.exam.core.sameSizeWith import io.github.adven27.concordion.extensions.exam.core.toHtml import io.github.adven27.concordion.extensions.exam.core.toMap import io.github.adven27.concordion.extensions.exam.ws.RequestExecutor.Companion.fromEvaluator import io.restassured.http.ContentType import io.restassured.http.Method import org.concordion.api.CommandCall import org.concordion.api.Element import org.concordion.api.Evaluator import org.concordion.api.Fixture import org.concordion.api.ResultRecorder import java.nio.charset.Charset import java.util.Random private const val HEADERS = "headers" private const val TYPE = "contentType" private const val URL = "url" private const val DESC = "desc" private const val URL_PARAMS = "urlParams" private const val COOKIES = "cookies" private const val VARIABLES = "vars" private const val VALUES = "vals" private const val BODY = "body" private const val MULTI_PART = "multiPart" private const val PART = "part" private const val PART_NAME = "name" private const val FILE_NAME = "fileName" private const val EXPECTED = "expected" private const val WHERE = "where" private const val CASE = "case" private const val VERIFY_AS = "verifyAs" private const val PROTOCOL = "protocol" private const val STATUS_CODE = "statusCode" private const val REASON_PHRASE = "reasonPhrase" private const val FROM = "from" private const val ENDPOINT_HEADER_TMPL = //language=xml """ <div class="input-group input-group-sm"> <span class="input-group-text">%s</span> <span id='%s' class="form-control bg-light text-dark font-weight-light overflow-scroll"/> </div> """ private const val ENDPOINT_TMPL = //language=xml """ <div class="input-group mb-1 mt-1"> <span class="input-group-text %s text-white">%s</span> <span class="form-control bg-light text-primary font-weight-light overflow-scroll" id='%s'/> </div> """ class PutCommand(name: String, tag: String) : RequestCommand(name, tag, Method.PUT) class GetCommand(name: String, tag: String) : RequestCommand(name, tag, Method.GET) class PostCommand(name: String, tag: String) : RequestCommand(name, tag, Method.POST) class DeleteCommand(name: String, tag: String) : RequestCommand(name, tag, Method.DELETE) class SoapCommand(name: String, tag: String) : RequestCommand(name, tag, Method.POST, "application/soap+xml; charset=UTF-8;") sealed class RequestCommand( name: String, tag: String, private val method: Method, private val contentType: String = "application/json" ) : ExamCommand(name, tag) { override fun setUp( commandCall: CommandCall?, evaluator: Evaluator?, resultRecorder: ResultRecorder?, fixture: Fixture ) { val executor = RequestExecutor.newExecutor(evaluator!!).method(method) val root = commandCall.html() val url = attr(root, URL, "/", evaluator) val type = attr(root, TYPE, contentType, evaluator) val cookies = cookies(evaluator, root) val headers = headers(evaluator, root) startTable(root).prependChild( addRequestDescTo(url, type, cookies, headers) ) executor.type(type).url(url).headers(headers).cookies(cookies) } private fun startTable(html: Html): Html = table("class" to "ws-cases")( thead()( th( "Use cases:", "colspan" to "2", "style" to "text-align:center;", "class" to "text-secondary" ) ) ).apply { html.dropAllTo(this) } private fun cookies(eval: Evaluator?, html: Html): String? = html.takeAwayAttr(COOKIES, eval).apply { eval!!.setVariable("#cookies", this) } @Suppress("SpreadOperator") private fun addRequestDescTo(url: String, type: String, cookies: String?, headers: Map<String, String>) = div()( endpoint(url, method), contentType(type), if (cookies != null) cookies(cookies) else null, *headers.map { header(it) }.toTypedArray() ) private fun attr(html: Html, attrName: String, defaultValue: String, eval: Evaluator?): String = html.takeAwayAttr(attrName, defaultValue, eval!!).apply { eval.setVariable("#$attrName", this) } } private fun headers(eval: Evaluator, html: Html): Map<String, String> = html.takeAwayAttr(HEADERS)?.toMap()?.resolveValues(eval) ?: emptyMap() open class RestVerifyCommand(name: String, tag: String) : ExamVerifyCommand(name, tag, RestResultRenderer()) class CaseCheckCommand(name: String, tag: String) : ExamCommand(name, tag) { override fun setUp(cmd: CommandCall?, evaluator: Evaluator?, resultRecorder: ResultRecorder?, fixture: Fixture) { val checkTag = cmd.html() val td = td("colspan" to "2") checkTag.moveChildrenTo(td) checkTag.parent().below(tr()(td)) } } @Suppress("TooManyFunctions") class CaseCommand( tag: String, private val contentTypeConfigs: Map<ContentType, ContentTypeConfig>, private val contentTypeResolver: WsPlugin.ContentTypeResolver ) : RestVerifyCommand(CASE, tag) { private lateinit var contentTypeConfig: ContentTypeConfig private val cases: MutableMap<String, Map<String, Any?>> = LinkedHashMap() private var number = 0 @Suppress("SpreadOperator", "ComplexMethod") override fun setUp(cmd: CommandCall, eval: Evaluator, resultRecorder: ResultRecorder, fixture: Fixture) { val caseRoot = cmd.html() eval.setVariable("#$PLACEHOLDER_TYPE", if (fromEvaluator(eval).xml()) "xml" else "json") cases.clear() caseRoot.firstOptional(WHERE).map { where -> val vars = where.takeAwayAttr(VARIABLES, "", eval).split(",").map { it.trim() } val vals = RowParserEval(where, VALUES, eval).parse() caseRoot.remove(where) cases.putAll( vals.map { it.key to vars.sameSizeWith(it.value).mapIndexed { i, name -> "#$name" to it.value[i] }.toMap() }.toMap() ) }.orElseGet { cases["single"] = HashMap() } val body = caseRoot.first(BODY) val multiPart = caseRoot.first(MULTI_PART) val expected = caseRoot.firstOrThrow(EXPECTED) val contentType = fromEvaluator(eval).contentType() val resolvedType = contentTypeResolver.resolve(contentType) contentTypeConfig = expected.attr(VERIFY_AS)?.let { contentTypeConfig(it) } ?: byContentType(resolvedType) caseRoot.remove(body, expected, multiPart)( cases.map { val expectedToAdd = tag(EXPECTED).text(expected.text()) expected.attr(PROTOCOL)?.let { expectedToAdd.attrs(PROTOCOL to it) } expected.attr(STATUS_CODE)?.let { expectedToAdd.attrs(STATUS_CODE to it) } expected.attr(REASON_PHRASE)?.let { expectedToAdd.attrs(REASON_PHRASE to it) } expected.attr(FROM)?.let { expectedToAdd.attrs(FROM to it) } tag(CASE)( if (body == null) { null } else tag(BODY).text(body.text()).apply { body.attr(FROM)?.let { this.attrs(FROM to it) } }, if (multiPart == null) { null } else { val multiPartArray = multiPart.all(PART).map { html -> tag(PART).text(html.text()).apply { html.attr(NAME)?.let { this.attrs(NAME to it) } html.attr(TYPE)?.let { this.attrs(TYPE to it) } html.attr(FILE_NAME)?.let { this.attrs(FILE_NAME to it) } html.attr(FROM)?.let { this.attrs(FROM to it) } } }.toTypedArray() tag(MULTI_PART)(*multiPartArray) }, expectedToAdd ) } ) } private fun byContentType(resolvedType: ContentType): ContentTypeConfig = contentTypeConfigs[resolvedType] ?: throw IllegalStateException("Content type config for type $resolvedType not found. Provide one through WsPlugin constructor.") override fun execute( commandCall: CommandCall, evaluator: Evaluator, resultRecorder: ResultRecorder, fixture: Fixture ) { val childCommands = commandCall.children val root = commandCall.html() val executor = fromEvaluator(evaluator) val urlParams = root.takeAwayAttr(URL_PARAMS) val cookies = root.takeAwayAttr(COOKIES) val headers = root.takeAwayAttr(HEADERS) for (aCase in cases) { aCase.value.forEach { (key, value) -> evaluator.setVariable(key, value) } cookies?.let { executor.cookies(evaluator.resolveNoType(it)) } headers?.let { executor.headers(headers.toMap().resolveValues(evaluator)) } executor.urlParams(if (urlParams == null) null else evaluator.resolveNoType(urlParams)) val caseTR = tr().insteadOf(root.firstOrThrow(CASE)) val body = caseTR.first(BODY) if (body != null) { val content = body.content(evaluator) val bodyStr = contentTypeConfig.resolver.resolve(content, evaluator) td().insteadOf(body).css(contentTypeConfig.printer.style() + " exp-body") .style("min-width: 20%; width: 50%;") .removeChildren() .text(contentTypeConfig.printer.print(bodyStr)) executor.body(bodyStr) } processMultipart(caseTR, evaluator, executor) childCommands.setUp(evaluator, resultRecorder, fixture) evaluator.setVariable("#exam_response", executor.execute()) childCommands.execute(evaluator, resultRecorder, fixture) childCommands.verify(evaluator, resultRecorder, fixture) val expected = caseTR.firstOrThrow(EXPECTED) val expectedStatus = expectedStatus(expected) val statusEl = span().css("exp-status") check( td("colspan" to (if (body == null) "2" else "1")).css("exp-body").insteadOf(expected), statusEl, evaluator, resultRecorder, executor.contentType(), aCase.key ) if (checkStatusLine(expectedStatus)) { resultRecorder.check(statusEl, executor.statusLine(), statusLine(expectedStatus)) { a, e -> a.trim() == e.trim() } } else { resultRecorder.check(statusEl, executor.statusCode().toString(), expectedStatus.second) { a, e -> a.trim() == e.trim() } } } } private fun statusLine(status: Triple<String?, String, String?>) = "${status.first} ${status.second} ${status.third}" private fun checkStatusLine(status: Triple<String?, String, String?>) = status.third != null private fun processMultipart(caseTR: Html, evaluator: Evaluator, executor: RequestExecutor) { val multiPart = caseTR.first(MULTI_PART) if (multiPart != null) { val table = table() multiPart.all(PART).forEach { val mpType = it.takeAwayAttr(TYPE) val name = it.takeAwayAttr(PART_NAME) val fileName = it.takeAwayAttr(FILE_NAME) val content = it.content(evaluator) table( tr()( td()(badge("Part", "light")), td()( name?.let { badge(name.toString(), "warning") }, mpType?.let { badge(mpType.toString(), "info") }, fileName?.let { code(fileName.toString()) } ) ) ) val mpStr: String if (executor.xml(mpType.toString())) { mpStr = evaluator.resolveXml(content) table( tr()( td()(badge("Content", "dark")), td(mpStr.prettyXml()).css("xml") ) ) } else { mpStr = evaluator.resolveJson(content) table( tr()( td()(badge("Content", "dark")), td(mpStr.prettyJson()).css("json") ) ) } if (mpType == null) { executor.multiPart( name.toString(), fileName.toString(), mpStr.toByteArray(Charset.forName("UTF-8")) ) } else { executor.multiPart(name.toString(), mpType.toString(), mpStr) } } multiPart.removeChildren() td().insteadOf(multiPart)(table) } } private fun expectedStatus(expected: Html) = Triple( expected.takeAwayAttr(PROTOCOL, "HTTP/1.1").trim(), expected.takeAwayAttr(STATUS_CODE, "200").trim(), expected.takeAwayAttr(REASON_PHRASE)?.trim() ) override fun verify(cmd: CommandCall, evaluator: Evaluator, resultRecorder: ResultRecorder, fixture: Fixture) { val rt = cmd.html() val wheres = rt.el.getChildElements("tr") if (wheres.size > 2) { rt.below( tr()( td("colspan" to "2")( whereCaseTemplate( wheres.withIndex().groupBy { it.index / 2 } .map { entry -> tab(System.currentTimeMillis(), entry.value.map { it.value }) } ) ) ) ) } val caseDesc = caseDesc(rt.attr(DESC)) rt.attrs("data-type" to CASE, "id" to caseDesc).prependChild( tr()( td(caseDesc, "colspan" to "2").muted().css("bg-light").style("border-bottom: 1px solid lightgray;") ) ) } private fun caseDesc(desc: String?): String = "${++number}) " + (desc ?: "") @Suppress("LongParameterList") private fun check( root: Html, statusEl: Html, eval: Evaluator, resultRecorder: ResultRecorder, contentType: String, caseTitle: String ) { val executor = fromEvaluator(eval) check( executor.responseBody(), eval.resolveForContentType(root.content(eval), contentType), resultRecorder, root ) val trBodies = root.parent().deepClone() val case = root.parent().parent() case.remove(root.parent()) case()( trCaseDesc(caseTitle, statusEl, executor.hasRequestBody(), executor.responseTime(), executor.httpDesc()), trBodies ) } private fun check(actual: String, expected: String, resultRecorder: ResultRecorder, root: Html) { (contentTypeConfig.verifier to contentTypeConfig.printer).let { (verifier, printer) -> verifier.verify(expected, actual).onFailure { when (it) { is ContentVerifier.Fail -> { val diff = div().css(printer.style()) val (_, errorMsg) = errorMessage(message = it.details, html = diff, type = printer.style()) root.removeChildren()(errorMsg) resultRecorder.failure(diff, printer.print(it.actual), printer.print(it.expected)) } else -> throw it } }.onSuccess { root.removeChildren()( tag("exp").text(printer.print(expected)) css printer.style(), tag("act").text(printer.print(actual)) css printer.style() ) resultRecorder.pass(root) } } } @Suppress("SpreadOperator", "MagicNumber") private fun trCaseDesc(caseTitle: String, statusEl: Html, hasReqBody: Boolean, responseTime: Long, desc: String) = tr("data-case-title" to caseTitle)( td().style("width: ${if (hasReqBody) 50 else 100}%;")( div().css("httpstyle")( codeHighlight(desc, "http") ) ), td("style" to "padding-left: 0;")( tag("small")( statusEl, pill("${responseTime}ms", "light") ) ) ) } private fun endpoint(url: String, method: Method): Html = "endpoint-${Random().nextInt()}".let { id -> String.format(ENDPOINT_TMPL, method.background(), method.name, id).toHtml().apply { findBy(id)?.text(url) } } private fun Method.background() = when (this) { Method.GET -> "bg-primary" Method.POST -> "bg-success" Method.PUT -> "bg-warning" Method.PATCH -> "bg-warning" Method.DELETE -> "bg-danger" else -> "bg-dark" } private fun header(it: Map.Entry<String, String>) = "header-${Random().nextInt()}".let { id -> String.format(ENDPOINT_HEADER_TMPL, it.key, id).toHtml().apply { findBy(id)?.text(it.value) } } private fun cookies(cookies: String) = "header-${Random().nextInt()}".let { id -> String.format(ENDPOINT_HEADER_TMPL, "Cookies", id).toHtml().apply { findBy(id)?.text(cookies) } } private fun contentType(type: String) = "header-${Random().nextInt()}".let { id -> String.format(ENDPOINT_HEADER_TMPL, "Content-Type", id).toHtml().apply { findBy(id)?.text(type) } } private fun whereCaseTemplate(tabs: List<Pair<Html, Html>>): Html = tabs.let { list -> val failed = tabs.indexOfFirst { it.first.attr("class")?.contains("rest-failure") ?: false } val active = if (failed == -1) 0 else failed return div()( tag("nav")( ul("class" to "nav nav-tabs", "role" to "tablist")( list.mapIndexed { i, p -> li().css("nav-item")( p.first.apply { if (i == active) css("active show") } ) } ) ), div()( div("class" to "tab-content")( list.mapIndexed { i, p -> p.second.apply { if (i == active) css("active show") } } ) ) ) } private fun tab(id: Long, trs: List<Element>): Pair<Html, Html> { val cnt = trs.map { Html(it.deepClone()) } val parentElement = trs[0].parentElement parentElement.removeChild(trs[0]) parentElement.removeChild(trs[1]) val fail = cnt.any { it.descendants("fail").isNotEmpty() } val name = Random().nextInt() return Html( "button", cnt[0].attrOrFail("data-case-title"), "id" to "nav-$name-$id-tab", "class" to "nav-link small ${if (fail) "rest-failure" else "text-success"} ", "data-bs-toggle" to "tab", "data-bs-target" to "#nav-$name-$id", "role" to "tab", "aria-controls" to "nav-$name-$id", "aria-selected" to "false", "onclick" to "setTimeout(() => { window.dispatchEvent(new Event('resize')); }, 200)" ) to div( "class" to "tab-pane fade", "id" to "nav-$name-$id", "role" to "tabpanel", "aria-labelledby" to "nav-$name-$id-tab", )(table()(cnt)) }
mit
c983f437714401d1782a12fef5cb4f24
41.395038
137
0.595183
4.33548
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/geodesic-operations/src/main/java/com/esri/arcgisruntime/sample/geodesicoperations/MainActivity.kt
1
6147
/* Copyright 2018 Esri * * 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.esri.arcgisruntime.sample.geodesicoperations import android.graphics.Color import android.os.Bundle import android.view.MotionEvent import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geometry.GeodeticCurveType import com.esri.arcgisruntime.geometry.GeometryEngine import com.esri.arcgisruntime.geometry.LinearUnit import com.esri.arcgisruntime.geometry.LinearUnitId import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.PointCollection import com.esri.arcgisruntime.geometry.Polyline import com.esri.arcgisruntime.geometry.SpatialReferences import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.esri.arcgisruntime.sample.geodesicoperations.databinding.ActivityMainBinding import kotlin.math.roundToInt class MainActivity : AppCompatActivity() { private val srWgs84 = SpatialReferences.getWgs84() private val unitOfMeasurement = LinearUnit(LinearUnitId.KILOMETERS) private val units = "Kilometers" private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a map val map = ArcGISMap(BasemapStyle.ARCGIS_IMAGERY) // set a map to a map view mapView.map = map // create a graphic overlay val graphicOverlay = GraphicsOverlay() mapView.graphicsOverlays.add(graphicOverlay) // add a graphic at JFK to represent the flight start location val start = Point(-73.7781, 40.6413, srWgs84) val locationMarker = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF0000FF.toInt(), 10f) val startLocation = Graphic(start, locationMarker) // create a graphic for the destination val endLocation = Graphic() endLocation.symbol = locationMarker // create a graphic representing the geodesic path between the two locations val path = Graphic() path.symbol = SimpleLineSymbol(SimpleLineSymbol.Style.DASH, 0xFF0000FF.toInt(), 5f) // add graphics to graphics overlay graphicOverlay.graphics.apply { add(startLocation) add(endLocation) add(path) } // create listener to get the location of the tap in the screen mapView.onTouchListener = object : DefaultMapViewOnTouchListener(this, mapView) { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { // get the point that was clicked and convert it to a point in the map val clickLocation = android.graphics.Point(e.x.roundToInt(), e.y.roundToInt()) val mapPoint = mapView.screenToLocation(clickLocation) val destination = GeometryEngine.project(mapPoint, SpatialReferences.getWgs84()) endLocation.geometry = destination // create a straight line path between the start and end locations val points = PointCollection(listOf(start, destination as Point), srWgs84) val polyLine = Polyline(points) // densify the path as a geodesic curve with the path graphic val pathGeometry = GeometryEngine.densifyGeodetic( polyLine, 1.0, unitOfMeasurement, GeodeticCurveType.GEODESIC ) path.geometry = pathGeometry // calculate path distance val distance = GeometryEngine.lengthGeodetic( pathGeometry, unitOfMeasurement, GeodeticCurveType.GEODESIC ) // create a textView for the callout val calloutContent = TextView(applicationContext) calloutContent.setTextColor(Color.BLACK) calloutContent.setSingleLine() // format coordinates to 2 decimal places val distanceString = String.format("%.2f", distance) // display distance as a callout calloutContent.text = "Distance: $distanceString $units" val callout = mapView.callout callout.location = mapPoint callout.content = calloutContent callout.show() return true } } } override fun onPause() { super.onPause() mapView.pause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { super.onDestroy() mapView.dispose() } }
apache-2.0
7993c17e4a4a2b19a50fd52c6231c904
37.180124
96
0.673662
5.131052
false
false
false
false