repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hannesa2/owncloud-android
owncloudData/src/test/java/com/owncloud/android/data/authentication/repository/OCAuthenticationRepositoryTest.kt
2
10249
/** * ownCloud Android client application * * @author Abel García de Prada * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.authentication.repository import com.owncloud.android.data.authentication.datasources.LocalAuthenticationDataSource import com.owncloud.android.data.authentication.datasources.RemoteAuthenticationDataSource import com.owncloud.android.domain.exceptions.AccountNotFoundException import com.owncloud.android.domain.exceptions.AccountNotNewException import com.owncloud.android.domain.exceptions.NoConnectionWithServerException import com.owncloud.android.testutil.OC_ACCESS_TOKEN import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_AUTH_TOKEN_TYPE import com.owncloud.android.testutil.OC_REDIRECTION_PATH import com.owncloud.android.testutil.OC_REFRESH_TOKEN import com.owncloud.android.testutil.OC_SCOPE import com.owncloud.android.testutil.OC_SERVER_INFO import com.owncloud.android.testutil.OC_USER_INFO import com.owncloud.android.testutil.oauth.OC_CLIENT_REGISTRATION import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Assert.assertEquals import org.junit.Test class OCAuthenticationRepositoryTest { private val localAuthenticationDataSource = mockk<LocalAuthenticationDataSource>(relaxed = true) private val remoteAuthenticationDataSource = mockk<RemoteAuthenticationDataSource>(relaxed = true) private val ocAuthenticationRepository: OCAuthenticationRepository = OCAuthenticationRepository(localAuthenticationDataSource, remoteAuthenticationDataSource) @Test fun loginBasicOk() { every { remoteAuthenticationDataSource.loginBasic(any(), any(), any()) } returns Pair( OC_USER_INFO, OC_REDIRECTION_PATH.lastPermanentLocation ) every { localAuthenticationDataSource.addBasicAccount(any(), any(), any(), any(), any(), any()) } returns OC_ACCOUNT_NAME val accountName = ocAuthenticationRepository.loginBasic( OC_SERVER_INFO, "username", "password", null ) verify(exactly = 1) { remoteAuthenticationDataSource.loginBasic(OC_SERVER_INFO.baseUrl, "username", "password") localAuthenticationDataSource.addBasicAccount( "username", OC_REDIRECTION_PATH.lastPermanentLocation, "password", OC_SERVER_INFO, OC_USER_INFO, null ) } assertEquals(OC_ACCOUNT_NAME, accountName) } @Test(expected = NoConnectionWithServerException::class) fun loginBasicRemoteException() { every { remoteAuthenticationDataSource.loginBasic(any(), any(), any()) } throws NoConnectionWithServerException() every { localAuthenticationDataSource.addBasicAccount(any(), any(), any(), any(), any(), any()) } returns OC_ACCOUNT_NAME ocAuthenticationRepository.loginBasic(OC_SERVER_INFO, "test", "test", null) verify(exactly = 1) { remoteAuthenticationDataSource.loginBasic(any(), any(), any()) localAuthenticationDataSource.addBasicAccount(any(), any(), any(), any(), any(), any()) } } @Test(expected = AccountNotNewException::class) fun loginBasicLocalException() { every { remoteAuthenticationDataSource.loginBasic(any(), any(), any()) } returns Pair( OC_USER_INFO, OC_REDIRECTION_PATH.lastPermanentLocation ) every { localAuthenticationDataSource.addBasicAccount(any(), any(), any(), any(), any(), any()) } throws AccountNotNewException() ocAuthenticationRepository.loginBasic(OC_SERVER_INFO, "test", "test", null) verify(exactly = 1) { remoteAuthenticationDataSource.loginBasic(any(), any(), any()) localAuthenticationDataSource.addBasicAccount(any(), any(), any(), any(), any(), any()) } } @Test fun loginBasicOAuth() { every { remoteAuthenticationDataSource.loginOAuth(any(), any(), any()) } returns Pair( OC_USER_INFO, OC_REDIRECTION_PATH.lastPermanentLocation ) every { localAuthenticationDataSource.addOAuthAccount( any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) } returns OC_ACCOUNT_NAME val accountName = ocAuthenticationRepository.loginOAuth( OC_SERVER_INFO, "username", OC_AUTH_TOKEN_TYPE, OC_ACCESS_TOKEN, OC_REFRESH_TOKEN, OC_SCOPE, null, OC_CLIENT_REGISTRATION ) verify(exactly = 1) { remoteAuthenticationDataSource.loginOAuth(OC_SERVER_INFO.baseUrl, "username", OC_ACCESS_TOKEN) localAuthenticationDataSource.addOAuthAccount( "username", OC_REDIRECTION_PATH.lastPermanentLocation, OC_AUTH_TOKEN_TYPE, OC_ACCESS_TOKEN, OC_SERVER_INFO, OC_USER_INFO, OC_REFRESH_TOKEN, OC_SCOPE, null, OC_CLIENT_REGISTRATION ) } assertEquals(OC_ACCOUNT_NAME, accountName) } @Test(expected = NoConnectionWithServerException::class) fun loginOAuthRemoteException() { every { remoteAuthenticationDataSource.loginOAuth(any(), any(), any()) } throws NoConnectionWithServerException() every { localAuthenticationDataSource.addOAuthAccount( any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) } returns OC_ACCOUNT_NAME ocAuthenticationRepository.loginOAuth( OC_SERVER_INFO, "test", OC_AUTH_TOKEN_TYPE, OC_ACCESS_TOKEN, OC_REFRESH_TOKEN, OC_SCOPE, null, OC_CLIENT_REGISTRATION ) verify(exactly = 1) { remoteAuthenticationDataSource.loginOAuth(any(), any(), any()) localAuthenticationDataSource.addOAuthAccount( any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) } } @Test(expected = AccountNotNewException::class) fun loginOAuthLocalException() { every { remoteAuthenticationDataSource.loginOAuth(any(), any(), any()) } returns Pair( OC_USER_INFO, OC_REDIRECTION_PATH.lastPermanentLocation ) every { localAuthenticationDataSource.addOAuthAccount( any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) } throws AccountNotNewException() ocAuthenticationRepository.loginOAuth( OC_SERVER_INFO, "test", OC_AUTH_TOKEN_TYPE, OC_ACCESS_TOKEN, OC_REFRESH_TOKEN, OC_SCOPE, null, OC_CLIENT_REGISTRATION ) verify(exactly = 1) { remoteAuthenticationDataSource.loginOAuth(any(), any(), any()) localAuthenticationDataSource.addOAuthAccount( any(), any(), any(), any(), any(), any(), any(), any(), any(), any() ) } } @Test fun supportsOAuth2Ok() { every { localAuthenticationDataSource.supportsOAuth2(any()) } returns true ocAuthenticationRepository.supportsOAuth2UseCase(OC_ACCOUNT_NAME) verify(exactly = 1) { localAuthenticationDataSource.supportsOAuth2(OC_ACCOUNT_NAME) } } @Test(expected = AccountNotFoundException::class) fun supportsOAuth2Exception() { every { localAuthenticationDataSource.supportsOAuth2(any()) } throws AccountNotFoundException() ocAuthenticationRepository.supportsOAuth2UseCase(OC_ACCOUNT_NAME) verify(exactly = 1) { localAuthenticationDataSource.supportsOAuth2(any()) } } @Test fun getBaseUrlOk() { every { localAuthenticationDataSource.getBaseUrl(any()) } returns OC_SERVER_INFO.baseUrl ocAuthenticationRepository.getBaseUrl(OC_ACCOUNT_NAME) verify(exactly = 1) { localAuthenticationDataSource.getBaseUrl(OC_ACCOUNT_NAME) } } @Test(expected = AccountNotFoundException::class) fun getBaseUrlException() { every { localAuthenticationDataSource.getBaseUrl(any()) } throws AccountNotFoundException() ocAuthenticationRepository.getBaseUrl(OC_ACCOUNT_NAME) verify(exactly = 1) { localAuthenticationDataSource.getBaseUrl(any()) } } }
gpl-2.0
4871fffb375c994acf933ef1e9fed369
30.922118
106
0.583878
4.981526
false
true
false
false
AndroidX/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/Owner.kt
3
10193
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.node import androidx.compose.runtime.Applier import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.autofill.Autofill import androidx.compose.ui.autofill.AutofillTree import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.input.InputModeManager import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.pointer.PointerIconService import androidx.compose.ui.modifier.ModifierLocalManager import androidx.compose.ui.platform.AccessibilityManager import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.TextToolbar import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.platform.WindowInfo import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.TextInputService import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection /** * Owner implements the connection to the underlying view system. On Android, this connects * to Android [views][android.view.View] and all layout, draw, input, and accessibility is hooked * through them. */ internal interface Owner { /** * The root layout node in the component tree. */ val root: LayoutNode /** * Draw scope reused for drawing speed up. */ val sharedDrawScope: LayoutNodeDrawScope val rootForTest: RootForTest /** * Provide haptic feedback to the user. Use the Android version of haptic feedback. */ val hapticFeedBack: HapticFeedback /** * Provide information about the current input mode, and a way to programmatically change the * input mode. */ val inputModeManager: InputModeManager /** * Provide clipboard manager to the user. Use the Android version of clipboard manager. */ val clipboardManager: ClipboardManager /** * Provide accessibility manager to the user. Use the Android version of accessibility manager. */ val accessibilityManager: AccessibilityManager /** * Provide toolbar for text-related actions, such as copy, paste, cut etc. */ val textToolbar: TextToolbar /** * A data structure used to store autofill information. It is used by components that want to * provide autofill semantics. * TODO(ralu): Replace with SemanticsTree. This is a temporary hack until we have a semantics * tree implemented. */ @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalComposeUiApi @ExperimentalComposeUiApi val autofillTree: AutofillTree /** * The [Autofill] class can be used to perform autofill operations. It is used as a * CompositionLocal. */ @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalComposeUiApi @ExperimentalComposeUiApi val autofill: Autofill? val density: Density val textInputService: TextInputService val pointerIconService: PointerIconService /** * Provide a focus manager that controls focus within Compose. */ val focusManager: FocusManager /** * Provide information about the window that hosts this [Owner]. */ val windowInfo: WindowInfo @Deprecated( "fontLoader is deprecated, use fontFamilyResolver", replaceWith = ReplaceWith("fontFamilyResolver") ) @Suppress("DEPRECATION") val fontLoader: Font.ResourceLoader val fontFamilyResolver: FontFamily.Resolver val layoutDirection: LayoutDirection /** * `true` when layout should draw debug bounds. */ var showLayoutBounds: Boolean /** @suppress */ @InternalCoreApi set /** * Called by [LayoutNode] to request the Owner a new measurement+layout. [forceRequest] defines * whether the node should bypass the logic that would reject measure requests, and therefore * force the measure request to be evaluated even when it's already pending measure. * * [affectsLookahead] specifies whether this measure request is for the lookahead pass. */ fun onRequestMeasure( layoutNode: LayoutNode, affectsLookahead: Boolean = false, forceRequest: Boolean = false ) /** * Called by [LayoutNode] to request the Owner a new layout. [forceRequest] defines * whether the node should bypass the logic that would reject relayout requests, and therefore * force the relayout request to be evaluated even when it's already pending measure/layout. * * [affectsLookahead] specifies whether this relayout request is for the lookahead pass * pass. */ fun onRequestRelayout( layoutNode: LayoutNode, affectsLookahead: Boolean = false, forceRequest: Boolean = false ) /** * Called when graphics layers have changed the position of children and the * OnGloballyPositionedModifiers must be called. */ fun requestOnPositionedCallback(layoutNode: LayoutNode) /** * Called by [LayoutNode] when it is attached to the view system and now has an owner. * This is used by [Owner] to track which nodes are associated with it. It will only be * called when [node] is not already attached to an owner. */ fun onAttach(node: LayoutNode) /** * Called by [LayoutNode] when it is detached from the view system, such as during * [LayoutNode.removeAt]. This will only be called for [node]s that are already * [LayoutNode.attach]ed. */ fun onDetach(node: LayoutNode) /** * Returns the position relative to the containing window of the [localPosition], * the position relative to the [Owner]. If the [Owner] is rotated, scaled, or otherwise * transformed relative to the window, this will not be a simple translation. */ fun calculatePositionInWindow(localPosition: Offset): Offset /** * Returns the position relative to the [Owner] of the [positionInWindow], * the position relative to the window. If the [Owner] is rotated, scaled, or otherwise * transformed relative to the window, this will not be a simple translation. */ fun calculateLocalPosition(positionInWindow: Offset): Offset /** * Ask the system to provide focus to this owner. * * @return true if the system granted focus to this owner. False otherwise. */ fun requestFocus(): Boolean /** * Iterates through all LayoutNodes that have requested layout and measures and lays them out. * If [sendPointerUpdate] is `true` then a simulated PointerEvent may be sent to update pointer * input handlers. */ fun measureAndLayout(sendPointerUpdate: Boolean = true) /** * Measures and lays out only the passed [layoutNode]. It will be remeasured with the passed * [constraints]. */ fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) /** * Makes sure the passed [layoutNode] and its subtree is remeasured and has the final sizes. */ fun forceMeasureTheSubtree(layoutNode: LayoutNode) /** * Creates an [OwnedLayer] which will be drawing the passed [drawBlock]. */ fun createLayer(drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit): OwnedLayer /** * The semantics have changed. This function will be called when a SemanticsNode is added to * or deleted from the Semantics tree. It will also be called when a SemanticsNode in the * Semantics tree has some property change. */ fun onSemanticsChange() /** * The position and/or size of the [layoutNode] changed. */ fun onLayoutChange(layoutNode: LayoutNode) /** * The [FocusDirection] represented by the specified keyEvent. */ fun getFocusDirection(keyEvent: KeyEvent): FocusDirection? val measureIteration: Long /** * The [ViewConfiguration] to use in the application. */ val viewConfiguration: ViewConfiguration /** * Performs snapshot observation for blocks like draw and layout which should be re-invoked * automatically when the snapshot value has been changed. */ val snapshotObserver: OwnerSnapshotObserver val modifierLocalManager: ModifierLocalManager /** * Registers a call to be made when the [Applier.onEndChanges] is called. [listener] * should be called in [onEndApplyChanges] and then removed after being called. */ fun registerOnEndApplyChangesListener(listener: () -> Unit) /** * Called when [Applier.onEndChanges] executes. This must call all listeners registered * in [registerOnEndApplyChangesListener] and then remove them so that they are not * called again. */ fun onEndApplyChanges() /** * [listener] will be notified after the current or next layout has finished. */ fun registerOnLayoutCompletedListener(listener: OnLayoutCompletedListener) companion object { /** * Enables additional (and expensive to do in production) assertions. Useful to be set * to true during the tests covering our core logic. */ var enableExtraAssertions: Boolean = false } interface OnLayoutCompletedListener { fun onLayoutComplete() } }
apache-2.0
5408c2f4c5b38e6b18ef49e459f942ed
33.552542
99
0.708624
4.819385
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/notifications/service/delegates/ExpoHandlingDelegate.kt
2
4327
package abi42_0_0.expo.modules.notifications.service.delegates import android.content.Context import android.content.Intent import android.util.Log import androidx.lifecycle.Lifecycle import androidx.lifecycle.ProcessLifecycleOwner import expo.modules.notifications.notifications.NotificationManager import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationResponse import abi42_0_0.expo.modules.notifications.service.NotificationsService import abi42_0_0.expo.modules.notifications.service.interfaces.HandlingDelegate import java.lang.ref.WeakReference import java.util.* class ExpoHandlingDelegate(protected val context: Context) : HandlingDelegate { companion object { const val OPEN_APP_INTENT_ACTION = "expo.modules.notifications.OPEN_APP_ACTION" protected var sPendingNotificationResponses: MutableCollection<NotificationResponse> = ArrayList() /** * A weak map of listeners -> reference. Used to check quickly whether given listener * is already registered and to iterate over when notifying of new token. */ protected var sListenersReferences = WeakHashMap<NotificationManager, WeakReference<NotificationManager>>() /** * Used only by [NotificationManager] instances. If you look for a place to register * your listener, use [NotificationManager] singleton module. * * Purposefully the argument is expected to be a [NotificationManager] and just a listener. * * This class doesn't hold strong references to listeners, so you need to own your listeners. * * @param listener A listener instance to be informed of new push device tokens. */ fun addListener(listener: NotificationManager) { if (sListenersReferences.containsKey(listener)) { // Listener is already registered return } sListenersReferences[listener] = WeakReference(listener) if (!sPendingNotificationResponses.isEmpty()) { val responseIterator = sPendingNotificationResponses.iterator() while (responseIterator.hasNext()) { listener.onNotificationResponseReceived(responseIterator.next()) responseIterator.remove() } } } } fun isAppInForeground() = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) fun getListeners() = sListenersReferences.values.mapNotNull { it.get() } override fun handleNotification(notification: Notification) { if (isAppInForeground()) { getListeners().forEach { it.onNotificationReceived(notification) } } else { NotificationsService.present(context, notification) } } override fun handleNotificationResponse(notificationResponse: NotificationResponse) { if (notificationResponse.action.opensAppToForeground()) { openAppToForeground(context, notificationResponse) } if (getListeners().isEmpty()) { sPendingNotificationResponses.add(notificationResponse) } else { getListeners().forEach { it.onNotificationResponseReceived(notificationResponse) } } } protected fun openAppToForeground(context: Context, notificationResponse: NotificationResponse) { (getNotificationActionLauncher(context) ?: getMainActivityLauncher(context))?.let { intent -> NotificationsService.setNotificationResponseToIntent(intent, notificationResponse) context.startActivity(intent) return } Log.w("expo-notifications", "No launch intent found for application. Interacting with the notification won't open the app. The implementation uses `getLaunchIntentForPackage` to find appropriate activity.") } private fun getNotificationActionLauncher(context: Context): Intent? { Intent(OPEN_APP_INTENT_ACTION).also { intent -> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.setPackage(context.applicationContext.packageName) context.packageManager.resolveActivity(intent, 0)?.let { return intent } } return null } private fun getMainActivityLauncher(context: Context) = context.packageManager.getLaunchIntentForPackage(context.packageName) override fun handleNotificationsDropped() { getListeners().forEach { it.onNotificationsDropped() } } }
bsd-3-clause
59377ee70dc868d282b0df14ae5c77a3
37.633929
210
0.749018
5.008102
false
false
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/util/NotificationUtils.kt
2
3908
package com.ddu.util import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.graphics.Bitmap import android.os.Build import com.ddu.app.BaseApp import com.ddu.icore.common.ext.notificationManager /** * Created by yzbzz on 2017/4/27. */ class NotificationUtils private constructor() { private val mNotificationManager: NotificationManager by lazy { BaseApp.mContext.notificationManager } init { createNotificationChannel() } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelPrimary = NotificationChannel( PRIMARY_CHANNEL, PRIMARY_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) channelPrimary.setShowBadge(true) mNotificationManager.createNotificationChannel(channelPrimary) val channelSecond = NotificationChannel( SECONDARY_CHANNEL, SECONDARY_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) channelSecond.setShowBadge(true) mNotificationManager.createNotificationChannel(channelSecond) } } fun getPrimaryNotification(ctx: Context, title: String, body: String): Notification.Builder { return getNotification(ctx, title, title, body, 1, PRIMARY_CHANNEL, null, null) } fun getSecondNotification(ctx: Context, title: String, body: String): Notification.Builder { return getNotification(ctx, title, title, body, 1, SECONDARY_CHANNEL, null, null) } fun getNotification( context: Context, ticker: String, contentTitle: String, contentText: String, number: Int, channelId: String, largeIcon: Bitmap? = null, intent: PendingIntent? = null ): Notification.Builder { val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = mNotificationManager.getNotificationChannel(channelId) if (channel.importance == NotificationManager.IMPORTANCE_NONE) { // SystemUtils.openChannelSetting(context, channel.id) ToastUtils.showToast("请先打开通知") } Notification.Builder(context, channelId) } else { Notification.Builder(context) } // setDefaults(Notification.DEFAULT_SOUND) builder.setTicker(ticker) .setContentTitle(contentTitle) .setContentText(contentText) .setSmallIcon(smallIcon) .setWhen(System.currentTimeMillis()) .setNumber(number) .setAutoCancel(true) if (largeIcon != null) { // BitmapFactory.decodeResource(context.resources, smallIcon) builder.setLargeIcon(largeIcon) } if (intent != null) { builder.setContentIntent(intent) } return builder } fun notify(id: Int, builder: Notification.Builder, tag: String = "") { if (tag.isEmpty()) { mNotificationManager.notify(id, builder.build()) } else { mNotificationManager.notify(tag, id, builder.build()) } } private object SingletonHolder { val instance = NotificationUtils() } private val smallIcon: Int get() = android.R.drawable.stat_notify_chat companion object { const val PRIMARY_CHANNEL = "LIMI_PUSH" const val PRIMARY_CHANNEL_NAME = "Primary Channel" const val SECONDARY_CHANNEL = "second" const val SECONDARY_CHANNEL_NAME = "Second Channel" val instance: NotificationUtils get() = SingletonHolder.instance } }
apache-2.0
9f7aa03a36a4549bfe9fd92b6cce908f
30.934426
97
0.637064
5.05974
false
false
false
false
charleskorn/batect
app/src/testCommon/kotlin/batect/testutils/DoesNotThrowMatcher.kt
1
1442
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.testutils import com.natpryce.hamkrest.MatchResult import com.natpryce.hamkrest.Matcher import java.io.ByteArrayOutputStream import java.io.PrintStream fun doesNotThrow(): Matcher<() -> Unit> { return object : Matcher<() -> Unit> { override fun invoke(actual: () -> Unit): MatchResult = try { actual() MatchResult.Match } catch (e: Throwable) { val stream = ByteArrayOutputStream() val printer = PrintStream(stream) e.printStackTrace(printer) printer.flush() MatchResult.Mismatch("threw $stream") } override val description: String get() = "does not throw an exception" override val negatedDescription: String get() = "does throw an exception" } }
apache-2.0
92eb9446f82cf0993d59b356757319b5
34.170732
81
0.659501
4.938356
false
false
false
false
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/adapter/LocalSearchDelegate.kt
1
1408
/* * Copyright (C) 2016 IRA-Team * * 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.irateam.vkplayer.adapter import com.irateam.vkplayer.model.Audio class LocalSearchDelegate<T : Audio> : SearchDelegate { private val adapter: BaseAudioRecyclerAdapter<T, *> var original: List<T> = emptyList() private set override var query: String = "" constructor(adapter: BaseAudioRecyclerAdapter<T, *>) { this.adapter = adapter } override fun search(s: String) { if (query.isEmpty()) { original = adapter.audios } query = s.toLowerCase() adapter.audios = if (s.isNotEmpty()) { original.filter { query in it.title.toLowerCase() || query in it.artist.toLowerCase() } } else { original } adapter.notifyDataSetChanged() } }
apache-2.0
ab2de2a689ce85cb190ae10dd00906ff
26.627451
83
0.648438
4.332308
false
false
false
false
veyndan/reddit-client
app/src/main/java/com/veyndan/paper/reddit/post/media/delegate/LinkAdapterDelegate.kt
2
2042
package com.veyndan.paper.reddit.post.media.delegate import android.app.Activity import android.net.Uri import android.support.customtabs.CustomTabsClient import android.support.customtabs.CustomTabsIntent import android.support.customtabs.CustomTabsSession import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.hannesdorfmann.adapterdelegates3.AbsListItemAdapterDelegate import com.jakewharton.rxbinding2.view.clicks import com.veyndan.paper.reddit.databinding.PostMediaLinkBinding import com.veyndan.paper.reddit.post.media.model.Link import com.veyndan.paper.reddit.post.model.Post class LinkAdapterDelegate(private val activity: Activity, private val customTabsClient: CustomTabsClient?, private val customTabsIntent: CustomTabsIntent, private val post: Post) : AbsListItemAdapterDelegate<Link, Any, LinkAdapterDelegate.LinkViewHolder>() { override fun isForViewType(item: Any, items: List<Any>, position: Int): Boolean { return item is Link } override fun onCreateViewHolder(parent: ViewGroup): LinkViewHolder { val inflater: LayoutInflater = LayoutInflater.from(parent.context) val binding: PostMediaLinkBinding = PostMediaLinkBinding.inflate(inflater, parent, false) return LinkViewHolder(binding) } override fun onBindViewHolder(link: Link, holder: LinkViewHolder, payloads: List<Any>) { if (customTabsClient != null) { val session: CustomTabsSession = customTabsClient.newSession(null) session.mayLaunchUrl(Uri.parse(post.linkUrl), null, null) } holder.binding.postMediaUrl.clicks() .subscribe { customTabsIntent.launchUrl(activity, Uri.parse(post.linkUrl)) } holder.binding.postMediaUrl.text = link.domain } class LinkViewHolder(val binding: PostMediaLinkBinding) : RecyclerView.ViewHolder(binding.root) }
mit
a53414dde56d305e946ab43acc42018b
41.541667
99
0.731146
4.759907
false
false
false
false
BrianErikson/PushLocal-Android
PushLocal/src/main/java/com/beariksonstudios/automatic/pushlocal/pushlocal/server/tcp/TcpClient.kt
1
1834
package com.beariksonstudios.automatic.pushlocal.pushlocal.server.tcp import android.util.Log import com.beariksonstudios.automatic.pushlocal.pushlocal.server.Server import java.io.IOException import java.net.InetAddress import java.net.Socket /** * Created by BrianErikson on 8/18/2015. */ class TcpClient(private val socket: Socket, private val tcpHandler: TcpHandler) : Thread() { private val PACKET_SIZE = 1024 override fun run() { var data = ByteArray(PACKET_SIZE) while (Server.isRunning && !socket.isClosed) { try { val len = socket.inputStream.read(data) if (len < 0) { socket.close() break } var str = String(data) str = str.trim { it <= ' ' } data = ByteArray(PACKET_SIZE) Log.d("PushLocal", "Recieved Message from " + socket.inetAddress.hostName + ": " + str) handleMessage(str) Thread.sleep(0) } catch (e: IOException) { Log.e("PushLocal", " " + e.message) } catch (e: InterruptedException) { Log.e("PushLocal", " " + e.message) } } tcpHandler.removeClient(this) } @Throws(IOException::class) private fun handleMessage(msg: String) { if (msg.contains("connected")) { socket.outputStream.write("Indeed, we are.".toByteArray()) } } // TcpHandler thread @Synchronized @Throws(IOException::class) fun sendMessage(msg: String) { socket.outputStream.write(msg.toByteArray()) } val inetAddress: InetAddress get() = socket.inetAddress @Synchronized @Throws(IOException::class) fun dispose() { socket.close() } }
apache-2.0
77a15f7485bebe60c57c63b70d3c8870
27.65625
103
0.571974
4.315294
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangadventure/MangAdventureGenerator.kt
1
763
package eu.kanade.tachiyomi.multisrc.mangadventure import generator.ThemeSourceData.SingleLang import generator.ThemeSourceGenerator /** [MangAdventure] source generator. */ class MangAdventureGenerator : ThemeSourceGenerator { override val themePkg = "mangadventure" override val themeClass = "MangAdventure" override val baseVersionCode = 3 override val sources = listOf( SingleLang("Arc-Relight", "https://arc-relight.com", "en", className = "ArcRelight"), SingleLang("Assorted Scans", "https://assortedscans.com", "en"), SingleLang("Helvetica Scans", "https://helveticascans.com", "en"), ) companion object { @JvmStatic fun main(args: Array<String>) = MangAdventureGenerator().createAll() } }
apache-2.0
10a02a2d3997807271fb9340da5193c2
32.173913
93
0.710354
4.146739
false
false
false
false
cliffroot/awareness
app/src/main/java/hive/com/paradiseoctopus/awareness/createplace/CreatePlaceContracts.kt
1
1725
package hive.com.paradiseoctopus.awareness.createplace import android.net.wifi.ScanResult import com.google.android.gms.maps.model.LatLng import hive.com.paradiseoctopus.awareness.createplace.helper.FragmentTranstion import rx.Observable import rx.subjects.PublishSubject /** * Created by cliffroot on 14.09.16. */ interface CreatePlaceContracts { interface PlaceView { fun showPlaceChooser(transition: FragmentTranstion, location: LatLng, name : String) fun showDeviceChooser(transition: FragmentTranstion, savedNetwork : List<ScanResult>, selectedSsid : String?) fun showAdditionalSettings(transition: FragmentTranstion, intervalFrom : Pair<Int,Int>, intervalTo : Pair<Int, Int>, placeCode : String, placeName : String) fun progress(running : Boolean) fun dismiss(resultObservable : PublishSubject<Boolean>) fun finish() } interface PlacePresenter { fun provideView (placeView : PlaceView) fun getCurrentLocation() : Observable<LatLng> fun getNearbyDevices() : Observable<List<ScanResult>> fun placeDetailsRetrieved (updated : Map<String, Any>) fun hasPlaceImage(latitude : Double, longitude : Double) : Boolean fun coordinatesToName(latLng: LatLng, default : String) : Observable<String> fun restoreState() fun startCreation() fun dismiss() fun next() fun back() } } val latitudeField = "latitude" val longitudeField = "longitude" val nameField = "name" val intervalFromField = "intervalFrom" val intervalToField = "intervalTo" val placeIdField = "placeId" val deviceField = "device" val mapSnapshotField = "mapSnapshot"
apache-2.0
8e9164271af8c9c2315a0c66e8b427bc
30.962963
124
0.707826
4.356061
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/FastImageBorderRadiusAnimator.kt
1
1847
package com.reactnativenavigation.views.element.animators import android.animation.Animator import android.animation.ObjectAnimator import android.os.Build import android.view.View import android.widget.ImageView import androidx.annotation.RequiresApi import androidx.core.animation.doOnEnd import com.facebook.react.views.image.ReactImageView import com.reactnativenavigation.options.SharedElementTransitionOptions import com.reactnativenavigation.utils.BorderRadiusOutlineProvider class FastImageBorderRadiusAnimator(from: View, to: View) : PropertyAnimatorCreator<ImageView>(from, to) { override fun shouldAnimateProperty(fromChild: ImageView, toChild: ImageView): Boolean { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && fromChild !is ReactImageView && toChild !is ReactImageView && (getInheritedBorderRadius(from) != 0f || getInheritedBorderRadius(to) != 0f) } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun create(options: SharedElementTransitionOptions): Animator { from as ImageView; to as ImageView val fromRadius = getInheritedBorderRadius(from) val toRadius = getInheritedBorderRadius(to) val outlineProvider = BorderRadiusOutlineProvider(to, fromRadius) setInitialOutline(to, outlineProvider) return ObjectAnimator.ofObject( CornerRadiusEvaluator { outlineProvider.updateRadius(it) }, fromRadius, toRadius ).apply { doOnEnd { to.outlineProvider = null } } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun setInitialOutline(to: ImageView, provider: BorderRadiusOutlineProvider) { to.outlineProvider = provider to.clipToOutline = true to.invalidateOutline() } }
mit
a5488d4c873d62489f5440111306a111
40.044444
106
0.726042
4.951743
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/util/UserDataHolderBase.kt
1
1406
/* * Copyright (C) 2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.core.util import com.intellij.openapi.util.Key open class UserDataHolderBase : com.intellij.openapi.util.UserDataHolderBase() { fun <T> clearUserData(key: Key<T>): Boolean { val map = userMap val newMap = map.minus(key) return map === newMap || changeUserMap(map, map.minus(key)) } fun <T> computeUserDataIfAbsent(key: Key<T>, provider: () -> T): T { while (true) { val map = userMap val oldValue = map[key] if (oldValue != null) { return oldValue } val value = provider()!! val newMap = map.plus(key, value) if (newMap === map || changeUserMap(map, newMap)) { return value } } } }
apache-2.0
f3f8e50ee9ea97b72109d50d3020bbe7
33.292683
80
0.6266
4.111111
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/params/RequestParameter.kt
1
1274
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.endpoints.params import org.apache.sling.models.annotations.Source import org.apache.sling.models.spi.injectorspecific.InjectAnnotation @Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER) @Retention(AnnotationRetention.RUNTIME) @InjectAnnotation @Source("apm-request-parameter") annotation class RequestParameter(val value: String, val optional: Boolean = true, val fileName: Boolean = false)
apache-2.0
bf097f030bcc015e453c1a619563d9a9
40.533333
113
0.682889
4.51773
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/DateItem.kt
1
1614
package eu.kanade.tachiyomi.ui.recent_updates import android.support.v7.widget.RecyclerView import android.text.format.DateUtils import android.view.View import android.widget.TextView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import java.util.* class DateItem(val date: Date) : AbstractHeaderItem<DateItem.Holder>() { override fun getLayoutRes(): Int { return R.layout.recent_chapters_section_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>?) { holder.bind(this) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other is DateItem) { return date == other.date } return false } override fun hashCode(): Int { return date.hashCode() } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, true) { private val now = Date().time val section_text: TextView = view.findViewById(R.id.section_text) fun bind(item: DateItem) { section_text.text = DateUtils.getRelativeTimeSpanString(item.date.time, now, DateUtils.DAY_IN_MILLIS) } } }
apache-2.0
9d2401f29111b3cc776a38a534e1f8bd
31.3
149
0.70632
4.362162
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/source/SourceManager.kt
1
6051
package eu.kanade.tachiyomi.source import android.content.Context import eu.kanade.domain.source.model.SourceData import eu.kanade.domain.source.repository.SourceDataRepository import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import rx.Observable import uy.kohesive.injekt.injectLazy class SourceManager( private val context: Context, private val extensionManager: ExtensionManager, private val sourceRepository: SourceDataRepository, ) { private val downloadManager: DownloadManager by injectLazy() private val scope = CoroutineScope(Job() + Dispatchers.IO) private var sourcesMap = emptyMap<Long, Source>() set(value) { field = value sourcesMapFlow.value = field } private val sourcesMapFlow = MutableStateFlow(sourcesMap) private val stubSourcesMap = mutableMapOf<Long, StubSource>() val catalogueSources: Flow<List<CatalogueSource>> = sourcesMapFlow.map { it.values.filterIsInstance<CatalogueSource>() } val onlineSources: Flow<List<HttpSource>> = catalogueSources.map { sources -> sources.filterIsInstance<HttpSource>() } init { scope.launch { extensionManager.installedExtensionsFlow .collectLatest { extensions -> val mutableMap = mutableMapOf<Long, Source>(LocalSource.ID to LocalSource(context)) extensions.forEach { extension -> extension.sources.forEach { mutableMap[it.id] = it registerStubSource(it.toSourceData()) } } sourcesMap = mutableMap } } scope.launch { sourceRepository.subscribeAll() .collectLatest { sources -> val mutableMap = stubSourcesMap.toMutableMap() sources.forEach { mutableMap[it.id] = StubSource(it) } } } } fun get(sourceKey: Long): Source? { return sourcesMap[sourceKey] } fun getOrStub(sourceKey: Long): Source { return sourcesMap[sourceKey] ?: stubSourcesMap.getOrPut(sourceKey) { runBlocking { createStubSource(sourceKey) } } } fun getOnlineSources() = sourcesMap.values.filterIsInstance<HttpSource>() fun getCatalogueSources() = sourcesMap.values.filterIsInstance<CatalogueSource>() fun getStubSources(): List<StubSource> { val onlineSourceIds = getOnlineSources().map { it.id } return stubSourcesMap.values.filterNot { it.id in onlineSourceIds } } private fun registerStubSource(sourceData: SourceData) { scope.launch { val (id, lang, name) = sourceData val dbSourceData = sourceRepository.getSourceData(id) if (dbSourceData == sourceData) return@launch sourceRepository.upsertSourceData(id, lang, name) if (dbSourceData != null) { downloadManager.renameSource(StubSource(dbSourceData), StubSource(sourceData)) } } } private suspend fun createStubSource(id: Long): StubSource { sourceRepository.getSourceData(id)?.let { return StubSource(it) } extensionManager.getSourceData(id)?.let { registerStubSource(it) return StubSource(it) } return StubSource(SourceData(id, "", "")) } @Suppress("OverridingDeprecatedMember") open inner class StubSource(private val sourceData: SourceData) : Source { override val id: Long = sourceData.id override val name: String = sourceData.name.ifBlank { id.toString() } override val lang: String = sourceData.lang override suspend fun getMangaDetails(manga: SManga): SManga { throw getSourceNotInstalledException() } @Deprecated("Use the 1.x API instead", replaceWith = ReplaceWith("getMangaDetails")) override fun fetchMangaDetails(manga: SManga): Observable<SManga> { return Observable.error(getSourceNotInstalledException()) } override suspend fun getChapterList(manga: SManga): List<SChapter> { throw getSourceNotInstalledException() } @Deprecated("Use the 1.x API instead", replaceWith = ReplaceWith("getChapterList")) override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { return Observable.error(getSourceNotInstalledException()) } override suspend fun getPageList(chapter: SChapter): List<Page> { throw getSourceNotInstalledException() } @Deprecated("Use the 1.x API instead", replaceWith = ReplaceWith("getPageList")) override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { return Observable.error(getSourceNotInstalledException()) } override fun toString(): String { return if (sourceData.isMissingInfo.not()) "$name (${lang.uppercase()})" else id.toString() } fun getSourceNotInstalledException(): SourceNotInstalledException { return SourceNotInstalledException(toString()) } } inner class SourceNotInstalledException(val sourceString: String) : Exception(context.getString(R.string.source_not_installed, sourceString)) }
apache-2.0
9907d14051b64bc387b7f37bf8571233
36.351852
124
0.663692
5.119289
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/components/TabbedScreen.kt
1
4132
package eu.kanade.presentation.components import androidx.annotation.StringRes import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.rememberPagerState import eu.kanade.tachiyomi.widget.TachiyomiBottomNavigationView import kotlinx.coroutines.launch @Composable fun TabbedScreen( @StringRes titleRes: Int, tabs: List<TabContent>, startIndex: Int? = null, searchQuery: String? = null, @StringRes placeholderRes: Int? = null, onChangeSearchQuery: (String?) -> Unit = {}, incognitoMode: Boolean, downloadedOnlyMode: Boolean, ) { val scope = rememberCoroutineScope() val state = rememberPagerState() LaunchedEffect(startIndex) { if (startIndex != null) { state.scrollToPage(startIndex) } } Scaffold( topBar = { if (searchQuery == null) { AppBar( title = stringResource(titleRes), actions = { AppBarActions(tabs[state.currentPage].actions) }, ) } else { SearchToolbar( searchQuery = searchQuery, placeholderText = placeholderRes?.let { stringResource(it) }, onChangeSearchQuery = { onChangeSearchQuery(it) }, onClickCloseSearch = { onChangeSearchQuery(null) }, onClickResetSearch = { onChangeSearchQuery("") }, ) } }, ) { contentPadding -> Column( modifier = Modifier.padding( top = contentPadding.calculateTopPadding(), start = contentPadding.calculateStartPadding(LocalLayoutDirection.current), end = contentPadding.calculateEndPadding(LocalLayoutDirection.current), ), ) { TabRow( selectedTabIndex = state.currentPage, indicator = { TabIndicator(it[state.currentPage]) }, ) { tabs.forEachIndexed { index, tab -> Tab( selected = state.currentPage == index, onClick = { scope.launch { state.animateScrollToPage(index) } }, text = { TabText(stringResource(tab.titleRes), tab.badgeNumber, state.currentPage == index) }, ) } } AppStateBanners(downloadedOnlyMode, incognitoMode) HorizontalPager( count = tabs.size, modifier = Modifier.fillMaxSize(), state = state, verticalAlignment = Alignment.Top, ) { page -> tabs[page].content( TachiyomiBottomNavigationView.withBottomNavPadding( PaddingValues(bottom = contentPadding.calculateBottomPadding()), ), ) } } } } data class TabContent( @StringRes val titleRes: Int, val badgeNumber: Int? = null, val actions: List<AppBar.Action> = emptyList(), val content: @Composable (contentPadding: PaddingValues) -> Unit, )
apache-2.0
644add0d458ba8beed2c452dbb93e384
34.930435
110
0.586157
5.606513
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.kt
1
6585
package info.nightscout.androidaps.plugins.pump.medtronic.comm.message import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType import kotlin.math.min /** * Created by geoff on 5/29/16. */ class PumpMessage : RLMessage { private val aapsLogger: AAPSLogger private var packetType: PacketType? = PacketType.Carelink var address: ByteArray? = byteArrayOf(0, 0, 0) var commandType: MedtronicCommandType? = null private var invalidCommandType: Byte? = null var messageBody: MessageBody? = MessageBody() var error: String? = null constructor(aapsLogger: AAPSLogger, error: String?) { this.error = error this.aapsLogger = aapsLogger } constructor(aapsLogger: AAPSLogger, rxData: ByteArray?) { this.aapsLogger = aapsLogger init(rxData) } constructor(aapsLogger: AAPSLogger) { this.aapsLogger = aapsLogger } @Suppress("unused") val isErrorResponse: Boolean get() = error != null fun init(packetType: PacketType?, address: ByteArray?, commandType: MedtronicCommandType?, messageBody: MessageBody?) { this.packetType = packetType this.address = address this.commandType = commandType this.messageBody = messageBody } fun init(rxData: ByteArray?) { if (rxData == null) { return } if (rxData.isNotEmpty()) { packetType = PacketType.getByValue(rxData[0].toShort()) } if (rxData.size > 3) { address = ByteUtil.substring(rxData, 1, 3) } if (rxData.size > 4) { commandType = MedtronicCommandType.getByCode(rxData[4]) if (commandType == MedtronicCommandType.InvalidCommand) { aapsLogger.error(LTag.PUMPCOMM, "PumpMessage - Unknown commandType " + rxData[4]) } } if (rxData.size > 5) { messageBody = MedtronicCommandType.constructMessageBody(commandType, ByteUtil.substring(rxData, 5, rxData.size - 5)) } } override fun getTxData(): ByteArray { var rval = ByteUtil.concat(byteArrayOf(packetType!!.value), address) rval = ByteUtil.concat(rval, commandType!!.commandCode) rval = ByteUtil.concat(rval, messageBody!!.txData) return rval } val contents: ByteArray get() = ByteUtil.concat(byteArrayOf(commandType!!.commandCode), messageBody!!.txData)// length is not always correct so, we check whole array if we have // data, after length // check if displayed length is invalid // check Old Way // if (isLogEnabled()) // LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: " // + commandType); // rawContent = just response without code (contents-2, messageBody.txData-1); val rawContent: ByteArray get() { if (messageBody == null || messageBody!!.txData == null || messageBody?.txData?.size == 0) return byteArrayOf() val data = messageBody!!.txData var length = ByteUtil.asUINT8(data!![0]) // length is not always correct so, we check whole array if we have // data, after length //val originalLength = length // check if displayed length is invalid if (length > data.size - 1) { return data } // check Old Way var oldWay = false for (i in length + 1 until data.size) { if (data[i] != 0x00.toByte()) { oldWay = true } } if (oldWay) { length = data.size - 1 } val arrayOut = ByteArray(length) messageBody?.txData?.let { System.arraycopy(it, 1, arrayOut, 0, length) } // if (isLogEnabled()) // LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: " // + commandType); return arrayOut } val rawContentOfFrame: ByteArray get() { val raw = messageBody!!.txData return if (raw == null || raw.isEmpty()) { byteArrayOf() } else { ByteUtil.substring(raw, 1, min(FRAME_DATA_LENGTH, raw.size - 1)) } } override fun isValid(): Boolean { if (packetType == null) return false if (address == null) return false return if (commandType == null) false else messageBody != null } val responseContent: String get() { val sb = StringBuilder("PumpMessage [response=") var showData = true if (commandType != null) { if (commandType == MedtronicCommandType.CommandACK) { sb.append("Acknowledged") showData = false } else if (commandType == MedtronicCommandType.CommandNAK) { sb.append("NOT Acknowledged") showData = false } else { sb.append(commandType!!.name) } } else { sb.append("Unknown_Type") sb.append(" ($invalidCommandType)") } if (showData) { sb.append(", rawResponse=") sb.append(ByteUtil.shortHexString(rawContent)) } sb.append("]") return sb.toString() } override fun toString(): String { val sb = StringBuilder("PumpMessage [") sb.append("packetType=") sb.append(if (packetType == null) "null" else packetType!!.name) sb.append(", address=(") sb.append(ByteUtil.shortHexString(address)) sb.append("), commandType=") sb.append(if (commandType == null) "null" else commandType!!.name) if (invalidCommandType != null) { sb.append(", invalidCommandType=") sb.append(invalidCommandType) } sb.append(", messageBody=(") sb.append(if (messageBody == null) "null" else messageBody) sb.append(")]") return sb.toString() } companion object { const val FRAME_DATA_LENGTH = 64 } }
agpl-3.0
fbbfd9f97493cfa0db1eda707db3477f
34.219251
160
0.574487
4.630802
false
false
false
false
PolymerLabs/arcs
java/arcs/core/data/Capabilities.kt
1
3305
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.data /** * Store capabilities containing a combination of individual [Capability]s (e.g. Persistence * and/or Ttl and/or Queryable etc). * If a certain capability does not appear in the combination, it is not restricted. */ class Capabilities(capabilities: List<Capability> = emptyList()) { val ranges: List<Capability.Range> constructor(capability: Capability) : this(listOf(capability)) init { ranges = capabilities.map { it -> it.toRange() } require(ranges.distinctBy { it.min.tag }.size == capabilities.size) { "Capabilities must be unique $capabilities." } } val persistence: Capability.Persistence? get() = getCapability<Capability.Persistence>() val ttl: Capability.Ttl? get() = getCapability<Capability.Ttl>() val isEncrypted: Boolean? get() = getCapability<Capability.Encryption>()?.let { it.value } val isQueryable: Boolean? get() = getCapability<Capability.Queryable>()?.let { it.value } val isShareable: Boolean? get() = getCapability<Capability.Shareable>()?.let { it.value } val isEmpty = ranges.isEmpty() /** * Returns true, if the given [Capability] is within the corresponding [Capability.Range] * of same type of this. * For example, [Capabilities] with Ttl range of 1-5 days `contains` a Ttl of 3 days. */ fun contains(capability: Capability): Boolean { return ranges.find { it.isCompatible(capability) }?.contains(capability) ?: false } /** * Returns true if all ranges in the given [Capabilities] are contained in this. */ fun containsAll(other: Capabilities): Boolean { return other.ranges.all { otherRange -> contains(otherRange) } } fun isEquivalent(other: Capabilities): Boolean { return ranges.size == other.ranges.size && other.ranges.all { hasEquivalent(it) } } fun hasEquivalent(capability: Capability): Boolean { return ranges.any { it.isCompatible(capability) && it.isEquivalent(capability) } } override fun toString(): String = "Capabilities($ranges)" private inline fun <reified T : Capability> getCapability(): T? { return ranges.find { it.min is T }?.let { require(it.min.isEquivalent(it.max)) { "Cannot get capability for a range" } it.min as T } } companion object { fun fromAnnotations(annotations: List<Annotation>): Capabilities { val ranges = mutableListOf<Capability.Range>() Capability.Persistence.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) } Capability.Encryption.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) } Capability.Ttl.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) } Capability.Queryable.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) } Capability.Shareable.fromAnnotations(annotations)?.let { ranges.add(it.toRange()) } return Capabilities(ranges) } fun fromAnnotation(annotation: Annotation) = fromAnnotations(listOf(annotation)) } }
bsd-3-clause
f756a1b4cc7b3f5a3ac48b7720aba2fa
33.427083
96
0.699244
4.210191
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LL1/grammar/Grammar.kt
1
2526
package com.bajdcc.LL1.grammar import com.bajdcc.LALR1.semantic.lexer.TokenFactory import com.bajdcc.LL1.grammar.error.GrammarException import com.bajdcc.LL1.syntax.Syntax import com.bajdcc.LL1.syntax.handler.SyntaxException import com.bajdcc.LL1.syntax.prediction.PredictionTable import com.bajdcc.util.lexer.error.RegexException import com.bajdcc.util.lexer.token.Token import com.bajdcc.util.lexer.token.TokenType /** * 【语法分析】语法分析 * * @author bajdcc */ class Grammar @Throws(RegexException::class) constructor(context: String) : Syntax(true) { /** * 单词流工厂 */ private val tokenFactory: TokenFactory /** * 单词流 */ private var arrTokens: MutableList<Token>? = null /** * 预测分析表 */ private var table: PredictionTable? = null /** * 获得预测分析表描述 * * @return 预测分析表描述 */ val predictionString: String get() = table!!.toString() /** * 获得单词流描述 * * @return 单词流描述 */ val tokenString: String get() { val sb = StringBuilder() sb.append("#### 单词流 ####") sb.append(System.lineSeparator()) for (token in arrTokens!!) { sb.append(token.toString()) sb.append(System.lineSeparator()) } return sb.toString() } init { tokenFactory = TokenFactory(context)// 用于分析的文本 tokenFactory.discard(TokenType.COMMENT) tokenFactory.discard(TokenType.WHITESPACE) tokenFactory.discard(TokenType.ERROR) tokenFactory.discard(TokenType.MACRO) tokenFactory.scan() } /** * 初始化 * * @param startSymbol 开始符号 * @throws SyntaxException 词法错误 */ @Throws(SyntaxException::class) override fun initialize(startSymbol: String) { super.initialize(startSymbol) generateTable() } /** * 生成预测分析表 */ private fun generateTable() { table = PredictionTable(arrNonTerminals, arrTerminals, mapNonTerminals[beginRuleName]!!.rule, mapTerminals[epsilon]!!, tokenFactory) } /** * 进行语法分析 * * @throws GrammarException 语法错误 */ @Throws(GrammarException::class) fun run() { table!!.run() arrTokens = tokenFactory.tokenList().toMutableList() } }
mit
15d7c132f5c888eec611f0fab631d817
22.48
62
0.602641
4.090592
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/graphics/DefaultCharacterTileString.kt
1
4738
package org.hexworks.zircon.internal.graphics import org.hexworks.zircon.api.data.CharacterTile import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.graphics.CharacterTileString import org.hexworks.zircon.api.graphics.TextWrap import org.hexworks.zircon.internal.behavior.impl.DefaultCursorHandler data class DefaultCharacterTileString internal constructor( override val characterTiles: List<CharacterTile>, override val size: Size, private val textWrap: TextWrap ) : CharacterTileString, Iterable<CharacterTile> by characterTiles { override val tiles: Map<Position, Tile> get() = buildTiles() private fun buildTiles(): Map<Position, Tile> { val tiles = mutableMapOf<Position, Tile>() val (cols, rows) = size val charIter = characterTiles.iterator() val cursorHandler = DefaultCursorHandler(size) if (characterTiles.isEmpty()) return tiles.toMap() if (textWrap == TextWrap.WORD_WRAP) { val wordCharacterIterator = CharacterTileIterator(charIter) if (cursorIsNotAtBottomRightCorner(cursorHandler) && wordCharacterIterator.hasNext()) { do { val nextWord = wordCharacterIterator.next() val wordSize = nextWord.size var spaceRemaining = cols - cursorHandler.cursorPosition.x //the word is bigger then 1 line when this happens we should character wrap if (wordSize > cols) { nextWord.forEach { tc -> tiles[cursorHandler.cursorPosition] = tc cursorHandler.moveCursorForward() } } //this means we can plunk the word on our line if (spaceRemaining >= wordSize) { nextWord.forEach { tc -> tiles[cursorHandler.cursorPosition] = tc cursorHandler.moveCursorForward() } } else { //this means we are at the last yLength and therefore we cannot wrap anymore. Therefore we should //stop rendering val row = cursorHandler.cursorPosition.y if (row == rows - 1) { return tiles.toMap() } //as our word couldn't fit on the last line lets move down a yLength cursorHandler.cursorPosition = cursorHandler.cursorPosition.withRelativeY(1).withX(0) //recalculate our space remaining spaceRemaining = cols - cursorHandler.cursorPosition.x if (spaceRemaining >= wordSize) { //this means we can plunk the word on our line nextWord.forEach { tc -> tiles[cursorHandler.cursorPosition] = tc cursorHandler.moveCursorForward() } } } } while (cursorIsNotAtBottomRightCorner(cursorHandler) && wordCharacterIterator.hasNext()) } return tiles.toMap() } tiles[cursorHandler.cursorPosition] = charIter.next() if (cursorIsNotAtBottomRightCorner(cursorHandler) && charIter.hasNext()) { do { cursorHandler.moveCursorForward() tiles[cursorHandler.cursorPosition] = charIter.next() } while (cursorHandler.isCursorAtTheEndOfTheLine.not() && charIter.hasNext()) if (textWrap == TextWrap.WRAP && charIter.hasNext() && cursorHandler.isCursorAtTheLastRow.not()) { do { cursorHandler.moveCursorForward() tiles[cursorHandler.cursorPosition] = charIter.next() } while (cursorIsNotAtBottomRightCorner(cursorHandler) && charIter.hasNext()) } } return tiles.toMap() } override fun plus(other: CharacterTileString) = DefaultCharacterTileString( characterTiles = characterTiles.plus(other.characterTiles), textWrap = textWrap, size = size + other.size ) override fun withSize(size: Size): CharacterTileString { return copy(size = size) } private fun cursorIsNotAtBottomRightCorner(cursorHandler: DefaultCursorHandler) = (cursorHandler.isCursorAtTheLastRow && cursorHandler.isCursorAtTheEndOfTheLine).not() }
apache-2.0
ff2ef1410fef75ec8732068dfea15329
42.072727
121
0.581469
5.282051
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/ModalBuilder.kt
1
3717
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.builder.base.BaseComponentBuilder import org.hexworks.zircon.api.component.modal.Modal import org.hexworks.zircon.api.component.modal.ModalResult import org.hexworks.zircon.api.component.renderer.ComponentRenderer import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.internal.component.modal.DefaultModal import org.hexworks.zircon.internal.component.renderer.DefaultComponentRenderingStrategy import org.hexworks.zircon.internal.component.renderer.DefaultModalRenderer import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic import kotlin.jvm.JvmOverloads @Suppress("UNCHECKED_CAST") @ZirconDsl class ModalBuilder<T : ModalResult> private constructor() : BaseComponentBuilder<Modal<T>, ModalBuilder<T>>(DefaultModalRenderer()) { var darkenPercent: Double = 0.0 var centeredDialog: Boolean = false var contentComponent: Component? = null var onClosed: (T) -> Unit = {} private var shouldCloseWith: T? = null @JvmOverloads fun withCenteredDialog(centeredDialog: Boolean = true) = also { this.centeredDialog = centeredDialog } fun withComponent(dialogComponent: Component) = also { this.contentComponent = dialogComponent } fun withDarkenPercent(percentage: Double) = also { this.darkenPercent = percentage } fun withOnClosed(onClosed: (T) -> Unit) = also { this.onClosed = onClosed } fun close(result: T) { shouldCloseWith = result } override fun build(): Modal<T> { require(tileset.isNotUnknown) { "Since a Modal has no parent it must have its own tileset" } require(colorTheme.isNotUnknown || componentStyleSet.isNotUnknown) { "Since a Modal has no parent it must have its own color theme or component style set" } require(size.isNotUnknown) { "Can't build a modal without knowing the size of the parent." } require(contentComponent != null) { "Can't build a modal without a content component." } val component = contentComponent!! require(size.toRect().containsBoundable(component.rect)) { "The component $component doesn't fit within the modal of size $size." } if (centeredDialog) { component.moveTo( Position.create( x = (size.width - component.size.width) / 2, y = (size.height - component.size.height) / 2 ) ) } val modalRenderer = DefaultComponentRenderingStrategy( decorationRenderers = decorations, componentRenderer = componentRenderer as ComponentRenderer<Modal<out ModalResult>> ) val modal = DefaultModal<T>( darkenPercent = darkenPercent, componentMetadata = createMetadata(), renderingStrategy = modalRenderer ) modal.addComponent(component) return modal.apply { onClosed(onClosed) shouldCloseWith?.let { result -> close(result) } } } override fun createCopy() = newBuilder<T>() .withProps(props.copy()) .withCenteredDialog(centeredDialog).apply { contentComponent?.let { component -> withComponent(component) } }.withDarkenPercent(darkenPercent) .withPreferredSize(size) companion object { @JvmStatic fun <T : ModalResult> newBuilder() = ModalBuilder<T>() } }
apache-2.0
54e2c893fef43573e3a03a9ce041cd3d
34.066038
97
0.654291
4.722999
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/CustomPackagingElementEntityImpl.kt
1
16009
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CustomPackagingElementEntityImpl : CustomPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, CompositePackagingElementEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ARTIFACT_CONNECTION_ID, CHILDREN_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val artifact: ArtifactEntity? get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) override val children: List<PackagingElementEntity> get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() @JvmField var _typeId: String? = null override val typeId: String get() = _typeId!! @JvmField var _propertiesXmlTag: String? = null override val propertiesXmlTag: String get() = _propertiesXmlTag!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: CustomPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<CustomPackagingElementEntity>(), CustomPackagingElementEntity.Builder { constructor() : this(CustomPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CustomPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } if (!getEntityData().isTypeIdInitialized()) { error("Field CustomPackagingElementEntity#typeId should be initialized") } if (!getEntityData().isPropertiesXmlTagInitialized()) { error("Field CustomPackagingElementEntity#propertiesXmlTag should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CustomPackagingElementEntity this.entitySource = dataSource.entitySource this.typeId = dataSource.typeId this.propertiesXmlTag = dataSource.propertiesXmlTag if (parents != null) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var artifact: ArtifactEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } else { this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value } changedProperty.add("artifact") } override var children: List<PackagingElementEntity> get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList() } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence()) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var typeId: String get() = getEntityData().typeId set(value) { checkModificationAllowed() getEntityData().typeId = value changedProperty.add("typeId") } override var propertiesXmlTag: String get() = getEntityData().propertiesXmlTag set(value) { checkModificationAllowed() getEntityData().propertiesXmlTag = value changedProperty.add("propertiesXmlTag") } override fun getEntityData(): CustomPackagingElementEntityData = result ?: super.getEntityData() as CustomPackagingElementEntityData override fun getEntityClass(): Class<CustomPackagingElementEntity> = CustomPackagingElementEntity::class.java } } class CustomPackagingElementEntityData : WorkspaceEntityData<CustomPackagingElementEntity>() { lateinit var typeId: String lateinit var propertiesXmlTag: String fun isTypeIdInitialized(): Boolean = ::typeId.isInitialized fun isPropertiesXmlTagInitialized(): Boolean = ::propertiesXmlTag.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<CustomPackagingElementEntity> { val modifiable = CustomPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): CustomPackagingElementEntity { val entity = CustomPackagingElementEntityImpl() entity._typeId = typeId entity._propertiesXmlTag = propertiesXmlTag entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CustomPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CustomPackagingElementEntity(typeId, propertiesXmlTag, entitySource) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull() } } 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::class != other::class) return false other as CustomPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.typeId != other.typeId) return false if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as CustomPackagingElementEntityData if (this.typeId != other.typeId) return false if (this.propertiesXmlTag != other.propertiesXmlTag) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + typeId.hashCode() result = 31 * result + propertiesXmlTag.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + typeId.hashCode() result = 31 * result + propertiesXmlTag.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
9a18a44b7ed51522fdab0a86e950b110
41.690667
178
0.671685
5.802465
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractClassNameCalculatorTest.kt
1
3842
// 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.debugger.test import com.intellij.psi.PsiComment import com.intellij.psi.PsiFile import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.codegen.ClassBuilderFactories import org.jetbrains.kotlin.codegen.binding.CodegenBinding import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.base.psi.getLineNumber import org.jetbrains.kotlin.idea.debugger.base.util.ClassNameCalculator import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory abstract class AbstractClassNameCalculatorTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE protected fun doTest(unused: String) { val testFile = dataFile() myFixture.configureByFile(testFile) project.executeWriteCommand("Add class name information") { deleteExistingComments(file) val ktFile = file as KtFile val allNames = ClassNameCalculator.getClassNames(ktFile) checkConsistency(ktFile, allNames) val ktPsiFactory = KtPsiFactory(project) for ((element, name) in allNames) { val comment = ktPsiFactory.createComment("/* $name */") element.addBefore(comment, element.firstChild) } } myFixture.checkResultByFile(testFile) } private fun checkConsistency(file: KtFile, allNames: Map<KtElement, String>) { val analysisResult = file.analyzeWithAllCompilerChecks() assert(!analysisResult.isError()) val generationState = GenerationState.Builder( project, ClassBuilderFactories.TEST, analysisResult.moduleDescriptor, analysisResult.bindingContext, listOf(file), CompilerConfiguration.EMPTY ).build() try { generationState.beforeCompile() val inconsistencies = mutableListOf<String>() for ((element, name) in allNames) { val target = when (element) { is KtLambdaExpression -> element.functionLiteral else -> element } val backendType = CodegenBinding.asmTypeForAnonymousClassOrNull(generationState.bindingContext, target) val backendName = backendType?.className if (backendName != null && backendName != name) { inconsistencies += "Line ${target.getLineNumber()}: Oracle[$name], Backend[$backendName]" } } if (inconsistencies.isNotEmpty()) { inconsistencies.forEach { System.err.print(it) } throw AssertionError("Inconsistencies found (see above).") } } finally { generationState.destroy() } } private fun deleteExistingComments(file: PsiFile) { val comments = mutableListOf<PsiComment>() file.accept(object : PsiRecursiveElementVisitor() { override fun visitComment(comment: PsiComment) { comments += comment } }) comments.forEach { it.delete() } } }
apache-2.0
3686806b720554fa5a8ce64e19207873
38.214286
120
0.680115
5.472934
false
true
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/data/library/Track.kt
1
1485
package com.kelsos.mbrc.data.library import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonPropertyOrder import com.kelsos.mbrc.data.Data import com.kelsos.mbrc.data.db.RemoteDatabase import com.kelsos.mbrc.utilities.RemoteUtils import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder("artist", "title", "src", "trackno", "disc") @Table(name = "track", database = RemoteDatabase::class) data class Track( @JsonProperty("artist") @Column var artist: String? = null, @JsonProperty("title") @Column var title: String? = null, @JsonProperty("src") @Column var src: String? = null, @JsonProperty("trackno") @Column var trackno: Int = 0, @JsonProperty("disc") @Column var disc: Int = 0, @JsonProperty("album_artist") @Column(name = "album_artist") var albumArtist: String? = null, @JsonProperty("album") @Column var album: String? = null, @JsonProperty("genre") @Column var genre: String? = null, @JsonIgnore @Column(name="date_added") var dateAdded: Long = 0, @JsonIgnore @Column @PrimaryKey(autoincrement = true) var id: Long = 0 ) : Data fun Track.key(): String = RemoteUtils.sha1("${albumArtist}_${album}")
gpl-3.0
1417d34ffc8d4588338bb984c5dd3e6e
27.557692
69
0.7367
3.657635
false
false
false
false
MarcBob/StickMan
StickMan/app/src/main/kotlin/marmor/com/stickman/Joint.kt
1
3838
package marmor.com.stickman import android.graphics.PointF import android.util.Log import java.util.ArrayList public class Joint(var position: PointF, var name: String, var canPropagate: Boolean) { private val MOVEMENT_DEPTH = 2 private var incomingLimbs: MutableList<Limb> = ArrayList() private var outgoingLimbs: MutableList<Limb> = ArrayList() public var angleSwitcher: Int = 1 public fun switchAngleDirection(){ angleSwitcher *= -1 } public fun registerIncomingLimb(limb: Limb) { this.incomingLimbs.add(limb) limb.endJoint = this } public fun registerOutgoingLimb(limb: Limb) { this.outgoingLimbs.add(limb) limb.startJoint = this } public fun pull(destination: PointF, limbs: MutableList<Limb> = ArrayList()){ if(limbs.size() < MOVEMENT_DEPTH - 1) { for (limb in incomingLimbs) { limb.pull(destination, limbs) } } else{ //FIXME this should work for more than 2 later val firstLimb = limbs[0] if(canPropagate && incomingLimbs.size > 0) { val secondLimb = incomingLimbs[0] reachDestination(destination, firstLimb, secondLimb) } else reachDestination(destination, firstLimb); } } private fun reachDestination(destination: PointF, limb: Limb){ val angle = (Math.PI / 2) - Math.atan2((destination.y - position.y).toDouble(), (destination.x - position.x).toDouble()) propagateAngleToOutgoingLimbs(angle, limb) limb.angle = angle } private fun reachDestination(destination: PointF, incomingLimb: Limb, predecessorLimb: Limb) { Log.d("Destination", "destination: " + destination.toString()) var limbLength = incomingLimb.length.toDouble() var predLimbLength = predecessorLimb.length.toDouble() var distance = predecessorLimb.startJoint.distanceTo(destination.x.toDouble(), destination.y.toDouble()) if(distance > limbLength + predLimbLength) distance = limbLength + predLimbLength val angleCB = angleSwitcher * Math.acos(Math.min(1.0,(((predLimbLength * predLimbLength) + (distance * distance) - (limbLength * limbLength)) / (2 * predLimbLength * distance)))) val angleAB = angleSwitcher * Math.acos(Math.min(1.0,(((predLimbLength * predLimbLength) + (limbLength * limbLength) - (distance * distance)) / (2 * predLimbLength * limbLength)))) val angleAC = angleSwitcher * Math.PI - angleAB - angleCB val deltaX = destination.x - predecessorLimb.startJoint.position.x val deltaY = destination.y - predecessorLimb.startJoint.position.y val z = (Math.PI / 2) - Math.atan2(deltaY.toDouble(), deltaX.toDouble()) val angleCBFinal = angleCB + z val y = z - angleAC val angleACFinal = y propagateAngleToOutgoingLimbs(angleACFinal, incomingLimb) propagateAngleToOutgoingLimbs(angleCBFinal, predecessorLimb, incomingLimb) incomingLimb.angle = angleACFinal predecessorLimb.angle = angleCBFinal } private fun propagateAngleToOutgoingLimbs(angle: Double, limb: Limb, exceptionLimb: Limb? = null) { val angleDiff = limb.angle - angle for (limb: Limb in limb.endJoint.outgoingLimbs) { if(limb != exceptionLimb) { limb.angle -= angleDiff for (nextLimb: Limb in limb.endJoint.outgoingLimbs) { nextLimb.angle -= angleDiff } } } } public fun distanceTo(x: Double, y: Double): Double { var deltaX = this.position.x - x var deltaY = this.position.y - y return Math.sqrt(Math.pow(deltaX, 2.0) + Math.pow(deltaY, 2.0)) } }
apache-2.0
0f9ac73e3675410e11f1b2bfd586bca8
36.262136
188
0.637311
3.861167
false
false
false
false
micolous/metrodroid
src/main/java/au/id/micolous/metrodroid/fragment/SupportedCardsFragment.kt
1
8957
/* * SupportedCardsFragment.kt * * Copyright 2011, 2017 Eric Butler * Copyright 2015-2019 Michael Farrell * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.fragment import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.nfc.NfcAdapter import android.os.Bundle import androidx.appcompat.content.res.AppCompatResources import android.util.Log import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.BaseExpandableListAdapter import android.widget.ImageView import android.widget.ListView import android.widget.TextView import au.id.micolous.farebot.R import au.id.micolous.metrodroid.MetrodroidApplication import au.id.micolous.metrodroid.activity.MainActivity import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.classic.ClassicAndroidReader import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.CardInfoRegistry import au.id.micolous.metrodroid.util.DrawableUtils import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.getErrorMessage import au.id.micolous.metrodroid.util.Utils /** * @author Eric Butler, Michael Farrell */ class SupportedCardsFragment : ExpandableListFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) listAdapter = CardsAdapter(context!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) return true } return false } private class CardsAdapter internal constructor(val context: Context) : BaseExpandableListAdapter() { val keyBundles: Set<String>? = ClassicAndroidReader.getKeyRetriever(context).forClassicStatic()?.allBundles val cards = CardInfoRegistry.allCardsByRegion private val mLayoutInflater: LayoutInflater = context.getSystemService( Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater override fun getGroupCount(): Int = cards.size override fun getGroup(i: Int) = cards[i].second override fun isChildSelectable(i: Int, i1: Int): Boolean = false override fun hasStableIds(): Boolean = true override fun getChildrenCount(i: Int): Int = cards[i].second.size override fun getChild(parent: Int, child: Int): Any = cards[parent].second[child] override fun getGroupId(i: Int): Long = (i.toLong() + 0x10) override fun getChildId(parent: Int, child: Int): Long = ((parent.toLong() shl 12) + child + 0x10000000) override fun getGroupView(group: Int, isExpanded: Boolean, convertViewReuse: View?, parent: ViewGroup): View { val convertView = convertViewReuse ?: mLayoutInflater.inflate(R.layout.supported_region_header, parent, false)!! val textView1 = convertView.findViewById<TextView>(android.R.id.text1) textView1.text = cards[group].first.translatedName val textView2 = convertView.findViewById<TextView>(android.R.id.text2) val cnt = cards[group].second.size textView2.text = Localizer.localizePlural(R.plurals.supported_cards_format, cnt, cnt) return convertView } override fun getChildView(parent: Int, child: Int, isLast: Boolean, convertViewReuse: View?, viewGroup: ViewGroup): View { try { return getChildViewReal(parent, child, convertViewReuse) } catch (e: Exception) { val convertView = Utils.loadMultiReuse(convertViewReuse, mLayoutInflater, android.R.layout.simple_list_item_1, null, false) val tv = convertView.findViewById<TextView>(android.R.id.text1) tv.text = getErrorMessage(e) return convertView } } private fun getChildViewReal(parent: Int, child: Int, convertViewReuse: View?): View { val convertView = Utils.loadMultiReuse(convertViewReuse, mLayoutInflater, R.layout.supported_card, null, false) val info = cards[parent].second[child] convertView.findViewById<TextView>(R.id.card_name).text = info.name val locationTextView = convertView.findViewById<TextView>(R.id.card_location) if (info.locationId != null) { locationTextView.text = context.getString(info.locationId) locationTextView.visibility = View.VISIBLE } else locationTextView.visibility = View.GONE val image = convertView.findViewById<ImageView>(R.id.card_image) var d: Drawable? = null if (info.hasBitmap) d = DrawableUtils.getCardInfoDrawable(context, info) if (d == null) d = AppCompatResources.getDrawable(context, R.drawable.logo) image.setImageDrawable(d) image.invalidate() image.contentDescription = info.name var notes = "" val app = MetrodroidApplication.instance val nfcAdapter = NfcAdapter.getDefaultAdapter(app) val nfcAvailable = nfcAdapter != null val cardSupported = nfcAvailable && ( info.cardType != CardType.MifareClassic || ClassicAndroidReader.mifareClassicSupport != false) convertView.findViewById<View>(R.id.card_not_supported).visibility = View.GONE if (cardSupported) { convertView.findViewById<View>(R.id.card_not_supported_icon).visibility = View.GONE } else { // This device does not support NFC, so all cards are not supported. if (Preferences.hideUnsupportedRibbon) { notes += Localizer.localizeString(R.string.card_not_supported_on_device) + " " } else { convertView.findViewById<View>(R.id.card_not_supported).visibility = View.VISIBLE } convertView.findViewById<View>(R.id.card_not_supported_icon).visibility = View.VISIBLE } // Keys being required is secondary to the card not being supported. val lockIcon = convertView.findViewById<ImageView>(R.id.card_locked) if (info.keysRequired && info.keyBundle != null && info.keyBundle in keyBundles.orEmpty()) { notes += Localizer.localizeString(R.string.keys_loaded) + " " val a = context.obtainStyledAttributes(intArrayOf(R.attr.LockImageUnlocked)) lockIcon.setImageResource(a.getResourceId(0, R.drawable.unlocked)) a.recycle() lockIcon.contentDescription = Localizer.localizeString(R.string.keys_loaded) lockIcon.visibility = View.VISIBLE } else if (info.keysRequired) { notes += Localizer.localizeString(R.string.keys_required) + " " val a = context.obtainStyledAttributes(intArrayOf(R.attr.LockImage)) lockIcon.setImageResource(a.getResourceId(0, R.drawable.locked)) a.recycle() lockIcon.contentDescription = Localizer.localizeString(R.string.keys_required) lockIcon.visibility = View.VISIBLE } else lockIcon.visibility = View.GONE if (info.preview) { notes += Localizer.localizeString(R.string.card_preview_reader) + " " } if (info.resourceExtraNote != null) { notes += Localizer.localizeString(info.resourceExtraNote) + " " } val note = convertView.findViewById<TextView>(R.id.card_note) note.text = notes if (notes.isEmpty()) note.visibility = View.GONE else note.visibility = View.VISIBLE return convertView } } }
gpl-3.0
4b3b45b4c3c2424732db1af58da3499f
43.785
139
0.660712
4.648158
false
false
false
false
ACRA/acra
acra-core/src/main/java/org/acra/util/IOUtils.kt
1
3072
/* * Copyright 2016 * * 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.acra.util import android.util.Base64 import org.acra.ACRAConstants import org.acra.log.warn import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.Closeable import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.OutputStreamWriter import java.io.Serializable /** * @author William Ferguson &amp; F43nd1r * @since 4.6.0 */ object IOUtils { /** * Closes a Closeable. * * @param closeable Closeable to close. If closeable is null then method just returns. */ @JvmStatic fun safeClose(closeable: Closeable?) { if (closeable == null) return try { closeable.close() } catch (ignored: IOException) { // We made out best effort to release this resource. Nothing more we can do. } } @JvmStatic fun deleteFile(file: File) { val deleted = file.delete() if (!deleted) { warn { "Could not delete file: $file" } } } @JvmStatic @Throws(IOException::class) fun writeStringToFile(file: File, content: String) { val writer = OutputStreamWriter(FileOutputStream(file), ACRAConstants.UTF8) try { writer.write(content) writer.flush() } finally { safeClose(writer) } } fun serialize(serializable: Serializable): String? { val out = ByteArrayOutputStream() try { ObjectOutputStream(out).use { outputStream -> outputStream.writeObject(serializable) return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT) } } catch (e: IOException) { e.printStackTrace() } return null } fun <T : Serializable> deserialize(clazz: Class<T>, s: String?): T? { if (s != null) { try { ObjectInputStream(ByteArrayInputStream(Base64.decode(s, Base64.DEFAULT))).use { inputStream -> val o = inputStream.readObject() if (clazz.isInstance(o)) { return clazz.cast(o) } } } catch (e: IOException) { e.printStackTrace() } catch (e: ClassNotFoundException) { e.printStackTrace() } } return null } }
apache-2.0
1a833b4bd95e1389fa423db0bedc9f32
29.127451
110
0.608398
4.478134
false
false
false
false
GunoH/intellij-community
plugins/performanceTesting/src/com/jetbrains/performancePlugin/commands/OpenFileCommand.kt
2
2868
package com.jetbrains.performancePlugin.commands import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.application.EDT import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.ui.playback.PlaybackContext import com.intellij.openapi.ui.playback.commands.PlaybackCommandCoroutineAdapter import com.intellij.openapi.util.Ref import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.jetbrains.performancePlugin.PerformanceTestSpan import com.jetbrains.performancePlugin.PerformanceTestingBundle import io.opentelemetry.api.trace.Span import io.opentelemetry.context.Scope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.annotations.NonNls import java.util.concurrent.CompletableFuture internal class OpenFileCommand(text: String, line: Int) : PlaybackCommandCoroutineAdapter(text, line) { companion object { const val PREFIX: @NonNls String = CMD_PREFIX + "openFile" const val SPAN_NAME: @NonNls String = "firstCodeAnalysis" @JvmStatic fun findFile(filePath: String, project: Project): VirtualFile? { return when { filePath.contains(JarFileSystem.JAR_SEPARATOR) -> JarFileSystem.getInstance().findFileByPath(filePath) FileUtil.isAbsolute(filePath) -> LocalFileSystem.getInstance().findFileByPath(filePath) else -> project.guessProjectDir()?.findFileByRelativePath(filePath) } } } override suspend fun doExecute(context: PlaybackContext) { val filePath = text.split(' ', limit = 2)[1] val project = context.project val file = findFile(filePath, project) ?: error(PerformanceTestingBundle.message("command.file.not.found", filePath)) val job = CompletableFuture<Unit>() val connection = project.messageBus.simpleConnect() val span = PerformanceTestSpan.TRACER.spanBuilder(SPAN_NAME).setParent(PerformanceTestSpan.getContext()) val spanRef = Ref<Span>() val scopeRef = Ref<Scope>() connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { override fun daemonFinished() { try { connection.disconnect() context.message(PerformanceTestingBundle.message("command.file.opened", file.name), line) } finally { spanRef.get()?.end() scopeRef.get()?.close() job.complete(Unit) } } }) withContext(Dispatchers.EDT) { spanRef.set(span.startSpan()) scopeRef.set(spanRef.get().makeCurrent()) FileEditorManager.getInstance(project).openFile(file, true) } job.join() } }
apache-2.0
7f60feb35c70ff18146a3268b0923d69
41.191176
121
0.75523
4.530806
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/ClassNameCalculator.kt
5
5068
// 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.debugger.base.util import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.containers.Stack import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import java.util.* /* JVM backend requires files to be analyzed against JVM-targeted libraries, so calling it from common modules (that depend on common libraries) leads to unpredictable results. Also, JVM backend initialization is quite expensive as it calculates a lot more information than the debugger needs. `ClassNameCalculator` aims to fix breakpoints in common modules. It's somehow similar to Ultra Light Classes – it also doesn't depend on the backend. In case if all goes wrong, there's a registry key available that turns off the new behavior. */ object ClassNameCalculator { fun getClassNames(file: KtFile): Map<KtElement, String> { return CachedValuesManager.getCachedValue(file) { val visitor = ClassNameCalculatorVisitor() file.accept(visitor) CachedValueProvider.Result(visitor.allNames, file) } } fun getClassName(element: KtElement): String? { val target = when (element) { is KtFunctionLiteral -> element.parent as? KtLambdaExpression ?: element else -> element } return getClassNames(element.containingKtFile)[target] } } private class ClassNameCalculatorVisitor : KtTreeVisitorVoid() { private val names = Stack<String?>() private val anonymousIndices = Stack<Int>() private var collectedNames = WeakHashMap<KtElement, String>() val allNames: Map<KtElement, String> get() = collectedNames override fun visitKtFile(file: KtFile) { saveName(file, JvmFileClassUtil.getFileClassInfoNoResolve(file).fileClassFqName.asString()) super.visitKtFile(file) } override fun visitScript(script: KtScript) { push(script, script.fqName.asString()) super.visitScript(script) pop() } override fun visitClassOrObject(klass: KtClassOrObject) { if (klass.name == null) { // Containing object literal is already in stack super.visitClassOrObject(klass) return } push(klass, if (klass.isTopLevel()) klass.fqName?.asString() else klass.name) super.visitClassOrObject(klass) pop() } override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) { push(expression, nextAnonymousName()) super.visitObjectLiteralExpression(expression) pop() } override fun visitLambdaExpression(expression: KtLambdaExpression) { push(expression, nextAnonymousName()) super.visitLambdaExpression(expression) pop() } override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) { push(expression, nextAnonymousName()) super.visitCallableReferenceExpression(expression) pop() } override fun visitProperty(property: KtProperty) { push(property, if (property.isTopLevel) getTopLevelName(property) else property.name, recordName = false) if (property.hasDelegate()) { nextAnonymousName() // Extra $1 closure for properties with delegates } super.visitProperty(property) pop() } override fun visitNamedFunction(function: KtNamedFunction) { val isLocal = function.isLocal val name = when { isLocal -> nextAnonymousName() function.isTopLevel -> getTopLevelName(function) else -> function.name } push(function, name, recordName = isLocal) if (function.hasModifier(KtTokens.SUSPEND_KEYWORD) && !isLocal) { nextAnonymousName() // Extra $1 closure for suspend functions } super.visitNamedFunction(function) pop() } private fun getTopLevelName(declaration: KtDeclaration): String? { val selfName = declaration.name ?: return null val info = JvmFileClassUtil.getFileClassInfoNoResolve(declaration.containingKtFile) return info.facadeClassFqName.asString() + "$" + selfName } private fun push(element: KtElement, name: String?, recordName: Boolean = true) { names.push(name) anonymousIndices.push(0) if (recordName) { saveName(element, names.joinToString("$")) } } private fun saveName(element: KtElement, name: String) { collectedNames[element] = name } private fun pop() { names.pop() anonymousIndices.pop() } private fun nextAnonymousName(): String { val index = anonymousIndices.pop() + 1 anonymousIndices.push(index) return index.toString() } }
apache-2.0
76f16da57d6ca72ebe49b6cd216e9977
33.705479
137
0.679432
4.937622
false
false
false
false
jk1/intellij-community
plugins/settings-repository/src/readOnlySourcesEditor.kt
3
5207
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.settingsRepository import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.ConfigurableUi import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.ui.TextBrowseFolderListener import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.components.dialog import com.intellij.ui.layout.* import com.intellij.util.Function import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.text.nullize import com.intellij.util.text.trimMiddle import com.intellij.util.ui.table.TableModelEditor import gnu.trove.THashSet import org.jetbrains.settingsRepository.git.asProgressMonitor import org.jetbrains.settingsRepository.git.cloneBare import javax.swing.JTextField private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() { override fun getColumnClass() = Boolean::class.java override fun valueOf(item: ReadonlySource) = item.active override fun setValue(item: ReadonlySource, value: Boolean) { item.active = value } }, object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() { override fun valueOf(item: ReadonlySource) = item.url override fun setValue(item: ReadonlySource, value: String) { item.url = value } }) internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> { val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource> { override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active) override fun getItemClass() = ReadonlySource::class.java override fun edit(item: ReadonlySource, mutator: Function<ReadonlySource, ReadonlySource>, isAdd: Boolean) { val urlField = TextFieldWithBrowseButton(JTextField(20)) urlField.addBrowseFolderListener(TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor())) val panel = panel { row("URL:") { urlField() } } dialog(title = "Add read-only source", panel = panel, focusedComponent = urlField) { val url = urlField.text.nullize(true) validateUrl(url, null)?.let { return@dialog listOf(ValidationInfo(it)) } mutator.`fun`(item).url = url return@dialog null } .show() } override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) { newItem.url = oldItem.url } override fun isUseDialogToAdd() = true } val editor = TableModelEditor(COLUMNS, itemEditor, "No sources configured") editor.reset(if (ApplicationManager.getApplication().isUnitTestMode) emptyList() else icsManager.settings.readOnlySources) return object : ConfigurableUi<IcsSettings> { override fun isModified(settings: IcsSettings) = editor.isModified override fun apply(settings: IcsSettings) { val oldList = settings.readOnlySources val toDelete = THashSet<String>(oldList.size) for (oldSource in oldList) { ContainerUtil.addIfNotNull(toDelete, oldSource.path) } val toCheckout = THashSet<ReadonlySource>() val newList = editor.apply() for (newSource in newList) { val path = newSource.path if (path != null && !toDelete.remove(path)) { toCheckout.add(newSource) } } if (toDelete.isEmpty && toCheckout.isEmpty) { return } runModalTask(icsMessage("task.sync.title")) { indicator -> indicator.isIndeterminate = true val root = icsManager.readOnlySourcesManager.rootDir if (toDelete.isNotEmpty()) { indicator.text = "Deleting old repositories" for (path in toDelete) { indicator.checkCanceled() LOG.runAndLogException { indicator.text2 = path root.resolve(path).delete() } } } if (toCheckout.isNotEmpty()) { for (source in toCheckout) { indicator.checkCanceled() LOG.runAndLogException { indicator.text = "Cloning ${source.url!!.trimMiddle(255)}" val dir = root.resolve(source.path!!) if (dir.exists()) { dir.delete() } cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close() } } } icsManager.readOnlySourcesManager.setSources(newList) // blindly reload all icsManager.schemeManagerFactory.value.process { it.reload() } } } override fun reset(settings: IcsSettings) { editor.reset(settings.readOnlySources) } override fun getComponent() = editor.createComponent() } }
apache-2.0
a0d34afb488ff86de532ad74d9b545ff
33.946309
140
0.692337
4.839219
false
false
false
false
Kyuubey/site
src/main/kotlin/moe/kyubey/site/db/schema/Logs.kt
1
934
package moe.kyubey.site.db.schema import me.aurieh.ares.exposed.pg.jsonbArray import me.aurieh.ares.exposed.pg.pgArray import org.jetbrains.exposed.sql.Table import org.json.JSONObject object Logs : Table() { val event = varchar("event", 6) // Message val messageId = long("messageId") val content = varchar("content", 2000) val attachments = pgArray<String>("attachments", "text") val embeds = jsonbArray<JSONObject>("embeds") val timestamp = long("timestamp") // Author val authorId = long("authorId") val authorName = varchar("authorName", 33) val authorDiscrim = varchar("authorDiscrim", 4) val authorAvatar = text("authorAvatar") val authorNick = varchar("authorNick", 33) // Guild val guildId = long("guildId") val guildName = varchar("guildName", 100) // Channel val channelId = long("channelId") val channelName = varchar("channelName", 100) }
mit
3e5f9507bba1257ba0a1ab9f460577b1
28.1875
60
0.683084
3.90795
false
false
false
false
NiciDieNase/chaosflix
common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/recording/ConferenceDto.kt
1
2893
package de.nicidienase.chaosflix.common.mediadata.entities.recording import androidx.annotation.Keep import com.google.gson.annotations.SerializedName import de.nicidienase.chaosflix.common.util.ConferenceUtil @Keep data class ConferenceDto( @SerializedName("acronym") var acronym: String = "", @SerializedName("aspect_ratio") var aspectRatio: String = "", @SerializedName("updated_at") var updatedAt: String? = "", @SerializedName("title") var title: String = "", @SerializedName("schedule_url") var scheduleUrl: String?, @SerializedName("slug") var slug: String = "", @SerializedName("event_last_released_at") var lastReleaseAt: String? = "", @SerializedName("webgen_location") var webgenLocation: String? = "", @SerializedName("logo_url") var logoUrl: String = "", @SerializedName("images_url") var imagesUrl: String = "", @SerializedName("recordings_url") var recordingsUrl: String = "", @SerializedName("url") var url: String = "", @SerializedName("events") var events: List<EventDto>? ) : Comparable<ConferenceDto> { val conferenceID: Long get() = getIdFromUrl() private val eventsByTags: Map<String, List<EventDto>> by lazy { getEventsMap(events) } private val sensibleTags: Set<String> val tagsUsefull: Boolean init { sensibleTags = ConferenceUtil.getSensibleTags(eventsByTags.keys, acronym) tagsUsefull = sensibleTags.isNotEmpty() } private fun getEventsMap(events: List<EventDto>?): Map<String, List<EventDto>> { val map = HashMap<String, MutableList<EventDto>>() val untagged = ArrayList<EventDto>() if (events != null) { for (event in events) { if (event.tags?.isNotEmpty() == true) { val tags = event.tags for (tag: String in tags?.filterNotNull() ?: emptyList()) { val list: MutableList<EventDto> if (map.keys.contains(tag)) { list = map[tag]!! } else { list = ArrayList() map[tag] = list } list.add(event) } } else { untagged.add(event) } } if (untagged.size > 0) { map["untagged"] = untagged } } return map } private fun getIdFromUrl(url: String = this.url): Long { val strings = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() try { return ((strings[strings.size - 1]).toLong()) } catch (e: NumberFormatException) { return 0 } } override fun compareTo(other: ConferenceDto): Int { return slug.compareTo(other.slug) } }
mit
963ceda7224a60f78f20653490450988
36.089744
92
0.572071
4.513261
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/export/ImportPresenter.kt
1
7005
package lt.markmerkk.export import lt.markmerkk.ActiveDisplayRepository import lt.markmerkk.TimeProvider import lt.markmerkk.entities.Log import lt.markmerkk.entities.Log.Companion.clone import lt.markmerkk.entities.Log.Companion.cloneAsNewLocal import lt.markmerkk.entities.TicketCode import lt.markmerkk.export.entities.ExportWorklogViewModel import lt.markmerkk.utils.LogFormatters import org.joda.time.Duration import org.slf4j.LoggerFactory class ImportPresenter( private val activeDisplayRepository: ActiveDisplayRepository, private val timeProvider: TimeProvider, ) : ImportContract.Presenter { override val defaultProjectFilter: String = PROJECT_FILTER_ALL private var view: ImportContract.View? = null private var worklogsImported: List<Log> = emptyList() private var worklogsModified: List<Log> = emptyList() override fun onAttach(view: ImportContract.View) { this.view = view } override fun onDetach() { } override fun loadWorklogs(importWorklogs: List<Log>, projectFilter: String) { this.worklogsImported = importWorklogs this.worklogsModified = worklogsImported .applyProjectFilter(projectFilter = projectFilter) val viewModels = worklogsModified .map { ExportWorklogViewModel(it, includeDate = true) } val selectableTicketFilters = loadProjectFilters(worklogsImported) view?.showWorklogs(viewModels) view?.showProjectFilters(selectableTicketFilters, defaultProjectFilter) view?.showTotal(calcTotal(worklogsModified)) } override fun filterClear(projectFilter: String) { this.worklogsModified = worklogsImported .applyProjectFilter(projectFilter) renderWorklogs(worklogsModified) } override fun filterWorklogsWithCodeFromComment(projectFilter: String) { this.worklogsModified = worklogsImported .applyProjectFilter(projectFilter) .applyTicketCodeFromComment() renderWorklogs(worklogsModified) } override fun filterWorklogsNoCode(projectFilter: String) { this.worklogsModified = worklogsImported .applyProjectFilter(projectFilter) .applyNoTicketCode() renderWorklogs(worklogsModified) } override fun filterWorklogsWithCodeAndRemoveFromComment(projectFilter: String) { this.worklogsModified = worklogsImported .applyProjectFilter(projectFilter) .applyTicketCodeAndRemoveFromComment() renderWorklogs(worklogsModified) } override fun import( worklogViewModels: List<ExportWorklogViewModel>, skipTicketCode: Boolean ) { val importWorklogs = if (skipTicketCode) { worklogViewModels .filter { it.selectedProperty.get() } .map { it.log.clearTicketCode() } } else { worklogViewModels .filter { it.selectedProperty.get() } .map { it.log } } importWorklogs .forEach { activeDisplayRepository.insertOrUpdate(it) } view?.showImportSuccess() } private fun renderWorklogs(worklogsModified: List<Log>) { val viewModels = worklogsModified .map { ExportWorklogViewModel(it, includeDate = true) } view?.showWorklogs(viewModels) view?.showTotal(calcTotal(worklogsModified)) } /** * Loads project filters (selections of possible ticket codes) */ private fun loadProjectFilters(worklogs: List<Log>): List<String> { val filterWithBoundTickets = worklogs.map { val projectCode = it.code.codeProject if (projectCode.isEmpty()) { PROJECT_FILTER_NOT_BOUND } else { projectCode } }.filterNot { it == PROJECT_FILTER_NOT_BOUND } .toSet() return listOf(PROJECT_FILTER_ALL, PROJECT_FILTER_NOT_BOUND) .plus(filterWithBoundTickets) } private fun calcTotal(worklogs: List<Log>): String { val totalDuration = worklogs.map { it.time.duration } .fold(Duration(0)) { acc, next -> acc.plus(next) } return LogFormatters.humanReadableDuration(totalDuration) } companion object { private val l = LoggerFactory.getLogger(ImportPresenter::class.java)!! const val PROJECT_FILTER_ALL = "All" const val PROJECT_FILTER_NOT_BOUND = "Not assigned" internal fun List<Log>.applyProjectFilter(projectFilter: String): List<Log> { return when { projectFilter.isEmpty() || projectFilter == PROJECT_FILTER_ALL -> { this.sortedBy { it.time.start } } projectFilter == PROJECT_FILTER_NOT_BOUND -> { this.filter { it.code.codeProject.isEmpty() } .sortedBy { it.time.start } } else -> { this.filter { it.code.codeProject == projectFilter } .sortedBy { it.time.start } } } } internal fun Log.extractTicketCodeFromComment(): Log { val ticketCode = TicketCode.new(this.comment) return this.copy( code = ticketCode, ) } internal fun Log.extractTicketCodeAndRemoveFromComment(): Log { val commentSplit: List<String> = comment.split(" ") var commentCodeIndex = -1 var commentTicketCode = TicketCode.asEmpty() for (commentIndex in commentSplit.indices) { val commentPart = commentSplit[commentIndex] val commentPartTicketCode = TicketCode.new(commentPart) if (!commentPartTicketCode.isEmpty()) { commentCodeIndex = commentIndex commentTicketCode = commentPartTicketCode break } } val newComment = if (!commentTicketCode.isEmpty()) { commentSplit.toMutableList() .apply { this.removeAt(commentCodeIndex) } .toList() .joinToString(separator = " ") .trim() } else { this.comment } return this.copy( code = commentTicketCode, comment = newComment, ) } internal fun List<Log>.applyTicketCodeFromComment(): List<Log> { return this.map { it.extractTicketCodeFromComment() } } internal fun List<Log>.applyTicketCodeAndRemoveFromComment(): List<Log> { return this.map { it.extractTicketCodeAndRemoveFromComment() } } internal fun List<Log>.applyNoTicketCode(): List<Log> { return this.map { it.copy(code = TicketCode.asEmpty()) } } } }
apache-2.0
cccff5cccb0e3b078bbd8260579039f1
36.068783
85
0.613419
5.079768
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/streaming/StreamProxy.kt
1
5719
package io.casey.musikcube.remote.service.playback.impl.streaming import android.content.Context import android.content.SharedPreferences import android.net.Uri import android.util.Base64 import com.danikula.videocache.CacheListener import com.danikula.videocache.HttpProxyCacheServer import com.danikula.videocache.file.Md5FileNameGenerator import io.casey.musikcube.remote.Application import io.casey.musikcube.remote.injection.DaggerServiceComponent import io.casey.musikcube.remote.service.gapless.db.GaplessDb import io.casey.musikcube.remote.service.gapless.db.GaplessTrack import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.shared.util.NetworkUtil import java.io.File import java.util.* import javax.inject.Inject class StreamProxy(private val context: Context) { @Inject lateinit var gaplessDb: GaplessDb private lateinit var proxy: HttpProxyCacheServer private val prefs: SharedPreferences = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) init { DaggerServiceComponent.builder() .appComponent(Application.appComponent) .build().inject(this) gaplessDb.prune() restart() } @Synchronized fun registerCacheListener(cl: CacheListener, uri: String) { proxy.registerCacheListener(cl, uri) /* let it throw */ } @Synchronized fun unregisterCacheListener(cl: CacheListener) { proxy.unregisterCacheListener(cl) } @Synchronized fun isCached(url: String): Boolean { return proxy.isCached(url) } @Synchronized fun getProxyUrl(url: String): String { return proxy.getProxyUrl(url) } @Synchronized fun getProxyFilename(url: String): String { return proxy.cacheDirectory.canonicalPath + "/" + FILENAME_GENERATOR(url) } @Synchronized fun reload() { proxy.shutdown() restart() } private fun restart() { if (this.prefs.getBoolean(Prefs.Key.CERT_VALIDATION_DISABLED, Prefs.Default.CERT_VALIDATION_DISABLED)) { NetworkUtil.disableCertificateValidation() } else { NetworkUtil.enableCertificateValidation() } var diskCacheIndex = this.prefs.getInt( Prefs.Key.DISK_CACHE_SIZE_INDEX, Prefs.Default.DISK_CACHE_SIZE_INDEX) if (diskCacheIndex < 0 || diskCacheIndex > CACHE_SETTING_TO_BYTES.size) { diskCacheIndex = 0 } val cachePath = File(context.externalCacheDir, "audio") proxy = HttpProxyCacheServer.Builder(context.applicationContext) .cacheDirectory(cachePath) .maxCacheSize(CACHE_SETTING_TO_BYTES[diskCacheIndex] ?: MINIMUM_CACHE_SIZE_BYTES) .headerInjector { val headers = HashMap<String, String>() val userPass = "default:" + prefs.getString(Prefs.Key.PASSWORD, Prefs.Default.PASSWORD)!! val encoded = Base64.encodeToString(userPass.toByteArray(), Base64.NO_WRAP) headers["Authorization"] = "Basic $encoded" headers } .headerReceiver { url: String, headers: Map<String, List<String>> -> /* if we have a 'X-musikcube-Estimated-Content-Length' header in the response, that means the on-demand transcoder is running, therefore gapless information won't be available yet. track this download so we can patch up the header later, once the file finishes transcoding */ val estimated = headers[ESTIMATED_LENGTH] if (estimated?.firstOrNull() == "true") { synchronized (proxy) { val dao = gaplessDb.dao() if (dao.queryByUrl(url).isEmpty()) { dao.insert(GaplessTrack(null, url, GaplessTrack.DOWNLOADING)) } } } } .fileNameGenerator(FILENAME_GENERATOR) .build() } companion object { private const val BYTES_PER_MEGABYTE = 1048576L private const val BYTES_PER_GIGABYTE = 1073741824L private const val ESTIMATED_LENGTH = "X-musikcube-Estimated-Content-Length" const val MINIMUM_CACHE_SIZE_BYTES = BYTES_PER_MEGABYTE * 128 val CACHE_SETTING_TO_BYTES: MutableMap<Int, Long> = mutableMapOf( 0 to MINIMUM_CACHE_SIZE_BYTES, 1 to BYTES_PER_GIGABYTE / 2, 2 to BYTES_PER_GIGABYTE, 3 to BYTES_PER_GIGABYTE * 2, 4 to BYTES_PER_GIGABYTE * 3, 5 to BYTES_PER_GIGABYTE * 4) private val DEFAULT_FILENAME_GENERATOR = Md5FileNameGenerator() private val FILENAME_GENERATOR: (String) -> String = gen@ { url -> try { val uri = Uri.parse(url) /* format matches: audio/external_id/<id> */ val segments = uri.pathSegments if (segments.size == 3 && "external_id" == segments[1]) { /* url params, hyphen separated */ val params = when (uri?.query.isNullOrBlank()) { true -> "" false -> "-" + uri!!.query!! .replace("?", "-") .replace("&", "-") .replace("=", "-") } return@gen "${segments[2]}$params" } } catch (ex: Exception) { /* eh... */ } return@gen DEFAULT_FILENAME_GENERATOR.generate(url) } } }
bsd-3-clause
3adbdd2d49d987810fa5b729a631faa3
37.38255
112
0.597657
4.528108
false
false
false
false
dahlstrom-g/intellij-community
platform/diagnostic/src/startUpPerformanceReporter/IdeIdeaFormatWriter.kt
3
8462
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.diagnostic.startUpPerformanceReporter import com.fasterxml.jackson.core.JsonGenerator import com.intellij.diagnostic.ActivityImpl import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.ThreadNameManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.lang.ClassPath import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import org.bouncycastle.crypto.generators.Argon2BytesGenerator import org.bouncycastle.crypto.params.Argon2Parameters import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.management.ManagementFactory import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* import java.util.concurrent.TimeUnit internal class IdeIdeaFormatWriter(activities: Map<String, MutableList<ActivityImpl>>, private val pluginCostMap: MutableMap<String, Object2LongOpenHashMap<String>>, threadNameManager: ThreadNameManager) : IdeaFormatWriter(activities, threadNameManager, StartUpPerformanceReporter.VERSION) { val publicStatMetrics = Object2IntOpenHashMap<String>() init { publicStatMetrics.defaultReturnValue(-1) } fun writeToLog(log: Logger) { stringWriter.write("\n=== Stop: StartUp Measurement ===") log.info(stringWriter.toString()) } override fun writeAppInfo(writer: JsonGenerator) { val appInfo = ApplicationInfo.getInstance() writer.writeStringField("build", appInfo.build.asStringWithoutProductCode()) writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME)) writer.writeStringField("productCode", appInfo.build.productCode) // see CDSManager from platform-impl @Suppress("SpellCheckingInspection") if (ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }) { writer.writeBooleanField("cds", true) } } override fun writeProjectName(writer: JsonGenerator, projectName: String) { writer.writeStringField("project", System.getProperty("idea.performanceReport.projectName") ?: safeHashValue(projectName)) } override fun writeExtraData(writer: JsonGenerator) { val stats = getClassAndResourceLoadingStats() writer.obj("classLoading") { val time = stats.getValue("classLoadingTime") writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(time)) val defineTime = stats.getValue("classDefineTime") writer.writeNumberField("searchTime", TimeUnit.NANOSECONDS.toMillis(time - defineTime)) writer.writeNumberField("defineTime", TimeUnit.NANOSECONDS.toMillis(defineTime)) writer.writeNumberField("count", stats.getValue("classRequests")) } writer.obj("resourceLoading") { writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stats.getValue("resourceLoadingTime"))) writer.writeNumberField("count", stats.getValue("resourceRequests")) } writeServiceStats(writer) writeIcons(writer) } private fun getClassAndResourceLoadingStats(): Map<String, Long> { // data from bootstrap classloader val classLoader = IdeIdeaFormatWriter::class.java.classLoader @Suppress("UNCHECKED_CAST") val stats = MethodHandles.lookup() .findVirtual(classLoader::class.java, "getLoadingStats", MethodType.methodType(Map::class.java)) .bindTo(classLoader).invokeExact() as MutableMap<String, Long> // data from core classloader val coreStats = ClassPath.getLoadingStats() if (coreStats.get("identity") != stats.get("identity")) { for (entry in coreStats.entries) { val v1 = stats.getValue(entry.key) if (v1 != entry.value) { stats.put(entry.key, v1 + entry.value) } } } return stats } override fun writeTotalDuration(writer: JsonGenerator, end: Long, timeOffset: Long): Long { val totalDurationActual = super.writeTotalDuration(writer, end, timeOffset) publicStatMetrics.put("totalDuration", totalDurationActual.toInt()) return totalDurationActual } override fun beforeActivityWrite(item: ActivityImpl, ownOrTotalDuration: Long, fieldName: String) { item.pluginId?.let { StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", ownOrTotalDuration, pluginCostMap) } if (fieldName == "items") { when (val itemName = item.name) { "splash initialization" -> { publicStatMetrics["splash"] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt() publicStatMetrics["splashShown"] = TimeUnit.NANOSECONDS.toMillis(item.end - StartUpMeasurer.getStartTime()).toInt() } "bootstrap", "app initialization" -> { publicStatMetrics[itemName] = TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt() } "project frame initialization" -> { publicStatMetrics["projectFrameVisible"] = TimeUnit.NANOSECONDS.toMillis(item.start - StartUpMeasurer.getStartTime()).toInt() } } } } } private fun writeIcons(writer: JsonGenerator) { writer.array("icons") { for (stat in IconLoadMeasurer.getStats()) { writer.obj { writer.writeStringField("name", stat.name) writer.writeNumberField("count", stat.count) writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalDuration)) } } } } private fun safeHashValue(value: String): String { val generator = Argon2BytesGenerator() generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build()) // 160 bit is enough for uniqueness val result = ByteArray(20) generator.generateBytes(value.toByteArray(), result, 0, result.size) return Base64.getEncoder().withoutPadding().encodeToString(result) } private fun writeServiceStats(writer: JsonGenerator) { class StatItem(val name: String) { var app = 0 var project = 0 var module = 0 } // components can be inferred from data, but to verify that items reported correctly (and because for items threshold is applied (not all are reported)) val component = StatItem("component") val service = StatItem("service") val pluginSet = PluginManagerCore.getPluginSet() for (plugin in pluginSet.getEnabledModules()) { service.app += plugin.appContainerDescriptor.services.size service.project += plugin.projectContainerDescriptor.services.size service.module += plugin.moduleContainerDescriptor.services.size component.app += plugin.appContainerDescriptor.components?.size ?: 0 component.project += plugin.projectContainerDescriptor.components?.size ?: 0 component.module += plugin.moduleContainerDescriptor.components?.size ?: 0 } writer.obj("stats") { writer.writeNumberField("plugin", pluginSet.enabledPlugins.size) for (statItem in listOf(component, service)) { writer.obj(statItem.name) { writer.writeNumberField("app", statItem.app) writer.writeNumberField("project", statItem.project) writer.writeNumberField("module", statItem.module) } } } writer.array("plugins") { for (plugin in pluginSet.enabledPlugins) { val classLoader = plugin.pluginClassLoader as? PluginAwareClassLoader ?: continue if (classLoader.loadedClassCount == 0L) { continue } writer.obj { writer.writeStringField("id", plugin.pluginId.idString) writer.writeNumberField("classCount", classLoader.loadedClassCount) writer.writeNumberField("classLoadingEdtTime", TimeUnit.NANOSECONDS.toMillis(classLoader.edtTime)) writer.writeNumberField("classLoadingBackgroundTime", TimeUnit.NANOSECONDS.toMillis(classLoader.backgroundTime)) } } } }
apache-2.0
a43c182badbb4fca98c0bc06fbe9fd2d
41.315
165
0.729378
4.740616
false
false
false
false
dahlstrom-g/intellij-community
java/java-analysis-api/src/com/intellij/uast/UastHintedVisitorAdapter.kt
7
1889
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uast import com.intellij.lang.Language import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.jetbrains.uast.UElement import org.jetbrains.uast.UastLanguagePlugin import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class UastHintedVisitorAdapter(private val plugin: UastLanguagePlugin, private val visitor: AbstractUastNonRecursiveVisitor, private val directOnly: Boolean, private val uElementTypesHint: Array<Class<out UElement>> ) : PsiElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) val uElement = plugin.convertElementWithParent(element, uElementTypesHint) ?: return if (directOnly && uElement.sourcePsi !== element) return uElement.accept(visitor) } companion object { @JvmStatic @JvmOverloads fun create(language: Language, visitor: AbstractUastNonRecursiveVisitor, uElementTypesHint: Array<Class<out UElement>>, directOnly: Boolean = true): PsiElementVisitor { val plugin = UastLanguagePlugin.byLanguage(language) ?: return EMPTY_VISITOR if (uElementTypesHint.size == 1) { return object: PsiElementVisitor() { override fun visitElement(element: PsiElement) { val uElement = plugin.convertElementWithParent(element, uElementTypesHint[0]) ?: return if (!directOnly || uElement.sourcePsi === element) { uElement.accept(visitor) } } } } return UastHintedVisitorAdapter(plugin, visitor, directOnly, uElementTypesHint) } } }
apache-2.0
707df5a078a520386f3a3076fc0d4c8d
41
140
0.681313
5.261838
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinTypeAliasByExpansionShortNameIndex.kt
3
1595
// 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 object KotlinTypeAliasByExpansionShortNameIndex : StringStubIndexExtension<KtTypeAlias>() { val KEY: StubIndexKey<String, KtTypeAlias> = StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasByExpansionShortNameIndex") override fun getKey(): StubIndexKey<String, KtTypeAlias> = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> { return StubIndex.getElements(KEY, key, project, scope, KtTypeAlias::class.java) } @JvmField @Suppress("REDECLARATION") val Companion: Companion = getJavaClass<Companion>().getField("INSTANCE").get(null) as Companion @Suppress("REDECLARATION") object Companion { @Deprecated( "Use KotlinTypeAliasByExpansionShortNameIndex as object instead.", ReplaceWith("KotlinTypeAliasByExpansionShortNameIndex"), DeprecationLevel.ERROR ) @JvmStatic fun getINSTANCE() = KotlinTypeAliasByExpansionShortNameIndex } } private inline fun <reified T: Any> getJavaClass(): Class<T> = T::class.java
apache-2.0
6b1f4f069c7ae74e1059fbe8fb05ba3a
41
158
0.755486
5.015723
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt
2
6616
// 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.console import com.intellij.execution.configurations.CompositeParameterTargetedValue import com.intellij.execution.configurations.JavaCommandLineState import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetedCommandLine import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.KotlinIdeaReplBundle import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.plugin.KotlinCompilerClasspathProvider import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.util.JavaParametersBuilder import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.projectStructure.version import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.platform.subplatformsOfType import java.util.concurrent.ConcurrentHashMap import kotlin.io.path.absolutePathString import kotlin.io.path.exists import kotlin.io.path.notExists class KotlinConsoleKeeper(val project: Project) { private val consoleMap: MutableMap<VirtualFile, KotlinConsoleRunner> = ConcurrentHashMap() fun getConsoleByVirtualFile(virtualFile: VirtualFile) = consoleMap[virtualFile] fun putVirtualFileToConsole(virtualFile: VirtualFile, console: KotlinConsoleRunner) = consoleMap.put(virtualFile, console) fun removeConsole(virtualFile: VirtualFile) = consoleMap.remove(virtualFile) fun run(module: Module, previousCompilationFailed: Boolean = false): KotlinConsoleRunner { val path = module.moduleFilePath val (environmentRequest, cmdLine) = createReplCommandLine(project, module) val consoleRunner = KotlinConsoleRunner( module, environmentRequest, cmdLine, previousCompilationFailed, project, KotlinIdeaReplBundle.message("name.kotlin.repl"), path ) consoleRunner.initAndRun() return consoleRunner } companion object { private val LOG = Logger.getInstance("#org.jetbrains.kotlin.console") @JvmStatic fun getInstance(project: Project): KotlinConsoleKeeper = project.service() fun createReplCommandLine(project: Project, module: Module?): Pair<TargetEnvironmentRequest, TargetedCommandLine> { val javaParameters = JavaParametersBuilder(project) .withSdkFrom(module, true) .withMainClassName("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler") .build() val wslConfiguration = JavaCommandLineState.checkCreateWslConfiguration(javaParameters.jdk) val request = wslConfiguration?.createEnvironmentRequest(project) ?: LocalTargetEnvironmentRequest() javaParameters.charset = null with(javaParameters.vmParametersList) { add("-Dkotlin.repl.ideMode=true") if (isUnitTestMode() && javaParameters.jdk?.version?.isAtLeast(JavaSdkVersion.JDK_1_9) == true) { // TODO: Have to get rid of illegal access to java.util.ResourceBundle.setParent(java.util.ResourceBundle): // WARNING: Illegal reflective access by com.intellij.util.ReflectionUtil (file:...kotlin-ide/intellij/out/kotlinc-dist/kotlinc/lib/kotlin-compiler.jar) to method java.util.ResourceBundle.setParent(java.util.ResourceBundle) // WARNING: Please consider reporting this to the maintainers of com.intellij.util.ReflectionUtil // WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations // WARNING: All illegal access operations will be denied in a future release add("--add-opens") add("java.base/java.util=ALL-UNNAMED") } } javaParameters.classPath.apply { val classPath = KotlinCompilerClasspathProvider.compilerWithScriptingClasspath.value addAll(classPath.map { file -> val path = file.toPath() val absolutePath = path.absolutePathString() if (path.notExists()) { LOG.warn("Compiler dependency classpath $absolutePath does not exist") } absolutePath }) } if (module != null) { val classPath = JavaParametersBuilder.getModuleDependencies(module) if (classPath.isNotEmpty()) { javaParameters.setUseDynamicParameters(javaParameters.isDynamicClasspath) with(javaParameters.programParametersList) { add("-cp") val compositeValue = CompositeParameterTargetedValue() for ((index, s) in classPath.withIndex()) { if (index > 0) { compositeValue.addLocalPart(request.targetPlatform.platform.pathSeparator.toString()) } compositeValue.addPathPart(s) } add(compositeValue) } } module.platform.subplatformsOfType<JdkPlatform>().firstOrNull()?.targetVersion?.let { with(javaParameters.programParametersList) { add("-jvm-target") add(it.description) } } } with(javaParameters.programParametersList) { add("-kotlin-home") val kotlinHome = KotlinPluginLayout.kotlinc check(kotlinHome.exists()) { "Kotlin compiler is not found" } add(CompositeParameterTargetedValue().addPathPart(kotlinHome.toPath().absolutePathString())) } return request to javaParameters.toCommandLine(request).build() } } }
apache-2.0
45baa482330a082d0f42f6909e9fab55
49.121212
244
0.664601
5.405229
false
false
false
false
flesire/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/pagination/PaginatedList.kt
1
1416
package net.nemerosa.ontrack.model.pagination /** * List of objects with some pagination information. * * @property pageInfo Information about the current page * @property pageItems Items in the current page */ class PaginatedList<T>( val pageInfo: PageInfo, val pageItems: List<T> ) { companion object { @JvmStatic fun <T> create( items: List<T>, offset: Int, pageSize: Int ) = create( items.subList( maxOf(offset, 0), maxOf(minOf(offset + pageSize, items.size), 0) ), offset, pageSize, items.size ) fun <T> create( items: List<T>, offset: Int, pageSize: Int, total: Int): PaginatedList<T> { return PaginatedList( pageInfo = PageInfo( totalSize = total, currentOffset = offset, currentSize = items.size, previousPage = PageRequest(offset, items.size).previous(total, pageSize), nextPage = PageRequest(offset, items.size).next(total, pageSize) ), pageItems = items ) } } }
mit
45fe0be9dcf3546007c6ffb390d2d31e
29.148936
101
0.456215
5.488372
false
false
false
false
paplorinc/intellij-community
python/pydevSrc/com/jetbrains/python/debugger/pydev/RecurrentTaskExecutor.kt
7
6527
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.debugger.pydev import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ConcurrencyUtil import com.jetbrains.python.debugger.pydev.RecurrentTaskExecutor.Companion.FIXED_THREAD_POOL_SIZE import com.jetbrains.python.debugger.pydev.RecurrentTaskExecutor.Companion.PERFORM_TASK_ATTEMPT_DELAY import com.jetbrains.python.debugger.pydev.RecurrentTaskExecutor.RecurrentTask import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * Provides the way to execute monotonous lengthy tasks performed by the * [recurrentTask]. The task may either succeed and the [T] result is returned * or it may fail and the [Exception] is thrown in this case. * * The tasks are tried to be executed using [FIXED_THREAD_POOL_SIZE] threads. * The new task execution is scheduled after the [RecurrentTaskExecutor] * receives new request(s) using [incrementRequests]. When this happens one of * the [executorService] threads calls [RecurrentTask.tryToPerform] of the * [recurrentTask]. If the call does not end in [PERFORM_TASK_ATTEMPT_DELAY] * period of time or fail within it then the next thread attempts to do the * same task. * * Finally when the next task has been successfully executed the number of * requests is decreased. * * **Note!** The single request could be successfully executed by several * threads what would decrement [activeRequests] so that it could become a * negative number. * * The workflow of using the [RecurrentTaskExecutor]: * - instantiate [RecurrentTaskExecutor]; * - call [RecurrentTaskExecutor.incrementRequests] when the new request is * required to be performed; * - handle the successfully executed request at * [RecurrentTaskExecutor.Callback.onSuccess]; * - call [RecurrentTaskExecutor.dispose] when `this` [RecurrentTaskExecutor] * is no longer needed to shutdown the executor service and stop the task * threads. */ class RecurrentTaskExecutor<out T>(threadsName: String, private val recurrentTask: RecurrentTask<T>, private val callback: Callback<T>) { private val executorService: ExecutorService /** * Guards [activeRequests]. */ private val lock = ReentrantLock() /** * Represents the number of the: * - increased on [incrementRequests]; * - decreased on the successful task execution after which the * [RecurrentTaskExecutor.Callback.onSuccess] callback method executed. * * Guarded by [lock]. */ private var activeRequests = 0 /** * Occurs when [activeRequests] > 0. */ private val notZeroRequests = lock.newCondition() private val timeCondition = lock.newCondition() /** * Guarded by [lock]. */ private var lastRequestAttemptTime = System.nanoTime() init { val threadFactory = ConcurrencyUtil.newNamedThreadFactory(threadsName) executorService = Executors.newFixedThreadPool(FIXED_THREAD_POOL_SIZE, threadFactory) repeat(FIXED_THREAD_POOL_SIZE, { executorService.submit(TaskRunnable()) }) } fun incrementRequests() { lock.withLock { activeRequests++ notZeroRequests.signalAll() } } fun dispose() { executorService.shutdownNow() } private inner class TaskRunnable : Runnable { override fun run() { while (true) { try { waitForRequests() tryToPerformTaskAndHandleSuccess() } catch (e: InterruptedException) { if (executorService.isShutdown) { // exit while loop return } else { // this case is not generally expected LOG.debug(e) } } catch (e: Exception) { LOG.debug(e) } } } } /** * Waits for [hasActiveRequests] to become `true`. Also the method does not * return until [PERFORM_TASK_ATTEMPT_DELAY] elapses since the last * [waitForRequests] exit. * * @throws InterruptedException if [dispose] has been called and the * [executorService] has been shut down */ @Throws(InterruptedException::class) private fun waitForRequests() { lock.withLock { do { while (!hasActiveRequests()) { notZeroRequests.await() } // we have process requests, let's check if we should start do { // check the latest time we tried to perform the task val currentTime = System.nanoTime() val timeToStart = lastRequestAttemptTime + PERFORM_TASK_ATTEMPT_DELAY if (timeToStart > currentTime) { val timeToSleep = timeToStart - currentTime timeCondition.awaitNanos(timeToSleep) } else { // it's time to run! break } } while (hasActiveRequests()) } while (!hasActiveRequests()) // let's check requests again // finally we made through it lastRequestAttemptTime = System.nanoTime() } } /** * **Note!** Should be called within [lock]. */ private fun hasActiveRequests() = activeRequests > 0 /** * Tries to perform the task using [RecurrentTask.tryToPerform]. On * successful execution it decrements the [activeRequests] number and * discharges the [lastRequestAttemptTime] for other worker threads to try * their luck if [hasActiveRequests] is still `true`. */ @Throws(Exception::class, InterruptedException::class) private fun tryToPerformTaskAndHandleSuccess() { val requestResult = recurrentTask.tryToPerform() lock.withLock { activeRequests-- // let the next tasks attempt to perform the task lastRequestAttemptTime = System.nanoTime() - PERFORM_TASK_ATTEMPT_DELAY timeCondition.signalAll() } callback.onSuccess(requestResult) } interface RecurrentTask<out T> { @Throws(Exception::class, InterruptedException::class) fun tryToPerform(): T } interface Callback<in T> { fun onSuccess(result: T) } companion object { private const val FIXED_THREAD_POOL_SIZE = 10 private val LOG = Logger.getInstance(RecurrentTaskExecutor::class.java) private val PERFORM_TASK_ATTEMPT_DELAY = TimeUnit.MILLISECONDS.toNanos(500L) } }
apache-2.0
197256107f03c72cd306a56926a9a998
31.157635
140
0.68546
4.535789
false
false
false
false
google/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/LanguageToolChecker.kt
3
10550
package com.intellij.grazie.grammar import com.intellij.grazie.GrazieBundle import com.intellij.grazie.GrazieConfig import com.intellij.grazie.GraziePlugin import com.intellij.grazie.detection.LangDetector import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.jlanguage.LangTool import com.intellij.grazie.text.* import com.intellij.grazie.utils.* import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.ClassLoaderUtil import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.TextRange import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.ExceptionUtil import com.intellij.util.containers.Interner import kotlinx.html.* import org.languagetool.JLanguageTool import org.languagetool.Languages import org.languagetool.markup.AnnotatedTextBuilder import org.languagetool.rules.GenericUnpairedBracketsRule import org.languagetool.rules.RuleMatch import org.slf4j.LoggerFactory import java.util.* open class LanguageToolChecker : TextChecker() { override fun getRules(locale: Locale): Collection<Rule> { val language = Languages.getLanguageForLocale(locale) val state = GrazieConfig.get() val lang = state.enabledLanguages.find { language == it.jLanguage } ?: return emptyList() return grammarRules(LangTool.getTool(lang), lang) } override fun check(extracted: TextContent): List<Problem> { return CachedValuesManager.getManager(extracted.containingFile.project).getCachedValue(extracted) { CachedValueProvider.Result.create(doCheck(extracted), extracted.containingFile) } } private fun doCheck(extracted: TextContent): List<Problem> { val str = extracted.toString() if (str.isBlank()) return emptyList() val lang = LangDetector.getLang(str) ?: return emptyList() return try { ClassLoaderUtil.computeWithClassLoader<List<Problem>, Throwable>(GraziePlugin.classLoader) { val tool = LangTool.getTool(lang) val sentences = tool.sentenceTokenize(str) if (sentences.any { it.length > 1000 }) emptyList() else { val annotated = AnnotatedTextBuilder().addText(str).build() val matches = tool.check(annotated, true, JLanguageTool.ParagraphHandling.NORMAL, null, JLanguageTool.Mode.ALL, JLanguageTool.Level.PICKY) matches.asSequence() .map { Problem(it, lang, extracted, this is TestChecker) } .filterNot { isGitCherryPickedFrom(it.match, extracted) } .filterNot { isKnownLTBug(it.match, extracted) } .filterNot { val range = if (it.fitsGroup(RuleGroup.CASING)) includeSentenceBounds(extracted, it.patternRange) else it.patternRange extracted.hasUnknownFragmentsIn(range) } .toList() } } } catch (e: Throwable) { if (ExceptionUtil.causedBy(e, ProcessCanceledException::class.java)) { throw ProcessCanceledException() } logger.warn("Got exception from LanguageTool", e) emptyList() } } private fun includeSentenceBounds(text: CharSequence, range: TextRange): TextRange { var start = range.startOffset var end = range.endOffset while (start > 0 && text[start - 1].isWhitespace()) start-- while (end < text.length && text[end].isWhitespace()) end++ return TextRange(start, end) } class Problem(val match: RuleMatch, lang: Lang, text: TextContent, val testDescription: Boolean) : TextProblem(LanguageToolRule(lang, match.rule), text, TextRange(match.fromPos, match.toPos)) { override fun getShortMessage(): String = match.shortMessage.trimToNull() ?: match.rule.description.trimToNull() ?: match.rule.category.name override fun getDescriptionTemplate(isOnTheFly: Boolean): String = if (testDescription) match.rule.id else match.messageSanitized override fun getTooltipTemplate(): String = toTooltipTemplate(match) override fun getSuggestions(): List<Suggestion> = match.suggestedReplacements.map { Suggestion.replace(highlightRanges[0], it) } override fun getPatternRange() = TextRange(match.patternFromPos, match.patternToPos) override fun fitsGroup(group: RuleGroup): Boolean { val highlightRange = highlightRanges[0] val ruleId = match.rule.id if (RuleGroup.INCOMPLETE_SENTENCE in group.rules) { if (highlightRange.startOffset == 0 && (ruleId == "SENTENCE_FRAGMENT" || ruleId == "SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA" || ruleId == "AGREEMENT_SENT_START")) { return true } if (ruleId == "MASS_AGREEMENT" && text.subSequence(highlightRange.endOffset, text.length).startsWith(".")) { return true } } if (RuleGroup.UNDECORATED_SENTENCE_SEPARATION in group.rules && ruleId in sentenceSeparationRules) { return true } return super.fitsGroup(group) || group.rules.any { id -> isAbstractCategory(id) && ruleId == id } } private fun isAbstractCategory(id: String) = id == RuleGroup.SENTENCE_END_PUNCTUATION || id == RuleGroup.SENTENCE_START_CASE || id == RuleGroup.UNLIKELY_OPENING_PUNCTUATION } companion object { private val logger = LoggerFactory.getLogger(LanguageToolChecker::class.java) private val interner = Interner.createWeakInterner<String>() private val sentenceSeparationRules = setOf("LC_AFTER_PERIOD", "PUNT_GEEN_HL", "KLEIN_NACH_PUNKT") private val openClosedRangeStart = Regex("[\\[(].+?(\\.\\.|:|,).+[])]") private val openClosedRangeEnd = Regex(".*" + openClosedRangeStart.pattern) internal fun grammarRules(tool: JLanguageTool, lang: Lang): List<LanguageToolRule> { return tool.allRules.asSequence() .distinctBy { it.id } .filter { r -> !r.isDictionaryBasedSpellingRule } .map { LanguageToolRule(lang, it) } .toList() } /** * Git adds "cherry picked from", which doesn't seem entirely grammatical, * but zillions of tools depend on this message, and it's unlikely to be changed. * So we ignore this pattern in commit messages and literals (which might be used for parsing git output) */ private fun isGitCherryPickedFrom(match: RuleMatch, text: TextContent): Boolean { return match.rule.id == "EN_COMPOUNDS" && match.fromPos > 0 && text.startsWith("(cherry picked from", match.fromPos - 1) && (text.domain == TextContent.TextDomain.LITERALS || text.domain == TextContent.TextDomain.PLAIN_TEXT && CommitMessage.isCommitMessage(text.containingFile)) } private fun isKnownLTBug(match: RuleMatch, text: TextContent): Boolean { if (match.rule is GenericUnpairedBracketsRule && match.fromPos > 0) { if (text.startsWith("\")", match.fromPos - 1) || text.subSequence(0, match.fromPos).contains("(\"")) { return true //https://github.com/languagetool-org/languagetool/issues/5269 } if (couldBeOpenClosedRange(text, match.fromPos)) { return true } } if (match.rule.id == "ARTICLE_ADJECTIVE_OF" && text.substring(match.fromPos, match.toPos).equals("iterable", ignoreCase = true)) { return true // https://github.com/languagetool-org/languagetool/issues/5270 } if (match.rule.id.endsWith("DOUBLE_PUNCTUATION") && (isNumberRange(match.fromPos, match.toPos, text) || isPathPart(match.fromPos, match.toPos, text))) { return true } return false } // https://github.com/languagetool-org/languagetool/issues/6566 private fun couldBeOpenClosedRange(text: TextContent, index: Int): Boolean { val unpaired = text[index] return "([".contains(unpaired) && openClosedRangeStart.matchesAt(text, index) || ")]".contains(unpaired) && openClosedRangeEnd.matches(text.subSequence(0, index + 1)) } // https://github.com/languagetool-org/languagetool/issues/5230 private fun isNumberRange(startOffset: Int, endOffset: Int, text: TextContent): Boolean { return startOffset > 0 && endOffset < text.length && text[startOffset - 1].isDigit() && text[endOffset].isDigit() } // https://github.com/languagetool-org/languagetool/issues/5883 private fun isPathPart(startOffset: Int, endOffset: Int, text: TextContent): Boolean { return text.subSequence(0, startOffset).endsWith('/') || text.subSequence(endOffset, text.length).startsWith('/') } @NlsSafe private fun toTooltipTemplate(match: RuleMatch): String { val html = html { val withCorrections = match.rule.incorrectExamples.filter { it.corrections.isNotEmpty() }.takeIf { it.isNotEmpty() } val incorrectExample = (withCorrections ?: match.rule.incorrectExamples).minByOrNull { it.example.length } p { incorrectExample?.let { style = "padding-bottom: 8px;" } +match.messageSanitized nbsp() } table { cellpading = "0" cellspacing = "0" incorrectExample?.let { tr { td { valign = "top" style = "padding-right: 5px; color: gray; vertical-align: top;" +" " +GrazieBundle.message("grazie.settings.grammar.rule.incorrect") +" " nbsp() } td { style = "width: 100%;" toIncorrectHtml(it) nbsp() } } if (it.corrections.isNotEmpty()) { tr { td { valign = "top" style = "padding-top: 5px; padding-right: 5px; color: gray; vertical-align: top;" +" " +GrazieBundle.message("grazie.settings.grammar.rule.correct") +" " nbsp() } td { style = "padding-top: 5px; width: 100%;" toCorrectHtml(it) nbsp() } } } } } p { style = "text-align: left; font-size: x-small; color: gray; padding-top: 10px; padding-bottom: 0px;" +" " +GrazieBundle.message("grazie.tooltip.powered-by-language-tool") } } return interner.intern(html) } } class TestChecker: LanguageToolChecker() }
apache-2.0
8ef1a09831f579037a4441cc3b75ac24
39.421456
141
0.652512
4.271255
false
false
false
false
google/intellij-community
platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringStateChanges.kt
6
8576
// 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.refactoring.suggested import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.suggested.SuggestedRefactoringState.ErrorLevel import com.intellij.refactoring.suggested.SuggestedRefactoringState.ParameterMarker import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature /** * A service transforming a sequence of declaration states into [SuggestedRefactoringState]. */ abstract class SuggestedRefactoringStateChanges(protected val refactoringSupport: SuggestedRefactoringSupport) { /** * Extracts information from declaration and stores it in an instance of [Signature] class. * * For performance reasons, don't use any resolve in this method. More accurate information about changes can be obtained later * with use of [SuggestedRefactoringAvailability.refineSignaturesWithResolve]. * @param anchor declaration or call-site in its current state. * Only PsiElement's that are classified as anchors by [SuggestedRefactoringSupport.isAnchor] may be passed to this parameter. * @param prevState previous state of accumulated signature changes, or *null* if the user is just about to start editing the signature. * @return An instance of [Signature] class, representing the current state of the declaration, * or *null* if the declaration is in an incorrect state and no signature can be created. */ abstract fun signature(anchor: PsiElement, prevState: SuggestedRefactoringState?): Signature? /** * Provides "marker ranges" for parameters in the declaration. * * Marker ranges are used to keep track of parameter identity when its name changes. * A good marker range must have high chances of staying the same while editing the signature (with help of a [RangeMarker], of course). * If the language has a fixed separator between parameter name and type such as ':' - use it as a marker. * A whitespace between the type and the name is not so reliable because it may change its length or temporarily disappear. * Parameter type range is also a good marker because it's unlikely to change at the same time as the name changes. * @param anchor declaration or call-site in its current state. * Only PsiElement's that are classified as anchors by [SuggestedRefactoringSupport.isAnchor] may be passed to this parameter. * @return a list containing a marker range for each parameter, or *null* if no marker can be provided for this parameter */ abstract fun parameterMarkerRanges(anchor: PsiElement): List<TextRange?> open fun createInitialState(anchor: PsiElement): SuggestedRefactoringState? { val signature = signature(anchor, null) ?: return null val signatureRange = refactoringSupport.signatureRange(anchor) ?: return null val psiDocumentManager = PsiDocumentManager.getInstance(anchor.project) val file = anchor.containingFile val document = psiDocumentManager.getDocument(file)!! require(psiDocumentManager.isCommitted(document)) return SuggestedRefactoringState( anchor, refactoringSupport, errorLevel = ErrorLevel.NO_ERRORS, oldDeclarationText = document.getText(signatureRange), oldImportsText = refactoringSupport.importsRange(file) ?.extendWithWhitespace(document.charsSequence) ?.let { document.getText(it) }, oldSignature = signature, newSignature = signature, parameterMarkers = parameterMarkers(anchor, signature) ) } /** * Returns a declaration for a given anchor. Returns anchor itself if it's already a declaration, * or a declaration if anchor is a use-site. * * @param anchor declaration or call-site in its current state. * Only PsiElement's that are classified as anchors by [SuggestedRefactoringSupport.isAnchor] may be passed to this parameter. * @return found declaration. Could be null if anchor is a call-site that does not properly resolve. */ open fun findDeclaration(anchor: PsiElement): PsiElement? = anchor open fun updateState(state: SuggestedRefactoringState, anchor: PsiElement): SuggestedRefactoringState { val newSignature = signature(anchor, state) ?: return state.withErrorLevel(ErrorLevel.SYNTAX_ERROR) val idsPresent = newSignature.parameters.map { it.id }.toSet() val disappearedParameters = state.disappearedParameters.entries .filter { (_, id) -> id !in idsPresent } .associate { it.key to it.value } .toMutableMap() for ((id, name) in state.newSignature.parameters) { if (id !in idsPresent && state.oldSignature.parameterById(id) != null) { disappearedParameters[name] = id // one more parameter disappeared } } val parameterMarkers = parameterMarkers(anchor, newSignature).toMutableList() val syntaxError = refactoringSupport.hasSyntaxError(anchor) if (syntaxError) { // when there is a syntax error inside the signature, there can be parameters which are temporarily not parsed as parameters // we must keep their markers in order to match them later for (marker in state.parameterMarkers) { if (marker.rangeMarker.isValid && newSignature.parameterById(marker.parameterId) == null) { parameterMarkers += marker } } } return state .withAnchor(anchor) .withNewSignature(newSignature) .withErrorLevel(if (syntaxError) ErrorLevel.SYNTAX_ERROR else ErrorLevel.NO_ERRORS) .withParameterMarkers(parameterMarkers) .withDisappearedParameters(disappearedParameters) } protected fun matchParametersWithPrevState( signature: Signature, newDeclaration: PsiElement, prevState: SuggestedRefactoringState ): Signature { // first match all parameters by names (in prevState or in the history of changes) val ids = signature.parameters.map { guessParameterIdByName(it, prevState) }.toMutableList() // now match those that we could not match by name via marker ranges val markerRanges = parameterMarkerRanges(newDeclaration) for (index in signature.parameters.indices) { val markerRange = markerRanges[index] if (ids[index] == null && markerRange != null) { val id = guessParameterIdByMarkers(markerRange, prevState) if (id != null && id !in ids) { ids[index] = id } } } val newParameters = signature.parameters.zip(ids) { parameter, id -> parameter.copy(id = id ?: Any()/*new id*/) } return Signature.create(signature.name, signature.type, newParameters, signature.additionalData)!! } protected fun guessParameterIdByName(parameter: SuggestedRefactoringSupport.Parameter, prevState: SuggestedRefactoringState): Any? { prevState.newSignature.parameterByName(parameter.name) ?.let { return it.id } prevState.disappearedParameters[parameter.name] ?.let { return it } return null } protected open fun guessParameterIdByMarkers(markerRange: TextRange, prevState: SuggestedRefactoringState): Any? { return prevState.parameterMarkers.firstOrNull { it.rangeMarker.range == markerRange }?.parameterId } /** * Use this implementation of [SuggestedRefactoringStateChanges], if only Rename refactoring is supported for the language. */ class RenameOnly(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringStateChanges(refactoringSupport) { override fun signature(anchor: PsiElement, prevState: SuggestedRefactoringState?): Signature? { val name = (anchor as? PsiNamedElement)?.name ?: return null return Signature.create(name, null, emptyList(), null)!! } override fun parameterMarkerRanges(anchor: PsiElement): List<TextRange?> { return emptyList() } } } fun SuggestedRefactoringStateChanges.parameterMarkers(declaration: PsiElement, signature: Signature): List<ParameterMarker> { val document = PsiDocumentManager.getInstance(declaration.project).getDocument(declaration.containingFile)!! val markerRanges = parameterMarkerRanges(declaration) require(markerRanges.size == signature.parameters.size) return markerRanges.zip(signature.parameters) .mapNotNull { (range, parameter) -> range?.let { ParameterMarker(document.createRangeMarker(it), parameter.id) } } }
apache-2.0
9dd2a9b2696c3b53f58405b8955b75cd
48.572254
140
0.746502
4.917431
false
false
false
false
nicolaiparlog/energy-model
src/main/kotlin/org/codefx/demo/bingen/math/RomanNumerals.kt
4
1052
package org.codefx.demo.bingen.math fun asRoman(n: Int): String { if (n < 1 || 50 < n) { return "Invalid value $n for roman numerals." } var decimalRemainder = n var romanOutput = "" while (decimalRemainder >= 1) { if (decimalRemainder == 50) { romanOutput += "L" decimalRemainder -= 50 } else if (decimalRemainder >= 40) { romanOutput += "XL" decimalRemainder -= 40 } else if (decimalRemainder >= 10) { romanOutput += "X" decimalRemainder -= 10 } else if (decimalRemainder >= 9) { romanOutput += "IX" decimalRemainder -= 9 } else if (decimalRemainder >= 5) { romanOutput += "V" decimalRemainder -= 5 } else if (decimalRemainder >= 4) { romanOutput += "IV" decimalRemainder -= 4 } else if (decimalRemainder >= 1) { romanOutput += "I" decimalRemainder -= 1 } } return romanOutput }
cc0-1.0
23d723dfb8b66ad7166be543456e6b70
28.222222
53
0.507605
3.940075
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/DirectoryPackagingElementEntityImpl.kt
1
15297
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class DirectoryPackagingElementEntityImpl(val dataSource: DirectoryPackagingElementEntityData) : DirectoryPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, CompositePackagingElementEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ARTIFACT_CONNECTION_ID, CHILDREN_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val artifact: ArtifactEntity? get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) override val children: List<PackagingElementEntity> get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val directoryName: String get() = dataSource.directoryName override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: DirectoryPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<DirectoryPackagingElementEntity>(), DirectoryPackagingElementEntity.Builder { constructor() : this(DirectoryPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity DirectoryPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field CompositePackagingElementEntity#children should be initialized") } } if (!getEntityData().isDirectoryNameInitialized()) { error("Field DirectoryPackagingElementEntity#directoryName 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 DirectoryPackagingElementEntity this.entitySource = dataSource.entitySource this.directoryName = dataSource.directoryName if (parents != null) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var artifact: ArtifactEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } else { this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value } changedProperty.add("artifact") } override var children: List<PackagingElementEntity> get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList() } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence()) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var directoryName: String get() = getEntityData().directoryName set(value) { checkModificationAllowed() getEntityData().directoryName = value changedProperty.add("directoryName") } override fun getEntityData(): DirectoryPackagingElementEntityData = result ?: super.getEntityData() as DirectoryPackagingElementEntityData override fun getEntityClass(): Class<DirectoryPackagingElementEntity> = DirectoryPackagingElementEntity::class.java } } class DirectoryPackagingElementEntityData : WorkspaceEntityData<DirectoryPackagingElementEntity>() { lateinit var directoryName: String fun isDirectoryNameInitialized(): Boolean = ::directoryName.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<DirectoryPackagingElementEntity> { val modifiable = DirectoryPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): DirectoryPackagingElementEntity { return getCached(snapshot) { val entity = DirectoryPackagingElementEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return DirectoryPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return DirectoryPackagingElementEntity(directoryName, entitySource) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull() } } 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::class != other::class) return false other as DirectoryPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.directoryName != other.directoryName) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as DirectoryPackagingElementEntityData if (this.directoryName != other.directoryName) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + directoryName.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + directoryName.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
8d9d90dc589f3023feee755e131c5ea2
42.457386
178
0.669412
5.931369
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/learnIde/InteractiveCoursePanel.kt
7
9063
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen.learnIde import com.intellij.icons.AllIcons import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.wm.InteractiveCourseData import com.intellij.ui.RoundedLineBorder import com.intellij.ui.components.JBLabel import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import com.intellij.util.ui.StartupUiUtil import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.MouseListener import javax.swing.* import javax.swing.border.CompoundBorder import javax.swing.border.EmptyBorder import javax.swing.plaf.FontUIResource import javax.swing.plaf.LabelUI class InteractiveCoursePanel(private val data: InteractiveCourseData) : JPanel() { private enum class ContentState { COLLAPSED, EXPANDED } private val pluginPanelWidth = 72 private val chevronPanelWidth = 55 val startLearningButton = JButton() private val newContentMarker = data.newContentMarker() private val nameLine: JPanel? = if (data.newContentMarker() != null) JPanel() else null private val interactiveCourseDescription = HeightLimitedPane(data.getDescription(), -1, LearnIdeContentColorsAndFonts.HeaderColor) private val interactiveCourseContent = createInteractiveCourseContent() private var contentState: ContentState = ContentState.COLLAPSED private val expandCollapseListener: MouseListener = createExpandCollapseListener() private val expandedCourseContent: JComponent by lazy { data.getExpandContent() } private val chevronPanel = JPanel() private val chevronLabel = JLabel(AllIcons.General.ChevronDown) val pluginPanel = JPanel() val pluginLabel = JLabel(data.getIcon()) private val roundBorder1pxActive = CompoundBorder(RoundedLineBorder(LearnIdeContentColorsAndFonts.ActiveInteractiveCoursesBorder, 8, 1), JBUI.Borders.emptyRight(5)) private val roundBorder1pxInactive = CompoundBorder(RoundedLineBorder(LearnIdeContentColorsAndFonts.InactiveInteractiveCoursesBorder, 8, 1), JBUI.Borders.emptyRight(5)) private val calculateInnerComponentHeight: () -> Int = { preferredSize.height } init { initPluginPanel() initChevronPanel() layout = BoxLayout(this, BoxLayout.LINE_AXIS) isOpaque = false border = roundBorder1pxInactive alignmentX = LEFT_ALIGNMENT add(pluginPanel) add(interactiveCourseContent) add(chevronPanel) addMouseListener(expandCollapseListener) interactiveCourseDescription.addMouseListener(expandCollapseListener) } private fun initChevronPanel() { chevronPanel.apply { layout = BorderLayout() isOpaque = false alignmentY = TOP_ALIGNMENT add(chevronLabel, BorderLayout.CENTER) add(createUnshrinkablePanel(chevronPanelWidth), BorderLayout.NORTH) } } private fun initPluginPanel() { pluginPanel.apply { layout = BorderLayout() border = EmptyBorder(12, 0, 0, 0) isOpaque = false add(pluginLabel, BorderLayout.NORTH) alignmentY = TOP_ALIGNMENT add(createUnshrinkablePanel(pluginPanelWidth), BorderLayout.CENTER) } } private fun createUnshrinkablePanel(_width: Int): JPanel { return object: JPanel() { init { preferredSize = Dimension(JBUIScale.scale(_width), 1) minimumSize = Dimension(JBUIScale.scale(_width), 1) isOpaque = false } override fun updateUI() { super.updateUI() preferredSize = Dimension(JBUIScale.scale(_width), 1) minimumSize = Dimension(JBUIScale.scale(_width), 1) isOpaque = false } } } override fun getMaximumSize(): Dimension { return Dimension(this.preferredSize.width, calculateInnerComponentHeight()) } private fun createInteractiveCourseContent(): JPanel { val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.PAGE_AXIS) panel.isOpaque = false panel.alignmentY = TOP_ALIGNMENT panel.add(rigid(12, 10)) val learnIdeFeaturesHeader = DynamicFontLabel(data.getName()) learnIdeFeaturesHeader.apply { val labelFont = StartupUiUtil.getLabelFont() font = labelFont.deriveFont(Font.BOLD).deriveFont(labelFont.size2D + if (SystemInfo.isWindows) JBUIScale.scale(1) else 0 ) } learnIdeFeaturesHeader.alignmentX = LEFT_ALIGNMENT if (nameLine != null) { nameLine.isOpaque = false nameLine.layout = BoxLayout(nameLine, BoxLayout.X_AXIS) nameLine.alignmentX = LEFT_ALIGNMENT nameLine.add(learnIdeFeaturesHeader) nameLine.add(rigid(10, 0)) nameLine.add(newContentMarker) panel.add(nameLine) } else { panel.add(learnIdeFeaturesHeader) } panel.add(rigid(1, 4)) panel.add(interactiveCourseDescription) panel.add(rigid(4, 9)) startLearningButton.action = data.getAction() startLearningButton.margin = Insets(0, 0, 0, 0) startLearningButton.isSelected = true startLearningButton.isOpaque = false startLearningButton.alignmentX = LEFT_ALIGNMENT val buttonPlace = buttonPixelHunting(startLearningButton) panel.add(buttonPlace) panel.add(rigid(18, 21)) return panel } private fun createExpandCollapseListener(): MouseAdapter { return object : MouseAdapter() { override fun mouseEntered(e: MouseEvent?) { if (contentState == ContentState.EXPANDED) return activateLearnIdeFeaturesPanel() } override fun mouseExited(e: MouseEvent?) { if (e == null) return deactivateLearnIdeFeaturesPanel(e.locationOnScreen) } override fun mousePressed(e: MouseEvent?) { onLearnIdeFeaturesPanelClick() } } } private fun buttonPixelHunting(button: JButton): JPanel { val buttonSizeWithoutInsets = Dimension(button.preferredSize.width - button.insets.left - button.insets.right, button.preferredSize.height - button.insets.top - button.insets.bottom) val buttonPlace = JPanel().apply { layout = null maximumSize = buttonSizeWithoutInsets preferredSize = buttonSizeWithoutInsets minimumSize = buttonSizeWithoutInsets isOpaque = false alignmentX = LEFT_ALIGNMENT } buttonPlace.add(button) button.bounds = Rectangle(-button.insets.left, -button.insets.top, button.preferredSize.width, button.preferredSize.height) return buttonPlace } private fun activateLearnIdeFeaturesPanel() { background = LearnIdeContentColorsAndFonts.HoveredColor isOpaque = true border = roundBorder1pxActive repaint() cursor = Cursor(Cursor.HAND_CURSOR) } private fun deactivateLearnIdeFeaturesPanel(mouseLocationOnScreen: Point) { if (pointerInLearnIdeFeaturesPanel(mouseLocationOnScreen)) return isOpaque = false border = roundBorder1pxInactive repaint() cursor = Cursor(Cursor.DEFAULT_CURSOR) } private fun onLearnIdeFeaturesPanelClick() { if (contentState == ContentState.COLLAPSED) { expandContent() chevronLabel.icon = AllIcons.General.ChevronUp contentState = ContentState.EXPANDED } else { collapseContent() chevronLabel.icon = AllIcons.General.ChevronDown contentState = ContentState.COLLAPSED } chevronLabel.repaint() } private fun expandContent() { this.isOpaque = false interactiveCourseDescription.maximumSize = interactiveCourseDescription.preferredSize interactiveCourseContent.add(expandedCourseContent) nameLine?.remove(newContentMarker) chevronPanel.maximumSize = chevronPanel.size interactiveCourseContent.revalidate() interactiveCourseContent.repaint() border = roundBorder1pxInactive repaint() } private fun collapseContent() { val pointerLocation = MouseInfo.getPointerInfo().location if (pointerInLearnIdeFeaturesPanel(pointerLocation)) activateLearnIdeFeaturesPanel() interactiveCourseContent.remove(expandedCourseContent) nameLine?.add(newContentMarker) interactiveCourseContent.revalidate() interactiveCourseContent.repaint() repaint() } private fun pointerInLearnIdeFeaturesPanel(mouseLocationOnScreen: Point) = Rectangle(Point(locationOnScreen.x + 1, locationOnScreen.y + 1), Dimension(bounds.size.width - 2, bounds.size.height - 2)).contains( mouseLocationOnScreen) private fun rigid(_width: Int, _height: Int): Component { return Box.createRigidArea( Dimension(JBUI.scale(_width), JBUI.scale(_height))).apply { (this as JComponent).alignmentX = LEFT_ALIGNMENT } } class DynamicFontLabel(@Nls text: String): JBLabel(text) { override fun setUI(ui: LabelUI?) { super.setUI(ui) if (font != null) { font = FontUIResource(font.deriveFont( StartupUiUtil.getLabelFont().size.toFloat() + if (SystemInfo.isWindows) JBUIScale.scale(1) else 0 ).deriveFont(Font.BOLD)) } } } }
apache-2.0
e5fd60d4d64ecda929ce0fc894c13685
32.323529
170
0.732208
4.497767
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/UselessCallOnNotNullInspection.kt
1
5406
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.quickfix.ReplaceWithDotCallFix import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.utils.addToStdlib.safeAs class UselessCallOnNotNullInspection : AbstractUselessCallInspection() { override val uselessFqNames = mapOf( "kotlin.collections.orEmpty" to deleteConversion, "kotlin.sequences.orEmpty" to deleteConversion, "kotlin.text.orEmpty" to deleteConversion, "kotlin.text.isNullOrEmpty" to Conversion("isEmpty"), "kotlin.text.isNullOrBlank" to Conversion("isBlank"), "kotlin.collections.isNullOrEmpty" to Conversion("isEmpty") ) override val uselessNames = uselessFqNames.keys.toShortNames() override fun QualifiedExpressionVisitor.suggestConversionIfNeeded( expression: KtQualifiedExpression, calleeExpression: KtExpression, context: BindingContext, conversion: Conversion ) { val newName = conversion.replacementName val safeExpression = expression as? KtSafeQualifiedExpression val notNullType = expression.receiverExpression.isNotNullType(context) val defaultRange = TextRange(expression.operationTokenNode.startOffset, calleeExpression.endOffset).shiftRight(-expression.startOffset) if (newName != null && (notNullType || safeExpression != null)) { val fixes = listOfNotNull( createRenameUselessCallFix(expression, newName, context), safeExpression?.let { IntentionWrapper(ReplaceWithDotCallFix(safeExpression)) } ) val descriptor = holder.manager.createProblemDescriptor( expression, defaultRange, KotlinBundle.message("call.on.not.null.type.may.be.reduced"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, *fixes.toTypedArray() ) holder.registerProblem(descriptor) } else if (notNullType) { val descriptor = holder.manager.createProblemDescriptor( expression, defaultRange, KotlinBundle.message("useless.call.on.not.null.type"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, isOnTheFly, RemoveUselessCallFix() ) holder.registerProblem(descriptor) } else if (safeExpression != null) { holder.registerProblem( safeExpression.operationTokenNode.psi, KotlinBundle.message("this.call.is.useless.with"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(ReplaceWithDotCallFix(safeExpression)) ) } } private fun KtExpression.isNotNullType(context: BindingContext): Boolean { val type = getType(context) ?: return false val dataFlowValueFactory = getResolutionFacade().dataFlowValueFactory val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, findModuleDescriptor()) val stableNullability = context.getDataFlowInfoBefore(this).getStableNullability(dataFlowValue) return !stableNullability.canBeNull() } private fun createRenameUselessCallFix( expression: KtQualifiedExpression, newFunctionName: String, context: BindingContext ): RenameUselessCallFix { if (expression.parent.safeAs<KtPrefixExpression>()?.operationToken != KtTokens.EXCL) { return RenameUselessCallFix(newFunctionName, invert = false) } val copy = expression.copy().safeAs<KtQualifiedExpression>()?.apply { callExpression?.calleeExpression?.replace(KtPsiFactory(expression.project).createExpression(newFunctionName)) } val newContext = copy?.analyzeAsReplacement(expression, context) val invertedName = copy?.invertSelectorFunction(newContext)?.callExpression?.calleeExpression?.text return if (invertedName != null) { RenameUselessCallFix(invertedName, invert = true) } else { RenameUselessCallFix(newFunctionName, invert = false) } } }
apache-2.0
e8eba9d52c6ffb409f12183eaa0a8a00
47.267857
158
0.715686
5.39521
false
false
false
false
littleGnAl/Accounting
app/src/main/java/com/littlegnal/accounting/base/DefaultItemDecoration.kt
1
2161
/* * Copyright (C) 2017 littlegnal * * 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.littlegnal.accounting.base import android.graphics.Canvas import android.graphics.drawable.ColorDrawable import androidx.recyclerview.widget.RecyclerView import android.view.View import androidx.recyclerview.widget.RecyclerView.State import com.airbnb.epoxy.EpoxyControllerAdapter import com.airbnb.epoxy.EpoxyModel import com.littlegnal.accounting.base.util.dip /** * 项目中默认的[RecyclerView.ItemDecoration],使用[isDrawableDividerItem]方法来控制是否绘制分割线 */ class DefaultItemDecoration( private val epoxyControllerAdapter: EpoxyControllerAdapter, private val isDrawableDividerItem: (EpoxyModel<*>) -> Boolean ) : RecyclerView.ItemDecoration() { private val divider: ColorDrawable = ColorDrawable(0xfff3f3f3.toInt()) override fun onDrawOver( c: Canvas, parent: RecyclerView, state: State ) { val childCount: Int? = parent.childCount for (i in 0 until childCount!!) { val child: View = parent.getChildAt(i) val adapterPosition: Int = parent.getChildAdapterPosition(child) if (adapterPosition >= 0 && adapterPosition < parent.adapter?.itemCount!! - 1) { val epoxyModel: EpoxyModel<*> = epoxyControllerAdapter.getModelAtPosition(adapterPosition) if (isDrawableDividerItem(epoxyModel)) { c.save() divider.setBounds( parent.dip(16), child.bottom, parent.width, child.bottom + parent.dip(1) ) divider.draw(c) c.restore() } } } } }
apache-2.0
1cfc7c87f27d00d5e2cfcee09c7ae0b6
32.634921
98
0.709769
4.289474
false
false
false
false
allotria/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ClassToIntConverter.kt
2
1231
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.google.common.collect.HashBiMap import com.intellij.workspaceModel.storage.WorkspaceEntity import java.util.concurrent.atomic.AtomicInteger internal object ClassToIntConverter { private val class2Int = HashBiMap.create<Class<*>, Int>() private val idGenerator = AtomicInteger() @Synchronized fun getInt(clazz: Class<*>): Int = class2Int.getOrPut(clazz) { idGenerator.getAndIncrement() } @Synchronized fun getClassOrDie(id: Int): Class<*> = class2Int.inverse().getValue(id) fun getMap(): HashBiMap<Class<*>, Int> = class2Int fun fromMap(map: Map<Class<*>, Int>) { class2Int.clear() class2Int.putAll(map) idGenerator.set((map.map { it.value }.maxOrNull() ?: -1) + 1) } } internal fun Class<*>.toClassId(): Int = ClassToIntConverter.getInt(this) internal inline fun <reified E> Int.findEntityClass(): Class<E> = ClassToIntConverter.getClassOrDie(this) as Class<E> internal fun Int.findWorkspaceEntity(): Class<WorkspaceEntity> = ClassToIntConverter.getClassOrDie(this) as Class<WorkspaceEntity>
apache-2.0
46173a34f0f6e9ee2f0edf373e3bbbc9
40.033333
140
0.754671
4.103333
false
false
false
false
stevesea/RPGpad
adventuresmith-core/src/main/kotlin/org/stevesea/adventuresmith/core/RangeMap.kt
2
3407
/* * Copyright (c) 2016 Steve Christensen * * This file is part of Adventuresmith. * * Adventuresmith 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. * * Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>. * */ package org.stevesea.adventuresmith.core import com.fasterxml.jackson.annotation.JsonIdentityInfo import com.fasterxml.jackson.annotation.ObjectIdGenerators import com.fasterxml.jackson.databind.annotation.JsonDeserialize import mu.KLoggable import java.util.TreeMap /** * a RangeMap is a map meant to hold entries like * 1..2, optionA * 3..4, optionB * 5..9, optionC * 10, optionD * * This implementation assumes (and enforces) the following * - there are no holes in the range * - there are no overlaps in the range */ @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator::class, property="@id") @JsonDeserialize(using = RangeMapDeserializer::class) class RangeMap( val delegate: TreeMap<Int, String> = TreeMap<Int, String>() ) : Map<Int, String> by delegate, KLoggable { override val logger = logger() var maxKey : Int = -1 val ranges: MutableSet<IntRange> = mutableSetOf() init { for (i in delegate.keys) { ranges.add(IntRange(i, i)) } if (delegate.keys.size > 0) { maxKey = delegate.lastKey() } } fun with(newRange: IntRange, value: String) : RangeMap { for (range in ranges) { if (!range.intersect(newRange).isEmpty()) { throw IllegalArgumentException("Invalid range $newRange already included in RangeMap") } } ranges.add(newRange) delegate.put(newRange.start, value) maxKey = Math.max(newRange.endInclusive, maxKey) return this } fun with(k: Int, value: String) : RangeMap { return with(k..k, value) } fun select(k: Int) : String { try { if (k < delegate.firstKey()) { return delegate.firstEntry().value } else if (k > delegate.lastKey()) { return delegate.lastEntry().value } else { return delegate.floorEntry(k).value } } catch (e: Exception) { logger.warn("Unable to lookup entry $k. Keyrange: ${keyRange()}") throw e } } fun keyRange() : IntRange { return IntRange(delegate.firstKey(), maxKey) } override fun toString(): String { return delegate.toString() } fun validateNoHoles() { val rangeSet : MutableSet<Int> = mutableSetOf() keyRange().toCollection(rangeSet) for (r in ranges) { rangeSet.removeAll(r.toSet()) } if (rangeSet.size != 0) { throw IllegalArgumentException("holes in range set. missing elements: $rangeSet") } } }
gpl-3.0
4b0930386e749123d73528a973463124
29.419643
102
0.633402
4.109771
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/adapter/HostAdapter.kt
1
3189
package jp.cordea.mackerelclient.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.activity.HostDetailActivity import jp.cordea.mackerelclient.activity.MetricsActivity import jp.cordea.mackerelclient.api.response.Tsdb import jp.cordea.mackerelclient.databinding.ListItemHostBinding import jp.cordea.mackerelclient.model.DisplayableHost import jp.cordea.mackerelclient.utils.StatusUtils import jp.cordea.mackerelclient.viewmodel.HostListItemViewModel class HostAdapter( val fragment: Fragment ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var items = emptyList<DisplayableHost>() private var metrics = emptyMap<String, Map<String, Tsdb>>() override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val context = fragment.context ?: return val item = items[position] (holder as? ViewHolder)?.binding?.run { cardView.setOnClickListener { val intent = MetricsActivity.createIntent(context, item.id) fragment.startActivity(intent) } detailButton.setOnClickListener { val intent = HostDetailActivity.createIntent(context, item) fragment.startActivityForResult(intent, HostDetailActivity.REQUEST_CODE) } val metric = metrics[item.id] val viewModel = HostListItemViewModel(context, item, metric) nameTextView.text = item.name detailTextView.text = item.memo roleTextView.text = viewModel.roleText healthView.setBackgroundColor( ContextCompat.getColor(context, StatusUtils.stringToStatusColor(item.status)) ) loadavg.run { titleTextView.text = fragment.resources.getString(R.string.host_card_loadavg_title) valueTextView.text = viewModel.loadavgText } cpu.run { titleTextView.text = fragment.resources.getString(R.string.host_card_cpu_title) valueTextView.text = viewModel.cpuText } memory.run { titleTextView.text = fragment.resources.getString(R.string.host_card_memory_title) valueTextView.text = viewModel.memoryText } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(fragment.context) .inflate(R.layout.list_item_host, parent, false) return ViewHolder(view) } override fun getItemCount(): Int = items.size fun update(items: List<DisplayableHost>, metrics: Map<String, Map<String, Tsdb>>) { this.items = items this.metrics = metrics notifyDataSetChanged() } private class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding: ListItemHostBinding = ListItemHostBinding.bind(view) } }
apache-2.0
26b7bce90f2ad51b6b5c4a11c499c64a
37.421687
99
0.685795
4.846505
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/util/Notifications.kt
1
18352
/* * Copyright (C) 2019 Veli Tasalı * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.util import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Typeface import android.os.Build import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.StyleSpan import androidx.core.app.NotificationCompat import com.genonbeta.android.framework.io.DocumentFile import org.monora.uprotocol.client.android.R import org.monora.uprotocol.client.android.activity.ContentBrowserActivity import org.monora.uprotocol.client.android.activity.HomeActivity import org.monora.uprotocol.client.android.database.model.SharedText import org.monora.uprotocol.client.android.database.model.Transfer import org.monora.uprotocol.client.android.database.model.UClient import org.monora.uprotocol.client.android.database.model.UTransferItem import org.monora.uprotocol.client.android.receiver.BgBroadcastReceiver import org.monora.uprotocol.client.android.receiver.BgBroadcastReceiver.Companion.ACTION_STOP_ALL_TASKS import org.monora.uprotocol.client.android.service.BackgroundService import org.monora.uprotocol.client.android.service.BackgroundService.Companion.ACTION_STOP_ALL import org.monora.uprotocol.client.android.service.backgroundservice.Task import org.monora.uprotocol.client.android.task.transfer.TransferParams import java.text.NumberFormat import com.genonbeta.android.framework.util.Files as FwFiles /** * created by: Veli * date: 26.01.2018 18:29 */ class Notifications(val backend: NotificationBackend) { val context: Context get() = backend.context private val percentFormat = NumberFormat.getPercentInstance() val foregroundNotification: DynamicNotification by lazy { val notification = backend.buildDynamicNotification( ID_BG_SERVICE, NotificationBackend.NOTIFICATION_CHANNEL_LOW ) val sendString = context.getString(R.string.sends) val receiveString = context.getString(R.string.receive) val sendIntent: PendingIntent = PendingIntent.getActivity( context, ID_BG_SERVICE + 1, Intent(context, ContentBrowserActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT ) val receiveIntent: PendingIntent = PendingIntent.getActivity( context, ID_BG_SERVICE + 2, Intent(context, HomeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT ) val exitAction = NotificationCompat.Action( R.drawable.ic_close_white_24dp_static, context.getString(R.string.exit), PendingIntent.getService( context, ID_BG_SERVICE + 3, Intent(context, BackgroundService::class.java).setAction(ACTION_STOP_ALL), PendingIntent.FLAG_UPDATE_CURRENT ) ) val homeIntent = PendingIntent.getActivity( context, ID_BG_SERVICE + 4, Intent(context, HomeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT ) notification.setSmallIcon(R.drawable.ic_trebleshot_rounded_white_24dp_static) .setContentTitle(context.getString(R.string.service_running_notice)) .setContentText(context.getString(R.string.tap_to_launch_notice)) .setContentIntent(homeIntent) .addAction(exitAction) .addAction(R.drawable.ic_arrow_up_white_24dp_static, sendString, sendIntent) .addAction(R.drawable.ic_arrow_down_white_24dp_static, receiveString, receiveIntent) notification.show() } fun notifyClientCredentialsChanged(client: UClient) { val uidHash = client.clientUid.hashCode() val notification = backend.buildDynamicNotification(uidHash, NotificationBackend.NOTIFICATION_CHANNEL_HIGH) val acceptIntent = Intent(context, BgBroadcastReceiver::class.java) acceptIntent.setAction(BgBroadcastReceiver.ACTION_DEVICE_KEY_CHANGE_APPROVAL) .putExtra(BgBroadcastReceiver.EXTRA_CLIENT, client) .putExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, notification.notificationId) .putExtra(BgBroadcastReceiver.EXTRA_ACCEPTED, true) val rejectIntent = Intent(acceptIntent) .putExtra(BgBroadcastReceiver.EXTRA_ACCEPTED, false) val positiveIntent: PendingIntent = PendingIntent.getBroadcast( context, uidHash + REQUEST_CODE_ACCEPT, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT ) val negativeIntent: PendingIntent = PendingIntent.getBroadcast( context, uidHash + REQUEST_CODE_REJECT, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT ) val contentText = context.getString(R.string.credentials_mismatch_notice, client.clientNickname) notification.setSmallIcon(R.drawable.ic_alert_circle_outline_white_24dp_static) .setContentTitle(context.getString(R.string.credentials_mismatch)) .setContentText(contentText) .setContentInfo(client.clientNickname) .setContentIntent( PendingIntent.getActivity( context, uidHash + REQUEST_CODE_NEUTRAL, Intent(context, HomeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT ) ) .setDefaults(backend.notificationSettings) .setDeleteIntent(negativeIntent) .addAction(R.drawable.ic_check_white_24dp_static, context.getString(R.string.invalidate), positiveIntent) .addAction(R.drawable.ic_close_white_24dp_static, context.getString(R.string.deny), negativeIntent) .setTicker(contentText) notification.show() } fun notifyTransferError() { // TODO: 8/31/21 Show transfer errors when the user is showing a related section. } fun notifyTransferRequest(client: UClient, transfer: Transfer, items: List<UTransferItem>) { val hash = transfer.id.toInt() val notification = backend.buildDynamicNotification(hash, NotificationBackend.NOTIFICATION_CHANNEL_HIGH) val itemsSize = items.size val acceptIntent: Intent = Intent(context, BgBroadcastReceiver::class.java) .setAction(BgBroadcastReceiver.ACTION_FILE_TRANSFER) .putExtra(BgBroadcastReceiver.EXTRA_CLIENT, client) .putExtra(BgBroadcastReceiver.EXTRA_TRANSFER, transfer) .putExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, notification.notificationId) .putExtra(BgBroadcastReceiver.EXTRA_ACCEPTED, true) val rejectIntent = Intent(acceptIntent) .putExtra(BgBroadcastReceiver.EXTRA_ACCEPTED, false) val transferDetail: Intent = Intent(context, HomeActivity::class.java) .setAction(HomeActivity.ACTION_OPEN_TRANSFER_DETAILS) .putExtra(HomeActivity.EXTRA_TRANSFER, transfer) val message = if (itemsSize > 1) { context.resources.getQuantityString(R.plurals.receive_files_question, itemsSize, itemsSize) } else { items[0].name } val positiveIntent: PendingIntent = PendingIntent.getBroadcast( context, hash + REQUEST_CODE_ACCEPT, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT ) val negativeIntent: PendingIntent = PendingIntent.getBroadcast( context, hash + REQUEST_CODE_REJECT, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT ) notification.setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentTitle(context.getString(R.string.receive_file_question)) .setContentText(message) .setContentInfo(client.clientNickname) .setContentIntent( PendingIntent.getActivity( context, hash + REQUEST_CODE_NEUTRAL, transferDetail, PendingIntent.FLAG_UPDATE_CURRENT ) ) .setDefaults(backend.notificationSettings) .setDeleteIntent(negativeIntent) .addAction(R.drawable.ic_check_white_24dp_static, context.getString(R.string.yes), positiveIntent) .addAction(R.drawable.ic_close_white_24dp_static, context.getString(R.string.no), negativeIntent) .setTicker(context.getString(R.string.receive_file_question)).priority = NotificationCompat.PRIORITY_HIGH notification.show() } fun notifyClipboardRequest(client: UClient, item: SharedText) { val notification = backend.buildDynamicNotification(item.id, NotificationBackend.NOTIFICATION_CHANNEL_HIGH) val copyIntent = Intent(context, BgBroadcastReceiver::class.java) .setAction(BgBroadcastReceiver.ACTION_CLIPBOARD_COPY) .putExtra(BgBroadcastReceiver.EXTRA_SHARED_TEXT, item) .putExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, notification.notificationId) val activityIntent = Intent(context, HomeActivity::class.java) .setAction(HomeActivity.ACTION_OPEN_SHARED_TEXT) .putExtra(HomeActivity.EXTRA_SHARED_TEXT, item) val copyIcon = if (Build.VERSION.SDK_INT >= 21) { R.drawable.ic_content_copy_white_24dp } else { R.drawable.ic_check_white_24dp_static } notification .setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentTitle(context.getString(R.string.receive_text_success)) .setContentText(item.text) .setStyle( NotificationCompat.BigTextStyle() .bigText(item.text) .setBigContentTitle(context.getString(R.string.receive_text_success)) ) .setContentInfo(client.clientNickname) .setContentIntent( PendingIntent.getActivity( context, item.id + REQUEST_CODE_NEUTRAL, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT ) ) .setDefaults(backend.notificationSettings) .addAction( copyIcon, context.getString(R.string.copy_to_clipboard), PendingIntent.getBroadcast( context, item.id + REQUEST_CODE_ACCEPT, copyIntent, PendingIntent.FLAG_UPDATE_CURRENT ) ) .setTicker(context.getString(R.string.receive_text_summary_success)) .priority = NotificationCompat.PRIORITY_HIGH notification.show() } fun notifyFileReceived(transferParams: TransferParams) { val notification = backend.buildDynamicNotification( transferParams.transfer.id.toInt(), NotificationBackend.NOTIFICATION_CHANNEL_HIGH ) val transferDetail: Intent = Intent(context, HomeActivity::class.java) .setAction(HomeActivity.ACTION_OPEN_TRANSFER_DETAILS) .putExtra(HomeActivity.EXTRA_TRANSFER, transferParams.transfer) notification .setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentInfo(transferParams.client.clientNickname) .setAutoCancel(true) .setDefaults(backend.notificationSettings) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent( PendingIntent.getActivity( context, transferParams.transfer.id.toInt() + REQUEST_CODE_NEUTRAL, transferDetail, PendingIntent.FLAG_UPDATE_CURRENT ) ) .setContentText( context.getString( R.string.receive_success_summary, FwFiles.formatLength(transferParams.bytesTotal), Time.formatElapsedTime(context, System.currentTimeMillis() - transferParams.startTime) ) ) .setContentTitle( context.resources.getQuantityString( R.plurals.receive_files_success_summary, transferParams.count, transferParams.count ) ) notification.show() } fun notifyTasksNotification( taskList: List<Task>, notification: DynamicNotification?, ): DynamicNotification { val notificationLocal = notification ?: backend.buildDynamicNotification( ID_BG_SERVICE, NotificationBackend.NOTIFICATION_CHANNEL_LOW ).also { val stopAllTasksAction = NotificationCompat.Action( R.drawable.ic_close_white_24dp_static, context.getString(R.string.stop_all), PendingIntent.getBroadcast( context, ID_BG_SERVICE + 2, Intent(context, BgBroadcastReceiver::class.java).setAction(ACTION_STOP_ALL_TASKS), PendingIntent.FLAG_UPDATE_CURRENT ) ) val homeIntent = PendingIntent.getActivity( context, ID_BG_SERVICE + 3, Intent(context, HomeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT ) it.setSmallIcon(R.drawable.ic_compare_arrows_white_24dp_static) .setContentTitle(context.getString(R.string.ongoing_task)) .setContentIntent(homeIntent) .setOngoing(true) .addAction(stopAllTasksAction) } val msg = SpannableStringBuilder() for (task in taskList) { val state: Task.State = task.state.value ?: continue val middleDot = " " + context.getString(R.string.middle_dot) + " " if (msg.isNotEmpty()) msg.append("\n") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { msg.append(task.name, StyleSpan(Typeface.BOLD), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { msg.append(task.name) } val content: String = when (state) { is Task.State.Pending, is Task.State.Finished -> context.getString(R.string.waiting) is Task.State.Running -> state.message is Task.State.Error -> state.error.message ?: context.getString(R.string.error) is Task.State.Progress -> { if (state.progress > 0 && state.total > 0) { msg.append(middleDot) val percentage: String = percentFormat.format(state.progress.toDouble() / state.total) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { msg.append(percentage, StyleSpan(Typeface.ITALIC), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { msg.append(percentage) } } state.message } } if (content.isNotEmpty()) msg.append(middleDot).append(content) if (msg.isEmpty()) msg.append(context.getString(R.string.empty_text)) } val summary = context.resources.getQuantityString( R.plurals.tasks, taskList.size, taskList.size ) val textStyle: NotificationCompat.BigTextStyle = NotificationCompat.BigTextStyle() .setBigContentTitle(context.getString(R.string.ongoing_task)) .setSummaryText(summary) .bigText(msg) notificationLocal.setContentText(summary) .setStyle(textStyle) return notificationLocal.show() } fun notifyReceivingOnWeb(file: DocumentFile): DynamicNotification { val notification = backend.buildDynamicNotification( file.getUri().hashCode(), NotificationBackend.NOTIFICATION_CHANNEL_LOW ) val homeIntent = PendingIntent.getActivity( context, ID_BG_SERVICE + 1, Intent(context, HomeActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT ) notification .setSmallIcon(android.R.drawable.stat_sys_download) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentText(file.getName()) .setContentTitle(context.getString(R.string.receiving_using_web_web_share)) .setContentIntent(homeIntent) notification.show() return notification } fun createAddingWifiNetworkNotification(ssid: String, password: String?): DynamicNotification { val notification = backend.buildDynamicNotification( ID_ADDING_WIFI_NETWORK, NotificationBackend.CHANNEL_INSTRUCTIVE ) notification .setSmallIcon(R.drawable.ic_help_white_24_static) .setContentTitle(context.getString(R.string.connect_to_wifi_notice, ssid)) .setContentText(context.getString(R.string.enter_wifi_password_notice, password)) .setAutoCancel(false) .setOngoing(true) return notification } companion object { const val ID_BG_SERVICE = 1 const val ID_ADDING_WIFI_NETWORK = 2 const val REQUEST_CODE_ACCEPT = 1 const val REQUEST_CODE_REJECT = 2 const val REQUEST_CODE_NEUTRAL = 3 } }
gpl-2.0
0ee1483d0fe37f218301aa596dd8b1b7
45.458228
117
0.650428
4.800157
false
false
false
false
himaaaatti/spigot-plugins
rocksmash/rocksmash.kt
1
2566
package com.github.himaaaatti.spigot.plugin.rocksmash import org.bukkit.Material import org.bukkit.block.Block import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.BlockBreakEvent import org.bukkit.plugin.java.JavaPlugin class Rocksmash: JavaPlugin() { override fun onEnable() { getServer().getPluginManager().registerEvents( object : Listener { fun isOre(block: Block) = when (block.getType()) { Material.IRON_ORE, Material.GOLD_ORE, Material.COAL_ORE, Material.LAPIS_ORE, Material.DIAMOND_ORE, Material.EMERALD_ORE, Material.GLOWING_REDSTONE_ORE, Material.QUARTZ_ORE, Material.REDSTONE_ORE, Material.OBSIDIAN -> true else -> false } fun breakBlock(block: Block, player: Player) { getServer().getScheduler().scheduleSyncDelayedTask( this@Rocksmash, object : Runnable { override fun run() { if (player.isValid() && isOre(block)) { val newEvent = BlockBreakEvent(block, player) getServer().getPluginManager().callEvent(newEvent) block.breakNaturally() } } }, 10 ) } @EventHandler fun onBlockBreak(event: BlockBreakEvent) { val ore = event.getBlock() if (!isOre(ore)) { return } val player = event.getPlayer() val item = player.getInventory().getItemInMainHand().getType() if(item == Material.WOOD_PICKAXE || item == Material.STONE_PICKAXE || item == Material.IRON_PICKAXE || item == Material.GOLD_PICKAXE || item == Material.DIAMOND_PICKAXE){ for (modY in -1..1) { for (modX in -1..1) { for (modZ in -1..1) { val block = ore.getRelative(modX, modY, modZ) breakBlock(block, player) } } } } } }, this ) } }
mit
726531950a1e467365c101795d69b971
34.638889
86
0.462588
5.121756
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/sdk/PySdkToInstall.kt
1
10701
// 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.jetbrains.python.sdk import com.google.common.hash.HashFunction import com.google.common.hash.Hashing import com.google.common.io.Files import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.icons.AllIcons import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.SimpleTextAttributes import com.intellij.util.io.HttpRequests import com.intellij.webcore.packaging.PackageManagementService import com.intellij.webcore.packaging.PackagesNotificationPanel import com.jetbrains.python.PyBundle import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.CalledInAwt import java.io.File import java.io.IOException import kotlin.math.absoluteValue private val LOGGER = Logger.getInstance(PySdkToInstall::class.java) @CalledInAny internal fun getSdksToInstall(): List<PySdkToInstall> { return if (SystemInfo.isWindows) listOf(getPy37ToInstallOnWindows(), getPy38ToInstallOnWindows()) else emptyList() } private fun getPy37ToInstallOnWindows(): PySdkToInstallOnWindows { val version = "3.7" val name = "Python $version" val hashFunction = Hashing.md5() return if (SystemInfo.is32Bit) { PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.7.6/python-3.7.6.exe", 25792544, "9e73a1b27bb894f87fdce430ef88b3d5", hashFunction, "python-3.7.6.exe" ) } else { PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.7.6/python-3.7.6-amd64.exe", 26802312, "cc31a9a497a4ec8a5190edecc5cdd303", hashFunction, "python-3.7.6-amd64.exe" ) } } private fun getPy38ToInstallOnWindows(): PySdkToInstallOnWindows { val version = "3.8" val name = "Python $version" val hashFunction = Hashing.md5() return if (SystemInfo.is32Bit) { PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.8.1/python-3.8.1.exe", 26446128, "2d4c7de97d6fcd8231fc3decbf8abf79", hashFunction, "python-3.8.1.exe" ) } else { PySdkToInstallOnWindows( name, version, "https://www.python.org/ftp/python/3.8.1/python-3.8.1-amd64.exe", 27543360, "3e4c42f5ff8fcdbe6a828c912b7afdb1", hashFunction, "python-3.8.1-amd64.exe" ) } } internal abstract class PySdkToInstall internal constructor(name: String, version: String) : ProjectJdkImpl(name, PythonSdkType.getInstance(), null, version) { @CalledInAny abstract fun renderInList(renderer: PySdkListCellRenderer) @CalledInAny abstract fun getInstallationWarning(defaultButtonName: String): String @CalledInAwt abstract fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? } private class PySdkToInstallOnWindows(name: String, version: String, private val url: String, private val size: Long, private val hash: String, private val hashFunction: HashFunction, private val targetFileName: String) : PySdkToInstall(name, version) { override fun renderInList(renderer: PySdkListCellRenderer) { renderer.append(name) renderer.append(" $url", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) renderer.icon = AllIcons.Actions.Download } override fun getInstallationWarning(defaultButtonName: String): String { val header = "Python executable is not found. Choose one of the following options:" val browseButtonName = "..." // ComponentWithBrowseButton val firstOption = "Click <strong>$browseButtonName</strong> to specify a path to python.exe in your file system" val size = StringUtil.formatFileSize(size) val secondOption = "Click <strong>$defaultButtonName</strong> to download and install Python from python.org ($size)" return "$header<ul><li>$firstOption</li><li>$secondOption</li></ul>" } override fun install(module: Module?, systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? { try { return ProgressManager.getInstance().run( object : Task.WithResult<PyDetectedSdk?, Exception>(module?.project, PyBundle.message("python.sdk.installing", name), true) { override fun compute(indicator: ProgressIndicator): PyDetectedSdk? = install(systemWideSdksDetector, indicator) } ) } catch (e: IOException) { handleIOException(e) } catch (e: PyInstallationExecutionException) { handleExecutionException(e) } catch (e: PyInstallationException) { handleInstallationException(e) } return null } private fun install(systemWideSdksDetector: () -> List<PyDetectedSdk>, indicator: ProgressIndicator): PyDetectedSdk? { val targetFile = File(PathManager.getTempPath(), targetFileName) try { indicator.text = PyBundle.message("python.sdk.downloading", targetFileName) if (indicator.isCanceled) return null downloadInstaller(targetFile, indicator) if (indicator.isCanceled) return null checkInstallerConsistency(targetFile) indicator.text = PyBundle.message("python.sdk.running", targetFileName) indicator.text2 = PyBundle.message("python.sdk.installing.windows.warning") indicator.isIndeterminate = true if (indicator.isCanceled) return null runInstaller(targetFile, indicator) return findInstalledSdk(systemWideSdksDetector) } finally { FileUtil.delete(targetFile) } } private fun downloadInstaller(targetFile: File, indicator: ProgressIndicator) { LOGGER.info("Downloading $url to $targetFile") return try { HttpRequests.request(url).saveToFile(targetFile, indicator) } catch (e: IOException) { throw IOException("Failed to download $url to $targetFile.", e) } } private fun checkInstallerConsistency(installer: File) { LOGGER.debug("Checking installer size") val sizeDiff = installer.length() - size if (sizeDiff != 0L) { throw IOException("Downloaded $installer has incorrect size, difference is ${sizeDiff.absoluteValue} bytes.") } LOGGER.debug("Checking installer checksum") val actualHashCode = Files.asByteSource(installer).hash(hashFunction).toString() if (!actualHashCode.equals(hash, ignoreCase = true)) { throw IOException("Checksums for $installer does not match. Actual value is $actualHashCode, expected $hash.") } } private fun handleIOException(e: IOException) { LOGGER.info(e) e.message?.let { PackagesNotificationPanel.showError( "Failed to install $name", PackageManagementService.ErrorDescription( it, null, e.cause?.message, "Try to install Python from https://www.python.org manually." ) ) } } private fun runInstaller(installer: File, indicator: ProgressIndicator) { val commandLine = GeneralCommandLine(installer.absolutePath, "/quiet") LOGGER.info("Running ${commandLine.commandLineString}") val output = runInstaller(commandLine, indicator) if (output.exitCode != 0 || output.isTimeout) throw PyInstallationException(commandLine, output) } private fun handleInstallationException(e: PyInstallationException) { val processOutput = e.output processOutput.checkSuccess(LOGGER) if (processOutput.isCancelled) { PackagesNotificationPanel.showError( "$name installation has been cancelled", PackageManagementService.ErrorDescription( "Some Python components that have been installed might get inconsistent after cancellation.", e.commandLine.commandLineString, listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() }, "Consider installing Python from https://www.python.org manually." ) ) } else { PackagesNotificationPanel.showError( "Failed to install $name", PackageManagementService.ErrorDescription( if (processOutput.isTimeout) "Timed out" else "Exit code ${processOutput.exitCode}", e.commandLine.commandLineString, listOf(processOutput.stderr, processOutput.stdout).firstOrNull { it.isNotBlank() }, "Try to install Python from https://www.python.org manually." ) ) } } private fun runInstaller(commandLine: GeneralCommandLine, indicator: ProgressIndicator): ProcessOutput { try { return CapturingProcessHandler(commandLine).runProcessWithProgressIndicator(indicator) } catch (e: ExecutionException) { throw PyInstallationExecutionException(commandLine, e) } } private fun handleExecutionException(e: PyInstallationExecutionException) { LOGGER.info(e) e.cause.message?.let { PackagesNotificationPanel.showError( "Failed to install $name", PackageManagementService.ErrorDescription( it, e.commandLine.commandLineString, null, "Try to install Python from https://www.python.org manually." ) ) } } private fun findInstalledSdk(systemWideSdksDetector: () -> List<PyDetectedSdk>): PyDetectedSdk? { LOGGER.debug("Resetting system-wide sdks detectors") resetSystemWideSdksDetectors() return systemWideSdksDetector() .also { sdks -> LOGGER.debug { sdks.joinToString(prefix = "Detected system-wide sdks: ") { it.homePath ?: it.name } } } .singleOrNull() } private class PyInstallationException(val commandLine: GeneralCommandLine, val output: ProcessOutput) : Exception() private class PyInstallationExecutionException(val commandLine: GeneralCommandLine, override val cause: ExecutionException) : Exception() }
apache-2.0
b555ae55bd8263bf5e147501cfa73b3c
34.912752
140
0.709373
4.412784
false
false
false
false
zdary/intellij-community
platform/analysis-impl/src/com/intellij/codeInsight/completion/PresentationInvariant.kt
3
991
// 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.codeInsight.completion import com.intellij.openapi.util.text.StringUtil import org.jetbrains.annotations.ApiStatus /** * @author peter */ @Deprecated("Use LookupElementPresentation directly") @ApiStatus.ScheduledForRemoval(inVersion = "2021.2") data class PresentationInvariant(val itemText: String?, val tail: String?, val type: String?): Comparable<PresentationInvariant> { override fun compareTo(other: PresentationInvariant): Int { var result = StringUtil.naturalCompare(itemText, other.itemText) if (result != 0) return result result = (tail?.length ?: 0).compareTo(other.tail?.length ?: 0) if (result != 0) return result result = StringUtil.naturalCompare(tail ?: "", other.tail ?: "") if (result != 0) return result return StringUtil.naturalCompare(type ?: "", other.type ?: "") } }
apache-2.0
d84a1b1fb174e2d726faa9cf3f86d622
37.153846
140
0.730575
4.217021
false
false
false
false
zdary/intellij-community
python/src/com/jetbrains/python/sdk/PySdkExt.kt
1
15236
/* * 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.jetbrains.python.sdk import com.intellij.execution.ExecutionException import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import com.intellij.util.ThreeState import com.intellij.webcore.packaging.PackagesNotificationPanel import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.PyCondaPackageService.getCondaName import com.jetbrains.python.packaging.PyCondaPackageService.getPythonName import com.jetbrains.python.packaging.ui.PyPackageManagementService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import com.jetbrains.python.ui.PyUiUtil import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths /** * @author vlan */ val BASE_DIR: Key<Path> = Key.create("PYTHON_BASE_PATH") fun findAllPythonSdks(baseDir: Path?): List<Sdk> { val context: UserDataHolder = UserDataHolderBase() if (baseDir != null) { context.putUserData(BASE_DIR, baseDir) } val existing = PythonSdkUtil.getAllSdks() return detectCondaEnvs(null, existing, context) + detectVirtualEnvs(null, existing, context) + findBaseSdks(existing, null, context) } fun findBaseSdks(existingSdks: List<Sdk>, module: Module?, context: UserDataHolder): List<Sdk> { val existing = filterSystemWideSdks(existingSdks) .sortedWith(PreferredSdkComparator.INSTANCE) .filterNot { PythonSdkUtil.isBaseConda(it.homePath) } val detected = detectSystemWideSdks(module, existingSdks, context).filterNot { PythonSdkUtil.isBaseConda(it.homePath) } return existing + detected } fun mostPreferred(sdks: List<Sdk>): Sdk? = sdks.minWithOrNull(PreferredSdkComparator.INSTANCE) fun filterSystemWideSdks(existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && it.isSystemWide } } @JvmOverloads fun detectSystemWideSdks(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder = UserDataHolderBase()): List<PyDetectedSdk> { if (module != null && module.isDisposed) return emptyList() val existingPaths = existingSdks.map { it.homePath }.toSet() return PythonSdkFlavor.getApplicableFlavors(false) .asSequence() .flatMap { it.suggestHomePaths(module, context).asSequence() } .filter { it !in existingPaths } .map { PyDetectedSdk(it) } .sortedWith(compareBy<PyDetectedSdk>({ it.guessedLanguageLevel }, { it.homePath }).reversed()) .toList() } fun resetSystemWideSdksDetectors() { PythonSdkFlavor.getApplicableFlavors(false).forEach(PythonSdkFlavor::dropCaches) } fun detectVirtualEnvs(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> = filterSuggestedPaths(VirtualEnvSdkFlavor.getInstance().suggestHomePaths(module, context), existingSdks, module) fun filterSharedCondaEnvs(module: Module?, existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && PythonSdkUtil.isConda(it) && !it.isAssociatedWithAnotherModule(module) } } fun detectCondaEnvs(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> = filterSuggestedPaths(CondaEnvSdkFlavor.getInstance().suggestHomePaths(module, context), existingSdks, module, true) fun guessCondaBaseEnvironment(condaPath: String): Sdk? { if (!condaPath.endsWith(File.separatorChar + getCondaName())) { return null } val interpreterPath = condaPath.replaceAfterLast(File.separatorChar, getPythonName()) val condaVirtualFile = VfsUtil.findFileByIoFile(File(interpreterPath), false) if (condaVirtualFile != null && condaVirtualFile.exists()) { return PyDetectedSdk(condaVirtualFile.path) } return null } fun filterAssociatedSdks(module: Module, existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && it.isAssociatedWithModule(module) } } fun detectAssociatedEnvironments(module: Module, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> { val virtualEnvs = detectVirtualEnvs(module, existingSdks, context).filter { it.isAssociatedWithModule(module) } val condaEnvs = detectCondaEnvs(module, existingSdks, context).filter { it.isAssociatedWithModule(module) } return virtualEnvs + condaEnvs } fun chooseEnvironmentToSuggest(module: Module, environments: List<PyDetectedSdk>, trustedState: ThreeState): Pair<PyDetectedSdk, Boolean>? { return if (trustedState == ThreeState.YES) { environments.firstOrNull()?.let { it to false } } else { val (detectedInnerEnvs, detectedOuterEnvs) = environments.partition { it.isLocatedInsideModule(module) } when { detectedInnerEnvs.isEmpty() || trustedState == ThreeState.NO -> detectedOuterEnvs.firstOrNull()?.let { it to false } else -> detectedInnerEnvs.firstOrNull()?.let { it to true } } } } fun createSdkByGenerateTask(generateSdkHomePath: Task.WithResult<String, ExecutionException>, existingSdks: List<Sdk>, baseSdk: Sdk?, associatedProjectPath: String?, suggestedSdkName: String?): Sdk? { val homeFile = try { val homePath = ProgressManager.getInstance().run(generateSdkHomePath) StandardFileSystems.local().refreshAndFindFileByPath(homePath) ?: throw ExecutionException( PyBundle.message("python.sdk.directory.not.found", homePath) ) } catch (e: ExecutionException) { showSdkExecutionException(baseSdk, e, PyBundle.message("python.sdk.failed.to.create.interpreter.title")) return null } val suggestedName = suggestedSdkName ?: suggestAssociatedSdkName(homeFile.path, associatedProjectPath) return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeFile, PythonSdkType.getInstance(), false, null, suggestedName) } fun showSdkExecutionException(sdk: Sdk?, e: ExecutionException, @NlsContexts.DialogTitle title: String) { runInEdt { val description = PyPackageManagementService.toErrorDescription(listOf(e), sdk) ?: return@runInEdt PackagesNotificationPanel.showError(title, description) } } fun Sdk.associateWithModule(module: Module?, newProjectPath: String?) { getOrCreateAdditionalData().apply { when { newProjectPath != null -> associateWithModulePath(newProjectPath) module != null -> associateWithModule(module) } } } fun Sdk.isAssociatedWithModule(module: Module?): Boolean { val basePath = module?.basePath val associatedPath = associatedModulePath if (basePath != null && associatedPath == basePath) return true if (isAssociatedWithAnotherModule(module)) return false return isLocatedInsideModule(module) || containsModuleName(module) } fun Sdk.isAssociatedWithAnotherModule(module: Module?): Boolean { val basePath = module?.basePath ?: return false val associatedPath = associatedModulePath ?: return false return basePath != associatedPath } val Sdk.associatedModulePath: String? // TODO: Support .project associations get() = associatedPathFromAdditionalData /*?: associatedPathFromDotProject*/ @Deprecated("Use Sdk.associatedModuleDir instead. There may be several Module objects opened in different projects for a single *.iml module file. To be removed in 2021.2") val Sdk.associatedModule: Module? get() { val associatedPath = associatedModulePath return ProjectManager.getInstance().openProjects .asSequence() .flatMap { ModuleManager.getInstance(it).modules.asSequence() } .firstOrNull { it?.basePath == associatedPath } } val Sdk.associatedModuleDir: VirtualFile? get() = associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it) } fun Sdk.adminPermissionsNeeded(): Boolean { val pathToCheck = sitePackagesDirectory?.path ?: homePath ?: return false return !Files.isWritable(Paths.get(pathToCheck)) } fun PyDetectedSdk.setup(existingSdks: List<Sdk>): Sdk? { val homeDir = homeDirectory ?: return null return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, null) } fun PyDetectedSdk.setupAssociated(existingSdks: List<Sdk>, associatedModulePath: String?): Sdk? { val homeDir = homeDirectory ?: return null val suggestedName = homePath?.let { suggestAssociatedSdkName(it, associatedModulePath) } return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, suggestedName) } var Module.pythonSdk: Sdk? get() = PythonSdkUtil.findPythonSdk(this) set(value) { ModuleRootModificationUtil.setModuleSdk(this, value) PyUiUtil.clearFileLevelInspectionResults(project) } var Project.pythonSdk: Sdk? get() { val sdk = ProjectRootManager.getInstance(this).projectSdk return when (sdk?.sdkType) { is PythonSdkType -> sdk else -> null } } set(value) { val application = ApplicationManager.getApplication() application.invokeAndWait { application.runWriteAction { ProjectRootManager.getInstance(this).projectSdk = value } } } fun Module.excludeInnerVirtualEnv(sdk: Sdk) { val root = sdk.homePath?.let { PythonSdkUtil.getVirtualEnvRoot(it) }?.let { LocalFileSystem.getInstance().findFileByIoFile(it) } ?: return val model = ModuleRootManager.getInstance(this).modifiableModel val contentEntry = model.contentEntries.firstOrNull { val contentFile = it.file contentFile != null && VfsUtil.isAncestor(contentFile, root, true) } ?: return contentEntry.addExcludeFolder(root) WriteAction.run<Throwable> { model.commit() } } private fun suggestAssociatedSdkName(sdkHome: String, associatedPath: String?): String? { // please don't forget to update com.jetbrains.python.inspections.PyInterpreterInspection.Visitor#getSuitableSdkFix // after changing this method val baseSdkName = PythonSdkType.suggestBaseSdkName(sdkHome) ?: return null val venvRoot = PythonSdkUtil.getVirtualEnvRoot(sdkHome)?.path val condaRoot = CondaEnvSdkFlavor.getCondaEnvRoot(sdkHome)?.path val associatedName = when { venvRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, venvRoot, true)) -> PathUtil.getFileName(venvRoot) condaRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, condaRoot, true)) -> PathUtil.getFileName(condaRoot) PythonSdkUtil.isBaseConda(sdkHome) -> "base" else -> associatedPath?.let { PathUtil.getFileName(associatedPath) } ?: return null } return "$baseSdkName ($associatedName)" } val File.isNotEmptyDirectory: Boolean get() = exists() && isDirectory && list()?.isEmpty()?.not() ?: false private val Sdk.isSystemWide: Boolean get() = !PythonSdkUtil.isRemote(this) && !PythonSdkUtil.isVirtualEnv( this) && !PythonSdkUtil.isCondaVirtualEnv(this) @Suppress("unused") private val Sdk.associatedPathFromDotProject: String? get() { val binaryPath = homePath ?: return null val virtualEnvRoot = PythonSdkUtil.getVirtualEnvRoot(binaryPath) ?: return null val projectFile = File(virtualEnvRoot, ".project") return try { projectFile.readText().trim() } catch (e: IOException) { null } } private val Sdk.associatedPathFromAdditionalData: String? get() = (sdkAdditionalData as? PythonSdkAdditionalData)?.associatedModulePath private val Sdk.sitePackagesDirectory: VirtualFile? get() = PythonSdkUtil.getSitePackagesDirectory(this) private fun Sdk.isLocatedInsideModule(module: Module?): Boolean { val homePath = homePath ?: return false val basePath = module?.basePath ?: return false return FileUtil.isAncestor(basePath, homePath, true) } val PyDetectedSdk.guessedLanguageLevel: LanguageLevel? get() { val path = homePath ?: return null val result = Regex(""".*python(\d\.\d)""").find(path) ?: return null val versionString = result.groupValues.getOrNull(1) ?: return null return LanguageLevel.fromPythonVersion(versionString) } private fun Sdk.containsModuleName(module: Module?): Boolean { val path = homePath ?: return false val name = module?.name ?: return false return path.contains(name, true) } fun Sdk.getOrCreateAdditionalData(): PythonSdkAdditionalData { val existingData = sdkAdditionalData as? PythonSdkAdditionalData if (existingData != null) return existingData val newData = PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(homePath)) val modificator = sdkModificator modificator.sdkAdditionalData = newData ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() } return newData } private fun filterSuggestedPaths(suggestedPaths: Collection<String>, existingSdks: List<Sdk>, module: Module?, mayContainCondaEnvs: Boolean = false): List<PyDetectedSdk> { val existingPaths = existingSdks.mapTo(HashSet()) { it.homePath } return suggestedPaths .asSequence() .filterNot { it in existingPaths } .distinct() .map { PyDetectedSdk(it) } .sortedWith( compareBy( { !it.isAssociatedWithModule(module) }, { if (mayContainCondaEnvs) !PythonSdkUtil.isBaseConda(it.homePath) else false }, { it.homePath } ) ) .toList() }
apache-2.0
866fcc5841a390ad7f058391927d4a7c
39.740642
172
0.750263
4.497048
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/productsearch/SearchedObject.kt
1
1626
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.productsearch import android.content.res.Resources import android.graphics.Bitmap import android.graphics.Rect import com.google.firebase.ml.md.R import com.google.firebase.ml.md.kotlin.Utils import com.google.firebase.ml.md.kotlin.objectdetection.DetectedObject /** Hosts the detected object info and its search result. */ class SearchedObject(resources: Resources, private val detectedObject: DetectedObject, val productList: List<Product>) { private val objectThumbnailCornerRadius: Int = resources.getDimensionPixelOffset(R.dimen.bounding_box_corner_radius) private var objectThumbnail: Bitmap? = null val objectIndex: Int get() = detectedObject.objectIndex val boundingBox: Rect get() = detectedObject.boundingBox @Synchronized fun getObjectThumbnail(): Bitmap = objectThumbnail ?: let { Utils.getCornerRoundedBitmap(detectedObject.getBitmap(), objectThumbnailCornerRadius) .also { objectThumbnail = it } } }
apache-2.0
53d384cebfefc1ec7e7cac4155eb3eed
36.813953
120
0.752768
4.382749
false
false
false
false
redundent/kotlin-xml-builder
kotlin-xml-dsl-generator/src/main/kotlin/org/redundent/kotlin/xml/gen/SchemaOutline.kt
1
1048
package org.redundent.kotlin.xml.gen import com.sun.tools.xjc.model.CClassInfo import com.sun.tools.xjc.model.CClassInfoParent import com.sun.tools.xjc.outline.Outline import org.redundent.kotlin.xml.gen.writer.XmlClass import org.redundent.kotlin.xml.gen.writer.XmlEnum class SchemaOutline(outline: Outline, private val opts: ExOptions) { private val innerClasses = outline.classes.filter { it.target.parent() is CClassInfo }.groupBy { it.target.parent() as CClassInfo } private val rootClasses = outline.classes.filter { it.target.parent() is CClassInfoParent.Package } val classes = rootClasses.sortedBy { if (it.target.isAbstract) 0 else 1 }.map { XmlClass(it, opts) } val enums = outline.enums.map(::XmlEnum) init { classes.forEach(this::recurseInnerClasses) } private fun recurseInnerClasses(clazz: XmlClass) { val innerClasses = innerClasses[clazz.clazz.target] innerClasses?.forEach { val innerClass = XmlClass(it, opts, innerClass = true) clazz.addInnerClass(innerClass) recurseInnerClasses(innerClass) } } }
apache-2.0
4ebda281b9f9c99c5abb43274bf09717
35.172414
132
0.771947
3.424837
false
false
false
false
android/compose-samples
Reply/app/src/main/java/com/example/reply/data/local/LocalEmailsDataProvider.kt
1
14907
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.data.local import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.EmailAttachment import com.example.reply.data.MailboxType /** * A static data store of [Email]s. */ object LocalEmailsDataProvider { private val threads = listOf( Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Your update on Google Play Store is live!", body = """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), mailbox = MailboxType.TRASH, createdAt = "3 hours ago", ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Update to Your Itinerary", body = "", createdAt = "2 hours ago", ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createdAt = "2 hours ago", mailbox = MailboxType.SENT ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Delivered", body = "Your shoes should be waiting for you at home!", createdAt = "2 hours ago", ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "(No subject)", body = """ Hey, Wanted to email and see what you thought of """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.DRAFTS ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountByUid(6L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Brunch this weekend?", body = """ I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever. If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico. Talk to you soon, Ali """.trimIndent(), createdAt = "40 mins ago", ), Email( id = 2L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Bonjour from Paris", body = "Here are some great shots from my trip...", attachments = listOf( EmailAttachment(R.drawable.paris_1, "Bridge in Paris"), EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"), EmailAttachment(R.drawable.paris_3, "City street in Paris"), EmailAttachment(R.drawable.paris_4, "Street with bike in Paris") ), isImportant = true, createdAt = "1 hour ago", ), ) val allEmails = listOf( Email( id = 0L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Package shipped!", body = """ Cucumber Mask Facial has shipped. Keep an eye out for a package to arrive between this Thursday and next Tuesday. If for any reason you don't receive your package before the end of next week, please reach out to us for details on your shipment. As always, thank you for shopping with us and we hope you love our specially formulated Cucumber Mask! """.trimIndent(), createdAt = "20 mins ago", isStarred = true, threads = threads, ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountByUid(6L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Brunch this weekend?", body = """ I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever. If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico. Talk to you soon, Ali """.trimIndent(), createdAt = "40 mins ago", threads = threads.shuffled(), ), Email( 2L, LocalAccountsDataProvider.getContactAccountByUid(5L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "Bonjour from Paris", "Here are some great shots from my trip...", listOf( EmailAttachment(R.drawable.paris_1, "Bridge in Paris"), EmailAttachment(R.drawable.paris_2, "Bridge in Paris at night"), EmailAttachment(R.drawable.paris_3, "City street in Paris"), EmailAttachment(R.drawable.paris_4, "Street with bike in Paris") ), true, createdAt = "1 hour ago", threads = threads.shuffled(), ), Email( 3L, LocalAccountsDataProvider.getContactAccountByUid(8L), listOf(LocalAccountsDataProvider.getDefaultUserAccount()), "High school reunion?", """ Hi friends, I was at the grocery store on Sunday night.. when I ran into Genie Williams! I almost didn't recognize her afer 20 years! Anyway, it turns out she is on the organizing committee for the high school reunion this fall. I don't know if you were planning on going or not, but she could definitely use our help in trying to track down lots of missing alums. If you can make it, we're doing a little phone-tree party at her place next Saturday, hoping that if we can find one person, thee more will... """.trimIndent(), createdAt = "2 hours ago", mailbox = MailboxType.SENT, threads = threads.shuffled(), ), Email( id = 4L, sender = LocalAccountsDataProvider.getContactAccountByUid(11L), recipients = listOf( LocalAccountsDataProvider.getDefaultUserAccount(), LocalAccountsDataProvider.getContactAccountByUid(8L), LocalAccountsDataProvider.getContactAccountByUid(5L) ), subject = "Brazil trip", body = """ Thought we might be able to go over some details about our upcoming vacation. I've been doing a bit of research and have come across a few paces in Northern Brazil that I think we should check out. One, the north has some of the most predictable wind on the planet. I'd love to get out on the ocean and kitesurf for a couple of days if we're going to be anywhere near or around Taiba. I hear it's beautiful there and if you're up for it, I'd love to go. Other than that, I haven't spent too much time looking into places along our road trip route. I'm assuming we can find places to stay and things to do as we drive and find places we think look interesting. But... I know you're more of a planner, so if you have ideas or places in mind, lets jot some ideas down! Maybe we can jump on the phone later today if you have a second. """.trimIndent(), createdAt = "2 hours ago", isStarred = true, threads = threads.shuffled(), ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Update to Your Itinerary", body = "", createdAt = "2 hours ago", threads = threads.shuffled() ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Recipe to try", "Raspberry Pie: We should make this pie recipe tonight! The filling is " + "very quick to put together.", createdAt = "2 hours ago", mailbox = MailboxType.SENT, threads = threads.shuffled() ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountByUid(9L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Delivered", body = "Your shoes should be waiting for you at home!", createdAt = "2 hours ago", threads = threads.shuffled() ), Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountByUid(13L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Your update on Google Play Store is live!", body = """ Your update, 0.1.1, is now live on the Play Store and available for your alpha users to start testing. Your alpha testers will be automatically notified. If you'd rather send them a link directly, go to your Google Play Console and follow the instructions for obtaining an open alpha testing link. """.trimIndent(), mailbox = MailboxType.TRASH, createdAt = "3 hours ago", threads = threads.shuffled(), ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountByUid(10L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "(No subject)", body = """ Hey, Wanted to email and see what you thought of """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.DRAFTS, threads = threads.shuffled(), ), Email( id = 10L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Try a free TrailGo account", body = """ Looking for the best hiking trails in your area? TrailGo gets you on the path to the outdoors faster than you can pack a sandwich. Whether you're an experienced hiker or just looking to get outside for the afternoon, there's a segment that suits you. """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.TRASH, threads = threads.shuffled(), ), Email( id = 11L, sender = LocalAccountsDataProvider.getContactAccountByUid(5L), recipients = listOf(LocalAccountsDataProvider.getDefaultUserAccount()), subject = "Free money", body = """ You've been selected as a winner in our latest raffle! To claim your prize, click on the link. """.trimIndent(), createdAt = "3 hours ago", mailbox = MailboxType.SPAM, threads = threads.shuffled(), ) ) /** * Get an [Email] with the given [id]. */ fun get(id: Long): Email? { return allEmails.firstOrNull { it.id == id } } /** * Create a new, blank [Email]. */ fun create(): Email { return Email( System.nanoTime(), // Unique ID generation. LocalAccountsDataProvider.getDefaultUserAccount(), createdAt = "Just now", subject = "Monthly hosting party", body = "I would like to invite everyone to our monthly event hosting party" ) } /** * Create a new [Email] that is a reply to the email with the given [replyToId]. */ fun createReplyTo(replyToId: Long): Email { val replyTo = get(replyToId) ?: return create() return Email( id = System.nanoTime(), sender = replyTo.recipients.firstOrNull() ?: LocalAccountsDataProvider.getDefaultUserAccount(), recipients = listOf(replyTo.sender) + replyTo.recipients, subject = replyTo.subject, isStarred = replyTo.isStarred, isImportant = replyTo.isImportant, createdAt = "Just now", body = "Responding to the above conversation." ) } /** * Get a list of [EmailFolder]s by which [Email]s can be categorized. */ fun getAllFolders() = listOf( "Receipts", "Pine Elementary", "Taxes", "Vacation", "Mortgage", "Grocery coupons" ) }
apache-2.0
aaaf73552c23e81e5537512d1557f36b
43.366071
703
0.595492
4.897175
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/deferred/PbrSceneShader.kt
1
10141
package de.fabmax.kool.pipeline.deferred import de.fabmax.kool.KoolContext import de.fabmax.kool.pipeline.BlendMode import de.fabmax.kool.pipeline.DepthCompareOp import de.fabmax.kool.pipeline.Pipeline import de.fabmax.kool.pipeline.TextureSampler2d import de.fabmax.kool.pipeline.ibl.EnvironmentMaps import de.fabmax.kool.pipeline.shadermodel.* import de.fabmax.kool.pipeline.shading.* import de.fabmax.kool.scene.Camera import de.fabmax.kool.scene.Mesh import de.fabmax.kool.util.CascadedShadowMap import de.fabmax.kool.util.Color import de.fabmax.kool.util.ShadowMap import de.fabmax.kool.util.SimpleShadowMap /** * 2nd pass shader for deferred pbr shading: Uses textures with view space position, normals, albedo, roughness, * metallic and texture-based AO and computes the final color output. */ open class PbrSceneShader(cfg: DeferredPbrConfig, model: ShaderModel = defaultDeferredPbrModel(cfg)) : ModeledShader(model) { private var deferredCameraNode: DeferredCameraNode? = null var sceneCamera: Camera? = null set(value) { field = value deferredCameraNode?.sceneCam = value } val depth = Texture2dInput("depth") val positionFlags = Texture2dInput("positionFlags") val normalRoughness = Texture2dInput("normalRoughness") val albedoMetal = Texture2dInput("albedoMetal") val emissiveAo = Texture2dInput("emissiveAo") // Lighting props val ambient = ColorInput("uAmbient", Color(0.03f, 0.03f, 0.03f, 1f)) val ambientShadowFactor = FloatInput("uAmbientShadowFactor", cfg.ambientShadowFactor) // Image based lighting maps val environmentMapOrientation = Mat3fInput("uEnvMapOri") val irradianceMap = TextureCubeInput("irradianceMap", cfg.environmentMaps?.irradianceMap) val reflectionMap = TextureCubeInput("reflectionMap", cfg.environmentMaps?.reflectionMap) val brdfLut = Texture2dInput("brdfLut") // Screen space AO and Reflection maps val scrSpcAmbientOcclusionMap = Texture2dInput("ssaoMap") val scrSpcReflectionMap = Texture2dInput("ssrMap") // Shadow Mapping private val shadowMaps = Array(cfg.shadowMaps.size) { cfg.shadowMaps[it] } private val depthSamplers = Array<TextureSampler2d?>(shadowMaps.size) { null } private val isReceivingShadow = cfg.shadowMaps.isNotEmpty() fun setMaterialInput(materialPass: MaterialPass) { sceneCamera = materialPass.camera depth(materialPass.depthTexture) positionFlags(materialPass.positionFlags) normalRoughness(materialPass.normalRoughness) albedoMetal(materialPass.albedoMetal) emissiveAo(materialPass.emissiveAo) } override fun onPipelineSetup(builder: Pipeline.Builder, mesh: Mesh, ctx: KoolContext) { brdfLut(ctx.defaultPbrBrdfLut) builder.depthTest = DepthCompareOp.ALWAYS builder.blendMode = BlendMode.DISABLED super.onPipelineSetup(builder, mesh, ctx) } override fun onPipelineCreated(pipeline: Pipeline, mesh: Mesh, ctx: KoolContext) { deferredCameraNode = model.findNode("deferredCam") deferredCameraNode?.let { it.sceneCam = sceneCamera } depth.connect(model) positionFlags.connect(model) normalRoughness.connect(model) albedoMetal.connect(model) emissiveAo.connect(model) ambient.connect(model) irradianceMap.connect(model) reflectionMap.connect(model) brdfLut.connect(model) environmentMapOrientation.connect(model) scrSpcAmbientOcclusionMap.connect(model) scrSpcReflectionMap.connect(model) if (isReceivingShadow) { for (i in depthSamplers.indices) { val sampler = model.findNode<Texture2dNode>("depthMap_$i")?.sampler depthSamplers[i] = sampler shadowMaps[i].setupSampler(sampler) } ambientShadowFactor.connect(model) } super.onPipelineCreated(pipeline, mesh, ctx) } companion object { fun defaultDeferredPbrModel(cfg: DeferredPbrConfig) = ShaderModel("defaultDeferredPbrModel()").apply { val ifTexCoords: StageInterfaceNode vertexStage { ifTexCoords = stageInterfaceNode("ifTexCoords", attrTexCoords().output) positionOutput = fullScreenQuadPositionNode(attrTexCoords().output).outQuadPos } fragmentStage { val coord = ifTexCoords.output val posFlagsTex = texture2dNode("positionFlags") val mrtDeMultiplex = addNode(DeferredPbrShader.MrtDeMultiplexNode(stage)).apply { inPositionFlags = texture2dSamplerNode(posFlagsTex, coord).outColor inNormalRough = texture2dSamplerNode(texture2dNode("normalRoughness"), coord).outColor inAlbedoMetallic = texture2dSamplerNode(texture2dNode("albedoMetal"), coord).outColor inEmissiveAo = texture2dSamplerNode(texture2dNode("emissiveAo"), coord).outColor } addNode(DiscardClearNode(stage)).apply { inViewPos = mrtDeMultiplex.outViewPos } val defCam = addNode(DeferredCameraNode(stage)) val worldPos = vec3TransformNode(mrtDeMultiplex.outViewPos, defCam.outInvViewMat, 1f).outVec3 val worldNrm = vec3TransformNode(mrtDeMultiplex.outViewNormal, defCam.outInvViewMat, 0f).outVec3 var lightNode: MultiLightNode? = null if (cfg.maxLights > 0) { lightNode = multiLightNode(worldPos, cfg.maxLights) cfg.shadowMaps.forEachIndexed { i, map -> lightNode.inShadowFacs[i] = when (map) { is CascadedShadowMap -> deferredCascadedShadowMapNode(map, "depthMap_$i", mrtDeMultiplex.outViewPos, worldPos, worldNrm).outShadowFac is SimpleShadowMap -> deferredSimpleShadowMapNode(map, "depthMap_$i", worldPos, worldNrm).outShadowFac else -> ShaderNodeIoVar(ModelVar1fConst(1f)) } } } val reflMap: TextureCubeNode? val brdfLut: Texture2dNode? val irrSampler: TextureCubeSamplerNode? val envMapOri: UniformMat3fNode? if (cfg.isImageBasedLighting) { envMapOri = uniformMat3fNode("uEnvMapOri") val irrDirection = vec3TransformNode(worldNrm, envMapOri.output).outVec3 val irrMap = textureCubeNode("irradianceMap") irrSampler = textureCubeSamplerNode(irrMap, irrDirection) reflMap = textureCubeNode("reflectionMap") brdfLut = texture2dNode("brdfLut") } else { irrSampler = null reflMap = null brdfLut = null envMapOri = null } val mat = pbrMaterialNode(reflMap, brdfLut).apply { inFragPos = worldPos inNormal = worldNrm inViewDir = viewDirNode(defCam.outCamPos, worldPos).output envMapOri?.let { inReflectionMapOrientation = it.output } val avgShadow: ShaderNodeIoVar if (lightNode != null) { inLightCount = lightNode.outLightCount inFragToLight = lightNode.outFragToLightDirection inRadiance = lightNode.outRadiance avgShadow = lightNode.outAvgShadowFac } else { avgShadow = constFloat(0f) } val irr = irrSampler?.outColor ?: pushConstantNodeColor("uAmbient").output val ambientShadowFac = pushConstantNode1f("uAmbientShadowFactor").output val shadowStr = multiplyNode(subtractNode(constFloat(1f), avgShadow).output, ambientShadowFac) val ambientStr = subtractNode(constFloat(1f), shadowStr.output).output inIrradiance = multiplyNode(irr, ambientStr).output inReflectionStrength = ambientStr inAlbedo = mrtDeMultiplex.outAlbedo inEmissive = mrtDeMultiplex.outEmissive inMetallic = mrtDeMultiplex.outMetallic inRoughness = mrtDeMultiplex.outRoughness inAlwaysLit = mrtDeMultiplex.outLightBacksides var aoFactor = mrtDeMultiplex.outAo if (cfg.isScrSpcAmbientOcclusion) { val aoMap = texture2dNode("ssaoMap") val aoNode = addNode(AoMapSampleNode(aoMap, graph)) aoNode.inViewport = defCam.outViewport aoFactor = multiplyNode(aoFactor, aoNode.outAo).output } inAmbientOccl = aoFactor if (cfg.isScrSpcReflections) { val ssr = texture2dSamplerNode(texture2dNode("ssrMap"), coord).outColor inReflectionColor = gammaNode(ssr).outColor inReflectionWeight = splitNode(ssr, "a").output } } colorOutput(mat.outColor) val depthSampler = texture2dSamplerNode(texture2dNode("depth"), coord) depthOutput(depthSampler.outColor) } } } class DeferredPbrConfig { var isImageBasedLighting = false var isScrSpcAmbientOcclusion = false var isScrSpcReflections = false var maxLights = 4 val shadowMaps = mutableListOf<ShadowMap>() var environmentMaps: EnvironmentMaps? = null var ambientShadowFactor = 0f fun useImageBasedLighting(environmentMaps: EnvironmentMaps?) { this.environmentMaps = environmentMaps isImageBasedLighting = environmentMaps != null } } }
apache-2.0
8b144e8349a342a4411814db80cbb9bb
44.075556
161
0.630608
4.459543
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XParentEntityImpl.kt
1
15029
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XParentEntityImpl : XParentEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val OPTIONALCHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildWithOptionalParentEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val CHILDCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, OPTIONALCHILDREN_CONNECTION_ID, CHILDCHILD_CONNECTION_ID, ) } @JvmField var _parentProperty: String? = null override val parentProperty: String get() = _parentProperty!! override val children: List<XChildEntity> get() = snapshot.extractOneToManyChildren<XChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val optionalChildren: List<XChildWithOptionalParentEntity> get() = snapshot.extractOneToManyChildren<XChildWithOptionalParentEntity>(OPTIONALCHILDREN_CONNECTION_ID, this)!!.toList() override val childChild: List<XChildChildEntity> get() = snapshot.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: XParentEntityData?) : ModifiableWorkspaceEntityBase<XParentEntity>(), XParentEntity.Builder { constructor() : this(XParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isParentPropertyInitialized()) { error("Field XParentEntity#parentProperty should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field XParentEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field XParentEntity#children should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(OPTIONALCHILDREN_CONNECTION_ID, this) == null) { error("Field XParentEntity#optionalChildren should be initialized") } } else { if (this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] == null) { error("Field XParentEntity#optionalChildren should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDCHILD_CONNECTION_ID, this) == null) { error("Field XParentEntity#childChild should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] == null) { error("Field XParentEntity#childChild 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 XParentEntity this.entitySource = dataSource.entitySource this.parentProperty = dataSource.parentProperty if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentProperty: String get() = getEntityData().parentProperty set(value) { checkModificationAllowed() getEntityData().parentProperty = value changedProperty.add("parentProperty") } // List of non-abstract referenced types var _children: List<XChildEntity>? = emptyList() override var children: List<XChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<XChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<XChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } // List of non-abstract referenced types var _optionalChildren: List<XChildWithOptionalParentEntity>? = emptyList() override var optionalChildren: List<XChildWithOptionalParentEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildWithOptionalParentEntity>(OPTIONALCHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] as? List<XChildWithOptionalParentEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] as? List<XChildWithOptionalParentEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(OPTIONALCHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, OPTIONALCHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, OPTIONALCHILDREN_CONNECTION_ID)] = value } changedProperty.add("optionalChildren") } // List of non-abstract referenced types var _childChild: List<XChildChildEntity>? = emptyList() override var childChild: List<XChildChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDCHILD_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] = value } changedProperty.add("childChild") } override fun getEntityData(): XParentEntityData = result ?: super.getEntityData() as XParentEntityData override fun getEntityClass(): Class<XParentEntity> = XParentEntity::class.java } } class XParentEntityData : WorkspaceEntityData<XParentEntity>() { lateinit var parentProperty: String fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<XParentEntity> { val modifiable = XParentEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): XParentEntity { val entity = XParentEntityImpl() entity._parentProperty = parentProperty entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return XParentEntity(parentProperty, 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::class != other::class) return false other as XParentEntityData if (this.entitySource != other.entitySource) return false if (this.parentProperty != other.parentProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XParentEntityData if (this.parentProperty != other.parentProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + parentProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
1ab74bf1753314f0de55b2c534e7847e
39.728997
194
0.641493
5.578693
false
false
false
false
leafclick/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/pinned/items/XDebuggerPinToTopManager.kt
1
5127
// 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.xdebugger.impl.pinned.items import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.util.Alarm import com.intellij.xdebugger.XDebuggerManager import com.intellij.xdebugger.impl.PinToTopManagerState import com.intellij.xdebugger.impl.XDebuggerManagerImpl import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode import com.intellij.xdebugger.impl.ui.tree.nodes.XValueContainerNode import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl import icons.PlatformDebuggerImplIcons open class XDebuggerPinToTopManager { companion object { fun getInstance(project: Project): XDebuggerPinToTopManager = (XDebuggerManager.getInstance(project) as XDebuggerManagerImpl).pinToTopManager private const val DEFAULT_ICON_DELAY = 300L } private val myListeners = mutableListOf<XDebuggerPinToTopListener>() private var myNodeHoverLifetime : Disposable? = null private var myActiveNode: XDebuggerTreeNode? = null private var myPinnedMembers = HashMap<String, PinnedItemInfo>() private val myPinToTopIconAlarm = Alarm() val pinToTopComparator : Comparator<XValueNodeImpl> = Comparator.comparing<XValueNodeImpl, Boolean> { !isItemPinned(it) } val compoundComparator = pinToTopComparator.then(XValueNodeImpl.COMPARATOR) fun isEnabled() : Boolean { return Registry.`is`("debugger.field.pin.to.top", true) } fun onNodeHovered(node: XDebuggerTreeNode?, lifetimeHolder: Disposable) { if (myActiveNode == node) { return } if (!isEnabled()) { return } disposeCurrentNodeHoverSubscription() if (!isPinToTopSupported(node)) { return } val valueNode = node as? XValueNodeImpl ?: return val pinnedValue = node.valueContainer as? PinToTopMemberValue ?: return if ((valueNode.parent as? XValueNodeImpl)?.valueContainer !is PinToTopParentValue) { return } if (!pinnedValue.canBePinned() || isItemPinned(node)) { return } var oldIcon = valueNode.icon val changeIconLifetime = Disposable { val xValuePresentation = node.valuePresentation if (node.icon == PlatformDebuggerImplIcons.PinToTop.UnpinnedItem && xValuePresentation != null) { node.setPresentation(oldIcon, xValuePresentation, !node.isLeaf) } myActiveNode = null } myActiveNode = node myPinToTopIconAlarm.addRequest({ val xValuePresentation = node.valuePresentation ?: return@addRequest oldIcon = node.icon //update icon with actual value node.setPresentation(PlatformDebuggerImplIcons.PinToTop.UnpinnedItem, xValuePresentation, !node.isLeaf) }, DEFAULT_ICON_DELAY) myNodeHoverLifetime = changeIconLifetime Disposer.register(lifetimeHolder, changeIconLifetime) } fun addListener(listener: XDebuggerPinToTopListener, disposable: Disposable) { myListeners.add(listener) Disposer.register(disposable, Disposable { myListeners.remove(listener) }) } fun removeListener(listener: XDebuggerPinToTopListener) { myListeners.remove(listener) } fun getPinnedItemInfos() = myPinnedMembers.values.toList() fun addItemInfo(typeName: String, fieldName: String) { val info = PinnedItemInfo(typeName, fieldName) myPinnedMembers[info.getKey()] = info for (listener in myListeners) { listener.onPinnedItemAdded(info) } } fun removeItemInfo(typeName: String, fieldName: String) { val key = PinnedItemInfo.getKey(typeName, fieldName) val info = myPinnedMembers[key] ?: return myPinnedMembers.remove(key) for (listener in myListeners) { listener.onPinnedItemRemoved(info) } } fun isItemPinned(node: XValueNodeImpl?) : Boolean { val typeName = ((node?.parent as? XValueContainerNode<*>)?.valueContainer as? PinToTopParentValue)?.getTypeName() ?: return false return myPinnedMembers.containsKey( PinnedItemInfo.getKey(typeName, node.name ?: "")) } private fun disposeCurrentNodeHoverSubscription() { Disposer.dispose(myNodeHoverLifetime ?: return) myPinToTopIconAlarm.cancelAllRequests() } fun saveState(state: PinToTopManagerState) { state.pinnedMembersList = myPinnedMembers.toList().map { it.second }.toMutableList() } fun loadState(state: PinToTopManagerState) { myPinnedMembers.putAll(state.pinnedMembersList.map { Pair(it.getKey(), it) }) } fun isPinToTopSupported(node: XDebuggerTreeNode?) : Boolean { if (node !is XValueContainerNode<*>) return false return node.valueContainer is PinToTopValue } }
apache-2.0
91368c872405b85ba6efa3ffd386eeb2
37.261194
149
0.70158
4.627256
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/MangaSyncTypeMapping.kt
2
3490
package eu.kanade.tachiyomi.data.database.mappers import android.content.ContentValues import android.database.Cursor import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.InsertQuery import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.models.MangaSync import eu.kanade.tachiyomi.data.database.models.MangaSyncImpl import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_ID import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_LAST_CHAPTER_READ import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_MANGA_ID import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_REMOTE_ID import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_SCORE import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_STATUS import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_SYNC_ID import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_TITLE import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.COL_TOTAL_CHAPTERS import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable.TABLE class MangaSyncTypeMapping : SQLiteTypeMapping<MangaSync>( MangaSyncPutResolver(), MangaSyncGetResolver(), MangaSyncDeleteResolver() ) class MangaSyncPutResolver : DefaultPutResolver<MangaSync>() { override fun mapToInsertQuery(obj: MangaSync) = InsertQuery.builder() .table(TABLE) .build() override fun mapToUpdateQuery(obj: MangaSync) = UpdateQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() override fun mapToContentValues(obj: MangaSync) = ContentValues(9).apply { put(COL_ID, obj.id) put(COL_MANGA_ID, obj.manga_id) put(COL_SYNC_ID, obj.sync_id) put(COL_REMOTE_ID, obj.remote_id) put(COL_TITLE, obj.title) put(COL_LAST_CHAPTER_READ, obj.last_chapter_read) put(COL_TOTAL_CHAPTERS, obj.total_chapters) put(COL_STATUS, obj.status) put(COL_SCORE, obj.score) } } class MangaSyncGetResolver : DefaultGetResolver<MangaSync>() { override fun mapFromCursor(cursor: Cursor): MangaSync = MangaSyncImpl().apply { id = cursor.getLong(cursor.getColumnIndex(COL_ID)) manga_id = cursor.getLong(cursor.getColumnIndex(COL_MANGA_ID)) sync_id = cursor.getInt(cursor.getColumnIndex(COL_SYNC_ID)) remote_id = cursor.getInt(cursor.getColumnIndex(COL_REMOTE_ID)) title = cursor.getString(cursor.getColumnIndex(COL_TITLE)) last_chapter_read = cursor.getInt(cursor.getColumnIndex(COL_LAST_CHAPTER_READ)) total_chapters = cursor.getInt(cursor.getColumnIndex(COL_TOTAL_CHAPTERS)) status = cursor.getInt(cursor.getColumnIndex(COL_STATUS)) score = cursor.getFloat(cursor.getColumnIndex(COL_SCORE)) } } class MangaSyncDeleteResolver : DefaultDeleteResolver<MangaSync>() { override fun mapToDeleteQuery(obj: MangaSync) = DeleteQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() }
gpl-3.0
f18663fcf825a734f2de9df41d7824b6
43.74359
87
0.744413
4.048724
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/local/feed/notifications/NotificationHelper.kt
1
7147
package org.schabi.newpipe.local.feed.notifications import android.app.NotificationManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import android.provider.Settings import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import com.squareup.picasso.Picasso import com.squareup.picasso.Target import org.schabi.newpipe.R import org.schabi.newpipe.extractor.stream.StreamInfoItem import org.schabi.newpipe.local.feed.service.FeedUpdateInfo import org.schabi.newpipe.util.Localization import org.schabi.newpipe.util.NavigationHelper import org.schabi.newpipe.util.PendingIntentCompat import org.schabi.newpipe.util.PicassoHelper /** * Helper for everything related to show notifications about new streams to the user. */ class NotificationHelper(val context: Context) { private val manager = context.getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager private val iconLoadingTargets = ArrayList<Target>() /** * Show a notification about new streams from a single channel. * Opening the notification will open the corresponding channel page. */ fun displayNewStreamsNotification(data: FeedUpdateInfo) { val newStreams: List<StreamInfoItem> = data.newStreams val summary = context.resources.getQuantityString( R.plurals.new_streams, newStreams.size, newStreams.size ) val builder = NotificationCompat.Builder( context, context.getString(R.string.streams_notification_channel_id) ) .setContentTitle(Localization.concatenateStrings(data.name, summary)) .setContentText( data.listInfo.relatedItems.joinToString( context.getString(R.string.enumeration_comma) ) { x -> x.name } ) .setNumber(newStreams.size) .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSmallIcon(R.drawable.ic_newpipe_triangle_white) .setColor(ContextCompat.getColor(context, R.color.ic_launcher_background)) .setColorized(true) .setAutoCancel(true) .setCategory(NotificationCompat.CATEGORY_SOCIAL) // Build style val style = NotificationCompat.InboxStyle() newStreams.forEach { style.addLine(it.name) } style.setSummaryText(summary) style.setBigContentTitle(data.name) builder.setStyle(style) // open the channel page when clicking on the notification builder.setContentIntent( PendingIntentCompat.getActivity( context, data.pseudoId, NavigationHelper .getChannelIntent(context, data.listInfo.serviceId, data.listInfo.url) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0 ) ) // a Target is like a listener for image loading events val target = object : Target { override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) { builder.setLargeIcon(bitmap) // set only if there is actually one manager.notify(data.pseudoId, builder.build()) iconLoadingTargets.remove(this) // allow it to be garbage-collected } override fun onBitmapFailed(e: Exception, errorDrawable: Drawable) { manager.notify(data.pseudoId, builder.build()) iconLoadingTargets.remove(this) // allow it to be garbage-collected } override fun onPrepareLoad(placeHolderDrawable: Drawable) { // Nothing to do } } // add the target to the list to hold a strong reference and prevent it from being garbage // collected, since Picasso only holds weak references to targets iconLoadingTargets.add(target) PicassoHelper.loadNotificationIcon(data.avatarUrl).into(target) } companion object { /** * Check whether notifications are enabled on the device. * Users can disable them via the system settings for a single app. * If this is the case, the app cannot create any notifications * and display them to the user. * <br> * On Android 26 and above, notification channels are used by NewPipe. * These can be configured by the user, too. * The notification channel for new streams is also checked by this method. * * @param context Context * @return <code>true</code> if notifications are allowed and can be displayed; * <code>false</code> otherwise */ fun areNotificationsEnabledOnDevice(context: Context): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = context.getString(R.string.streams_notification_channel_id) val manager = context.getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager val enabled = manager.areNotificationsEnabled() val channel = manager.getNotificationChannel(channelId) val importance = channel?.importance enabled && channel != null && importance != NotificationManager.IMPORTANCE_NONE } else { NotificationManagerCompat.from(context).areNotificationsEnabled() } } /** * Whether the user enabled the notifications for new streams in the app settings. */ @JvmStatic fun areNewStreamsNotificationsEnabled(context: Context): Boolean { return ( PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.enable_streams_notifications), false) && areNotificationsEnabledOnDevice(context) ) } /** * Open the system's notification settings for NewPipe on Android Oreo (API 26) and later. * Open the system's app settings for NewPipe on previous Android versions. */ fun openNewPipeSystemNotificationSettings(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } else { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.parse("package:" + context.packageName) context.startActivity(intent) } } } }
gpl-3.0
b73b329b3de267031d0ec3eacd9b6642
41.796407
99
0.649643
5.108649
false
false
false
false
bonepeople/SDCardCleaner
app/src/main/java/com/bonepeople/android/sdcardcleaner/adapter/CleanPathListAdapter.kt
1
1856
package com.bonepeople.android.sdcardcleaner.adapter import android.view.Gravity import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bonepeople.android.sdcardcleaner.R import com.bonepeople.android.widget.util.singleClick class CleanPathListAdapter(private val list: List<String>, private val clickAction: (Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == 1) { val textView = TextView(parent.context) textView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) textView.gravity = Gravity.CENTER textView.setText(R.string.state_emptyView) EmptyHolder(textView) } else { val textView = TextView(parent.context) textView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) textView.setPadding(20, 20, 20, 20) DataHolder(textView) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is DataHolder -> { holder.textView.text = list[position] holder.textView.singleClick { clickAction.invoke(position) } } } } override fun getItemCount() = if (list.isEmpty()) 1 else list.size override fun getItemViewType(position: Int) = if (list.isEmpty()) 1 else super.getItemViewType(position) private class DataHolder(val textView: TextView) : RecyclerView.ViewHolder(textView) private class EmptyHolder(textView: TextView) : RecyclerView.ViewHolder(textView) }
gpl-3.0
5435015ad885ff0fd7529057bf4fb72c
44.292683
150
0.706897
4.746803
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/native/internal/ObjCExportCoroutines.kt
2
2457
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.native.internal import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* import kotlin.coroutines.native.internal.* import kotlin.native.concurrent.* @ExportForCppRuntime private fun Kotlin_ObjCExport_createContinuationArgumentImpl( completionHolder: Any, exceptionTypes: NativePtr ): Continuation<Any?> = createContinuationArgumentFromCallback(EmptyCompletion) { result -> result.fold( onSuccess = { value -> runCompletionSuccess(completionHolder, value) }, onFailure = { exception -> runCompletionFailure(completionHolder, exception, exceptionTypes) } ) } private object EmptyCompletion : Continuation<Any?> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resumeWith(result: Result<Any?>) { val exception = result.exceptionOrNull() ?: return TerminateWithUnhandledException(exception) // Throwing the exception from [resumeWith] is not generally expected. // Also terminating is consistent with other pieces of ObjCExport machinery. } } @PublishedApi @ExportForCppRuntime("Kotlin_ObjCExport_resumeContinuationSuccess") // Also makes it a data flow root. internal fun resumeContinuation(continuation: Continuation<Any?>, value: Any?) { continuation.resume(value) } @PublishedApi @ExportForCppRuntime("Kotlin_ObjCExport_resumeContinuationFailure") // Also makes it a data flow root. internal fun resumeContinuationWithException(continuation: Continuation<Any?>, exception: Throwable) { continuation.resumeWithException(exception) } @PublishedApi @ExportForCompiler // Mark as data flow root. internal fun getCoroutineSuspended(): Any = COROUTINE_SUSPENDED @PublishedApi @ExportForCompiler // Mark as data flow root. internal fun interceptedContinuation(continuation: Continuation<Any?>): Continuation<Any?> = continuation.intercepted() @FilterExceptions @SymbolName("Kotlin_ObjCExport_runCompletionSuccess") private external fun runCompletionSuccess(completionHolder: Any, result: Any?) @FilterExceptions @SymbolName("Kotlin_ObjCExport_runCompletionFailure") private external fun runCompletionFailure(completionHolder: Any, exception: Throwable, exceptionTypes: NativePtr)
apache-2.0
be88448e3f74b9a0de02f5923dcd828d
36.242424
119
0.757428
4.894422
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/DummyAccessorInvocationTransformer.kt
3
2588
/* * Copyright 2010-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 org.jetbrains.kotlin.js.inline import org.jetbrains.kotlin.descriptors.PropertyGetterDescriptor import org.jetbrains.kotlin.descriptors.PropertySetterDescriptor import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.descriptor import org.jetbrains.kotlin.js.backend.ast.metadata.inlineStrategy import org.jetbrains.kotlin.js.backend.ast.metadata.psiElement class DummyAccessorInvocationTransformer : JsVisitorWithContextImpl() { override fun endVisit(x: JsNameRef, ctx: JsContext<in JsNode>) { super.endVisit(x, ctx) val dummy = tryCreatePropertyGetterInvocation(x) if (dummy != null) { ctx.replaceMe(dummy) } } override fun endVisit(x: JsBinaryOperation, ctx: JsContext<in JsNode>) { super.endVisit(x, ctx) val dummy = tryCreatePropertySetterInvocation(x) if (dummy != null) { ctx.replaceMe(dummy) } } private fun tryCreatePropertyGetterInvocation(x: JsNameRef): JsInvocation? { if (x.inlineStrategy != null && x.descriptor is PropertyGetterDescriptor) { val dummyInvocation = JsInvocation(x) copyInlineMetadata(x, dummyInvocation) return dummyInvocation } return null } private fun tryCreatePropertySetterInvocation(x: JsBinaryOperation): JsInvocation? { if (!x.operator.isAssignment || x.arg1 !is JsNameRef) return null val name = x.arg1 as JsNameRef if (name.inlineStrategy != null && name.descriptor is PropertySetterDescriptor) { val dummyInvocation = JsInvocation(name, x.arg2) copyInlineMetadata(name, dummyInvocation) return dummyInvocation } return null } private fun copyInlineMetadata(from: JsNameRef, to: JsInvocation) { to.inlineStrategy = from.inlineStrategy to.descriptor = from.descriptor to.psiElement = from.psiElement } }
apache-2.0
1e7e6fd5cf064afbd96aa559174cda50
37.058824
89
0.702087
4.393888
false
false
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/defFileDependencies.kt
2
5834
package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.konan.util.DefFile import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform import org.jetbrains.kotlin.native.interop.gen.jvm.buildNativeLibrary import org.jetbrains.kotlin.native.interop.gen.jvm.prepareTool import org.jetbrains.kotlin.native.interop.indexer.NativeLibraryHeaders import org.jetbrains.kotlin.native.interop.indexer.getHeaderPaths import org.jetbrains.kotlin.native.interop.tool.CInteropArguments import java.io.File fun defFileDependencies(args: Array<String>) { val defFiles = mutableListOf<File>() val targets = mutableListOf<String>() var index = 0 while (index < args.size) { val arg = args[index] ++index when (arg) { "-target" -> { targets += args[index] ++index } else -> { defFiles.add(File(arg)) } } } defFileDependencies(makeDependencyAssigner(targets, defFiles)) } private fun makeDependencyAssigner(targets: List<String>, defFiles: List<File>) = CompositeDependencyAssigner(targets.map { makeDependencyAssignerForTarget(it, defFiles) }) private fun makeDependencyAssignerForTarget(target: String, defFiles: List<File>): SingleTargetDependencyAssigner { val tool = prepareTool(target, KotlinPlatform.NATIVE) val cinteropArguments = CInteropArguments() cinteropArguments.argParser.parse(arrayOf()) val libraries = defFiles.associateWith { buildNativeLibrary( tool, DefFile(it, tool.substitutions), cinteropArguments, ImportsImpl(emptyMap()) ).getHeaderPaths() } return SingleTargetDependencyAssigner(libraries) } private fun defFileDependencies(dependencyAssigner: DependencyAssigner) { while (!dependencyAssigner.isDone()) { val (file, depends) = dependencyAssigner.getReady().entries.sortedBy { it.key }.first() dependencyAssigner.markDone(file) patchDepends(file, depends.sorted()) println("${file.name} done.") } } private fun patchDepends(file: File, newDepends: List<String>) { val defFileLines = file.readLines() val dependsLine = buildString { append("depends =") newDepends.forEach { append(" ") append(it) } } val newDefFileLines = listOf(dependsLine) + defFileLines.filter { !it.startsWith("depends =") } file.bufferedWriter().use { writer -> newDefFileLines.forEach { writer.appendLine(it) } } } private interface DependencyAssigner { fun isDone(): Boolean fun getReady(): Map<File, Set<String>> fun markDone(file: File) } private class CompositeDependencyAssigner(val dependencyAssigners: List<DependencyAssigner>) : DependencyAssigner { override fun isDone(): Boolean = dependencyAssigners.all { it.isDone() } override fun getReady(): Map<File, Set<String>> { return dependencyAssigners.map { it.getReady() }.reduce { left, right -> (left.keys intersect right.keys) .associateWith { left.getValue(it) union right.getValue(it) } }.also { require(it.isNotEmpty()) { "incompatible dependencies" } // TODO: add more info. } } override fun markDone(file: File) { dependencyAssigners.forEach { it.markDone(file) } } } private class SingleTargetDependencyAssigner( defFilesToHeaders: Map<File, NativeLibraryHeaders<String>> ) : DependencyAssigner { private val pendingDefFilesToHeaders = defFilesToHeaders.toMutableMap() private val processedHeadersToDefFiles = mutableMapOf<String, File>() init { val ownedHeaders = pendingDefFilesToHeaders.values.flatMap { it.ownHeaders } val unownedHeadersToDefFiles = mutableMapOf<String, File>() pendingDefFilesToHeaders.forEach { (def, lib) -> (lib.importedHeaders - ownedHeaders).forEach { unownedHeadersToDefFiles.putIfAbsent(it, def) } } if (unownedHeadersToDefFiles.isNotEmpty()) { error("Unowned headers:\n" + unownedHeadersToDefFiles.entries.joinToString("\n") { "${it.key}\n imported by: ${it.value.name}" }) } } override fun isDone(): Boolean = pendingDefFilesToHeaders.isEmpty() override fun getReady(): Map<File, Set<String>> { val result = mutableMapOf<File, Set<String>>() defFiles@for ((defFile, headers) in pendingDefFilesToHeaders) { val depends = mutableSetOf<String>() headers@for (header in (headers.ownHeaders + headers.importedHeaders)) { val dependency = processedHeadersToDefFiles[header] ?: if (header in headers.ownHeaders) continue@headers else continue@defFiles depends.add(dependency.nameWithoutExtension) } result[defFile] = depends } if (result.isEmpty()) { pendingDefFilesToHeaders.entries.forEach { (def, headers) -> println(def.name) println("Own headers:") headers.ownHeaders.forEach { println(it) } println("Unowned imported headers:") headers.importedHeaders.forEach { if (it !in processedHeadersToDefFiles) println(it) } println() } error("Cyclic dependency? Remaining libs:\n" + pendingDefFilesToHeaders.keys.joinToString("\n") { it.name }) } return result } override fun markDone(file: File) { val headers = pendingDefFilesToHeaders.remove(file)!! headers.ownHeaders.forEach { processedHeadersToDefFiles.putIfAbsent(it, file) } } }
apache-2.0
bd013f1a861411432c418f0222e048ce
34.579268
121
0.648612
4.353731
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/expression/FunctionTranslator.kt
1
4285
/* * Copyright 2010-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.kotlin.js.translate.expression import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PropertyAccessorDescriptor import org.jetbrains.kotlin.js.backend.ast.JsExpression import org.jetbrains.kotlin.js.backend.ast.JsFunction import org.jetbrains.kotlin.js.backend.ast.JsParameter import org.jetbrains.kotlin.js.backend.ast.metadata.functionDescriptor import org.jetbrains.kotlin.js.backend.ast.metadata.hasDefaultValue import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.reference.CallExpressionTranslator.shouldBeInlined import org.jetbrains.kotlin.js.translate.utils.BindingUtils import org.jetbrains.kotlin.js.translate.utils.FunctionBodyTranslator.translateFunctionBody import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi fun TranslationContext.translateAndAliasParameters( descriptor: FunctionDescriptor, targetList: MutableList<JsParameter> ): TranslationContext { val aliases = mutableMapOf<DeclarationDescriptor, JsExpression>() for (type in descriptor.getCorrectTypeParameters()) { if (type.isReified) { val paramNameForType = getNameForDescriptor(type) targetList += JsParameter(paramNameForType) val suggestedName = Namer.isInstanceSuggestedName(type) val paramName = scope().declareTemporaryName(suggestedName) targetList += JsParameter(paramName) aliases[type] = paramName.makeRef() } } if (descriptor.requiresExtensionReceiverParameter) { val receiverParameterName = scope().declareTemporaryName(Namer.getReceiverParameterName()) aliases[descriptor.extensionReceiverParameter!!] = receiverParameterName.makeRef() targetList += JsParameter(receiverParameterName) } for (valueParameter in descriptor.valueParameters) { targetList += JsParameter(getNameForDescriptor(valueParameter)).apply { hasDefaultValue = valueParameter.hasDefaultValue() } } val continuationDescriptor = continuationParameterDescriptor if (continuationDescriptor != null) { val jsParameter = JsParameter(getNameForDescriptor(continuationDescriptor)) targetList += jsParameter } return this.innerContextWithDescriptorsAliased(aliases) } private fun FunctionDescriptor.getCorrectTypeParameters() = (this as? PropertyAccessorDescriptor)?.correspondingProperty?.typeParameters ?: typeParameters private val FunctionDescriptor.requiresExtensionReceiverParameter get() = DescriptorUtils.isExtension(this) fun TranslationContext.translateFunction(declaration: KtDeclarationWithBody, function: JsFunction) { val descriptor = BindingUtils.getFunctionDescriptor(bindingContext(), declaration) if (declaration.hasBody()) { val body = translateFunctionBody(descriptor, declaration, this) function.body.statements += body.statements } function.functionDescriptor = descriptor } fun TranslationContext.wrapWithInlineMetadata(function: JsFunction, descriptor: FunctionDescriptor): JsExpression { return if (shouldBeInlined(descriptor, this) && descriptor.isEffectivelyPublicApi) { val metadata = InlineMetadata.compose(function, descriptor) metadata.functionWithMetadata } else { function } }
apache-2.0
5ca105eaecf9e0f1503ff10381d1fdad
42.72449
132
0.780163
5.041176
false
false
false
false
allotria/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/sam/samConversion.kt
1
8782
// 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 org.jetbrains.plugins.groovy.lang.sam import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil import com.intellij.psi.impl.source.resolve.graphInference.InferenceBound import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.MethodSignature import com.intellij.psi.util.TypeConversionUtil import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isTrait import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability import org.jetbrains.plugins.groovy.lang.resolve.api.ExplicitRuntimeTypeArgument import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.ExpectedType import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.GroovyInferenceSession import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypeConstraint import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.TypePositionConstraint import org.jetbrains.plugins.groovy.lang.typing.GroovyClosureType fun findSingleAbstractMethod(clazz: PsiClass): PsiMethod? = findSingleAbstractSignatureCached(clazz)?.method fun findSingleAbstractSignature(clazz: PsiClass): MethodSignature? = findSingleAbstractSignatureCached(clazz) private fun findSingleAbstractMethodAndClass(type: PsiType): Pair<PsiMethod, PsiClassType.ClassResolveResult>? { val groundType = (type as? PsiClassType)?.let { FunctionalInterfaceParameterizationUtil.getNonWildcardParameterization(it) } ?: return null val resolveResult = (groundType as PsiClassType).resolveGenerics() val samClass = resolveResult.element ?: return null val sam = findSingleAbstractMethod(samClass) ?: return null return sam to resolveResult } private fun findSingleAbstractSignatureCached(clazz: PsiClass): HierarchicalMethodSignature? { return CachedValuesManager.getCachedValue(clazz) { CachedValueProvider.Result.create(doFindSingleAbstractSignature(clazz), clazz) } } private fun doFindSingleAbstractSignature(clazz: PsiClass): HierarchicalMethodSignature? { var result: HierarchicalMethodSignature? = null for (signature in clazz.visibleSignatures) { if (!isEffectivelyAbstractMethod(signature)) continue if (result != null) return null // found another abstract method result = signature } return result } private fun isEffectivelyAbstractMethod(signature: HierarchicalMethodSignature): Boolean { val method = signature.method if (!method.hasModifierProperty(PsiModifier.ABSTRACT)) return false if (isObjectMethod(signature)) return false if (isImplementedTraitMethod(method)) return false return true } private fun isObjectMethod(signature: HierarchicalMethodSignature): Boolean { return signature.superSignatures.any { it.method.containingClass?.qualifiedName == JAVA_LANG_OBJECT } } private fun isImplementedTraitMethod(method: PsiMethod): Boolean { val clazz = method.containingClass ?: return false if (!isTrait(clazz)) return false val traitMethod = method as? GrMethod ?: return false return traitMethod.block != null } fun isSamConversionAllowed(context: PsiElement): Boolean { return GroovyConfigUtils.getInstance().isVersionAtLeast(context, GroovyConfigUtils.GROOVY2_2) } internal fun processSAMConversion(targetType: PsiType, closureType: GroovyClosureType, context: PsiElement): List<ConstraintFormula> { val constraints = mutableListOf<ConstraintFormula>() val pair = findSingleAbstractMethodAndClass(targetType) if (pair == null) { constraints.add( TypeConstraint(targetType, TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, context), context)) return constraints } val (sam, classResolveResult) = pair val groundClass = classResolveResult.element ?: return constraints val groundType = groundTypeForClosure(sam, groundClass, closureType, targetType, context) if (groundType != null) { constraints.add(TypeConstraint(targetType, groundType, context)) } return constraints } private fun returnTypeConstraint(samReturnType: PsiType?, returnType: PsiType?, context: PsiElement): ConstraintFormula? { if (returnType == null || samReturnType == null || samReturnType == PsiType.VOID) { return null } return TypeConstraint(samReturnType, returnType, context) } /** * JLS 18.5.3 * com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil.getFunctionalTypeExplicit */ private fun groundTypeForClosure(sam: PsiMethod, groundClass: PsiClass, closureType: GroovyClosureType, targetType: PsiType, context: PsiElement): PsiClassType? { if (!Registry.`is`("groovy.use.explicitly.typed.closure.in.inference", true)) return null val typeParameters = groundClass.typeParameters ?: return null if (typeParameters.isEmpty()) return null val samContainingClass = sam.containingClass ?: return null val groundClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(samContainingClass, groundClass, PsiSubstitutor.EMPTY) // erase all ground class parameters to null, otherwise explicit closure signature will be inapplicable val erasingSubstitutor = PsiSubstitutor.createSubstitutor(typeParameters.associate { it to PsiType.NULL }) val samParameterTypes = sam.parameterList.parameters.map { it.type } val arguments = samParameterTypes.map { val withInheritance = groundClassSubstitutor.substitute(it) ExplicitRuntimeTypeArgument(withInheritance, TypeConversionUtil.erasure(erasingSubstitutor.substitute(withInheritance))) } val argumentMapping = closureType.applyTo(arguments).find { it.applicability() == Applicability.applicable } ?: return null val samSession = GroovyInferenceSession(typeParameters, PsiSubstitutor.EMPTY, context, false) argumentMapping.expectedTypes.forEach { (expectedType, argument) -> val leftType = samSession.substituteWithInferenceVariables(groundClassSubstitutor.substitute(expectedType)) samSession.addConstraint( TypePositionConstraint(ExpectedType(leftType, GrTypeConverter.Position.METHOD_PARAMETER), argument.type, context)) } val returnTypeConstraint = returnTypeConstraint(sam.returnType, closureType.returnType(arguments), context) if (returnTypeConstraint != null) samSession.addConstraint(returnTypeConstraint) if (!samSession.repeatInferencePhases()) { return null } val resultSubstitutor = relaxUnboundTypeParameters(samSession.result(), samSession, targetType) val elementFactory = JavaPsiFacade.getElementFactory(context.project) return elementFactory.createType(groundClass, resultSubstitutor) } fun relaxUnboundTypeParameters(substitutor: PsiSubstitutor, samSession: GroovyInferenceSession, targetType : PsiType) : PsiSubstitutor { // Untyped parameters of functional expressions may turn into any type, not just Object. // In that case, we just replace unknown type parameter with the type we are expected to compare with val targetTypeSubstitutor = (targetType as? PsiClassType)?.resolveGenerics() ?: return substitutor val map = mutableMapOf<PsiTypeParameter, PsiType?>() for (inferenceVariable in samSession.inferenceVariables) { val typeParameter = inferenceVariable.delegate if (inferenceVariable.getBounds(InferenceBound.LOWER).isNullOrEmpty() && inferenceVariable.getBounds(InferenceBound.EQ).isNullOrEmpty() && inferenceVariable.getBounds(InferenceBound.UPPER).size == 1) { map[typeParameter] = targetTypeSubstitutor.substitutor.substitute(typeParameter) ?: substitutor.substitute(typeParameter) } else { map[typeParameter] = substitutor.substitute(typeParameter) } } return PsiSubstitutor.createSubstitutor(map) }
apache-2.0
ce09a197f0930d248470302242283fe4
48.067039
140
0.777613
5.102847
false
false
false
false
androidx/androidx
emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/EmojiView.kt
3
4563
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.emoji2.emojipicker import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Build import android.text.Layout import android.text.Spanned import android.text.StaticLayout import android.text.TextPaint import android.util.AttributeSet import android.util.TypedValue import android.view.View import androidx.annotation.RequiresApi import androidx.core.graphics.applyCanvas /** * A customized view to support drawing emojis asynchronously. */ internal class EmojiView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) { companion object { private const val EMOJI_DRAW_TEXT_SIZE_SP = 30 } private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { textSize = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, EMOJI_DRAW_TEXT_SIZE_SP.toFloat(), context.resources.displayMetrics ) } private val offscreenCanvasBitmap: Bitmap = with(textPaint.fontMetricsInt) { val size = bottom - top Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val size = MeasureSpec.getSize(widthMeasureSpec) setMeasuredDimension(size, size) } override fun draw(canvas: Canvas?) { super.draw(canvas) canvas?.run { save() scale( width.toFloat() / offscreenCanvasBitmap.width, height.toFloat() / offscreenCanvasBitmap.height ) drawBitmap(offscreenCanvasBitmap, 0f, 0f, null) restore() } } var emoji: CharSequence? = null set(value) { field = value offscreenCanvasBitmap.eraseColor(Color.TRANSPARENT) if (value != null) { post { drawEmoji(value) contentDescription = value invalidate() } } } private fun drawEmoji(emoji: CharSequence) { if (emoji == this.emoji) { offscreenCanvasBitmap.applyCanvas { if (emoji is Spanned) { createStaticLayout(emoji, width).draw(this) } else { val textWidth = textPaint.measureText(emoji, 0, emoji.length) drawText( emoji, /* start = */ 0, /* end = */ emoji.length, /* x = */ (width - textWidth) / 2, /* y = */ -textPaint.fontMetrics.top, textPaint, ) } } } } @RequiresApi(23) internal object Api23Impl { fun createStaticLayout(emoji: Spanned, textPaint: TextPaint, width: Int): StaticLayout = StaticLayout.Builder.obtain( emoji, 0, emoji.length, textPaint, width ).apply { setAlignment(Layout.Alignment.ALIGN_CENTER) setLineSpacing(/* spacingAdd = */ 0f, /* spacingMult = */ 1f) setIncludePad(false) }.build() } private fun createStaticLayout(emoji: Spanned, width: Int): StaticLayout { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return Api23Impl.createStaticLayout(emoji, textPaint, width) } else { @Suppress("DEPRECATION") return StaticLayout( emoji, textPaint, width, Layout.Alignment.ALIGN_CENTER, /* spacingmult = */ 1f, /* spacingadd = */ 0f, /* includepad = */ false, ) } } }
apache-2.0
d34c546294fec028e607f952217ca495
32.306569
99
0.587114
4.793067
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/synthetic/KspSyntheticFileMemberContainer.kt
3
3887
/* * 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.room.compiler.processing.ksp.synthetic import androidx.room.compiler.codegen.XClassName import androidx.room.compiler.processing.XAnnotation import androidx.room.compiler.processing.XAnnotationBox import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XEquality import androidx.room.compiler.processing.XNullability import androidx.room.compiler.processing.ksp.KspMemberContainer import androidx.room.compiler.processing.ksp.KspType import com.google.devtools.ksp.symbol.KSDeclaration import com.squareup.javapoet.ClassName import com.squareup.kotlinpoet.javapoet.toKClassName import kotlin.reflect.KClass /** * When a top level function/member is compiled, the generated Java class does not exist in KSP. * * This wrapper synthesizes one from the JVM binary name * * https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html#jls-13.1 */ internal class KspSyntheticFileMemberContainer( private val binaryName: String ) : KspMemberContainer, XEquality { override val equalityItems: Array<out Any?> by lazy { arrayOf(binaryName) } override val type: KspType? get() = null override val declaration: KSDeclaration? get() = null @Deprecated( "Use asClassName().toJavaPoet() to be clear the name is for JavaPoet.", replaceWith = ReplaceWith( "asClassName().toJavaPoet()", "androidx.room.compiler.codegen.toJavaPoet" ) ) override val className: ClassName by lazy { xClassName.java } private val xClassName: XClassName by lazy { val packageName = binaryName.substringBeforeLast( delimiter = '.', missingDelimiterValue = "" ) val shortNames = if (packageName == "") { binaryName } else { binaryName.substring(packageName.length + 1) }.split('$') val java = ClassName.get( packageName, shortNames.first(), *shortNames.drop(1).toTypedArray() ) // Even though the generated Java class is not referencable from Kotlin code, instead of // using 'Unavailable', for parity we use the same JavaPoet name for KotlinPoet, val kotlin = java.toKClassName() XClassName(java, kotlin, XNullability.NONNULL) } override fun asClassName() = xClassName override fun kindName(): String { return "synthethic top level file" } override val fallbackLocationText: String get() = binaryName override val docComment: String? get() = null override val enclosingElement: XElement? get() = null override val closestMemberContainer: KspSyntheticFileMemberContainer get() = this override fun validate(): Boolean { return true } override fun <T : Annotation> getAnnotations(annotation: KClass<T>): List<XAnnotationBox<T>> { return emptyList() } override fun getAllAnnotations(): List<XAnnotation> { return emptyList() } override fun hasAnnotation(annotation: KClass<out Annotation>): Boolean { return false } override fun hasAnnotationWithPackage(pkg: String): Boolean { return false } }
apache-2.0
06ffea8bc5e0119e3dfc5d10e4470f6b
31.132231
98
0.690507
4.649522
false
false
false
false
androidx/androidx
wear/watchface/watchface-client/src/main/java/androidx/wear/watchface/client/WatchUiState.kt
3
2538
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.client import android.app.NotificationManager import androidx.annotation.IntDef /** * The InterruptionFilter. * @hide */ @IntDef( value = [ NotificationManager.INTERRUPTION_FILTER_ALARMS, NotificationManager.INTERRUPTION_FILTER_ALL, NotificationManager.INTERRUPTION_FILTER_NONE, NotificationManager.INTERRUPTION_FILTER_PRIORITY, NotificationManager.INTERRUPTION_FILTER_UNKNOWN ] ) public annotation class InterruptionFilter /** * Describes the system state of the watch face ui. * * @param inAmbientMode Whether the device is is ambient mode or not. * @param interruptionFilter The interruption filter defines which notifications are allowed to * interrupt the user. For watch faces this value is one of: * [NotificationManager.INTERRUPTION_FILTER_ALARMS], * [NotificationManager.INTERRUPTION_FILTER_ALL], * [NotificationManager.INTERRUPTION_FILTER_NONE], * [NotificationManager.INTERRUPTION_FILTER_PRIORITY], * [NotificationManager.INTERRUPTION_FILTER_UNKNOWN]. @see [NotificationManager] for more details. */ public class WatchUiState( @get:JvmName("inAmbientMode") public val inAmbientMode: Boolean, @InterruptionFilter public val interruptionFilter: Int ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WatchUiState if (inAmbientMode != other.inAmbientMode) return false if (interruptionFilter != other.interruptionFilter) return false return true } override fun hashCode(): Int { var result = inAmbientMode.hashCode() result = 31 * result + interruptionFilter return result } override fun toString(): String { return "WatchUiState(inAmbientMode=$inAmbientMode, interruptionFilter=$interruptionFilter)" } }
apache-2.0
d6b6fd44cea57fdbc5fe28c02b4513b7
31.974026
99
0.729314
4.516014
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/lastfm/TrackEntity.kt
1
1599
package taiwan.no1.app.ssfm.models.entities.lastfm import com.google.gson.annotations.SerializedName /** * @author jieyi * @since 10/16/17 */ data class TrackEntity(var track: Track?) { data class Track(var streamable: Streamable?) : BaseTrack() data class TrackWithStreamableString(var streamable: String?) : BaseTrack() open class BaseTrack(var album: AlbumEntity.Album? = null, @SerializedName("@attr") var attr: Attr? = null, var artist: ArtistEntity.Artist? = null, var duration: String? = null, @SerializedName("image") var images: List<Image>? = null, var listeners: String? = null, var match: Double? = null, var mbid: String? = null, var name: String? = null, @SerializedName("playcount") var playcount: String? = null, @SerializedName("toptags") var topTag: Tags? = null, var url: String? = null, var realUrl: String? = null, var wiki: Wiki? = null) : BaseEntity { override fun toString() = """ album: $album attr: $attr artist: $artist duration: $duration images: $images listeners: $listeners match: $match mbid: $mbid name: $name playcount: $playcount topTag: $topTag url: $url realUrl: $realUrl wiki: $wiki """ } }
apache-2.0
30a9d941ca5f47b27d7a0063e45ce85d
31
79
0.512195
4.504225
false
false
false
false
oldcwj/iPing
commons/src/main/kotlin/com/simplemobiletools/commons/activities/LicenseActivity.kt
1
4057
package com.simplemobiletools.commons.activities import android.os.Bundle import android.text.SpannableString import android.text.style.UnderlineSpan import android.view.LayoutInflater import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.baseConfig import com.simplemobiletools.commons.extensions.getLinkTextColor import com.simplemobiletools.commons.extensions.launchViewIntent import com.simplemobiletools.commons.extensions.updateTextColors import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.License import kotlinx.android.synthetic.main.activity_license.* import kotlinx.android.synthetic.main.license_item.view.* class LicenseActivity : BaseSimpleActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_license) val linkTextColor = getLinkTextColor() updateTextColors(licenses_holder) val inflater = LayoutInflater.from(this) val licenses = initLicenses() val licenseMask = intent.getIntExtra(APP_LICENSES, 0) licenses.filter { licenseMask and it.id != 0 }.forEach { val license = it val view = inflater.inflate(R.layout.license_item, null) view.apply { license_title.text = getUnderlinedTitle(getString(license.titleId)) license_title.setOnClickListener { launchViewIntent(license.urlId) } license_title.setTextColor(linkTextColor) license_text.text = getString(license.textId) license_text.setTextColor(baseConfig.textColor) licenses_holder.addView(this) } } } fun getUnderlinedTitle(title: String): SpannableString { val underlined = SpannableString(title) underlined.setSpan(UnderlineSpan(), 0, title.length, 0) return underlined } fun initLicenses() = arrayOf( License(LICENSE_KOTLIN, R.string.kotlin_title, R.string.kotlin_text, R.string.kotlin_url), License(LICENSE_SUBSAMPLING, R.string.subsampling_title, R.string.subsampling_text, R.string.subsampling_url), License(LICENSE_GLIDE, R.string.glide_title, R.string.glide_text, R.string.glide_url), License(LICENSE_CROPPER, R.string.cropper_title, R.string.cropper_text, R.string.cropper_url), License(LICENSE_MULTISELECT, R.string.multiselect_title, R.string.multiselect_text, R.string.multiselect_url), License(LICENSE_RTL, R.string.rtl_viewpager_title, R.string.rtl_viewpager_text, R.string.rtl_viewpager_url), License(LICENSE_JODA, R.string.joda_title, R.string.joda_text, R.string.joda_url), License(LICENSE_STETHO, R.string.stetho_title, R.string.stetho_text, R.string.stetho_url), License(LICENSE_OTTO, R.string.otto_title, R.string.otto_text, R.string.otto_url), License(LICENSE_PHOTOVIEW, R.string.photoview_title, R.string.photoview_text, R.string.photoview_url), License(LICENSE_PICASSO, R.string.picasso_title, R.string.picasso_text, R.string.picasso_url), License(LICENSE_PATTERN, R.string.pattern_title, R.string.pattern_text, R.string.pattern_url), License(LICENSE_REPRINT, R.string.reprint_title, R.string.reprint_text, R.string.reprint_url), License(LICENSE_GIF_DRAWABLE, R.string.gif_drawable_title, R.string.gif_drawable_text, R.string.gif_drawable_url), License(LICENSE_AUTOFITTEXTVIEW, R.string.autofittextview_title, R.string.autofittextview_text, R.string.autofittextview_url), License(LICENSE_ROBOLECTRIC, R.string.robolectric_title, R.string.robolectric_text, R.string.robolectric_url), License(LICENSE_ESPRESSO, R.string.espresso_title, R.string.espresso_text, R.string.espresso_url) ) }
gpl-3.0
57d607b65633e394f5b9e072c0a2f0b1
58.661765
146
0.688686
4.110436
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/OneDimensionalFocusSearch.kt
3
10511
/* * 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.compose.ui.focus import androidx.compose.runtime.collection.MutableVector import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.ui.focus.FocusDirection.Companion.Next import androidx.compose.ui.focus.FocusDirection.Companion.Previous import androidx.compose.ui.focus.FocusStateImpl.Active import androidx.compose.ui.focus.FocusStateImpl.ActiveParent import androidx.compose.ui.focus.FocusStateImpl.Captured import androidx.compose.ui.focus.FocusStateImpl.Deactivated import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent import androidx.compose.ui.focus.FocusStateImpl.Inactive import androidx.compose.ui.node.LayoutNode import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract private const val InvalidFocusDirection = "This function should only be used for 1-D focus search" private const val NoActiveChild = "ActiveParent must have a focusedChild" internal fun FocusModifier.oneDimensionalFocusSearch( direction: FocusDirection, onFound: (FocusModifier) -> Boolean ): Boolean = when (direction) { Next -> forwardFocusSearch(onFound) Previous -> backwardFocusSearch(onFound) else -> error(InvalidFocusDirection) } private fun FocusModifier.forwardFocusSearch( onFound: (FocusModifier) -> Boolean ): Boolean = when (focusState) { ActiveParent, DeactivatedParent -> { val focusedChild = focusedChild ?: error(NoActiveChild) focusedChild.forwardFocusSearch(onFound) || generateAndSearchChildren(focusedChild, Next, onFound) } Active, Captured, Deactivated -> pickChildForForwardSearch(onFound) Inactive -> onFound.invoke(this) } private fun FocusModifier.backwardFocusSearch( onFound: (FocusModifier) -> Boolean ): Boolean = when (focusState) { ActiveParent, DeactivatedParent -> { val focusedChild = focusedChild ?: error(NoActiveChild) // Unlike forwardFocusSearch, backwardFocusSearch visits the children before the parent. when (focusedChild.focusState) { ActiveParent -> focusedChild.backwardFocusSearch(onFound) || // Don't forget to visit this item after visiting all its children. onFound.invoke(focusedChild) DeactivatedParent -> focusedChild.backwardFocusSearch(onFound) || // Since this item is deactivated, just skip it and search among its siblings. generateAndSearchChildren(focusedChild, Previous, onFound) // Since this item "is focused", it means we already visited all its children. // So just search among its siblings. Active, Captured -> generateAndSearchChildren(focusedChild, Previous, onFound) Deactivated, Inactive -> error(NoActiveChild) } } // BackwardFocusSearch is invoked at the root, and so it searches among siblings of the // ActiveParent for a child that is focused. If we encounter an active node (instead of an // ActiveParent) or a deactivated node (instead of a deactivated parent), it indicates // that the hierarchy does not have focus. ie. this is the initial focus state. // So we pick one of the children as the result. Active, Captured, Deactivated -> pickChildForBackwardSearch(onFound) // If we encounter an inactive node, we attempt to pick one of its children before picking // this node (backward search visits the children before the parent). Inactive -> pickChildForBackwardSearch(onFound) || onFound.invoke(this) } // Search among your children for the next child. // If the next child is not found, generate more children by requesting a beyondBoundsLayout. private fun FocusModifier.generateAndSearchChildren( focusedItem: FocusModifier, direction: FocusDirection, onFound: (FocusModifier) -> Boolean ): Boolean { // Search among the currently available children. if (searchChildren(focusedItem, direction, onFound)) { return true } // Generate more items until searchChildren() finds a result. return searchBeyondBounds(direction) { // Search among the added children. (The search continues as long as we return null). searchChildren(focusedItem, direction, onFound).takeIf { found -> // Stop searching when we find a result or if we don't have any more content. found || !hasMoreContent } } ?: false } // Search for the next sibling that should be granted focus. private fun FocusModifier.searchChildren( focusedItem: FocusModifier, direction: FocusDirection, onFound: (FocusModifier) -> Boolean ): Boolean { check(focusState == ActiveParent || focusState == DeactivatedParent) { "This function should only be used within a parent that has focus." } children.sortWith(FocusableChildrenComparator) when (direction) { Next -> children.forEachItemAfter(focusedItem) { child -> if (child.isEligibleForFocusSearch && child.forwardFocusSearch(onFound)) return true } Previous -> children.forEachItemBefore(focusedItem) { child -> if (child.isEligibleForFocusSearch && child.backwardFocusSearch(onFound)) return true } else -> error(InvalidFocusDirection) } // If all the children have been visited, return null if this is a forward search. If it is a // backward search, we want to move focus to the parent unless the parent is deactivated. // We also don't want to move focus to the root because from the user's perspective this would // look like nothing is focused. if (direction == Next || focusState == DeactivatedParent || isRoot()) return false return onFound.invoke(this) } private fun FocusModifier.pickChildForForwardSearch( onFound: (FocusModifier) -> Boolean ): Boolean { children.sortWith(FocusableChildrenComparator) return children.any { it.isEligibleForFocusSearch && it.forwardFocusSearch(onFound) } } private fun FocusModifier.pickChildForBackwardSearch( onFound: (FocusModifier) -> Boolean ): Boolean { children.sortWith(FocusableChildrenComparator) children.forEachReversed { if (it.isEligibleForFocusSearch && it.backwardFocusSearch(onFound)) { return true } } return false } private fun FocusModifier.isRoot() = parent == null @Suppress("BanInlineOptIn") @OptIn(ExperimentalContracts::class) private inline fun <T> MutableVector<T>.forEachItemAfter(item: T, action: (T) -> Unit) { contract { callsInPlace(action) } var itemFound = false for (index in indices) { if (itemFound) { action(get(index)) } if (get(index) == item) { itemFound = true } } } @Suppress("BanInlineOptIn") @OptIn(ExperimentalContracts::class) private inline fun <T> MutableVector<T>.forEachItemBefore(item: T, action: (T) -> Unit) { contract { callsInPlace(action) } var itemFound = false for (index in indices.reversed()) { if (itemFound) { action(get(index)) } if (get(index) == item) { itemFound = true } } } /** * We use this comparator to sort the focus modifiers in place order. * * We want to visit the nodes in placement order instead of composition order. * This is because components like LazyList reuse nodes without re-composing them, but it always * re-places nodes that are reused. * * Instead of sorting the items, we could just look for the next largest place order index in linear * time. However if the next item is deactivated, not eligible for focus search or none of its * children are focusable we would have to backtrack and find the item with the next largest place * order index. This would be more expensive than sorting the items. In addition to this, sorting * the items makes the next focus search more efficient. */ private object FocusableChildrenComparator : Comparator<FocusModifier> { override fun compare(focusModifier1: FocusModifier?, focusModifier2: FocusModifier?): Int { requireNotNull(focusModifier1) requireNotNull(focusModifier2) // Ignore focus modifiers that won't be considered during focus search. if (!focusModifier1.isEligibleForFocusSearch || !focusModifier2.isEligibleForFocusSearch) { if (focusModifier1.isEligibleForFocusSearch) return -1 if (focusModifier2.isEligibleForFocusSearch) return 1 return 0 } val layoutNode1 = checkNotNull(focusModifier1.coordinator?.layoutNode) val layoutNode2 = checkNotNull(focusModifier2.coordinator?.layoutNode) // Use natural order for focus modifiers within the same layout node. if (layoutNode1 == layoutNode2) return 0 // Compare the place order of the children of the least common ancestor. val pathFromRoot1 = pathFromRoot(layoutNode1) val pathFromRoot2 = pathFromRoot(layoutNode2) for (depth in 0..minOf(pathFromRoot1.lastIndex, pathFromRoot2.lastIndex)) { // If the items from the two paths are not equal, we have // found the first two children after the least common ancestor. // We use the place order of these two parents to compare the focus modifiers. if (pathFromRoot1[depth] != pathFromRoot2[depth]) { return pathFromRoot1[depth].placeOrder.compareTo(pathFromRoot2[depth].placeOrder) } } error("Could not find a common ancestor between the two FocusModifiers.") } private fun pathFromRoot(layoutNode: LayoutNode): MutableVector<LayoutNode> { val path = mutableVectorOf<LayoutNode>() var current: LayoutNode? = layoutNode while (current != null) { path.add(0, current) current = current.parent } return path } }
apache-2.0
a15ad4246520360f74eda4af98f2f821
41.383065
100
0.710589
4.652944
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/SimplifiableCallChainInspection.kt
4
15508
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.backend.common.descriptors.isSuspend import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.inspections.AssociateFunction import org.jetbrains.kotlin.idea.inspections.ReplaceAssociateFunctionFix import org.jetbrains.kotlin.idea.inspections.ReplaceAssociateFunctionInspection import org.jetbrains.kotlin.js.resolve.JsPlatformAnalyzerServices import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class SimplifiableCallChainInspection : AbstractCallChainChecker() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): KtVisitorVoid { return qualifiedExpressionVisitor(fun(expression) { var conversion = findQualifiedConversion(expression, conversionGroups) check@{ conversion, firstResolvedCall, _, context -> // Do not apply on maps due to lack of relevant stdlib functions val firstReceiverType = firstResolvedCall.resultingDescriptor?.extensionReceiverParameter?.type if (firstReceiverType != null) { if (conversion.replacement == "mapNotNull" && KotlinBuiltIns.isPrimitiveArray(firstReceiverType)) return@check false val builtIns = context[BindingContext.EXPRESSION_TYPE_INFO, expression]?.type?.builtIns ?: return@check false val firstReceiverRawType = firstReceiverType.constructor.declarationDescriptor?.defaultType if (firstReceiverRawType.isMap(builtIns)) return@check false } if (conversion.replacement.startsWith("joinTo")) { // Function parameter in map must have String result type if (!firstResolvedCall.hasLastFunctionalParameterWithResult(context) { it.isSubtypeOf(JsPlatformAnalyzerServices.builtIns.charSequence.defaultType) } ) return@check false } if (conversion.replacement in listOf("maxBy", "minBy", "minByOrNull", "maxByOrNull")) { val functionalArgumentReturnType = firstResolvedCall.lastFunctionalArgumentReturnType(context) ?: return@check false if (functionalArgumentReturnType.isNullable()) return@check false } if (conversion.removeNotNullAssertion && conversion.firstName == "map" && conversion.secondName in listOf("max", "maxOrNull", "min", "minOrNull") ) { val parent = expression.parent if (parent !is KtPostfixExpression || parent.operationToken != KtTokens.EXCLEXCL) return@check false } if (conversion.firstName == "map" && conversion.secondName == "sum" && conversion.replacement == "sumOf") { val type = firstResolvedCall.lastFunctionalArgumentReturnType(context) ?: return@check false if (!KotlinBuiltIns.isInt(type) && !KotlinBuiltIns.isLong(type) && !KotlinBuiltIns.isUInt(type) && !KotlinBuiltIns.isULong(type) && !KotlinBuiltIns.isDouble(type) ) return@check false } return@check conversion.enableSuspendFunctionCall || !containsSuspendFunctionCall(firstResolvedCall, context) } ?: return val associateFunction = getAssociateFunction(conversion, expression.receiverExpression) if (associateFunction != null) conversion = conversion.copy(replacement = associateFunction.functionName) val replacement = conversion.replacement val descriptor = holder.manager.createProblemDescriptor( expression, expression.firstCalleeExpression()!!.textRange.shiftRight(-expression.startOffset), KotlinBundle.message("call.chain.on.collection.type.may.be.simplified"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, SimplifyCallChainFix(conversion) { callExpression -> val lastArgumentName = if (replacement.startsWith("joinTo")) Name.identifier("transform") else null if (lastArgumentName != null) { val lastArgument = callExpression.valueArgumentList?.arguments?.singleOrNull() val argumentExpression = lastArgument?.getArgumentExpression() if (argumentExpression != null) { lastArgument.replace(createArgument(argumentExpression, lastArgumentName)) } } if (associateFunction != null) { ReplaceAssociateFunctionFix.replaceLastStatementForAssociateFunction(callExpression, associateFunction) } } ) holder.registerProblem(descriptor) }) } private fun ResolvedCall<*>.lastFunctionalArgumentReturnType(context: BindingContext): KotlinType? { val argument = valueArguments.entries.lastOrNull()?.value?.arguments?.firstOrNull() return when (val argumentExpression = argument?.getArgumentExpression()) { is KtLambdaExpression -> { val functionLiteral = argumentExpression.functionLiteral val body = argumentExpression.bodyExpression val lastStatementType = body?.statements?.lastOrNull()?.getType(context) val returnedTypes = body ?.collectDescendantsOfType<KtReturnExpression> { it.getTargetFunction(context) == functionLiteral } ?.mapNotNull { it.returnedExpression?.getType(context) } .orEmpty() val types = listOfNotNull(lastStatementType) + returnedTypes types.firstOrNull { it.isNullable() } ?: types.firstOrNull() } is KtNamedFunction -> argumentExpression.typeReference?.let { context[BindingContext.TYPE, it] } else -> null } } private fun containsSuspendFunctionCall(resolvedCall: ResolvedCall<*>, context: BindingContext): Boolean { return resolvedCall.call.callElement.anyDescendantOfType<KtCallExpression> { it.getResolvedCall(context)?.resultingDescriptor?.isSuspend == true } } private fun getAssociateFunction(conversion: Conversion, expression: KtExpression): AssociateFunction? { if (conversion.replacement != "associate") return null if (expression !is KtDotQualifiedExpression) return null val (associateFunction, problemHighlightType) = ReplaceAssociateFunctionInspection.getAssociateFunctionAndProblemHighlightType(expression) ?: return null if (problemHighlightType == ProblemHighlightType.INFORMATION) return null if (associateFunction != AssociateFunction.ASSOCIATE_WITH && associateFunction != AssociateFunction.ASSOCIATE_BY) return null return associateFunction } private val conversionGroups = conversions.group() companion object { private val conversions = listOf( Conversion("kotlin.collections.filter", "kotlin.collections.first", "first"), Conversion("kotlin.collections.filter", "kotlin.collections.firstOrNull", "firstOrNull"), Conversion("kotlin.collections.filter", "kotlin.collections.last", "last"), Conversion("kotlin.collections.filter", "kotlin.collections.lastOrNull", "lastOrNull"), Conversion("kotlin.collections.filter", "kotlin.collections.single", "single"), Conversion("kotlin.collections.filter", "kotlin.collections.singleOrNull", "singleOrNull"), Conversion("kotlin.collections.filter", "kotlin.collections.isNotEmpty", "any"), Conversion("kotlin.collections.filter", "kotlin.collections.List.isEmpty", "none"), Conversion("kotlin.collections.filter", "kotlin.collections.count", "count"), Conversion("kotlin.collections.filter", "kotlin.collections.any", "any"), Conversion("kotlin.collections.filter", "kotlin.collections.none", "none"), Conversion("kotlin.collections.sorted", "kotlin.collections.firstOrNull", "min"), Conversion("kotlin.collections.sorted", "kotlin.collections.lastOrNull", "max"), Conversion("kotlin.collections.sortedDescending", "kotlin.collections.firstOrNull", "max"), Conversion("kotlin.collections.sortedDescending", "kotlin.collections.lastOrNull", "min"), Conversion("kotlin.collections.sortedBy", "kotlin.collections.firstOrNull", "minBy"), Conversion("kotlin.collections.sortedBy", "kotlin.collections.lastOrNull", "maxBy"), Conversion("kotlin.collections.sortedByDescending", "kotlin.collections.firstOrNull", "maxBy"), Conversion("kotlin.collections.sortedByDescending", "kotlin.collections.lastOrNull", "minBy"), Conversion("kotlin.collections.sorted", "kotlin.collections.first", "min", addNotNullAssertion = true), Conversion("kotlin.collections.sorted", "kotlin.collections.last", "max", addNotNullAssertion = true), Conversion("kotlin.collections.sortedDescending", "kotlin.collections.first", "max", addNotNullAssertion = true), Conversion("kotlin.collections.sortedDescending", "kotlin.collections.last", "min", addNotNullAssertion = true), Conversion("kotlin.collections.sortedBy", "kotlin.collections.first", "minBy", addNotNullAssertion = true), Conversion("kotlin.collections.sortedBy", "kotlin.collections.last", "maxBy", addNotNullAssertion = true), Conversion("kotlin.collections.sortedByDescending", "kotlin.collections.first", "maxBy", addNotNullAssertion = true), Conversion("kotlin.collections.sortedByDescending", "kotlin.collections.last", "minBy", addNotNullAssertion = true), Conversion("kotlin.text.filter", "kotlin.text.first", "first"), Conversion("kotlin.text.filter", "kotlin.text.firstOrNull", "firstOrNull"), Conversion("kotlin.text.filter", "kotlin.text.last", "last"), Conversion("kotlin.text.filter", "kotlin.text.lastOrNull", "lastOrNull"), Conversion("kotlin.text.filter", "kotlin.text.single", "single"), Conversion("kotlin.text.filter", "kotlin.text.singleOrNull", "singleOrNull"), Conversion("kotlin.text.filter", "kotlin.text.isNotEmpty", "any"), Conversion("kotlin.text.filter", "kotlin.text.isEmpty", "none"), Conversion("kotlin.text.filter", "kotlin.text.count", "count"), Conversion("kotlin.text.filter", "kotlin.text.any", "any"), Conversion("kotlin.text.filter", "kotlin.text.none", "none"), Conversion("kotlin.collections.map", "kotlin.collections.joinTo", "joinTo", enableSuspendFunctionCall = false), Conversion("kotlin.collections.map", "kotlin.collections.joinToString", "joinToString", enableSuspendFunctionCall = false), Conversion("kotlin.collections.map", "kotlin.collections.filterNotNull", "mapNotNull"), Conversion("kotlin.collections.map", "kotlin.collections.toMap", "associate"), Conversion( "kotlin.collections.map", "kotlin.collections.sum", "sumOf", replaceableApiVersion = ApiVersion.KOTLIN_1_4 ), Conversion( "kotlin.collections.map", "kotlin.collections.max", "maxOf", removeNotNullAssertion = true, replaceableApiVersion = ApiVersion.KOTLIN_1_4 ), Conversion( "kotlin.collections.map", "kotlin.collections.max", "maxOfOrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_4, ), Conversion( "kotlin.collections.map", "kotlin.collections.maxOrNull", "maxOf", removeNotNullAssertion = true, replaceableApiVersion = ApiVersion.KOTLIN_1_4 ), Conversion( "kotlin.collections.map", "kotlin.collections.maxOrNull", "maxOfOrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_4, ), Conversion( "kotlin.collections.map", "kotlin.collections.min", "minOf", removeNotNullAssertion = true, replaceableApiVersion = ApiVersion.KOTLIN_1_4 ), Conversion( "kotlin.collections.map", "kotlin.collections.min", "minOfOrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_4, ), Conversion( "kotlin.collections.map", "kotlin.collections.minOrNull", "minOf", removeNotNullAssertion = true, replaceableApiVersion = ApiVersion.KOTLIN_1_4 ), Conversion( "kotlin.collections.map", "kotlin.collections.minOrNull", "minOfOrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_4, ), Conversion( "kotlin.collections.mapNotNull", "kotlin.collections.first", "firstNotNullOf", replaceableApiVersion = ApiVersion.KOTLIN_1_5 ), Conversion( "kotlin.collections.mapNotNull", "kotlin.collections.firstOrNull", "firstNotNullOfOrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_5 ), Conversion("kotlin.collections.listOf", "kotlin.collections.filterNotNull", "listOfNotNull") ).map { when (val replacement = it.replacement) { "min", "max", "minBy", "maxBy" -> { val additionalConversion = if ((replacement == "min" || replacement == "max") && it.addNotNullAssertion) { it.copy(replacement = "${replacement}Of", replaceableApiVersion = ApiVersion.KOTLIN_1_4, addNotNullAssertion = false, additionalArgument = "{ it }") } else { it.copy(replacement = "${replacement}OrNull", replaceableApiVersion = ApiVersion.KOTLIN_1_4) } listOf(additionalConversion, it) } else -> listOf(it) } }.flatten() } }
apache-2.0
c948dd89f8e544ec42e2d767a1ac45ea
63.086777
172
0.65708
5.409138
false
false
false
false
jsocle/jsocle-form
src/main/kotlin/com/github/jsocle/form/fields/RadioField.kt
2
837
package com.github.jsocle.form.fields import com.github.jsocle.form.FieldMapper import com.github.jsocle.form.SingleValueField import com.github.jsocle.html.elements.Ul import kotlin.collections.forEach public open class RadioField<T : Any>(public var choices: List<Pair<T, String>>, mapper: FieldMapper<T>) : SingleValueField<T, Ul>(mapper) { override fun render(): Ul { return Ul(class_ = "jsocle-form-field-radio") { choices.forEach { li { label { val checked = if (it.first == [email protected]) "checked" else null input(name = name, type = "radio", value = mapper.toString(it.first), checked = checked) +it.second } } } } } }
mit
7f5ce3f8f6c7eb9f9daced5655e08694
35.434783
112
0.565114
4.043478
false
false
false
false
GunoH/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/push/ui/PushLogChangesBrowser.kt
8
2991
// 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.dvcs.push.ui import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresEdt import javax.swing.tree.DefaultTreeModel class PushLogChangesBrowser(project: Project, showCheckboxes: Boolean, highlightProblems: Boolean, private val loadingPane: JBLoadingPanel) : ChangesBrowserBase(project, showCheckboxes, highlightProblems), Disposable { private val executor = AppExecutorUtil.createBoundedScheduledExecutorService("PushLogChangesBrowser Pool", 1) private var indicator: ProgressIndicator? = null private var currentChanges: List<Change> = emptyList() init { init() } override fun dispose() { indicator?.cancel() indicator = null executor.shutdown() } override fun buildTreeModel(): DefaultTreeModel { return buildTreeModel(currentChanges) } private fun buildTreeModel(changes: List<Change>): DefaultTreeModel { return TreeModelBuilder.buildFromChanges(myProject, grouping, changes, null) } @RequiresEdt fun setCommitsToDisplay(commitNodes: List<CommitNode>) { val taskIndicator = initIndicator() executor.execute { ProgressManager.getInstance().executeProcessUnderProgress({ loadChanges(commitNodes, taskIndicator) }, taskIndicator) } } private fun loadChanges(commitNodes: List<CommitNode>, taskIndicator: ProgressIndicator) { taskIndicator.checkCanceled() val changes = PushLog.collectAllChanges(commitNodes) taskIndicator.checkCanceled() val treeModel = buildTreeModel(changes) invokeLater(ModalityState.stateForComponent(this)) { taskIndicator.checkCanceled() resetIndicator(taskIndicator) currentChanges = changes (myViewer as ChangesBrowserTreeList).updateTreeModel(treeModel) } } @RequiresEdt private fun initIndicator(): ProgressIndicator { val taskIndicator = EmptyProgressIndicator() indicator?.cancel() indicator = taskIndicator loadingPane.startLoading() return taskIndicator } @RequiresEdt private fun resetIndicator(taskIndicator: ProgressIndicator) { if (indicator === taskIndicator) { indicator = null loadingPane.stopLoading() } } }
apache-2.0
0964bae664de240156b215b3c0a1dad1
33
123
0.759612
4.935644
false
false
false
false
Briseus/Lurker
app/src/main/java/torille/fi/lurkforreddit/comments/CommentsItemDecoration.kt
1
3233
package torille.fi.lurkforreddit.comments import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View import torille.fi.lurkforreddit.data.models.jsonResponses.CommentChild import torille.fi.lurkforreddit.data.models.view.Comment /** * Item decoration for [CommentChild] in [torille.fi.lurkforreddit.comments.CommentFragment.CommentRecyclerViewAdapter] * that adds padding to left depending on how deep the level of the comment is and also draws a line to the left side * of the comment */ internal class CommentsItemDecoration(private val mDivider: Drawable) : RecyclerView.ItemDecoration() { override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State?) { (0 until parent.childCount) .map { parent.getChildAt(it) } .forEach { if (parent.getChildViewHolder(it) is CommentRecyclerViewAdapter.CommentViewHolder) { draw( (parent.getChildViewHolder(it) as CommentRecyclerViewAdapter.CommentViewHolder).comment!!, it, canvas ) } else if (parent.getChildViewHolder(it) is CommentRecyclerViewAdapter.CommentLoadMoreViewHolder) { draw( (parent.getChildViewHolder(it) as CommentRecyclerViewAdapter.CommentLoadMoreViewHolder).comment!!, it, canvas ) } } } private fun draw(mItem: Comment, child: View, canvas: Canvas) { if (mItem.commentLevel > 0) { val left = child.left val right = left + mDivider.intrinsicHeight val top = child.top val bottom = child.bottom mDivider.setBounds(left, top, right, bottom) mDivider.draw(canvas) } } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State? ) { super.getItemOffsets(outRect, view, parent, state) if (parent.getChildAdapterPosition(view) == 0) { return } when { parent.getChildViewHolder(view) is CommentRecyclerViewAdapter.CommentViewHolder -> setPadding( (parent.getChildViewHolder(view) as CommentRecyclerViewAdapter.CommentViewHolder).comment!!, outRect ) parent.getChildViewHolder(view) is CommentRecyclerViewAdapter.CommentLoadMoreViewHolder -> setPadding( (parent.getChildViewHolder(view) as CommentRecyclerViewAdapter.CommentLoadMoreViewHolder).comment!!, outRect ) parent.getChildViewHolder(view) is CommentRecyclerViewAdapter.ProgressViewHolder -> setPadding( (parent.getChildViewHolder(view) as CommentRecyclerViewAdapter.ProgressViewHolder).comment!!, outRect ) } } private fun setPadding(mComment: Comment, outRect: Rect) { outRect.left = mComment.commentLevel * 16 } }
mit
fe97b7e14e10d03de591070811ce17a4
36.16092
122
0.631921
5.451939
false
false
false
false
jwren/intellij-community
platform/projectModel-impl/src/com/intellij/project/project.kt
7
1284
// 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.project import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.components.impl.stores.IComponentStoreOwner import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.ApiStatus import java.nio.file.Path val Project.stateStore: IProjectStore get() = (this as ProjectStoreOwner).componentStore @ApiStatus.Internal interface ProjectStoreOwner : IComponentStoreOwner { override val componentStore: IProjectStore } val Project.isDirectoryBased: Boolean get() = !isDefault && StorageScheme.DIRECTORY_BASED == (stateStore as? IProjectStore)?.storageScheme fun getProjectStoreDirectory(file: VirtualFile): VirtualFile? { return if (file.isDirectory) file.findChild(Project.DIRECTORY_STORE_FOLDER) else null } fun isEqualToProjectFileStorePath(project: Project, filePath: Path, storePath: String): Boolean { return project.isDirectoryBased && filePath == project.stateStore.storageManager.expandMacro(storePath) }
apache-2.0
ecaa208f3971289bc962817771dd035c
41.833333
140
0.82243
4.505263
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/lookup.kt
8
3428
// 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.lang.documentation.ide.impl import com.intellij.codeInsight.lookup.* import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider import com.intellij.lang.documentation.ide.ui.DocumentationPopupUI import com.intellij.lang.documentation.impl.DocumentationRequest import com.intellij.lang.documentation.impl.documentationRequest import com.intellij.openapi.application.readAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Disposer import com.intellij.psi.util.PsiUtilBase import com.intellij.ui.popup.AbstractPopup import com.intellij.util.ui.EDT import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.map internal fun lookupPopupContext(editor: Editor?): PopupContext? { val lookup = LookupManager.getActiveLookup(editor) ?: return null return LookupPopupContext(lookup) } internal class LookupPopupContext(val lookup: LookupEx) : SecondaryPopupContext() { override fun setUpPopup(popup: AbstractPopup, popupUI: DocumentationPopupUI) { super.setUpPopup(popup, popupUI) cancelPopupWhenLookupIsClosed(lookup, popup) } override fun requestFlow(): Flow<DocumentationRequest?> = lookup.elementFlow().map(lookupElementToRequestMapper(lookup)) override fun baseBoundsHandler(): PopupBoundsHandler { return AdjusterPopupBoundsHandler(lookup.component) } } private fun cancelPopupWhenLookupIsClosed(lookup: Lookup, popup: AbstractPopup) { val listener = object : LookupListener { override fun itemSelected(event: LookupEvent): Unit = lookupClosed() override fun lookupCanceled(event: LookupEvent): Unit = lookupClosed() private fun lookupClosed(): Unit = popup.cancel() } lookup.addLookupListener(listener) Disposer.register(popup) { lookup.removeLookupListener(listener) } } internal fun Lookup.elementFlow(): Flow<LookupElement> { EDT.assertIsEdt() val items = MutableSharedFlow<LookupElement>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) addLookupListener(object : LookupListener { override fun currentItemChanged(event: LookupEvent) { event.item?.let { lookupElement -> items.tryEmit(lookupElement) } } override fun itemSelected(event: LookupEvent): Unit = lookupClosed() override fun lookupCanceled(event: LookupEvent): Unit = lookupClosed() private fun lookupClosed() { removeLookupListener(this) } }) val currentItem = currentItem if (currentItem != null) { check(items.tryEmit(currentItem)) } return items.asSharedFlow() } internal fun lookupElementToRequestMapper(lookup: Lookup): suspend (LookupElement) -> DocumentationRequest? { val project = lookup.project val editor = lookup.editor val ideTargetProvider = IdeDocumentationTargetProvider.getInstance(project) return { lookupElement: LookupElement -> readAction { if (!lookupElement.isValid) { return@readAction null } val file = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return@readAction null ideTargetProvider.documentationTarget(editor, file, lookupElement)?.documentationRequest() } } }
apache-2.0
ea2007eed5905893b11bd097b5f4fbb9
35.860215
122
0.771004
4.492792
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.kt
1
3734
// 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. @file:JvmName("PluginsAdvertiser") package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.PluginNode import com.intellij.ide.plugins.RepositoryHelper import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationGroupManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.util.PlatformUtils.isIdeaUltimate import org.jetbrains.annotations.ApiStatus import java.io.IOException private const val IGNORE_ULTIMATE_EDITION = "ignoreUltimateEdition" @get:JvmName("getLog") internal val LOG = Logger.getInstance("#PluginsAdvertiser") private val propertiesComponent get() = PropertiesComponent.getInstance() var isIgnoreIdeSuggestion: Boolean get() = propertiesComponent.isTrueValue(IGNORE_ULTIMATE_EDITION) set(value) = propertiesComponent.setValue(IGNORE_ULTIMATE_EDITION, value) @JvmField @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") @Deprecated("Use `notificationGroup` property") val NOTIFICATION_GROUP = notificationGroup val notificationGroup: NotificationGroup get() = NotificationGroupManager.getInstance().getNotificationGroup("Plugins Suggestion") @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`") fun installAndEnablePlugins( pluginIds: Set<String>, onSuccess: Runnable, ) { installAndEnable( LinkedHashSet(pluginIds.map { PluginId.getId(it) }), onSuccess, ) } @Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`") fun installAndEnable( pluginIds: Set<PluginId>, onSuccess: Runnable, ) = installAndEnable(null, pluginIds, true, false, onSuccess) fun installAndEnable( project: Project?, pluginIds: Set<PluginId>, showDialog: Boolean = false, onSuccess: Runnable, ) = installAndEnable(project, pluginIds, showDialog, false, onSuccess) fun installAndEnable( project: Project?, pluginIds: Set<PluginId>, showDialog: Boolean = false, selectAlInDialog: Boolean, onSuccess: Runnable, ) = ProgressManager.getInstance().run(InstallAndEnableTask(project, pluginIds, showDialog, selectAlInDialog, onSuccess)) internal fun getBundledPluginToInstall(plugins: Collection<PluginData>): List<String> { return if (isIdeaUltimate()) { emptyList() } else { val descriptorsById = PluginManagerCore.buildPluginIdMap() plugins .filter { it.isBundled } .filterNot { descriptorsById.containsKey(it.pluginId) } .map { it.pluginName } } } /** * Loads list of plugins, compatible with a current build, from all configured repositories */ @JvmOverloads internal fun loadPluginsFromCustomRepositories(indicator: ProgressIndicator? = null): List<PluginNode> { return RepositoryHelper .getPluginHosts() .filterNot { it == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository() }.flatMap { try { RepositoryHelper.loadPlugins(it, null, indicator) } catch (e: IOException) { LOG.info("Couldn't load plugins from $it: $e") LOG.debug(e) emptyList<PluginNode>() } }.distinctBy { it.pluginId } }
apache-2.0
3824cc4d5e7f9b998063151ab8b0c2a6
33.256881
158
0.773433
4.548112
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/platform/kvstore/OrderedKeyComparator.kt
1
1833
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 12/18/19. * Copyright (c) 2019 breadwallet LLC * * 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.platform.kvstore import com.platform.sqlite.KVItem class OrderedKeyComparator(private val orderedKeys: List<String>) : Comparator<KVItem> { override fun compare(o1: KVItem?, o2: KVItem?): Int = when { o1 == null && o2 == null -> 0 o1 == null -> 1 o2 == null -> -1 orderedKeys.contains(o1.key) && orderedKeys.contains((o2.key)) -> orderedKeys.indexOf(o1.key) - orderedKeys.indexOf(o2.key) orderedKeys.contains(o1.key) -> -1 orderedKeys.contains(o2.key) -> 1 else -> o1.key.compareTo(o2.key) } }
mit
44424c90acda5ceb467f73dfb5b26d82
43.731707
88
0.695581
4.046358
false
false
false
false
samalasivakumar/WifiList3
app/src/main/java/com/example/sivakumar/wifilist3/MainActivity.kt
1
2148
package com.example.sivakumar.wifilist3 import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import android.media.AudioManager import android.bluetooth.BluetoothAdapter class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initTiles() } private fun initTiles() { val audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() tile_wifi.setOnClickListener { val intent = Intent(this, WifiInformation::class.java) startActivity(intent) } tile_silent.setOnClickListener { if (audioManager.ringerMode == AudioManager.RINGER_MODE_SILENT) { audioManager.ringerMode = AudioManager.RINGER_MODE_NORMAL tile_silent.setImageResource(R.drawable.silent) } else { audioManager.ringerMode = AudioManager.RINGER_MODE_SILENT tile_silent.setImageResource(R.drawable.silent_on) } } tile_vibrate.setOnClickListener { if (audioManager.ringerMode == AudioManager.RINGER_MODE_VIBRATE) { audioManager.ringerMode = AudioManager.RINGER_MODE_NORMAL tile_vibrate.setImageResource(R.drawable.vibrate) } else { audioManager.ringerMode = AudioManager.RINGER_MODE_VIBRATE tile_vibrate.setImageResource(R.drawable.vibrate_on) } } tile_bluetooth.setOnClickListener { if (bluetoothAdapter.isEnabled) { bluetoothAdapter.disable() tile_bluetooth.setImageResource(R.drawable.bluetooth) } else { bluetoothAdapter.enable() tile_bluetooth.setImageResource(R.drawable.bluetooth_on) } } } }
unlicense
dc9abe8c926673c52d0e8b96b072dacf
32.5625
101
0.652235
5.018692
false
false
false
false
sisbell/oulipo
oulipo-machine-browser/src/main/java/org/oulipo/browser/api/MenuContext.kt
1
1748
/******************************************************************************* * OulipoMachine licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package org.oulipo.browser.api import javafx.scene.control.Menu import javafx.scene.control.TabPane /** * Allows access to system level org.oulipo.browser Menus. */ class MenuContext( val windowMenu: Menu, val peopleMenu: Menu, val managerMenu: Menu, val toolsMenu: Menu, val fileMenu: Menu, val bookmarkMenu: Menu, val historyMenu: Menu, val tabs: TabPane ) { enum class Type { BOOKMARK, FILE, HISTORY, MANAGER, PEOPLE, TOOLS, WINDOW } fun getMenu(type: Type): Menu? { if (Type.BOOKMARK == type) { return bookmarkMenu } else if (Type.FILE == type) { return fileMenu } else if (Type.HISTORY == type) { return historyMenu } else if (Type.MANAGER == type) { return managerMenu } else if (Type.TOOLS == type) { return toolsMenu } else if (Type.WINDOW == type) { return windowMenu } return null } }
apache-2.0
927c4a890564d839ee58177f1e7de359
34.673469
111
0.637872
4.284314
false
false
false
false
npryce/snodge
common/src/main/com/natpryce/snodge/xml/XmlMutagens.kt
1
2031
package com.natpryce.snodge.xml import com.natpryce.snodge.combine import com.natpryce.snodge.reflect.troublesomeClasses import com.natpryce.snodge.text.possiblyMeaningfulStrings import com.natpryce.xmlk.QName import com.natpryce.xmlk.XmlElement import com.natpryce.xmlk.XmlNode import com.natpryce.xmlk.XmlText import com.natpryce.xmlk.minusAttribute import com.natpryce.xmlk.minusChild import com.natpryce.xmlk.replaceChild import com.natpryce.xmlk.withAttribute fun removeAttribute() = XmlMutagen<XmlElement> { _, element -> element.attributes.keys.asSequence().map { lazy { element.minusAttribute(it) } } } fun removeElement() = XmlMutagen<XmlElement> { _, element -> element.children.indices.map { lazy { element.minusChild(it) } }.asSequence() } fun removeNamespace() = XmlMutagen<XmlElement> { _, element -> sequenceOf(lazy { element.copy(name = element.name.withoutNamespace()) }) + element.attributes.asSequence() .filter { (name, _) -> name.namespaceURI != null } .map { (name, value) -> lazy { element.minusAttribute(name).withAttribute(name.withoutNamespace() to value) } } } inline fun <reified T: XmlNode> replaceNode(replacement: XmlNode) = replaceNodeIf({it is T}, replacement) fun replaceNodeIf(p: (XmlNode)->Boolean, replacement: XmlNode) = XmlMutagen<XmlElement> { _, element -> element.children.withIndex().asSequence() .filter { (_, child) -> p(child) } .map { (i, _) -> lazy { element.replaceChild(i, replacement) } } } fun replaceText(newText: String) = replaceNode<XmlText>(XmlText(newText)) private fun QName.withoutNamespace() = QName(localPart) fun defaultXmlMutagens() = combine( removeAttribute(), removeElement(), removeNamespace(), replaceNode<XmlNode>(XmlElement(QName("replacement"))), replaceNode<XmlNode>(XmlText("replacement")), combine( possiblyMeaningfulStrings().map(::replaceText) ), combine( troublesomeClasses().map(::replaceText) ) )
apache-2.0
875ac3d12984b45682c48ada5f76f9b3
34.631579
105
0.707533
3.768089
false
false
false
false
cmcpasserby/MayaCharm
src/main/kotlin/utils/ProcessUtils.kt
1
1726
package utils import com.intellij.openapi.util.SystemInfo import java.io.IOException import java.util.concurrent.TimeUnit private val timeout: Pair<Long, TimeUnit> = Pair(10, TimeUnit.SECONDS) private fun pathForPidWin(pid: Int): String? = try { ProcessBuilder("wmic process where 'ProcessID=$pid' get ExecutablePath".split("\\s".toRegex())) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start().apply { waitFor(timeout.first, timeout.second) } .inputStream.bufferedReader().readText().lines()[2].trim() } catch (err: IOException) { err.printStackTrace() null } private fun pathForPidMac(pid: Int): String? = try { ProcessBuilder("ps -p $pid".split("\\s".toRegex())) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start().apply { waitFor(timeout.first, timeout.second) } .inputStream.bufferedReader().readText() .lines()[1].let { it.substring(it.indexOf('/')) } } catch (err: IOException) { err.printStackTrace() null } private fun pathForPidUnix(pid: Int): String? = try { ProcessBuilder("readlink", "/proc/$pid/exe") .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start().apply { waitFor(timeout.first, timeout.second) } .inputStream.bufferedReader().readText().trim() } catch (err: IOException) { err.printStackTrace() null } fun pathForPid(pid: Int): String? = when { SystemInfo.isWindows -> { pathForPidWin(pid) } SystemInfo.isMac -> { pathForPidMac(pid) } else -> { pathForPidUnix(pid) } }
mit
3342ae1e72ea9deead377982f1875332
31.566038
99
0.669177
4.03271
false
false
false
false
seventhroot/elysium
bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/servlet/BankServlet.kt
1
15373
/* * Copyright 2019 Ren Binden * * 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.rpkit.banks.bukkit.servlet import com.rpkit.banks.bukkit.RPKBanksBukkit import com.rpkit.banks.bukkit.bank.RPKBankProvider import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.web.Alert import com.rpkit.core.web.RPKServlet import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider import com.rpkit.players.bukkit.profile.RPKProfileProvider import org.apache.velocity.VelocityContext import org.apache.velocity.app.Velocity import java.util.* import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse.SC_NOT_FOUND import javax.servlet.http.HttpServletResponse.SC_OK class BankServlet(private val plugin: RPKBanksBukkit): RPKServlet() { override val url = "/banks/bank/*" override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { if (req.pathInfo == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class) val currencyId = req.pathInfo.drop(1).dropLastWhile { it != '/' }.dropLast(1) if (currencyId.isEmpty()) { resp.contentType = "text/html" resp.status = SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val currency = currencyProvider.getCurrency(currencyId.toInt()) if (currency == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getActiveProfile(req) if (profile == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_FORBIDDEN val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/unauthorized.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/unauthorized.html", templateBuilder.toString()) return } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = req.pathInfo.drop(1).dropWhile { it != '/'}.drop(1) val character = characterProvider.getCharacter(characterId.toInt()) if (character == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } if (character.profile != profile) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_FORBIDDEN val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/unauthorized.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/unauthorized.html", templateBuilder.toString()) } val bankProvider = plugin.core.serviceManager.getServiceProvider(RPKBankProvider::class) val balance = bankProvider.getBalance(character, currency) resp.contentType = "text/html" resp.status = SC_OK val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/bank.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) velocityContext.put("alerts", listOf<Alert>()) velocityContext.put("activeProfile", profile) velocityContext.put("top", bankProvider.getRichestCharacters(currency, 5) .map { Pair(it, bankProvider.getBalance(it, currency)) } .toMap()) velocityContext.put("character", character) velocityContext.put("currency", currency) velocityContext.put("balance", balance) Velocity.evaluate(velocityContext, resp.writer, "/web/bank.html", templateBuilder.toString()) } override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { if (req.pathInfo == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class) val currencyId = req.pathInfo.drop(1).dropLastWhile { it != '/' }.dropLast(1) if (currencyId.isEmpty()) { resp.contentType = "text/html" resp.status = SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val currency = currencyProvider.getCurrency(currencyId.toInt()) if (currency == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getActiveProfile(req) if (profile == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_FORBIDDEN val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/unauthorized.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/unauthorized.html", templateBuilder.toString()) return } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = req.pathInfo.drop(1).dropWhile { it != '/'}.drop(1) val character = characterProvider.getCharacter(characterId.toInt()) if (character == null) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_NOT_FOUND val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/404.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/404.html", templateBuilder.toString()) return } if (character.profile != profile) { resp.contentType = "text/html" resp.status = HttpServletResponse.SC_FORBIDDEN val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/unauthorized.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) Velocity.evaluate(velocityContext, resp.writer, "/web/unauthorized.html", templateBuilder.toString()) return } val amount = req.getParameter("amount").toInt() val bankProvider = plugin.core.serviceManager.getServiceProvider(RPKBankProvider::class) var balance = bankProvider.getBalance(character, currency) val toCharacterId = req.getParameter("character") val toCharacter = if (toCharacterId != null) characterProvider.getCharacter(toCharacterId.toInt()) else null val alerts = mutableListOf<Alert>() when { amount < 1 -> alerts.add(Alert(Alert.Type.DANGER, "You must transfer at least 1 ${currency.nameSingular}.")) amount > balance -> alerts.add(Alert(Alert.Type.DANGER, "You do not have enough money to perform that transaction.")) toCharacter == null -> alerts.add(Alert(Alert.Type.DANGER, "You must set a character to transfer to.")) else -> { bankProvider.withdraw(character, currency, amount) bankProvider.deposit(toCharacter, currency, amount) balance -= amount } } resp.contentType = "text/html" resp.status = SC_OK val templateBuilder = StringBuilder() val scanner = Scanner(javaClass.getResourceAsStream("/web/bank.html")) while (scanner.hasNextLine()) { templateBuilder.append(scanner.nextLine()).append('\n') } scanner.close() val velocityContext = VelocityContext() velocityContext.put("server", plugin.core.web.title) velocityContext.put("navigationBar", plugin.core.web.navigationBar) velocityContext.put("alerts", alerts) velocityContext.put("activeProfile", profile) velocityContext.put("top", bankProvider.getRichestCharacters(currency, 5) .map { Pair(it, bankProvider.getBalance(it, currency)) } .toMap()) velocityContext.put("character", character) velocityContext.put("currency", currency) velocityContext.put("balance", balance) Velocity.evaluate(velocityContext, resp.writer, "/web/bank.html", templateBuilder.toString()) } }
apache-2.0
729590b2c43c7684544ab5d8fd421d0a
50.760943
129
0.645417
5.056908
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/usecase/NotePaste.kt
1
651
package com.orgzly.android.usecase import com.orgzly.android.db.NotesClipboard import com.orgzly.android.data.DataRepository import com.orgzly.android.ui.Place class NotePaste(val bookId: Long, val noteId: Long, val place: Place) : UseCase() { override fun run(dataRepository: DataRepository): UseCaseResult { val clipboard = NotesClipboard.load() val count = dataRepository.pasteNotes(clipboard, bookId, noteId, place) return UseCaseResult( modifiesLocalData = count > 0, triggersSync = if (count > 0) SYNC_DATA_MODIFIED else SYNC_NOT_REQUIRED, userData = count) } }
gpl-3.0
9a4e664f64dc678bc97d44b728a27437
35.222222
88
0.691244
4.398649
false
false
false
false
tingtingths/jukebot
app/src/main/java/com/jukebot/jukebot/util/Util.kt
1
2666
package com.jukebot.jukebot.util import com.jukebot.jukebot.logging.Logger import com.jukebot.jukebot.manager.PlaylistManager import com.jukebot.jukebot.pojo.Command import com.jukebot.jukebot.pojo.Track import com.pengrad.telegrambot.model.User import okhttp3.OkHttpClient import okhttp3.Request import java.util.regex.Matcher import java.util.regex.Pattern /** * Created by Ting. */ object Util { fun parseCmd(text: String): Command { fun norm(s: String?): String? { if (s != null && !s.isEmpty() && s.trim() != "null") return s.trim() return null } // original regex - ^([^\s@]+)@?(\S+)?\s?(.*)$ val regex: String = "^([^\\s@]+)@?(\\S+)?\\s?(.*)$" val pat: Pattern = Pattern.compile(regex) val m: Matcher = pat.matcher(text) var cmd: String? = null var bot: String? = null var args: String? = null Logger.log(this.javaClass.simpleName, "text=$text, matches=${m.matches()}") if (m.matches()) { cmd = norm(m.group(1))?.toLowerCase() bot = norm(m.group(2)) args = norm(m.group(3)) } return Command(cmd, bot, if (args == null) ArrayList() else args.split(" ")) } fun secToString(sec: Long): String { fun pad(i: Long): String = String.format("%02d", i) val h = sec / (60 * 60) val m = (sec - h * 60 * 60) / 60 val s = sec - h * 60 * 60 - m * 60 return (if (h.compareTo(0) == 0) "" else "${pad(h)}:") + "${pad(m)}:${pad(s)}" } fun buildNowPlaying(track: Track) = buildPlayerStatusMessage(track, "Now Playing") fun buildPaused(track: Track): String = buildPlayerStatusMessage(track, "Paused") private fun buildPlayerStatusMessage(track: Track, statusMsg: String): String { val from: User? = track.message.from() return "$statusMsg | ${track.title} (${Util.secToString(track.duration!!)})\n" + "DJ @${if (from?.username() != null) from.username() else "${from?.firstName()} ${from?.lastName() ?: ""}"}" } fun buildPlaylistMessage(): String { var reply = "" var count = 1 val iter: MutableIterator<Track> = PlaylistManager.iter() while (iter.hasNext()) { reply += "$count. ${iter.next().title}\n" count += 1 } return reply } fun httpGet(url: String): String { var client = OkHttpClient() var request = Request.Builder() .url(url) .build() return client.newCall(request).execute().body()?.string() ?: "" } }
mit
c4e89ef9180e22ce2ad58290afc590a5
29.643678
124
0.555514
3.803138
false
false
false
false
tangying91/profit
src/main/java/org/profit/app/StockHall.kt
1
2764
package org.profit.app import org.profit.app.analyse.StockVolumeAnalyzer import org.profit.app.schedule.StockExecutor import org.profit.util.DateUtils import org.profit.util.FileUtils import java.util.* /** * 数据大厅 * 选股数据模型 * * 1、【积】周期内,连续上涨天数较多 * 2、【金】周期内,资金持续流入天数较多 * 3、【突】周期末,股价成交量大幅拉升 * 4、【底】较长周期内涨幅较低,持续底部整理 */ object StockHall { /** * 下载数据 */ fun download() { // 读取当天的日志记录,看是否已经下载过数据 val logs = FileUtils.readLogs() val date = DateUtils.formatDate(System.currentTimeMillis()) allStockCodes.filter { !logs.contains(it) && !it.startsWith("3") && !it.startsWith("688") }.forEach { code -> // DownloadHistoryService(code, date).execute() StockExecutor.download(code, date) } } fun analyse() { val results = mutableListOf<String>() // 分析股价数据 allStockCodes.filter { !it.startsWith("3") && !it.startsWith("688") }.forEach { // StockDownAnalyzer(it, 20, 0.8).analyse() // StockHistoryAnalyzer(it, 180, 0.05).analyse() StockVolumeAnalyzer(it, 10, 2.0).analyse(results) } println("数据分析完成.") // 邮件 if (results.isNotEmpty()) { val content = StringBuffer() results.forEach { code -> val c = "$code ${stockName(code)}, 最近成交量出现异动, 快速查看: http://stockpage.10jqka.com.cn/$code/" content.append(c).append("\n") } content.append("批量汇总").append("\n") results.forEach { code -> val c = "http://stockpage.10jqka.com.cn/$code/" content.append(c).append("\n") } EMailSender.send("[email protected]", DateUtils.formatDate(System.currentTimeMillis()), content.toString()) } } /** * 股票池 * key -> code * value -> name */ private val stockMap: MutableMap<String, String> = HashMap() init { FileUtils.readStocks().forEach { val array = it.split(" ") stockMap[array[0]] = array[1] } } /** * 所有股票代码 */ val allStockCodes get() = stockMap.keys /** * 获取名称 */ fun stockName(code: String): String { return stockMap[code] ?: "" } }
apache-2.0
fb3d537c33c56cafae7cfa5a6c0e5ae2
24.063158
118
0.509297
3.549498
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/core/request/EndpointHost.kt
1
2419
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.core.request import io.ktor.http.URLProtocol /** * Represents endpoint host. */ data class EndpointHost( /** * The domain. */ val domain: String, /** * The domain used in signing. */ val domainForSigning: String? = null, /** * The url protocol. */ val protocol: URLProtocol = URLProtocol.HTTPS, /** * The port. */ val port: Int = protocol.defaultPort ) { companion object { /** * Default endpoint host. */ val Default = EndpointHost("api.twitter.com") /** * Card endpoint host. */ val Card = EndpointHost("caps.twitter.com") /** * Media upload endpoint. */ val MediaUpload = EndpointHost("upload.twitter.com") /** * Publish endpoint. */ val Publish = EndpointHost("publish.twitter.com") /* Stream Endpoints */ /** * UserStream endpoint. */ val UserStream = EndpointHost("userstream.twitter.com") /** * Stream endpoint. */ val Stream = EndpointHost("stream.twitter.com") } }
mit
4a06aa3861a708fab0eca2afa4d7070c
26.488636
81
0.638694
4.4631
false
false
false
false
Stargamers/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/projects/columns/ProjectColumnFragment.kt
6
9344
package com.fastaccess.ui.modules.repos.projects.columns import android.content.Context import android.os.Bundle import android.support.annotation.StringRes import android.support.v4.widget.SwipeRefreshLayout import android.view.View import butterknife.BindView import butterknife.OnClick import com.fastaccess.R import com.fastaccess.data.dao.ProjectCardModel import com.fastaccess.data.dao.ProjectColumnModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.helper.Logger import com.fastaccess.helper.PrefGetter import com.fastaccess.provider.rest.loadmore.OnLoadMore import com.fastaccess.ui.adapter.ColumnCardAdapter import com.fastaccess.ui.base.BaseFragment import com.fastaccess.ui.modules.main.premium.PremiumActivity import com.fastaccess.ui.modules.repos.projects.crud.ProjectCurdDialogFragment import com.fastaccess.ui.modules.repos.projects.details.ProjectPagerMvp import com.fastaccess.ui.widgets.FontTextView import com.fastaccess.ui.widgets.StateLayout import com.fastaccess.ui.widgets.dialog.MessageDialogView import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView import com.fastaccess.ui.widgets.recyclerview.scroll.RecyclerViewFastScroller /** * Created by Hashemsergani on 11.09.17. */ class ProjectColumnFragment : BaseFragment<ProjectColumnMvp.View, ProjectColumnPresenter>(), ProjectColumnMvp.View { @BindView(R.id.recycler) lateinit var recycler: DynamicRecyclerView @BindView(R.id.refresh) lateinit var refresh: SwipeRefreshLayout @BindView(R.id.stateLayout) lateinit var stateLayout: StateLayout @BindView(R.id.fastScroller) lateinit var fastScroller: RecyclerViewFastScroller @BindView(R.id.columnName) lateinit var columnName: FontTextView @BindView(R.id.editColumnHolder) lateinit var editColumnHolder: View @BindView(R.id.editColumn) lateinit var editColumn: View @BindView(R.id.addCard) lateinit var addCard: View @BindView(R.id.deleteColumn) lateinit var deleteColumn: View private var onLoadMore: OnLoadMore<Long>? = null private val adapter by lazy { ColumnCardAdapter(presenter.getCards(), isOwner()) } private var pageCallback: ProjectPagerMvp.DeletePageListener? = null override fun onAttach(context: Context?) { super.onAttach(context) pageCallback = when { parentFragment is ProjectPagerMvp.DeletePageListener -> parentFragment as ProjectPagerMvp.DeletePageListener context is ProjectPagerMvp.DeletePageListener -> context else -> null } } override fun onDetach() { pageCallback = null super.onDetach() } @OnClick(R.id.editColumn) fun onEditColumn() { if (canEdit()) { ProjectCurdDialogFragment.newInstance(getColumn().name) .show(childFragmentManager, ProjectCurdDialogFragment.TAG) } } @OnClick(R.id.deleteColumn) fun onDeleteColumn() { if (canEdit()) { MessageDialogView.newInstance(getString(R.string.delete), getString(R.string.confirm_message), false, MessageDialogView.getYesNoBundle(context!!)) .show(childFragmentManager, MessageDialogView.TAG) } } @OnClick(R.id.addCard) fun onAddCard() { if (canEdit()) { ProjectCurdDialogFragment.newInstance(isCard = true) .show(childFragmentManager, ProjectCurdDialogFragment.TAG) } } override fun onNotifyAdapter(items: List<ProjectCardModel>?, page: Int) { hideProgress() if (items == null || items.isEmpty()) { adapter.clear() return } if (page <= 1) { adapter.insertItems(items) } else { adapter.addItems(items) } } override fun getLoadMore(): OnLoadMore<Long> { if (onLoadMore == null) { onLoadMore = OnLoadMore<Long>(presenter) } onLoadMore!!.parameter = getColumn().id return onLoadMore!! } override fun providePresenter(): ProjectColumnPresenter = ProjectColumnPresenter() override fun fragmentLayout(): Int = R.layout.project_columns_layout override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { val column = getColumn() columnName.text = column.name refresh.setOnRefreshListener { presenter.onCallApi(1, column.id) } stateLayout.setOnReloadListener { presenter.onCallApi(1, column.id) } stateLayout.setEmptyText(R.string.no_cards) recycler.setEmptyView(stateLayout, refresh) getLoadMore().initialize(presenter.currentPage, presenter.previousTotal) adapter.listener = presenter recycler.adapter = adapter recycler.addOnScrollListener(getLoadMore()) fastScroller.attachRecyclerView(recycler) if (presenter.getCards().isEmpty() && !presenter.isApiCalled) { presenter.onCallApi(1, column.id) } addCard.visibility = if(isOwner()) View.VISIBLE else View.GONE deleteColumn.visibility = if(isOwner()) View.VISIBLE else View.GONE editColumn.visibility = if(isOwner()) View.VISIBLE else View.GONE } override fun showProgress(@StringRes resId: Int) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showErrorMessage(message: String) { showReload() super.showErrorMessage(message) } override fun showMessage(titleRes: Int, msgRes: Int) { showReload() super.showMessage(titleRes, msgRes) } override fun onScrollTop(index: Int) { super.onScrollTop(index) recycler.scrollToPosition(0) } override fun onDestroyView() { recycler.removeOnScrollListener(getLoadMore()) super.onDestroyView() } override fun onCreatedOrEdited(text: String, isCard: Boolean, position: Int) { Logger.e(text, isCard, position) if (!isCard) { columnName.text = text presenter.onEditOrDeleteColumn(text, getColumn()) } else { if (position == -1) { presenter.createCard(text, getColumn().id) } else { presenter.editCard(text, adapter.getItem(position), position) } } } override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) { super.onMessageDialogActionClicked(isOk, bundle) if (isOk) { if (bundle != null) { if (bundle.containsKey(BundleConstant.ID)) { val position = bundle.getInt(BundleConstant.ID) presenter.onDeleteCard(position, adapter.getItem(position)) } else { presenter.onEditOrDeleteColumn(null, getColumn()) } } else { presenter.onEditOrDeleteColumn(null, getColumn()) } } } override fun deleteColumn() { pageCallback?.onDeletePage(getColumn()) hideBlockingProgress() } override fun showBlockingProgress() { super.showProgress(0) } override fun hideBlockingProgress() { super.hideProgress() } override fun isOwner(): Boolean = arguments!!.getBoolean(BundleConstant.EXTRA) override fun onDeleteCard(position: Int) { if (canEdit()) { val yesNoBundle = MessageDialogView.getYesNoBundle(context!!) yesNoBundle.putInt(BundleConstant.ID, position) MessageDialogView.newInstance(getString(R.string.delete), getString(R.string.confirm_message), false, yesNoBundle).show(childFragmentManager, MessageDialogView.TAG) } } override fun onEditCard(note: String?, position: Int) { if (canEdit()) { ProjectCurdDialogFragment.newInstance(note, true, position) .show(childFragmentManager, ProjectCurdDialogFragment.TAG) } } override fun addCard(it: ProjectCardModel) { hideBlockingProgress() adapter.addItem(it, 0) } override fun updateCard(response: ProjectCardModel, position: Int) { hideBlockingProgress() adapter.swapItem(response, position) } override fun onRemoveCard(position: Int) { hideBlockingProgress() adapter.removeItem(position) } private fun showReload() { hideProgress() stateLayout.showReload(adapter.itemCount) } private fun getColumn(): ProjectColumnModel = arguments!!.getParcelable(BundleConstant.ITEM) private fun canEdit(): Boolean = if (PrefGetter.isProEnabled() || PrefGetter.isAllFeaturesUnlocked()) { true } else { PremiumActivity.startActivity(context!!) false } companion object { fun newInstance(column: ProjectColumnModel, isCollaborator: Boolean): ProjectColumnFragment { val fragment = ProjectColumnFragment() fragment.arguments = Bundler.start() .put(BundleConstant.ITEM, column) .put(BundleConstant.EXTRA, isCollaborator) .end() return fragment } } }
gpl-3.0
cd639c914108821507cc4b08a638e307
34.942308
120
0.668557
4.745556
false
false
false
false
AlmasB/FXGL
fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/trade/ShopTest.kt
1
3043
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.trade import org.hamcrest.CoreMatchers.* import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test /** * * @author Almas Baimagambetov ([email protected]) */ class ShopTest { @Test fun `Basic shop functionality`() { val items = arrayListOf("hello", "world").map { TradeItem(it, "", "", 5, 5, 2) } val shop = Shop(10, items) assertThat(shop.moneyProperty().value, `is`(10)) assertThat(shop.money, `is`(10)) assertThat(shop.items, `is`(items)) } @Test fun `Buy and sell`() { val items1 = arrayListOf("hello", "world").map { TradeItem(it, "", "", 5, 3, 2) } val items2 = listOf<TradeItem<String>>() val shop1 = Shop(items1) val shop2 = Shop(items2) var count = 0 val listener = object : ShopListener<String> { override fun onSold(item: TradeItem<String>) { count++ } override fun onBought(item: TradeItem<String>) { count++ } } shop1.listener = listener shop2.listener = listener var wasBought = shop2.buyFrom(shop1, items1[0], 1) // no money assertFalse(wasBought) wasBought = shop2.buyFrom(shop1, items1[0], 3) // quantity is 2 in shop, but we wanted 3 assertFalse(wasBought) wasBought = shop2.buyFrom(shop1, TradeItem("some_item", "", "", 5, 3, 2), 1) // we wanted to buy an item that is not in shop assertFalse(wasBought) assertThat(count, `is`(0)) shop2.money = 100 wasBought = shop2.buyFrom(shop1, items1[0], 1) // buy + sell assertThat(count, `is`(2)) assertTrue(wasBought) assertThat(shop1.items, hasItem(items1[0])) assertThat(shop1.money, `is`(3)) assertThat(shop2.money, `is`(97)) assertThat(shop2.items.size, `is`(1)) assertThat(shop2.items[0].item, `is`("hello")) assertThat(shop2.items[0].description, `is`("")) assertThat(shop2.items[0].name, `is`("")) assertThat(shop2.items[0].sellPrice, `is`(5)) assertThat(shop2.items[0].buyPrice, `is`(3)) assertThat(shop2.items[0].quantity, `is`(1)) // buy again (the last one since qty was 2) wasBought = shop2.buyFrom(shop1, items1[0], 1) // buy + sell assertThat(count, `is`(4)) assertTrue(wasBought) assertThat(shop1.money, `is`(6)) assertThat(shop2.money, `is`(94)) assertThat(shop2.items.size, `is`(1)) // shop2 now has qty 2 assertThat(shop2.items[0].quantity, `is`(2)) // shop1 now does not have the time assertThat(shop1.items, not(hasItem(items1[0]))) } }
mit
1c8300df4aa6f69ca2b5e1a2be465ca4
27.185185
89
0.584292
3.59268
false
false
false
false
crunchersaspire/worshipsongs
app/src/main/java/org/worshipsongs/fragment/HomeFragment.kt
3
3320
package org.worshipsongs.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.fragment.app.Fragment import androidx.viewpager.widget.ViewPager import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.listener.SongContentViewListener import org.worshipsongs.registry.FragmentRegistry import java.util.* /** * @author: Madasamy * @since: 3.x */ class HomeFragment : Fragment(), SongContentViewListener { private var songContentFrameLayout: FrameLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.home_layout, container, false) as View setContentViewFragment(view) setTabsFragment() return view } private fun setTabsFragment() { val fragmentManager = fragmentManager val existingHomeTabFragment = fragmentManager!!.findFragmentByTag(HomeTabFragment::class.java.simpleName) as HomeTabFragment? if (isNewTabSelected(existingHomeTabFragment)) { val homeTabFragment = HomeTabFragment.newInstance() homeTabFragment.arguments = arguments if (songContentFrameLayout != null) { homeTabFragment.setSongContentViewListener(this) } val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.tabs_fragment, homeTabFragment, HomeTabFragment::class.java.simpleName) transaction.addToBackStack(null) transaction.commit() } } internal fun isNewTabSelected(homeTabFragment: HomeTabFragment?): Boolean { if (homeTabFragment != null) { val viewPager = homeTabFragment.view?.findViewById<ViewPager>(R.id.pager) val existingCurrentItem = viewPager?.currentItem if (arguments != null && arguments!!.containsKey(CommonConstants.TAB_SELECTED_ITEM_ID)) { return arguments!!.getInt(CommonConstants.TAB_SELECTED_ITEM_ID) != existingCurrentItem } } return true } private fun setContentViewFragment(view: View) { songContentFrameLayout = view.findViewById(R.id.song_content_fragment) } override fun displayContent(title: String, titleList: List<String>, position: Int) { if (songContentFrameLayout != null) { val songContentPortraitViewFragment = SongContentPortraitViewFragment.newInstance(title, ArrayList(titleList)) val transaction = fragmentManager!!.beginTransaction() transaction.replace(R.id.song_content_fragment, songContentPortraitViewFragment) transaction.addToBackStack(null) transaction.commit() } } override fun onSaveInstanceState(state: Bundle) { super.onSaveInstanceState(state) } companion object { fun newInstance(): HomeFragment { return HomeFragment() } } }
apache-2.0
acad3e9055bf49ba66421f4ed3126e69
30.923077
133
0.680422
5.236593
false
false
false
false
libktx/ktx
ashley/src/main/kotlin/ktx/ashley/properties.kt
1
2761
package ktx.ashley import com.badlogic.ashley.core.Component import com.badlogic.ashley.core.ComponentMapper import com.badlogic.ashley.core.Entity import kotlin.reflect.KProperty /** * Property delegate for an [Entity] wrapping around a [ComponentMapper]. * Allows accessing components assigned to entities with the property syntax. * Designed for non-nullable components that are available for all entities * without the risk of a [NullPointerException]. * * @see OptionalComponentDelegate */ class ComponentDelegate<T : Component>(private val mapper: ComponentMapper<T>) { operator fun getValue(thisRef: Entity, property: KProperty<*>): T = mapper[thisRef]!! operator fun setValue(thisRef: Entity, property: KProperty<*>, value: T) { thisRef.add(value) } } /** * Returns a delegated property for the [Entity] class to access the given [Component]. * Allows accessing and setting mandatory components assigned to entities with the property * syntax. * * Passing a [mapper] is optional; if no value is given, it will create a new [ComponentMapper] for * the chosen [Component] class. * * @see optionalPropertyFor * @see ComponentDelegate **/ inline fun <reified T : Component> propertyFor(mapper: ComponentMapper<T> = mapperFor()): ComponentDelegate<T> = ComponentDelegate(mapper) /** * Property delegate for an [Entity] wrapping around a [ComponentMapper]. * Designed for components that might not be defined for each entity and can be null. * Attempting to assign a null value to the property will remove the component from the entity. * * @see ComponentDelegate */ class OptionalComponentDelegate<T : Component>( private val mapper: ComponentMapper<T>, private val componentClass: Class<T> ) { operator fun getValue(thisRef: Entity, property: KProperty<*>): T? = if (mapper.has(thisRef)) mapper[thisRef] else null operator fun setValue(thisRef: Entity, property: KProperty<*>, value: T?) { if (value != null) { thisRef.add(value) } else if (mapper.has(thisRef)) { thisRef.remove(componentClass) } } } /** * Returns a delegated property for the [Entity] class to access the given [Component]. * Allows accessing and setting optional components assigned to entities with the property syntax. * Attempting to assign a null value to the property will remove the component it from the entity. * * Passing a [mapper] is optional; if no value is given, it will create a new [ComponentMapper] for * the chosen [Component] class. * * @see propertyFor * @see OptionalComponentDelegate **/ inline fun <reified T : Component> optionalPropertyFor( mapper: ComponentMapper<T> = mapperFor() ): OptionalComponentDelegate<T> = OptionalComponentDelegate(mapper, T::class.java)
cc0-1.0
0323fa74584fe0e08e96624a1d1e62cb
35.328947
112
0.74176
4.228178
false
false
false
false
guyca/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/utils/ImageLoader.kt
2
4730
package com.reactnativenavigation.utils import android.app.Activity import android.content.Context import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.net.Uri import android.os.StrictMode import android.view.View import androidx.core.content.ContextCompat import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper import com.reactnativenavigation.R import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream import java.net.URL import java.util.* open class ImageLoader { interface ImagesLoadingListener { fun onComplete(drawable: List<Drawable>) fun onComplete(drawable: Drawable) fun onError(error: Throwable?) } open fun getBackButtonIcon(context: Activity): Drawable? { val isRTL = context.window.decorView.layoutDirection == View.LAYOUT_DIRECTION_RTL return ContextCompat.getDrawable(context, if (isRTL) R.drawable.ic_arrow_back_black_rtl_24dp else R.drawable.ic_arrow_back_black_24dp) } open fun loadIcon(context: Context, uri: String?): Drawable? { if (uri == null) return null try { return getDrawable(context, uri) } catch (e: IOException) { e.printStackTrace() } return null } open fun loadIcon(context: Context, uri: String, listener: ImagesLoadingListener) { try { listener.onComplete(getDrawable(context, uri)) } catch (e: IOException) { listener.onError(e) } } open fun loadIcons(context: Context, uris: List<String>, listener: ImagesLoadingListener) { try { val drawables: MutableList<Drawable> = ArrayList() for (uri in uris) { val drawable = getDrawable(context, uri) drawables.add(drawable) } listener.onComplete(drawables) } catch (e: IOException) { listener.onError(e) } } @Throws(IOException::class) private fun getDrawable(context: Context, source: String): Drawable { var drawable: Drawable? if (isLocalFile(Uri.parse(source))) { drawable = loadFile(context, source) } else { drawable = loadResource(context, source) if (drawable == null && context.isDebug()) { drawable = readJsDevImage(context, source) } } if (drawable == null) throw RuntimeException("Could not load image $source") return drawable } @Throws(IOException::class) private fun readJsDevImage(context: Context, source: String): Drawable { val threadPolicy = adjustThreadPolicyDebug(context) val `is` = openStream(context, source) val bitmap = BitmapFactory.decodeStream(`is`) restoreThreadPolicyDebug(context, threadPolicy) return BitmapDrawable(context.resources, bitmap) } private fun isLocalFile(uri: Uri): Boolean { return FILE_SCHEME == uri.scheme } private fun loadFile(context: Context, uri: String): Drawable { val bitmap = BitmapFactory.decodeFile(Uri.parse(uri).path) return BitmapDrawable(context.resources, bitmap) } private fun adjustThreadPolicyDebug(context: Context): StrictMode.ThreadPolicy? { var threadPolicy: StrictMode.ThreadPolicy? = null if (context.isDebug()) { threadPolicy = StrictMode.getThreadPolicy() StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitNetwork().build()) } return threadPolicy } private fun restoreThreadPolicyDebug(context: Context, threadPolicy: StrictMode.ThreadPolicy?) { if (context.isDebug() && threadPolicy != null) { StrictMode.setThreadPolicy(threadPolicy) } } companion object { private const val FILE_SCHEME = "file" private fun loadResource(context: Context, iconSource: String): Drawable? { return ResourceDrawableIdHelper.getInstance().getResourceDrawable(context, iconSource) } @Throws(IOException::class) private fun openStream(context: Context, uri: String): InputStream? { return if (uri.contains("http")) remoteUrl(uri) else localFile(context, uri) } @Throws(IOException::class) private fun remoteUrl(uri: String): InputStream { return URL(uri).openStream() } @Throws(FileNotFoundException::class) private fun localFile(context: Context, uri: String): InputStream? { return context.contentResolver.openInputStream(Uri.parse(uri)) } } }
mit
cd15492ba770e4c6c84dfb482eba42e8
34.840909
142
0.659831
4.73
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/module/common/player/MusicPlayerWrapper.kt
1
3141
/* * Copyright (C) 2017 YangBin * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package tech.summerly.quiet.module.common.player import android.content.Context import android.content.Intent import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.service.MusicPlayService import tech.summerly.quiet.service.SimpleMusicPlayer import kotlin.reflect.KClass /** * author : yangbin10 * date : 2017/11/20 * 这是一个空壳 */ object MusicPlayerWrapper : IMusicPlayer { private var player: IMusicPlayer? = null get() { if (field == null) { field = SimpleMusicPlayer.instance.also { it.restore() } } return field } override var playMode: PlayMode get() = player?.playMode ?: PlayMode.SEQUENCE set(value) { player?.playMode = value } fun setPlayer(player: IMusicPlayer?) { destroy() this.player = player } override fun currentPlaying(): Music? = player?.currentPlaying() override fun isPlaying(): Boolean = player?.isPlaying() ?: false override fun playNext() { player?.playNext() } override fun playPrevious() { player?.playPrevious() } override fun playPause() { player?.playPause() } override fun stop() { player?.stop() } override fun play(music: Music) { player?.play(music) } override fun setPlaylist(musics: List<Music>) { player?.setPlaylist(musics) } override fun getPlaylist(): List<Music> = player?.getPlaylist() ?: emptyList() override fun remove(music: Music) { player?.remove(music) } override fun addToNext(music: Music) { player?.addToNext(music) } override fun seekToPosition(position: Long) { player?.seekToPosition(position) } override fun currentPosition(): Long { return player?.currentPosition() ?: 0 } override fun destroy() { player?.destroy() player = null } fun <T : IMusicPlayer> belongTo(type: KClass<T>): Boolean = player?.let { it::class == type } ?: false override fun restore() = Unit override fun save() = Unit fun bindToService(context: Context) { val intent = Intent(context, MusicPlayService::class.java) .setAction(MusicPlayService.action_play_none) context.startService(intent) } }
gpl-2.0
9def9570884560b88ea9f82b551be676
25.752137
82
0.647172
4.303989
false
false
false
false
zxj5470/BugKotlinDocument
src/main/kotlin/com/github/zxj5470/bugktdoc/constants/DecorationConstants.kt
1
304
package com.github.zxj5470.bugktdoc.constants /** * @author zxj5470 * @date 2018/4/12 */ const val CONSTRUCTOR = "@constructor" const val PARAM = "@param" const val PROPERTY = "@property" const val RECEIVER = "@receiver" const val RETURN = "@return" const val THROWS = "@throws" const val LF = "\n"
apache-2.0
c693a2597fe677c488cfeef722f8fde8
19.333333
45
0.694079
3.2
false
false
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/IDependencyManager.kt
1
3589
package com.beust.kobalt.api import com.beust.kobalt.maven.aether.Filters.EXCLUDE_OPTIONAL_FILTER import com.beust.kobalt.maven.aether.KobaltMavenResolver import com.beust.kobalt.maven.aether.Scope import com.beust.kobalt.misc.kobaltLog import org.eclipse.aether.graph.DependencyFilter import org.eclipse.aether.graph.DependencyNode /** * Manage the creation of dependencies and also provide dependencies for projects. */ interface IDependencyManager { /** * Parse the id and return the correct IClasspathDependency */ fun create(id: String, optional: Boolean = false, projectDirectory: String? = null): IClasspathDependency /** * Create an IClasspathDependency from a Maven id. */ fun createMaven(id: String, optional: Boolean = false): IClasspathDependency /** * Create an IClasspathDependency from a path. */ fun createFile(path: String): IClasspathDependency /** * @return the source dependencies for this project, including the contributors. */ fun dependencies(project: Project, context: KobaltContext, scopes: List<Scope>): List<IClasspathDependency> /** * @return the test dependencies for this project, including the contributors. */ fun testDependencies(project: Project, context: KobaltContext): List<IClasspathDependency> /** * @return the classpath for this project, including the IClasspathContributors. * allDependencies is typically either compileDependencies or testDependencies */ fun calculateDependencies(project: Project?, context: KobaltContext, dependencyFilter: DependencyFilter = createDependencyFilter(project, project?.compileDependencies ?: emptyList()), scopes: List<Scope> = listOf(Scope.COMPILE), vararg passedDependencies: List<IClasspathDependency>): List<IClasspathDependency> /** * Create an Aether dependency filter that uses the dependency configuration included in each * IClasspathDependency. */ fun createDependencyFilter(project: Project?, dependencies: List<IClasspathDependency>) : DependencyFilter { return DependencyFilter { p0, p1 -> fun isNodeExcluded(node: DependencyNode, passedDep: IClasspathDependency) : Boolean { val dep = create(KobaltMavenResolver.artifactToId(node.artifact)) return passedDep.excluded.any { ex -> ex.isExcluded(dep)} } fun isDepExcluded(node: DependencyNode, excluded: List<IClasspathDependency>?) : Boolean { val dep = create(KobaltMavenResolver.artifactToId(node.artifact)) return excluded?.map { it.id }?.contains(dep.id) ?: false } val accept = dependencies.isEmpty() || dependencies.any { // Is this dependency excluded? val isExcluded = isNodeExcluded(p0, it) || isDepExcluded(p0, project?.excludedDependencies) // Is the parent dependency excluded? val isParentExcluded = if (p1.any()) { isNodeExcluded(p1[0], it) || isDepExcluded(p1[0], project?.excludedDependencies) } else { false } // Only accept if no exclusions were found ! isExcluded && ! isParentExcluded } if (! accept) { kobaltLog(2, "Excluding $p0") } if (accept) EXCLUDE_OPTIONAL_FILTER.accept(p0, p1) else accept } } }
apache-2.0
80fe326a8d4dfc1806339a9f60c8c95e
39.795455
112
0.650878
5.04782
false
false
false
false