repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
AndroidX/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/UseCaseManager.kt
3
13265
/* * 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.camera.camera2.pipe.integration.impl import android.media.MediaCodec import android.os.Build import androidx.annotation.GuardedBy import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.core.Log import androidx.camera.camera2.pipe.integration.adapter.CameraStateAdapter import androidx.camera.camera2.pipe.integration.config.CameraConfig import androidx.camera.camera2.pipe.integration.config.CameraScope import androidx.camera.camera2.pipe.integration.config.UseCaseCameraComponent import androidx.camera.camera2.pipe.integration.config.UseCaseCameraConfig import androidx.camera.camera2.pipe.integration.interop.Camera2CameraControl import androidx.camera.camera2.pipe.integration.interop.ExperimentalCamera2Interop import androidx.camera.core.UseCase import androidx.camera.core.impl.DeferrableSurface import androidx.camera.core.impl.SessionConfig.ValidatingBuilder import javax.inject.Inject import kotlinx.coroutines.Job import kotlinx.coroutines.joinAll /** * This class keeps track of the currently attached and active [UseCase]'s for a specific camera. * A [UseCase] during its lifetime, can be: * * - Attached: This happens when a use case is bound to a CameraX Lifecycle, and signals that the * camera should be opened, and a camera capture session should be created to include the * stream corresponding to the use case. In the integration layer here, we'll recreate a * CameraGraph when a use case is attached. * - Detached: This happens when a use case is unbound from a CameraX Lifecycle, and signals that * we no longer need this specific use case and therefore its corresponding stream in our * current capture session. In the integration layer, we'll also recreate a CameraGraph when * a use case is detached, though it might not be strictly necessary. * - Active: This happens when the use case is considered "ready", meaning that the use case is * ready to have frames delivered to it. In the case of the integration layer, this means we * can start submitting the capture requests corresponding to the use case. An important note * here is that a use case can actually become "active" before it is "attached", and thus we * should only take action when a use case is both "attached" and "active". * - Inactive: This happens when use case no longer needs frames delivered to it. This is can be * seen as an optimization signal, as we technically are allowed to continue submitting * capture requests, but we no longer need to. An example of this is when you clear the * analyzer during ImageAnalysis. * * In this class, we also define a new term - "Running". A use case is considered running when it's * both "attached" and "active". This means we should have a camera opened, a capture session with * the streams created and have capture requests submitting. */ @OptIn(ExperimentalCamera2Interop::class) @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @CameraScope class UseCaseManager @Inject constructor( private val cameraConfig: CameraConfig, private val builder: UseCaseCameraComponent.Builder, @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") // Java version required for Dagger private val controls: java.util.Set<UseCaseCameraControl>, private val camera2CameraControl: Camera2CameraControl, private val cameraStateAdapter: CameraStateAdapter, cameraProperties: CameraProperties, displayInfoManager: DisplayInfoManager, ) { private val lock = Any() @GuardedBy("lock") private val attachedUseCases = mutableSetOf<UseCase>() @GuardedBy("lock") private val activeUseCases = mutableSetOf<UseCase>() private val meteringRepeating by lazy { MeteringRepeating.Builder( cameraProperties, displayInfoManager ).build() } @Volatile private var _activeComponent: UseCaseCameraComponent? = null val camera: UseCaseCamera? get() = _activeComponent?.getUseCaseCamera() private val closingCameraJobs = mutableListOf<Job>() private val allControls = controls.toMutableSet().apply { add(camera2CameraControl) } /** * This attaches the specified [useCases] to the current set of attached use cases. When any * changes are identified (i.e., a new use case is added), the subsequent actions would trigger * a recreation of the current CameraGraph if there is one. */ fun attach(useCases: List<UseCase>) = synchronized(lock) { if (useCases.isEmpty()) { Log.warn { "Attach [] from $this (Ignored)" } return } Log.debug { "Attaching $useCases from $this" } // Notify state attached to use cases for (useCase in useCases) { if (!attachedUseCases.contains(useCase)) { useCase.onStateAttached() } } if (attachedUseCases.addAll(useCases)) { if (shouldAddRepeatingUseCase(getRunningUseCases())) { addRepeatingUseCase() return } refreshAttachedUseCases(attachedUseCases) } } /** * This detaches the specified [useCases] from the current set of attached use cases. When any * changes are identified (i.e., an existing use case is removed), the subsequent actions would * trigger a recreation of the current CameraGraph. */ fun detach(useCases: List<UseCase>) = synchronized(lock) { if (useCases.isEmpty()) { Log.warn { "Detaching [] from $this (Ignored)" } return } Log.debug { "Detaching $useCases from $this" } // When use cases are detached, they should be considered inactive as well. Also note that // we remove the use cases from our set directly because the subsequent cleanup actions from // detaching the use cases should suffice here. activeUseCases.removeAll(useCases) // Notify state detached to use cases for (useCase in useCases) { if (attachedUseCases.contains(useCase)) { useCase.onStateDetached() } } // TODO: We might only want to tear down when the number of attached use cases goes to // zero. If a single UseCase is removed, we could deactivate it? if (attachedUseCases.removeAll(useCases)) { if (shouldRemoveRepeatingUseCase(getRunningUseCases())) { removeRepeatingUseCase() return } refreshAttachedUseCases(attachedUseCases) } } /** * This marks the specified [useCase] as active ("activate"). This refreshes the current set of * active use cases, and if any changes are identified, we update [UseCaseCamera] with the * latest set of "running" (attached and active) use cases, which will in turn trigger actions * for SessionConfig updates. */ fun activate(useCase: UseCase) = synchronized(lock) { if (activeUseCases.add(useCase)) { refreshRunningUseCases() } } /** * This marks the specified [useCase] as inactive ("deactivate"). This refreshes the current set * of active use cases, and if any changes are identified, we update [UseCaseCamera] with the * latest set of "running" (attached and active) use cases, which will in turn trigger actions * for SessionConfig updates. */ fun deactivate(useCase: UseCase) = synchronized(lock) { if (activeUseCases.remove(useCase)) { refreshRunningUseCases() } } fun update(useCase: UseCase) = synchronized(lock) { if (attachedUseCases.contains(useCase)) { refreshRunningUseCases() } } fun reset(useCase: UseCase) = synchronized(lock) { if (attachedUseCases.contains(useCase)) { refreshAttachedUseCases(attachedUseCases) } } suspend fun close() { val closingJobs = synchronized(lock) { if (attachedUseCases.isNotEmpty()) { detach(attachedUseCases.toList()) } meteringRepeating.onDetached() closingCameraJobs.toList() } closingJobs.joinAll() } override fun toString(): String = "UseCaseManager<${cameraConfig.cameraId}>" @GuardedBy("lock") private fun refreshRunningUseCases() { val runningUseCases = getRunningUseCases() when { shouldAddRepeatingUseCase(runningUseCases) -> addRepeatingUseCase() shouldRemoveRepeatingUseCase(runningUseCases) -> removeRepeatingUseCase() else -> camera?.runningUseCases = runningUseCases } } @GuardedBy("lock") private fun refreshAttachedUseCases(newUseCases: Set<UseCase>) { val useCases = newUseCases.toList() // Close prior camera graph camera.let { _activeComponent = null it?.close()?.let { closingJob -> closingCameraJobs.add(closingJob) closingJob.invokeOnCompletion { synchronized(lock) { closingCameraJobs.remove(closingJob) } } } } // Update list of active useCases if (useCases.isEmpty()) { for (control in allControls) { control.useCaseCamera = null control.reset() } return } // Create and configure the new camera component. _activeComponent = builder.config(UseCaseCameraConfig(useCases, cameraStateAdapter)).build() for (control in allControls) { control.useCaseCamera = camera } refreshRunningUseCases() } @GuardedBy("lock") private fun getRunningUseCases(): Set<UseCase> { return attachedUseCases.intersect(activeUseCases) } @GuardedBy("lock") private fun shouldAddRepeatingUseCase(runningUseCases: Set<UseCase>): Boolean { val meteringRepeatingEnabled = attachedUseCases.contains(meteringRepeating) val coreLibraryUseCases = runningUseCases.filterNot { it is MeteringRepeating } val onlyVideoCapture = coreLibraryUseCases.onlyVideoCapture() val requireMeteringRepeating = coreLibraryUseCases.requireMeteringRepeating() return !meteringRepeatingEnabled && (onlyVideoCapture || requireMeteringRepeating) } @GuardedBy("lock") private fun addRepeatingUseCase() { meteringRepeating.setupSession() attach(listOf(meteringRepeating)) activate(meteringRepeating) } @GuardedBy("lock") private fun shouldRemoveRepeatingUseCase(runningUseCases: Set<UseCase>): Boolean { val meteringRepeatingEnabled = runningUseCases.contains(meteringRepeating) val coreLibraryUseCases = runningUseCases.filterNot { it is MeteringRepeating } val onlyVideoCapture = coreLibraryUseCases.onlyVideoCapture() val requireMeteringRepeating = coreLibraryUseCases.requireMeteringRepeating() return meteringRepeatingEnabled && !onlyVideoCapture && !requireMeteringRepeating } @GuardedBy("lock") private fun removeRepeatingUseCase() { deactivate(meteringRepeating) detach(listOf(meteringRepeating)) meteringRepeating.onDetached() } private fun Collection<UseCase>.onlyVideoCapture(): Boolean { return isNotEmpty() && checkSurfaces { _, sessionSurfaces -> sessionSurfaces.isNotEmpty() && sessionSurfaces.all { it.containerClass == MediaCodec::class.java } } } private fun Collection<UseCase>.requireMeteringRepeating(): Boolean { return isNotEmpty() && checkSurfaces { repeatingSurfaces, sessionSurfaces -> // There is no repeating UseCases sessionSurfaces.isNotEmpty() && repeatingSurfaces.isEmpty() } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun Collection<UseCase>.checkSurfaces( predicate: ( repeatingSurfaces: List<DeferrableSurface>, sessionSurfaces: List<DeferrableSurface> ) -> Boolean ): Boolean = ValidatingBuilder().let { validatingBuilder -> forEach { useCase -> validatingBuilder.add(useCase.sessionConfig) } val sessionConfig = validatingBuilder.build() val captureConfig = sessionConfig.repeatingCaptureConfig return predicate(captureConfig.surfaces, sessionConfig.surfaces) } }
apache-2.0
android/xAnd11
core/src/main/java/com/monksanctum/xand11/core/input/XKeyboardManager.kt
1
2633
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.monksanctum.xand11.input import org.monksanctum.xand11.core.KeyEvent import org.monksanctum.xand11.core.getMaxKeyCode import org.monksanctum.xand11.core.initCharMap class XKeyboardManager { val keysPerSym: Int val keyboardMap: IntArray val modifiers = byteArrayOf(KeyEvent.KEYCODE_SHIFT_LEFT.toByte(), KeyEvent.KEYCODE_SHIFT_RIGHT.toByte(), 0, 0, 0, 0, KeyEvent.KEYCODE_ALT_LEFT.toByte(), KeyEvent.KEYCODE_ALT_RIGHT.toByte(), 0, 0, 0, 0, 0, 0, 0, 0) private val mState = BooleanArray(modifiers.size) val state: Int get() { var state = 0 for (i in mState.indices) { if (mState[i]) { state = state or (1 shl i / 2) } } return state } init { val modifiers = intArrayOf(0, KeyEvent.META_SHIFT_ON, KeyEvent.META_ALT_ON) keysPerSym = modifiers.size val maxKeyCode = getMaxKeyCode() keyboardMap = IntArray(modifiers.size * maxKeyCode) initCharMap(keyboardMap, modifiers) keyboardMap[keysPerSym * KeyEvent.KEYCODE_DEL] = 127 for (i in this.modifiers.indices) { this.modifiers[i] = translate(this.modifiers[i].toInt()).toByte() } } fun translate(keyCode: Int): Int { return keyCode + 8 } private fun modIndex(keyCode: Int): Int { for (i in modifiers.indices) { if (modifiers[i].toInt() == keyCode) { return i } } return -1 } fun onKeyDown(keyCode: Int) { val modIndex = modIndex(translate(keyCode)) if (modIndex < 0) return mState[modIndex] = true } fun onKeyUp(keyCode: Int) { val modIndex = modIndex(translate(keyCode)) if (modIndex < 0) return mState[modIndex] = false } }
apache-2.0
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/layers/LinearGaugeLayer.kt
1
1810
package com.teamwizardry.librarianlib.facade.layers import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.value.IMValue import com.teamwizardry.librarianlib.facade.value.IMValueDouble import com.teamwizardry.librarianlib.math.Direction2d import com.teamwizardry.librarianlib.core.util.rect import kotlin.math.roundToInt public open class LinearGaugeLayer: GuiLayer { public constructor(): super() public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) /** * @see fillFraction */ public val fillFraction_im: IMValueDouble = imDouble(1.0) /** * How full the gauge is. Ranges from 0–1 */ public var fillFraction: Double by fillFraction_im /** * The direction to expand (e.g. [UP][Direction2d.UP] means the gauge will sit at the bottom and rise up) */ public var direction: Direction2d = Direction2d.UP /** * The contents of the gauge. This is the layer that is resized based on [fillFraction]. */ public val contents: GuiLayer = GuiLayer() init { this.add(contents) } override fun prepareLayout() { val fillFraction = fillFraction val totalSize = direction.axis.get(this.size) val fullSize = (totalSize * fillFraction).roundToInt() val emptySize = (totalSize * (1 - fillFraction)).roundToInt() contents.frame = when (direction) { Direction2d.UP -> rect(0, emptySize, width, fullSize) Direction2d.DOWN -> rect(0, 0, width, fullSize) Direction2d.LEFT -> rect(emptySize, 0, fullSize, height) Direction2d.RIGHT -> rect(0, 0, fullSize, height) } } }
lgpl-3.0
Tapchicoma/ultrasonic
core/domain/src/main/kotlin/org/moire/ultrasonic/domain/JukeboxStatus.kt
2
209
package org.moire.ultrasonic.domain data class JukeboxStatus( var positionSeconds: Int? = null, var currentPlayingIndex: Int? = null, var gain: Float? = null, var isPlaying: Boolean = false )
gpl-3.0
yzbzz/beautifullife
app/src/main/java/com/ddu/app/BaseApp.kt
2
3235
package com.ddu.app import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import java.lang.ref.WeakReference import java.util.* import kotlin.properties.Delegates open class BaseApp : Application(), Application.ActivityLifecycleCallbacks { companion object { var instance by Delegates.notNull<BaseApp>() lateinit var mApp: Application lateinit var mContext: Context var mainHandler = Handler(Looper.getMainLooper()) fun post(r: Runnable) { mainHandler.post(r) } fun postDelayed(r: Runnable, delayMillis: Long) { mainHandler.postDelayed(r, delayMillis) } fun getContext(): Application { return mApp } } lateinit var currentActivity: WeakReference<Activity> private val sCacheActivities: MutableMap<Int, WeakReference<Activity>> by lazy { mutableMapOf<Int, WeakReference<Activity>>() } val cacheActivities: Map<Int, WeakReference<Activity>>? get() = sCacheActivities override fun onCreate() { super.onCreate() mApp = this mContext = applicationContext } open fun addActivity(activity: Activity) { currentActivity = WeakReference(activity) val hashCode = activity.hashCode() if (sCacheActivities.containsKey(hashCode)) { sCacheActivities.remove(hashCode) } sCacheActivities.put(hashCode, WeakReference(activity)) } open fun removeActivity(activity: Activity) { val hashCode = activity.hashCode() if (sCacheActivities.containsKey(hashCode)) { sCacheActivities.remove(hashCode) } } open fun getCacheActivity(hashCode: Int): Activity? { val weakReference = sCacheActivities[hashCode] ?: return null return weakReference.get() } open fun finishAllActivity(): Int { var finishCount = 0 if (sCacheActivities != null && !sCacheActivities.isEmpty()) { val activities = ArrayList(sCacheActivities.values) for (activity in activities) { val tempActivity = activity.get() ?: continue sCacheActivities.remove(tempActivity.hashCode()) if (tempActivity !== currentActivity.get()) { if (tempActivity != null && !tempActivity.isFinishing) { tempActivity.finish() finishCount++ } } } } return finishCount } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { addActivity(activity) } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityDestroyed(activity: Activity) { removeActivity(activity) } }
apache-2.0
yzbzz/beautifullife
app/src/main/java/com/ddu/ui/fragment/MeFragment.kt
2
8668
package com.ddu.ui.fragment import android.app.PendingIntent import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.SystemClock import android.util.Log import androidx.fragment.app.DialogFragment import com.ddu.R import com.ddu.app.BaseApp import com.ddu.icore.callback.InConsumer3 import com.ddu.icore.common.ext.act import com.ddu.icore.common.ext.ctx import com.ddu.icore.dialog.AlertDialogFragment import com.ddu.icore.dialog.BottomDialogFragment import com.ddu.icore.dialog.DefaultGridBottomDialogFragment import com.ddu.icore.entity.BottomItem import com.ddu.icore.entity.BottomItemEntity import com.ddu.icore.ui.fragment.DefaultFragment import com.ddu.icore.ui.help.ShapeInject import com.ddu.ui.fragment.person.PhoneInfoFragment import com.ddu.ui.fragment.person.SettingFragment import com.ddu.util.NotificationUtils import kotlinx.android.synthetic.main.fragment_me.* /** * Created by yzbzz on 2018/1/17. */ class MeFragment : DefaultFragment() { var mHits = LongArray(COUNTS) var dialog: AlertDialogFragment? = null var nid = 0 override fun initData(savedInstanceState: Bundle?) { dialog = AlertDialogFragment().apply { title = "彩蛋" msg = "逗你玩" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() } } } override fun getLayoutId(): Int { return R.layout.fragment_me } override fun initView() { setTitle(R.string.main_tab_me) tv_usr_name.text = "yzbzz" tv_usr_number.text = "186-xxxx-xxx" oiv_buddha.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2ffff00")) oiv_friend_link.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2fdbc40")) oiv_friend_link.setOnClickListener { showShareDialog() } oiv_plan.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b200ff00")) oiv_fav.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2ff0000")) oiv_eggs.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2437fda")) oiv_eggs.setOnClickListener { System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1) mHits[mHits.size - 1] = SystemClock.uptimeMillis() if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) { dialog?.let { if (!it.isVisible) { it.show(childFragmentManager, "") } } } } oiv_setting.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b234c749")) oiv_setting.setOnClickListener { startFragment(SettingFragment::class.java) } oiv_phone_info.enableDefaultLeftText(Color.parseColor("#b24897fa")) oiv_phone_info.setOnClickListener { startFragment(PhoneInfoFragment::class.java) } oiv_notification.enableDefaultLeftText(Color.parseColor("#b2ff4141")) oiv_notification.setOnClickListener { val intent = Intent("cn.android.intent.user.click") val pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val builder = NotificationUtils.instance.getPrimaryNotification(ctx, "hello", "hello world") val builder1 = NotificationUtils.instance.getSecondNotification(ctx, "hello", "hello world") NotificationUtils.instance.notify(nid++, builder1) // NotificationUtils.instance.notify(2, builder1) } oiv_show_dialog.enableDefaultLeftText(Color.parseColor("#b234c749")) oiv_show_dialog.setOnClickListener { val dialog = AlertDialogFragment().apply { title = "彩蛋" msg = "逗你玩" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() } } dialog.show(parentFragmentManager, "") BaseApp.postDelayed(Runnable { val sb = StringBuilder() sb.append("isadd: ${dialog.isAdded} ") sb.append("isDetached: ${dialog.isDetached} ") sb.append("isHidden: ${dialog.isHidden} ") sb.append("isRemoving: ${dialog.isRemoving} ") sb.append("isVisible: ${dialog.isVisible} ") Log.v("lhz", sb.toString()) dialog.dismissAllowingStateLoss() }, 2000) } oiv_show_bottom_dialog.enableDefaultLeftText(Color.parseColor("#b2ff00ff")) oiv_show_bottom_dialog.setOnClickListener { showBottomDialog() } rl_person_info.setOnClickListener { val i = 5 / 0 } } companion object { internal const val COUNTS = 10//点击次数 internal const val DURATION = (3 * 1000).toLong()//规定有效时间 fun newInstance(): MeFragment { val fragment = MeFragment() val args = Bundle() fragment.arguments = args return fragment } } private fun showBottomDialog() { var shareEntities = mutableListOf<BottomItem>() val github = BottomItem() github.id = 0 github.icon = resources.getDrawable(R.drawable.me_friend_link_github) github.title = "GitHub" val blog = BottomItem() blog.id = 1 blog.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog.title = "Blog" val blog1 = BottomItem() blog1.id = 1 blog1.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog1.title = "Blog" val blog2 = BottomItem() blog2.id = 1 blog2.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog2.title = "Blog" val blog3 = BottomItem() blog3.id = 1 blog3.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog3.title = "Blog" shareEntities.add(github) shareEntities.add(blog) shareEntities.add(blog1) shareEntities.add(blog2) shareEntities.add(blog3) val dialogFragment = BottomDialogFragment.Builder() .setItems(shareEntities) .setTitle("分享") .gridLayout() .setItemClickListener(object : InConsumer3<DialogFragment, BottomItem, Int> { override fun accept(a: DialogFragment, d: BottomItem, p: Int) { a.dismissAllowingStateLoss() Log.v("lhz", "d: " + d.title + " p: " + p) } }).create() dialogFragment.showDialog(act) } private fun showShareDialog() { var shareEntities = mutableListOf<BottomItemEntity>() val github = BottomItemEntity() github.name = "GitHub" github.resId = R.drawable.me_friend_link_github github.data = "https://github.com/yzbzz" val blog = BottomItemEntity() blog.name = "Blog" blog.resId = R.drawable.me_friend_link_blog blog.data = "http://yzbzz.github.io" shareEntities.add(github) shareEntities.add(blog) val shareDialog = DefaultGridBottomDialogFragment.newInstance(list = shareEntities, cb = { data, _, shareDialog -> data?.apply { shareDialog.dismissAllowingStateLoss() val dialog = AlertDialogFragment().apply { title = "即将前往" msg = "${data.data}" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() val args = Bundle() args.putString("title", name) args.putString("url", data.data) startFragment(WebFragment::class.java, args) } } dialog.show(parentFragmentManager, "") } }) shareDialog.show(parentFragmentManager, "") } }
apache-2.0
androidx/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazyGridSpanLayoutProvider.kt
3
9773
/* * 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.tv.foundation.lazy.grid import androidx.compose.foundation.ExperimentalFoundationApi import kotlin.math.min import kotlin.math.sqrt @Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta @OptIn(ExperimentalFoundationApi::class) internal class LazyGridSpanLayoutProvider(private val itemProvider: LazyGridItemProvider) { class LineConfiguration(val firstItemIndex: Int, val spans: List<TvGridItemSpan>) /** Caches the bucket info on lines 0, [bucketSize], 2 * [bucketSize], etc. */ private val buckets = ArrayList<Bucket>().apply { add(Bucket(0)) } /** * The interval at each we will store the starting element of lines. These will be then * used to calculate the layout of arbitrary lines, by starting from the closest * known "bucket start". The smaller the bucketSize, the smaller cost for calculating layout * of arbitrary lines but the higher memory usage for [buckets]. */ private val bucketSize get() = sqrt(1.0 * totalSize / slotsPerLine).toInt() + 1 /** Caches the last calculated line index, useful when scrolling in main axis direction. */ private var lastLineIndex = 0 /** Caches the starting item index on [lastLineIndex]. */ private var lastLineStartItemIndex = 0 /** Caches the span of [lastLineStartItemIndex], if this was already calculated. */ private var lastLineStartKnownSpan = 0 /** * Caches a calculated bucket, this is useful when scrolling in reverse main axis * direction. We cannot only keep the last element, as we would not know previous max span. */ private var cachedBucketIndex = -1 /** * Caches layout of [cachedBucketIndex], this is useful when scrolling in reverse main axis * direction. We cannot only keep the last element, as we would not know previous max span. */ private val cachedBucket = mutableListOf<Int>() /** * List of 1x1 spans if we do not have custom spans. */ private var previousDefaultSpans = emptyList<TvGridItemSpan>() private fun getDefaultSpans(currentSlotsPerLine: Int) = if (currentSlotsPerLine == previousDefaultSpans.size) { previousDefaultSpans } else { List(currentSlotsPerLine) { TvGridItemSpan(1) }.also { previousDefaultSpans = it } } val totalSize get() = itemProvider.itemCount /** The number of slots on one grid line e.g. the number of columns of a vertical grid. */ var slotsPerLine = 0 set(value) { if (value != field) { field = value invalidateCache() } } fun getLineConfiguration(lineIndex: Int): LineConfiguration { if (!itemProvider.hasCustomSpans) { // Quick return when all spans are 1x1 - in this case we can easily calculate positions. val firstItemIndex = lineIndex * slotsPerLine return LineConfiguration( firstItemIndex, getDefaultSpans(slotsPerLine.coerceAtMost(totalSize - firstItemIndex) .coerceAtLeast(0)) ) } val bucketIndex = min(lineIndex / bucketSize, buckets.size - 1) // We can calculate the items on the line from the closest cached bucket start item. var currentLine = bucketIndex * bucketSize var currentItemIndex = buckets[bucketIndex].firstItemIndex var knownCurrentItemSpan = buckets[bucketIndex].firstItemKnownSpan // ... but try using the more localised cached values. if (lastLineIndex in currentLine..lineIndex) { // The last calculated value is a better start point. Common when scrolling main axis. currentLine = lastLineIndex currentItemIndex = lastLineStartItemIndex knownCurrentItemSpan = lastLineStartKnownSpan } else if (bucketIndex == cachedBucketIndex && lineIndex - currentLine < cachedBucket.size ) { // It happens that the needed line start is fully cached. Common when scrolling in // reverse main axis, as we decided to cacheThisBucket previously. currentItemIndex = cachedBucket[lineIndex - currentLine] currentLine = lineIndex knownCurrentItemSpan = 0 } val cacheThisBucket = currentLine % bucketSize == 0 && lineIndex - currentLine in 2 until bucketSize if (cacheThisBucket) { cachedBucketIndex = bucketIndex cachedBucket.clear() } check(currentLine <= lineIndex) while (currentLine < lineIndex && currentItemIndex < totalSize) { if (cacheThisBucket) { cachedBucket.add(currentItemIndex) } var spansUsed = 0 while (spansUsed < slotsPerLine && currentItemIndex < totalSize) { val span = if (knownCurrentItemSpan == 0) { spanOf(currentItemIndex, slotsPerLine - spansUsed) } else { knownCurrentItemSpan.also { knownCurrentItemSpan = 0 } } if (spansUsed + span > slotsPerLine) { knownCurrentItemSpan = span break } currentItemIndex++ spansUsed += span } ++currentLine if (currentLine % bucketSize == 0 && currentItemIndex < totalSize) { val currentLineBucket = currentLine / bucketSize // This should happen, as otherwise this should have been used as starting point. check(buckets.size == currentLineBucket) buckets.add(Bucket(currentItemIndex, knownCurrentItemSpan)) } } lastLineIndex = lineIndex lastLineStartItemIndex = currentItemIndex lastLineStartKnownSpan = knownCurrentItemSpan val firstItemIndex = currentItemIndex val spans = mutableListOf<TvGridItemSpan>() var spansUsed = 0 while (spansUsed < slotsPerLine && currentItemIndex < totalSize) { val span = if (knownCurrentItemSpan == 0) { spanOf(currentItemIndex, slotsPerLine - spansUsed) } else { knownCurrentItemSpan.also { knownCurrentItemSpan = 0 } } if (spansUsed + span > slotsPerLine) break currentItemIndex++ spans.add(TvGridItemSpan(span)) spansUsed += span } return LineConfiguration(firstItemIndex, spans) } /** * Calculate the line of index [itemIndex]. */ fun getLineIndexOfItem(itemIndex: Int): LineIndex { if (totalSize <= 0) { return LineIndex(0) } require(itemIndex < totalSize) if (!itemProvider.hasCustomSpans) { return LineIndex(itemIndex / slotsPerLine) } val lowerBoundBucket = buckets.binarySearch { it.firstItemIndex - itemIndex }.let { if (it >= 0) it else -it - 2 } var currentLine = lowerBoundBucket * bucketSize var currentItemIndex = buckets[lowerBoundBucket].firstItemIndex require(currentItemIndex <= itemIndex) var spansUsed = 0 while (currentItemIndex < itemIndex) { val span = spanOf(currentItemIndex++, slotsPerLine - spansUsed) if (spansUsed + span < slotsPerLine) { spansUsed += span } else if (spansUsed + span == slotsPerLine) { ++currentLine spansUsed = 0 } else { // spansUsed + span > slotsPerLine ++currentLine spansUsed = span } if (currentLine % bucketSize == 0) { val currentLineBucket = currentLine / bucketSize if (currentLineBucket >= buckets.size) { buckets.add(Bucket(currentItemIndex - if (spansUsed > 0) 1 else 0)) } } } if (spansUsed + spanOf(itemIndex, slotsPerLine - spansUsed) > slotsPerLine) { ++currentLine } return LineIndex(currentLine) } private fun spanOf(itemIndex: Int, maxSpan: Int) = with(itemProvider) { with(TvLazyGridItemSpanScopeImpl) { maxCurrentLineSpan = maxSpan maxLineSpan = slotsPerLine getSpan(itemIndex).currentLineSpan.coerceIn(1, slotsPerLine) } } private fun invalidateCache() { buckets.clear() buckets.add(Bucket(0)) lastLineIndex = 0 lastLineStartItemIndex = 0 cachedBucketIndex = -1 cachedBucket.clear() } private class Bucket( /** Index of the first item in the bucket */ val firstItemIndex: Int, /** Known span of the first item. Not zero only if this item caused "line break". */ val firstItemKnownSpan: Int = 0 ) private object TvLazyGridItemSpanScopeImpl : TvLazyGridItemSpanScope { override var maxCurrentLineSpan = 0 override var maxLineSpan = 0 } }
apache-2.0
androidx/androidx
bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothManager.kt
3
7248
/* * 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.bluetooth.core import android.bluetooth.BluetoothDevice as FwkBluetoothDevice import android.bluetooth.BluetoothGattServer as FwkBluetoothGattServer import android.bluetooth.BluetoothGattServerCallback as FwkBluetoothGattServerCallback import android.bluetooth.BluetoothManager as FwkBluetoothManager import android.bluetooth.BluetoothProfile as FwkBluetoothProfile import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.annotation.RequiresFeature import androidx.annotation.RequiresPermission /** * High level manager used to obtain an instance of an {@link BluetoothAdapter} * and to conduct overall Bluetooth Management. * <p> * Use {@link android.content.Context#getSystemService(java.lang.String)} * with {@link Context#BLUETOOTH_SERVICE} to create an {@link BluetoothManager}, * then call {@link #getAdapter} to obtain the {@link BluetoothAdapter}. * </p> * <div class="special reference"> * <h3>Developer Guides</h3> * <p> * For more information about using BLUETOOTH, read the <a href= * "{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer * guide. * </p> * </div> * * @see Context#getSystemService * @see BluetoothAdapter#getDefaultAdapter() * * @hide */ // @SystemService(Context.BLUETOOTH_SERVICE) @RequiresFeature( name = PackageManager.FEATURE_BLUETOOTH, enforcement = "android.content.pm.PackageManager#hasSystemFeature" ) class BluetoothManager(context: Context) { companion object { private const val TAG = "BluetoothManager" private const val DBG = false } private val fwkBluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as FwkBluetoothManager /** * Get the BLUETOOTH Adapter for this device. * * @return the BLUETOOTH Adapter */ fun getAdapter(): BluetoothAdapter? { return BluetoothAdapter(fwkBluetoothManager.adapter ?: return null) } /** * Get the current connection state of the profile to the remote device. * * * This is not specific to any application configuration but represents * the connection state of the local Bluetooth adapter for certain profile. * This can be used by applications like status bar which would just like * to know the state of Bluetooth. * * @param device Remote bluetooth device. * @param profile GATT or GATT_SERVER * @return State of the profile connection. One of [FwkBluetoothProfile.STATE_CONNECTED], * [FwkBluetoothProfile.STATE_CONNECTING], [FwkBluetoothProfile.STATE_DISCONNECTED], * [FwkBluetoothProfile.STATE_DISCONNECTING] * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getConnectionState(device: FwkBluetoothDevice, profile: Int): Int { return fwkBluetoothManager.getConnectionState(device, profile) } /** * Get connected devices for the specified profile. * * * Return the set of devices which are in state [FwkBluetoothProfile.STATE_CONNECTED] * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available * * * This is not specific to any application configuration but represents * the connection state of Bluetooth for this profile. * This can be used by applications like status bar which would just like * to know the state of Bluetooth. * * @param profile GATT or GATT_SERVER * @return List of devices. The list will be empty on error. */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getConnectedDevices(profile: Int): List<FwkBluetoothDevice> { return fwkBluetoothManager.getConnectedDevices(profile) } /** * Get a list of devices that match any of the given connection * states. * * * If none of the devices match any of the given states, * an empty list will be returned. * * * This is not specific to any application configuration but represents * the connection state of the local Bluetooth adapter for this profile. * This can be used by applications like status bar which would just like * to know the state of the local adapter. * * @param profile GATT or GATT_SERVER * @param states Array of states. States can be one of [FwkBluetoothProfile.STATE_CONNECTED], * [FwkBluetoothProfile.STATE_CONNECTING], [FwkBluetoothProfile.STATE_DISCONNECTED], * [FwkBluetoothProfile.STATE_DISCONNECTING], * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available * @return List of devices. The list will be empty on error. */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getDevicesMatchingConnectionStates( profile: Int, states: IntArray ): List<FwkBluetoothDevice> { return fwkBluetoothManager.getDevicesMatchingConnectionStates(profile, states) } /** * Open a GATT Server * The callback is used to deliver results to Caller, such as connection status as well * as the results of any other GATT server operations. * The method returns a BluetoothGattServer instance. You can use BluetoothGattServer * to conduct GATT server operations. * * @param context App context * @param callback GATT server callback handler that will receive asynchronous callbacks. * @return BluetoothGattServer instance */ // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothGattServerCallback to core.BluetoothGattServerCallback when it is available // TODO(ofy) Change FwkBluetoothGattServer to core.BluetoothGattServer when it is available fun openGattServer( context: Context, callback: FwkBluetoothGattServerCallback ): FwkBluetoothGattServer { return fwkBluetoothManager.openGattServer(context, callback) } }
apache-2.0
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/platform/client/request/UpsertExerciseRouteRequest.kt
3
1808
/* * Copyright (C) 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.health.platform.client.request import android.os.Parcelable import androidx.health.platform.client.impl.data.ProtoParcelable import androidx.health.platform.client.proto.DataProto import androidx.health.platform.client.proto.RequestProto /** * Internal parcelable for IPC calls. * * @suppress */ class UpsertExerciseRouteRequest(val sessionUid: String, val route: DataProto.DataPoint) : ProtoParcelable<RequestProto.UpsertExerciseRouteRequest>() { override val proto: RequestProto.UpsertExerciseRouteRequest get() { val obj = this return RequestProto.UpsertExerciseRouteRequest.newBuilder() .setSessionUid(obj.sessionUid) .setExerciseRoute(obj.route) .build() } companion object { @JvmField val CREATOR: Parcelable.Creator<UpsertExerciseRouteRequest> = ProtoParcelable.newCreator { val proto = RequestProto.UpsertExerciseRouteRequest.parseFrom(it) fromProto(proto) } internal fun fromProto( proto: RequestProto.UpsertExerciseRouteRequest, ): UpsertExerciseRouteRequest { return UpsertExerciseRouteRequest(proto.sessionUid, proto.exerciseRoute) } } }
apache-2.0
jean79/yested
src/main/kotlin/net/yested/layout/containers/horizontal.kt
2
3071
package net.yested.layout.containers import jquery.jq import net.yested.* import net.yested.utils.css import net.yested.utils.registerResizeHandler import org.w3c.dom.HTMLElement class HorizontalContainer(width: Dimension, val height: Dimension? = null, val gap:Int = 0) : Component { private val items = arrayListOf<ContainerItem>() override val element = createElement("div") with { setAttribute("style", "position: relative; width: ${width.toHtml()}; height: ${height?.toHtml() ?: ""};") } init { element.whenAddedToDom { recalculatePositions() registerResizeHandler(element.parentNode as HTMLElement) { x, y -> recalculatePositions() } } } private fun needToCalculateHeight() = height == null fun column(width: Dimension, height: Dimension? = null, init: HTMLComponent.() -> Unit) { val child = Div() with { style = "position: absolute; overflow-x: hidden; height: ${height?.toHtml()};" init() } if (items.size > 0 && gap > 0) { val gap = createElement("div") with { setAttribute("style", "width: ${gap}px;")} element.appendChild(gap) } items.add(ContainerItem(child, width)) element.appendChild(child.element) recalculatePositions() if (needToCalculateHeight()) { recalculateHeight() registerResizeHandler(child.element) { x, y -> recalculateHeight() } } } private fun recalculatePositions() { val gaps = (items.size - 1) * gap val totalDimension = jq(element).width() val totalFixed = items.filter { it.dimension is Pixels }.map { (it.dimension as Pixels).value }.sum() val totalPercents = items.filter { it.dimension is Percent }.map { (it.dimension as Percent).value }.sum() val dimensionAvailableToPct = totalDimension.toInt() - totalFixed - gaps var position = 0 items.forEach { item -> val calculatedDimension: Int = if (item.dimension is Pixels) { item.dimension.value } else if (item.dimension is Percent) { (item.dimension.value / totalPercents * dimensionAvailableToPct).toInt() } else { throw Exception("Unsupported dimension type for horizontal column width: ${item.dimension}") } jq(item.div.element).css("left", "${position}px") jq(item.div.element).css("width", "${calculatedDimension}px") position += calculatedDimension + gap } } private fun recalculateHeight() { val maxHeightOfChildren = items.map { jq(it.div.element).height().toInt() }.max() jq(element).css("height", "$maxHeightOfChildren") } } fun HTMLComponent.horizontalContainer(width: Dimension, height: Dimension? = null, gap: Int = 0, init: HorizontalContainer.() -> Unit) { +(HorizontalContainer(width = width, height = height, gap = gap) with { init() }) }
mit
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_compute_shader.kt
1
4627
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_compute_shader = "ARBComputeShader".nativeClassGL("ARB_compute_shader") { documentation = """ Native bindings to the $registryLink extension. Recent graphics hardware has become extremely powerful and a strong desire to harness this power for work (both graphics and non-graphics) that does not fit the traditional graphics pipeline well has emerged. To address this, this extension adds a new single-stage program type known as a compute program. This program may contain one or more compute shaders which may be launched in a manner that is essentially stateless. This allows arbitrary workloads to be sent to the graphics hardware with minimal disturbance to the GL state machine. In most respects, a compute program is identical to a traditional OpenGL program object, with similar status, uniforms, and other such properties. It has access to many of the same resources as fragment and other shader types, such as textures, image variables, atomic counters, and so on. However, it has no predefined inputs nor any fixed-function outputs. It cannot be part of a pipeline and its visible side effects are through its actions on images and atomic counters. OpenCL is another solution for using graphics processors as generalized compute devices. This extension addresses a different need. For example, OpenCL is designed to be usable on a wide range of devices ranging from CPUs, GPUs, and DSPs through to FPGAs. While one could implement GL on these types of devices, the target here is clearly GPUs. Another difference is that OpenCL is more full featured and includes features such as multiple devices, asynchronous queues and strict IEEE semantics for floating point operations. This extension follows the semantics of OpenGL - implicitly synchronous, in-order operation with single-device, single queue logical architecture and somewhat more relaxed numerical precision requirements. Although not as feature rich, this extension offers several advantages for applications that can tolerate the omission of these features. Compute shaders are written in GLSL, for example and so code may be shared between compute and other shader types. Objects are created and owned by the same context as the rest of the GL, and therefore no interoperability API is required and objects may be freely used by both compute and graphics simultaneously without acquire-release semantics or object type translation. Requires ${GL42.core}. ${GL43.promoted} """ IntConstant( "Accepted by the {@code type} parameter of CreateShader and returned in the {@code params} parameter by GetShaderiv.", "COMPUTE_SHADER"..0x91B9 ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetFloatv, GetDoublev and GetInteger64v.", "MAX_COMPUTE_UNIFORM_BLOCKS"..0x91BB, "MAX_COMPUTE_TEXTURE_IMAGE_UNITS"..0x91BC, "MAX_COMPUTE_IMAGE_UNIFORMS"..0x91BD, "MAX_COMPUTE_SHARED_MEMORY_SIZE"..0x8262, "MAX_COMPUTE_UNIFORM_COMPONENTS"..0x8263, "MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS"..0x8264, "MAX_COMPUTE_ATOMIC_COUNTERS"..0x8265, "MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS"..0x8266, "MAX_COMPUTE_WORK_GROUP_INVOCATIONS"..0x90EB ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegeri_v, GetBooleani_v, GetFloati_v, GetDoublei_v and GetInteger64i_v.", "MAX_COMPUTE_WORK_GROUP_COUNT"..0x91BE, "MAX_COMPUTE_WORK_GROUP_SIZE"..0x91BF ) IntConstant( "Accepted by the {@code pname} parameter of GetProgramiv.", "COMPUTE_WORK_GROUP_SIZE"..0x8267 ) IntConstant( "Accepted by the {@code pname} parameter of GetActiveUniformBlockiv.", "UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER"..0x90EC ) IntConstant( "Accepted by the {@code pname} parameter of GetActiveAtomicCounterBufferiv.", "ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER"..0x90ED ) IntConstant( "Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and GetBufferPointerv.", "DISPATCH_INDIRECT_BUFFER"..0x90EE ) IntConstant( "Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetInteger64v, GetFloatv, and GetDoublev.", "DISPATCH_INDIRECT_BUFFER_BINDING"..0x90EF ) IntConstant( "Accepted by the {@code stages} parameter of UseProgramStages.", "COMPUTE_SHADER_BIT"..0x00000020 ) GL43 reuse "DispatchCompute" GL43 reuse "DispatchComputeIndirect" }
bsd-3-clause
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/inspection/MixinCancellableInspection.kt
1
5319
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.INJECT import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO_RETURNABLE import com.demonwav.mcdev.util.fullQualifiedName import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiExpressionList import com.intellij.psi.PsiFile import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiUtil class MixinCancellableInspection : MixinInspection() { override fun getStaticDescription(): String = "Reports missing or unused cancellable @Inject usages" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { val injectAnnotation = method.getAnnotation(INJECT) ?: return val cancellableAttribute = injectAnnotation.findAttributeValue("cancellable") as? PsiLiteral ?: return val isCancellable = cancellableAttribute.value == true val ciParam = method.parameterList.parameters.firstOrNull { val className = (it.type as? PsiClassType)?.fullQualifiedName ?: return@firstOrNull false className == CALLBACK_INFO || className == CALLBACK_INFO_RETURNABLE } ?: return val ciType = (ciParam.type as? PsiClassType)?.resolve() ?: return val searchingFor = ciType.findMethodsByName("setReturnValue", false).firstOrNull() ?: ciType.findMethodsByName("cancel", false).firstOrNull() ?: return var mayUseCancel = false var definitelyUsesCancel = false for (ref in ReferencesSearch.search(ciParam)) { val parent = PsiUtil.skipParenthesizedExprUp(ref.element.parent) if (parent is PsiExpressionList) { // method argument, we can't tell whether it uses cancel mayUseCancel = true } val methodCall = parent as? PsiReferenceExpression ?: continue if (methodCall.references.any { it.isReferenceTo(searchingFor) }) { definitelyUsesCancel = true break } } if (definitelyUsesCancel && !isCancellable) { holder.registerProblem( method.nameIdentifier ?: method, "@Inject must be marked as cancellable in order to be cancelled", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, MakeInjectCancellableFix(injectAnnotation) ) } else if (!definitelyUsesCancel && !mayUseCancel && isCancellable) { holder.registerProblem( cancellableAttribute.parent, "@Inject is cancellable but is never cancelled", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, RemoveInjectCancellableFix(injectAnnotation) ) } } } private class MakeInjectCancellableFix(element: PsiAnnotation) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Mark as cancellable" override fun getText(): String = familyName override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val annotation = startElement as PsiAnnotation val value = PsiElementFactory.getInstance(project).createExpressionFromText("true", annotation) annotation.setDeclaredAttributeValue("cancellable", value) } } private class RemoveInjectCancellableFix(element: PsiAnnotation) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Remove unused cancellable attribute" override fun getText(): String = familyName override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val annotation = startElement as PsiAnnotation annotation.setDeclaredAttributeValue("cancellable", null) } } }
mit
minecraft-dev/MinecraftDev
src/main/kotlin/util/bytecode-utils.kt
1
5239
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiType import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.TypeConversionUtil private const val INTERNAL_CONSTRUCTOR_NAME = "<init>" // Type val PsiPrimitiveType.internalName: Char get() = when (this) { PsiType.BYTE -> 'B' PsiType.CHAR -> 'C' PsiType.DOUBLE -> 'D' PsiType.FLOAT -> 'F' PsiType.INT -> 'I' PsiType.LONG -> 'J' PsiType.SHORT -> 'S' PsiType.BOOLEAN -> 'Z' PsiType.VOID -> 'V' else -> throw IllegalArgumentException("Unsupported primitive type: $this") } fun getPrimitiveType(internalName: Char): PsiPrimitiveType? { return when (internalName) { 'B' -> PsiType.BYTE 'C' -> PsiType.CHAR 'D' -> PsiType.DOUBLE 'F' -> PsiType.FLOAT 'I' -> PsiType.INT 'J' -> PsiType.LONG 'S' -> PsiType.SHORT 'Z' -> PsiType.BOOLEAN 'V' -> PsiType.VOID else -> null } } val PsiType.descriptor get() = appendDescriptor(StringBuilder()).toString() fun getPrimitiveWrapperClass(internalName: Char, project: Project): PsiClass? { val type = getPrimitiveType(internalName) ?: return null val boxedTypeName = type.boxedTypeName ?: return null return JavaPsiFacade.getInstance(project).findClass(boxedTypeName, GlobalSearchScope.allScope(project)) } private fun PsiClassType.erasure() = TypeConversionUtil.erasure(this) as PsiClassType @Throws(ClassNameResolutionFailedException::class) private fun PsiClassType.appendInternalName(builder: StringBuilder): StringBuilder = erasure().resolve()?.appendInternalName(builder) ?: builder @Throws(ClassNameResolutionFailedException::class) private fun PsiType.appendDescriptor(builder: StringBuilder): StringBuilder { return when (this) { is PsiPrimitiveType -> builder.append(internalName) is PsiArrayType -> componentType.appendDescriptor(builder.append('[')) is PsiClassType -> appendInternalName(builder.append('L')).append(';') else -> throw IllegalArgumentException("Unsupported PsiType: $this") } } fun parseClassDescriptor(descriptor: String): String { val internalName = descriptor.substring(1, descriptor.length - 1) return internalName.replace('/', '.') } // Class val PsiClass.internalName: String? get() { realName?.let { return it } return try { outerQualifiedName?.replace('.', '/') ?: buildInternalName(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiClass.appendInternalName(builder: StringBuilder): StringBuilder { return outerQualifiedName?.let { builder.append(it.replace('.', '/')) } ?: buildInternalName(builder) } @Throws(ClassNameResolutionFailedException::class) private fun PsiClass.buildInternalName(builder: StringBuilder): StringBuilder { buildInnerName(builder, { it.outerQualifiedName?.replace('.', '/') }) return builder } val PsiClass.descriptor: String? get() { return try { appendInternalName(StringBuilder().append('L')).append(';').toString() } catch (e: ClassNameResolutionFailedException) { null } } fun PsiClass.findMethodsByInternalName(internalName: String, checkBases: Boolean = false): Array<PsiMethod> { return if (internalName == INTERNAL_CONSTRUCTOR_NAME) { constructors } else { findMethodsByName(internalName, checkBases) } } // Method val PsiMethod.internalName: String get() { val realName = realName return when { isConstructor -> INTERNAL_CONSTRUCTOR_NAME realName != null -> realName else -> name } } val PsiMethod.descriptor: String? get() { return try { appendDescriptor(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiMethod.appendDescriptor(builder: StringBuilder): StringBuilder { builder.append('(') for (parameter in parameterList.parameters) { parameter.type.appendDescriptor(builder) } builder.append(')') return (returnType ?: PsiType.VOID).appendDescriptor(builder) } // Field val PsiField.descriptor: String? get() { return try { appendDescriptor(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiField.appendDescriptor(builder: StringBuilder): StringBuilder = type.appendDescriptor(builder)
mit
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/anime/resolver/DailymotionStreamResolver.kt
2
3106
package me.proxer.app.anime.resolver import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonEncodingException import io.reactivex.Single import me.proxer.app.MainApplication.Companion.GENERIC_USER_AGENT import me.proxer.app.exception.StreamResolutionException import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.toBodySingle import me.proxer.app.util.extension.toPrefixedUrlOrNull import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import java.util.regex.Pattern.quote /** * @author Ruben Gees */ object DailymotionStreamResolver : StreamResolver() { private val regex = Regex("\"qualities\":(${quote("{")}.+${quote("}")}${quote("]")}${quote("}")}),") override val name = "Dailymotion" @Suppress("SwallowedException") override fun resolve(id: String): Single<StreamResolutionResult> { return api.anime.link(id) .buildSingle() .flatMap { url -> client.newCall( Request.Builder() .get() .url(url.toPrefixedUrlOrNull() ?: throw StreamResolutionException()) .header("User-Agent", GENERIC_USER_AGENT) .header("Connection", "close") .build() ) .toBodySingle() } .map { html -> val qualitiesJson = regex.find(html)?.value ?: throw StreamResolutionException() val qualityMap = try { moshi.adapter(DailymotionQualityMap::class.java) .fromJson("{${qualitiesJson.trimEnd(',')}}") ?: throw StreamResolutionException() } catch (error: JsonDataException) { throw StreamResolutionException() } catch (error: JsonEncodingException) { throw StreamResolutionException() } val link = qualityMap.qualities .flatMap { (quality, links) -> links.mapNotNull { (type, url) -> url.toHttpUrlOrNull()?.let { DailymotionLinkWithQuality(quality, type, it) } } } .filter { it.type == "application/x-mpegURL" || it.type == "video/mp4" } .sortedWith(compareBy<DailymotionLinkWithQuality> { it.type }.thenByDescending { it.quality }) .firstOrNull() ?: throw StreamResolutionException() StreamResolutionResult.Video(link.url, link.type) } } @JsonClass(generateAdapter = true) internal data class DailymotionQualityMap(val qualities: Map<String, Array<DailymotionLink>>) @JsonClass(generateAdapter = true) internal data class DailymotionLink(val type: String, val url: String) private data class DailymotionLinkWithQuality(val quality: String, val type: String, val url: HttpUrl) }
gpl-3.0
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/MyApp.kt
1
1870
package nerd.tuxmobil.fahrplan.congress import androidx.annotation.CallSuper import androidx.multidex.MultiDexApplication import info.metadude.android.eventfahrplan.commons.logging.Logging import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.ConferenceTimeFrame import org.ligi.tracedroid.TraceDroid import java.util.Calendar import java.util.GregorianCalendar import java.util.TimeZone class MyApp : MultiDexApplication() { enum class TASKS { NONE, FETCH, PARSE } companion object { private val FIRST_DAY_START = getMilliseconds( "Europe/Paris", BuildConfig.SCHEDULE_FIRST_DAY_START_YEAR, BuildConfig.SCHEDULE_FIRST_DAY_START_MONTH, BuildConfig.SCHEDULE_FIRST_DAY_START_DAY ) private val LAST_DAY_END = getMilliseconds( "Europe/Paris", BuildConfig.SCHEDULE_LAST_DAY_END_YEAR, BuildConfig.SCHEDULE_LAST_DAY_END_MONTH, BuildConfig.SCHEDULE_LAST_DAY_END_DAY ) private fun getMilliseconds(timeZoneId: String, year: Int, month: Int, day: Int): Long { val zeroBasedMonth = month - 1 val zone = TimeZone.getTimeZone(timeZoneId) return GregorianCalendar(zone).apply { set(year, zeroBasedMonth, day, 0, 0, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis } val conferenceTimeFrame = ConferenceTimeFrame(FIRST_DAY_START, LAST_DAY_END) @JvmField var taskRunning = TASKS.NONE } @CallSuper override fun onCreate() { super.onCreate() TraceDroid.init(this) taskRunning = TASKS.NONE AppRepository.initialize( context = applicationContext, logging = Logging.get() ) } }
apache-2.0
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/notification/AccountNotificationEvent.kt
2
97
package me.proxer.app.notification /** * @author Ruben Gees */ class AccountNotificationEvent
gpl-3.0
RobotPajamas/Blueteeth
blueteeth-sample/src/main/kotlin/com/robotpajamas/android/blueteeth/ui/device/DeviceActivity.kt
1
825
package com.robotpajamas.android.blueteeth.ui.device import android.app.Activity import androidx.databinding.DataBindingUtil import android.os.Bundle import com.robotpajamas.android.blueteeth.R import com.robotpajamas.android.blueteeth.databinding.ActivityDeviceBinding class DeviceActivity : Activity(), DeviceViewModel.Navigator { private val vm by lazy { val macAddress = intent.getStringExtra(getString(R.string.extra_mac_address)) ?: "" DeviceViewModel(macAddress, this) } private lateinit var binding: ActivityDeviceBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_device) binding.vm = vm } override fun navigateBack() { } }
apache-2.0
adgvcxz/Diycode
app/src/main/java/com/adgvcxz/diycode/bean/Abilities.kt
1
282
package com.adgvcxz.diycode.bean import com.google.gson.annotations.SerializedName /** * zhaowei * Created by zhaowei on 2017/2/27. */ class Abilities { @SerializedName("update") var isUpdate: Boolean = false @SerializedName("destroy") var isDestroy: Boolean = false }
apache-2.0
inorichi/tachiyomi-extensions
src/id/nyanfm/src/eu/kanade/tachiyomi/extension/id/nyanfm/NyanFM.kt
1
5135
package eu.kanade.tachiyomi.extension.id.nyanfm import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList 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.ParsedHttpSource import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class NyanFM : ParsedHttpSource() { override val name = "Nyan FM" override val baseUrl = "https://nyanfm.com" override val lang = "id" override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient // popular override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/scanlation/", headers) } override fun popularMangaSelector() = ".elementor-column .elementor-widget-wrap .elementor-widget-container .elementor-cta:has(.elementor-cta__bg)" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select(".elementor-cta__bg-wrapper .elementor-cta__bg").attr("style").substringAfter("(").substringBefore(")") manga.url = element.select(".elementor-cta__content a.elementor-button").attr("href").substringAfter(".com") manga.title = element.select(".elementor-cta__content h2").text().trim() return manga } override fun popularMangaNextPageSelector() = "#nav-below .nav-links .next.page-numbers" // latest override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException() override fun latestUpdatesSelector(): String = throw UnsupportedOperationException() override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException() override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException() // search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("https://nyanfm.com/page/$page/?s=$query") } override fun searchMangaSelector() = "#main article .inside-article:has(.entry-summary:has(a))" override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select(".post-image img").attr("src") element.select(".entry-summary:has(p) a").let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun searchMangaNextPageSelector() = ".nav-links .next" // manga details override fun mangaDetailsParse(document: Document): SManga { return SManga.create().apply { document.select(".entry-content div.elementor-section-wrap").firstOrNull()?.let { infoElement -> thumbnail_url = infoElement.select("div.elementor-widget-wrap div.elementor-element.elementor-hidden-tablet.elementor-widget img").attr("src") title = infoElement.select("h1").text().trim() artist = infoElement.select("div.elementor-element:has(h3:contains(author)) + div.elementor-element p").firstOrNull()?.ownText() status = parseStatus(infoElement.select("div.elementor-element:has(h3:contains(status)) + div.elementor-element p").text()) genre = infoElement.select("div.elementor-element:has(h3:contains(genre)) + div.elementor-element p").joinToString(", ") { it.text() } description = infoElement.select("div.elementor-element:has(h3:contains(sinopsis)) + div.elementor-element p").joinToString("\n") { it.text() } } } } private fun parseStatus(element: String): Int = when { element.toLowerCase().contains("ongoing") -> SManga.ONGOING element.toLowerCase().contains("completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } // chapters override fun chapterListSelector() = "table tbody tr" override fun chapterFromElement(element: Element) = SChapter.create().apply { element.select("td:last-child a").let { name = it.text() url = it.attr("href").substringAfter(baseUrl) } date_upload = parseChapterDate(element.select("td:first-child").text()) } private fun parseChapterDate(date: String): Long { return SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH).parse(date)?.time ?: 0L } // pages override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select("div.elementor-widget-container > div.elementor-image a > img.attachment-large.size-large").forEach { element -> val url = element.attr("src") i++ if (url.isNotEmpty()) { pages.add(Page(i, "", url)) } } return pages } override fun imageUrlParse(document: Document) = "" }
apache-2.0
VKCOM/vk-android-sdk
core/src/main/java/com/vk/api/sdk/okhttp/RequestTag.kt
1
1761
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.vk.api.sdk.okhttp data class RequestTag @JvmOverloads constructor(val uid: Long? = null, val awaitNetwork: Boolean? = null, val reason: String? = null, val retryCount: Int? = null) { fun toMap(): Map<String, Any?>? { return mutableMapOf( "UID" to uid, "AWAIT_NETWORK" to awaitNetwork, "REASON" to reason, "RETRY_COUNT" to retryCount) } }
mit
inorichi/tachiyomi-extensions
multisrc/overrides/madara/zinmanga/src/ZinManga.kt
1
326
package eu.kanade.tachiyomi.extension.en.zinmanga import eu.kanade.tachiyomi.multisrc.madara.Madara import okhttp3.Headers class ZinManga : Madara("Zin Translator", "https://zinmanga.com", "en") { override fun headersBuilder(): Headers.Builder = super.headersBuilder() .add("Referer", "https://zinmanga.com/") }
apache-2.0
raxden/square
sample/src/main/java/com/raxdenstudios/square/sample/commons/FragmentNavigationDrawerActivity.kt
2
5034
package com.raxdenstudios.square.sample.commons import android.content.res.Configuration import android.os.Bundle import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Gravity import android.view.Menu import android.view.View import com.raxdenstudios.square.interceptor.Interceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.AutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.HasAutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.injectfragment.HasInjectFragmentInterceptor import com.raxdenstudios.square.interceptor.commons.injectfragment.InjectFragmentInterceptor import com.raxdenstudios.square.interceptor.commons.fragmentnavigationdrawer.HasFragmentNavigationDrawerInterceptor import com.raxdenstudios.square.interceptor.commons.fragmentnavigationdrawer.FragmentNavigationDrawerInterceptor import kotlinx.android.synthetic.main.fragment_navigation_drawer_activity.* class FragmentNavigationDrawerActivity : AppCompatActivity(), HasAutoInflateLayoutInterceptor, HasInjectFragmentInterceptor<InjectedFragment>, HasFragmentNavigationDrawerInterceptor<InjectedFragment> { private lateinit var mAutoInflateLayoutInterceptor: AutoInflateLayoutInterceptor private lateinit var mInjectFragmentInterceptor: InjectFragmentInterceptor private lateinit var mFragmentNavigationDrawerInterceptor: FragmentNavigationDrawerInterceptor var mContentView: View? = null var mToolbarView: Toolbar? = null var mInjectedLeftFragment: InjectedFragment? = null var mInjectedRightFragment: InjectedFragment? = null var mInjectedContentFragment: InjectedFragment? = null override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) mFragmentNavigationDrawerInterceptor.onConfigurationChanged(newConfig) } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { mFragmentNavigationDrawerInterceptor.onPrepareOptionsMenu(menu) return super.onPrepareOptionsMenu(menu) } override fun onBackPressed() { if (!mFragmentNavigationDrawerInterceptor.onBackPressed()) super.onBackPressed() } // ======== HasInflateLayoutInterceptor ==================================================== override fun onContentViewCreated(view: View) { mContentView = view } // ======== HasToolbarInterceptor ============================================================== override fun onCreateToolbarView(): Toolbar = toolbar_view override fun onToolbarViewCreated(toolbar: Toolbar) { mToolbarView = toolbar } // ======== HasFloatingActionButtonFragmentInterceptor ======================================================= override fun onLoadFragmentContainer(): View = container_view override fun onCreateFragment(): InjectedFragment = InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment") }) override fun onFragmentLoaded(fragment: InjectedFragment) { mInjectedContentFragment = fragment } // ======== HasFragmentNavigationDrawerInterceptor ======================================================= override fun onCreateContentDrawerFragment(gravity: Int): InjectedFragment = when (gravity) { Gravity.START -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment LEFT") }) Gravity.END -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment RIGHT") }) else -> InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment LEFT") }) } override fun onContentDrawerFragmentLoaded(gravity: Int, fragment: InjectedFragment) { when (gravity) { Gravity.START -> mInjectedLeftFragment = fragment Gravity.END -> mInjectedRightFragment = fragment } } override fun onCreateContentDrawerView(gravity: Int): View = when (gravity) { Gravity.START -> left_offscreen_container Gravity.END -> right_offscreen_container else -> left_offscreen_container } override fun onCreateDrawerLayout(): DrawerLayout = drawer_layout override fun onDrawerLayoutCreated(drawerLayout: DrawerLayout) {} override fun onActionBarDrawerToggleCreated(drawerToggle: ActionBarDrawerToggle) {} // ============================================================================================= override fun onInterceptorCreated(interceptor: Interceptor) { when (interceptor) { is AutoInflateLayoutInterceptor -> mAutoInflateLayoutInterceptor = interceptor is InjectFragmentInterceptor -> mInjectFragmentInterceptor = interceptor is FragmentNavigationDrawerInterceptor -> mFragmentNavigationDrawerInterceptor = interceptor } } }
apache-2.0
ligee/kotlin-jupyter
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/JREInfoProvider.kt
1
1165
package org.jetbrains.kotlinx.jupyter.api /** * Provides information about used Java runtime */ interface JREInfoProvider { /** * JRE version, i.e. "1.8" or "11" */ val version: String /** * JRE version as integer, i.e. 8 or 11 */ val versionAsInt: Int /** * Does nothing if [condition] returns true for current JRE version, throws [AssertionError] otherwise * * @param message Exception message * @param condition Condition to check */ fun assertVersion(message: String = "JRE version requirements are not satisfied", condition: (Int) -> Boolean) /** * Does nothing if current JRE version is higher or equal than [minVersion], throws [AssertionError] otherwise * * @param minVersion Minimal accepted version */ fun assertVersionAtLeast(minVersion: Int) /** * Does nothing if current JRE version is between [minVersion] and [maxVersion], throws [AssertionError] otherwise * * @param minVersion Minimal accepted version * @param maxVersion Maximal accepted version */ fun assertVersionInRange(minVersion: Int, maxVersion: Int) }
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/test/uk/co/reecedunn/intellij/plugin/xpath/tests/lang/highlighter/AnnotatorTestCase.kt
1
1328
/* * Copyright (C) 2016-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.xpath.tests.lang.highlighter import com.intellij.lang.LanguageASTFactory import uk.co.reecedunn.intellij.plugin.core.tests.parser.AnnotatorTestCase import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPath import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathASTFactory import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition abstract class AnnotatorTestCase : AnnotatorTestCase<XPath>("xqy", XPathParserDefinition()) { override fun registerServicesAndExtensions() { super.registerServicesAndExtensions() addExplicitExtension( LanguageASTFactory.INSTANCE, xqt.platform.intellij.xpath.XPath, XPathASTFactory() ) } }
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/context/XpmUsageType.kt
1
2160
/* * Copyright (C) 2018, 2020-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.xpm.context import uk.co.reecedunn.intellij.plugin.xdm.resources.XdmBundle import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType enum class XpmUsageType(val label: String, val namespaceType: XdmNamespaceType) { Annotation(XdmBundle.message("usage-type.annotation"), XdmNamespaceType.XQuery), Attribute(XdmBundle.message("usage-type.attribute"), XdmNamespaceType.None), DecimalFormat(XdmBundle.message("usage-type.decimal-format"), XdmNamespaceType.None), Element(XdmBundle.message("usage-type.element"), XdmNamespaceType.DefaultElement), FunctionDecl(XdmBundle.message("usage-type.function"), XdmNamespaceType.DefaultFunctionDecl), FunctionRef(XdmBundle.message("usage-type.function"), XdmNamespaceType.DefaultFunctionRef), MapKey(XdmBundle.message("usage-type.map-key"), XdmNamespaceType.None), Namespace(XdmBundle.message("usage-type.namespace"), XdmNamespaceType.None), Option(XdmBundle.message("usage-type.option"), XdmNamespaceType.XQuery), Parameter(XdmBundle.message("usage-type.parameter"), XdmNamespaceType.None), Pragma(XdmBundle.message("usage-type.pragma"), XdmNamespaceType.None), ProcessingInstruction(XdmBundle.message("usage-type.processing-instruction"), XdmNamespaceType.None), Type(XdmBundle.message("usage-type.type"), XdmNamespaceType.DefaultType), Unknown(XdmBundle.message("usage-type.identifier"), XdmNamespaceType.Undefined), Variable(XdmBundle.message("usage-type.variable"), XdmNamespaceType.None) }
apache-2.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathPostfixExprPsiImpl.kt
1
1659
/* * Copyright (C) 2016-2018, 2020-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.xpath.psi.impl.xpath import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNodeItem import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathPostfixExpr import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmAxisType class XPathPostfixExprPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathPostfixExpr { // region XpmPathStep override val axisType: XpmAxisType = XpmAxisType.Self override val nodeName: XsQNameValue? = null override val nodeType: XdmItemType = XdmNodeItem override val predicateExpression: XpmExpression? = null // endregion // region XpmExpression override val expressionElement: PsiElement? = null // endregion }
apache-2.0
PublicXiaoWu/XiaoWuMySelf
app/src/main/java/com/xiaowu/myself/main/mvp/contract/MainContract.kt
1
378
package com.xiaowu.myself.main.mvp.contract import com.xiaowu.myself.app.base.BasePresenter import com.xiaowu.myself.app.base.BaseView /** * 作者:Administrator on 2017/9/7 16:06 * 邮箱:[email protected] */ interface MainContract { interface Model { } interface View : BaseView<Presenter> { } interface Presenter : BasePresenter { } }
apache-2.0
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/adapters/DailyListAdapter.kt
1
707
package com.habitrpg.wearos.habitica.ui.adapters import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.databinding.RowDailyBinding import com.habitrpg.wearos.habitica.ui.viewHolders.tasks.DailyViewHolder class DailyListAdapter: TaskListAdapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == 1) { return DailyViewHolder(RowDailyBinding.inflate(parent.context.layoutInflater, parent, false).root) } else { super.onCreateViewHolder(parent, viewType) } } }
gpl-3.0
Zeyad-37/GenericUseCase
usecases/src/main/java/com/zeyad/usecases/exceptions/NetworkConnectionException.kt
2
367
package com.zeyad.usecases.exceptions /** * Exception throw by the application when a there is a network connection exception. */ class NetworkConnectionException(message: String) : Exception(message), IErrorBundle { override fun message(): String { return localizedMessage } override fun exception(): Exception { return this } }
apache-2.0
kazhida/kotos2d
src/jp/kazhida/kotos2d/Kotos2dActivity.kt
1
2288
package jp.kazhida.kotos2d import android.app.Activity import android.content.Context import android.os.Build import android.util.Log import android.os.Message import android.os.Bundle import android.widget.FrameLayout import android.view.ViewGroup /** * Created by kazhida on 2013/07/27. */ public abstract class Kotos2dActivity : Activity(), Kotos2dHelper.HelperListener { class object { val TAG = javaClass<Kotos2dActivity>().getSimpleName() var context: Context? = null val isAndroidEmulator: Boolean get() { val model = Build.MODEL val product = Build.PRODUCT Log.d(TAG, "model=" + model + ", product=" + product) return product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_") } } var surfaceView: Kotos2dGLSurfaceView? = null val handler = Kotos2dHandler(this) open fun onCreateView(): Kotos2dGLSurfaceView { return Kotos2dGLSurfaceView(this) } override fun onCreate(savedInstanceState: Bundle?) { super<Activity>.onCreate(savedInstanceState) context = this val MP = ViewGroup.LayoutParams.MATCH_PARENT val WC = ViewGroup.LayoutParams.WRAP_CONTENT val frameLayout = FrameLayout(this) //todo: EditText関連 surfaceView = onCreateView(); surfaceView?.renderer = Kotos2dRenderer() if (isAndroidEmulator) surfaceView?.setEGLConfigChooser(8, 8, 8, 8, 16, 0) setContentView(frameLayout, ViewGroup.LayoutParams(MP, MP)) Kotos2dHelper.init(this, this) } override fun onResume() { super<Activity>.onResume() Kotos2dHelper.sharedInstance().onResume() surfaceView?.onResume() } override fun onPause() { super<Activity>.onPause() Kotos2dHelper.sharedInstance().onPause() surfaceView?.onPause() } override fun runOnGLThread(runnable: Runnable) { surfaceView?.queueEvent(runnable) } override fun showDialog(title: String, message: String) { val msg = Message() msg.what = Kotos2dHandler.HANDLE_SHOW_DIALOG msg.obj = Kotos2dHandler.DialogMessage(title, message) handler.sendMessage(msg) } }
mit
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/instance/ScopedInstanceFactory.kt
1
2329
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.koin.core.instance import org.koin.core.definition.BeanDefinition import org.koin.core.scope.Scope import org.koin.core.scope.ScopeID import org.koin.mp.KoinPlatformTools import org.koin.mp.KoinPlatformTools.safeHashMap /** * Single instance holder * @author Arnaud Giuliani */ class ScopedInstanceFactory<T>(beanDefinition: BeanDefinition<T>) : InstanceFactory<T>(beanDefinition) { private var values = hashMapOf<ScopeID,T>() override fun isCreated(context: InstanceContext?): Boolean = (values[context?.scope?.id] != null) override fun drop(scope: Scope?) { scope?.let { beanDefinition.callbacks.onClose?.invoke(values[it.id]) values.remove(it.id) } } override fun create(context: InstanceContext): T { return if (values[context.scope.id] == null) { super.create(context) } else values[context.scope.id] ?: error("Scoped instance not found for ${context.scope.id} in $beanDefinition") } override fun get(context: InstanceContext): T { if (context.scope.scopeQualifier != beanDefinition.scopeQualifier){ error("Wrong Scope: trying to open instance for ${context.scope.id} in $beanDefinition") } KoinPlatformTools.synchronized(this) { if (!isCreated(context)) { values[context.scope.id] = create(context) } } return values[context.scope.id] ?: error("Scoped instance not found for ${context.scope.id} in $beanDefinition") } override fun dropAll(){ values.clear() } fun refreshInstance(scopeID: ScopeID, instance: Any) { values[scopeID] = instance as T } }
apache-2.0
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/controlStructures/kt299.kt
5
414
class MyRange1() : ClosedRange<Int> { override val start: Int get() = 0 override val endInclusive: Int get() = 0 override fun contains(item: Int) = true } class MyRange2() { operator fun contains(item: Int) = true } fun box(): String { if (1 in MyRange1()) { if (1 in MyRange2()) { return "OK" } return "fail 2" } return "fail 1" }
apache-2.0
worker8/TourGuide
tourguide/src/main/java/tourguide/tourguide/util/StandardExtension.kt
2
394
package tourguide.tourguide.util /** * example usage: * ``` * * var recipe: String? = null * var uri: Boolean? = null * * recipe.let(uri) { recipe, uri -> * // safe usage here * } * } * ``` */ inline fun <T, T2, R> T?.letWith(secondArg: T2?, block: (T, T2) -> R): R? { return this?.let { secondArg?.let { block(this, secondArg) } } }
mit
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/di/module/NetModule.kt
1
2158
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.di.module import android.app.Application import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * Created by giulio on 06/11/2017. */ @Module class NetModule(var baseUrl: String) { @Provides @Singleton fun provideHttpCache(application: Application): Cache { val cacheSize: Long = 10 * 1024 * 1024 val cache = Cache(application.cacheDir, cacheSize) return cache } @Provides @Singleton fun provideGson(): Gson { val gsonBuilder = GsonBuilder() gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) return gsonBuilder.create() } @Provides @Singleton fun provideOkhttpClient(cache: Cache): OkHttpClient { val client = OkHttpClient.Builder() client.cache(cache) return client.build() } @Provides @Singleton fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(baseUrl) .client(okHttpClient) .build() } }
apache-2.0
da1z/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/internal/javaInternalUastUtils.kt
1
3844
/* * 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 org.jetbrains.uast.java import com.intellij.openapi.util.Key import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.impl.source.tree.CompositeElement import com.intellij.psi.tree.IElementType import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UElement import org.jetbrains.uast.UastBinaryOperator import java.lang.ref.WeakReference internal val JAVA_CACHED_UELEMENT_KEY = Key.create<WeakReference<UElement>>("cached-java-uelement") internal fun IElementType.getOperatorType() = when (this) { JavaTokenType.EQ -> UastBinaryOperator.ASSIGN JavaTokenType.PLUS -> UastBinaryOperator.PLUS JavaTokenType.MINUS -> UastBinaryOperator.MINUS JavaTokenType.ASTERISK -> UastBinaryOperator.MULTIPLY JavaTokenType.DIV -> UastBinaryOperator.DIV JavaTokenType.PERC -> UastBinaryOperator.MOD JavaTokenType.ANDAND -> UastBinaryOperator.LOGICAL_AND JavaTokenType.OROR -> UastBinaryOperator.LOGICAL_OR JavaTokenType.OR -> UastBinaryOperator.BITWISE_OR JavaTokenType.AND -> UastBinaryOperator.BITWISE_AND JavaTokenType.XOR -> UastBinaryOperator.BITWISE_XOR JavaTokenType.EQEQ -> UastBinaryOperator.IDENTITY_EQUALS JavaTokenType.NE -> UastBinaryOperator.IDENTITY_NOT_EQUALS JavaTokenType.GT -> UastBinaryOperator.GREATER JavaTokenType.GE -> UastBinaryOperator.GREATER_OR_EQUALS JavaTokenType.LT -> UastBinaryOperator.LESS JavaTokenType.LE -> UastBinaryOperator.LESS_OR_EQUALS JavaTokenType.LTLT -> UastBinaryOperator.SHIFT_LEFT JavaTokenType.GTGT -> UastBinaryOperator.SHIFT_RIGHT JavaTokenType.GTGTGT -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT JavaTokenType.PLUSEQ -> UastBinaryOperator.PLUS_ASSIGN JavaTokenType.MINUSEQ -> UastBinaryOperator.MINUS_ASSIGN JavaTokenType.ASTERISKEQ -> UastBinaryOperator.MULTIPLY_ASSIGN JavaTokenType.DIVEQ -> UastBinaryOperator.DIVIDE_ASSIGN JavaTokenType.PERCEQ -> UastBinaryOperator.REMAINDER_ASSIGN JavaTokenType.ANDEQ -> UastBinaryOperator.AND_ASSIGN JavaTokenType.XOREQ -> UastBinaryOperator.XOR_ASSIGN JavaTokenType.OREQ -> UastBinaryOperator.OR_ASSIGN JavaTokenType.LTLTEQ -> UastBinaryOperator.SHIFT_LEFT_ASSIGN JavaTokenType.GTGTEQ -> UastBinaryOperator.SHIFT_RIGHT_ASSIGN JavaTokenType.GTGTGTEQ -> UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN else -> UastBinaryOperator.OTHER } internal fun <T> singletonListOrEmpty(element: T?) = if (element != null) listOf(element) else emptyList<T>() @Suppress("NOTHING_TO_INLINE") internal inline fun String?.orAnonymous(kind: String = ""): String { return this ?: "<anonymous" + (if (kind.isNotBlank()) " $kind" else "") + ">" } internal fun <T> lz(initializer: () -> T) = lazy(LazyThreadSafetyMode.NONE, initializer) val PsiModifierListOwner.annotations: Array<PsiAnnotation> get() = modifierList?.annotations ?: emptyArray() internal inline fun <reified T : UDeclaration, reified P : PsiElement> unwrap(element: P): P { val unwrapped = if (element is T) element.psi else element assert(unwrapped !is UElement) return unwrapped as P } internal fun PsiElement.getChildByRole(role: Int) = (this as? CompositeElement)?.findChildByRoleAsPsiElement(role)
apache-2.0
da1z/intellij-community
platform/testFramework/src/com/intellij/testFramework/FixtureRule.kt
2
10267
// Copyright 2000-2017 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.testFramework import com.intellij.ide.highlighter.ProjectFileType import com.intellij.idea.IdeaTestApplication import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl import com.intellij.project.stateStore import com.intellij.util.SmartList import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.io.systemIndependentPath import org.junit.rules.ExternalResource import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.ByteArrayOutputStream import java.io.PrintStream import java.nio.file.Files import java.util.concurrent.atomic.AtomicBoolean private var sharedModule: Module? = null open class ApplicationRule : ExternalResource() { companion object { init { Logger.setFactory(TestLoggerFactory::class.java) } } override public final fun before() { IdeaTestApplication.getInstance() TestRunnerUtil.replaceIdeEventQueueSafely() (PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents() } } /** * Project created on request, so, could be used as a bare (only application). */ class ProjectRule(val projectDescriptor: LightProjectDescriptor = LightProjectDescriptor()) : ApplicationRule() { companion object { private var sharedProject: ProjectEx? = null private val projectOpened = AtomicBoolean() private fun createLightProject(): ProjectEx { (PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents() val projectFile = generateTemporaryPath("light_temp_shared_project${ProjectFileType.DOT_DEFAULT_EXTENSION}") val projectPath = projectFile.systemIndependentPath val buffer = ByteArrayOutputStream() Throwable(projectPath, null).printStackTrace(PrintStream(buffer)) val project = PlatformTestCase.createProject(projectPath, "Light project: $buffer") as ProjectEx PlatformTestUtil.registerProjectCleanup { try { disposeProject() } finally { Files.deleteIfExists(projectFile) } } // TODO uncomment and figure out where to put this statement // (VirtualFilePointerManager.getInstance() as VirtualFilePointerManagerImpl).storePointers() return project } private fun disposeProject() { val project = sharedProject ?: return sharedProject = null sharedModule = null (ProjectManager.getInstance() as ProjectManagerImpl).forceCloseProject(project, true) // TODO uncomment and figure out where to put this statement // (VirtualFilePointerManager.getInstance() as VirtualFilePointerManagerImpl).assertPointersAreDisposed() } } override public fun after() { if (projectOpened.compareAndSet(true, false)) { sharedProject?.let { runInEdtAndWait { (ProjectManager.getInstance() as ProjectManagerImpl).forceCloseProject(it, false) } } } } val projectIfOpened: ProjectEx? get() = if (projectOpened.get()) sharedProject else null val project: ProjectEx get() { var result = sharedProject if (result == null) { synchronized(IdeaTestApplication.getInstance()) { result = sharedProject if (result == null) { result = createLightProject() sharedProject = result } } } if (projectOpened.compareAndSet(false, true)) { runInEdtAndWait { ProjectManagerEx.getInstanceEx().openTestProject(project) } } return result!! } val module: Module get() { var result = sharedModule if (result == null) { runInEdtAndWait { projectDescriptor.setUpProject(project, object : LightProjectDescriptor.SetupHandler { override fun moduleCreated(module: Module) { result = module sharedModule = module } }) } } return result!! } } /** * rules: outer, middle, inner * out: * starting outer rule * starting middle rule * starting inner rule * finished inner rule * finished middle rule * finished outer rule */ class RuleChain(vararg val rules: TestRule) : TestRule { override fun apply(base: Statement, description: Description): Statement { var statement = base for (i in (rules.size - 1) downTo 0) { statement = rules[i].apply(statement, description) } return statement } } private fun <T : Annotation> Description.getOwnOrClassAnnotation(annotationClass: Class<T>) = getAnnotation(annotationClass) ?: testClass?.getAnnotation(annotationClass) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) annotation class RunsInEdt class EdtRule : TestRule { override fun apply(base: Statement, description: Description): Statement { return if (description.getOwnOrClassAnnotation(RunsInEdt::class.java) == null) { base } else { statement { runInEdtAndWait { base.evaluate() } } } } } class InitInspectionRule : TestRule { override fun apply(base: Statement, description: Description) = statement { runInInitMode { base.evaluate() } } } inline fun statement(crossinline runnable: () -> Unit) = object : Statement() { override fun evaluate() { runnable() } } /** * Do not optimise test load speed. * @see IProjectStore.setOptimiseTestLoadSpeed */ @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) annotation class RunsInActiveStoreMode class ActiveStoreRule(private val projectRule: ProjectRule) : TestRule { override fun apply(base: Statement, description: Description): Statement { return if (description.getOwnOrClassAnnotation(RunsInActiveStoreMode::class.java) == null) { base } else { statement { projectRule.project.runInLoadComponentStateMode { base.evaluate() } } } } } /** * In test mode component state is not loaded. Project or module store will load component state if project/module file exists. * So must be a strong reason to explicitly use this method. */ inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T { val store = stateStore val isModeDisabled = store.isOptimiseTestLoadSpeed if (isModeDisabled) { store.isOptimiseTestLoadSpeed = false } try { return task() } finally { if (isModeDisabled) { store.isOptimiseTestLoadSpeed = true } } } fun createHeavyProject(path: String, useDefaultProjectSettings: Boolean = false) = ProjectManagerEx.getInstanceEx().newProject(null, path, useDefaultProjectSettings, false)!! fun Project.use(task: (Project) -> Unit) { val projectManager = ProjectManagerEx.getInstanceEx() as ProjectManagerImpl try { runInEdtAndWait { projectManager.openTestProject(this) } task(this) } finally { runInEdtAndWait { projectManager.forceCloseProject(this, true) } } } class DisposeNonLightProjectsRule : ExternalResource() { override fun after() { val projectManager = if (ApplicationManager.getApplication().isDisposed) null else ProjectManager.getInstance() as ProjectManagerImpl projectManager?.openProjects?.forEachGuaranteed { if (!ProjectManagerImpl.isLight(it)) { runInEdtAndWait { projectManager.forceCloseProject(it, true) } } } } } class DisposeModulesRule(private val projectRule: ProjectRule) : ExternalResource() { override fun after() { projectRule.projectIfOpened?.let { val moduleManager = ModuleManager.getInstance(it) runInEdtAndWait { moduleManager.modules.forEachGuaranteed { if (!it.isDisposed && it !== sharedModule) { moduleManager.disposeModule(it) } } } } } } /** * Only and only if "before" logic in case of exception doesn't require "after" logic - must be no side effects if "before" finished abnormally. * So, should be one task per rule. */ class WrapRule(private val before: () -> () -> Unit) : TestRule { override fun apply(base: Statement, description: Description) = statement { val after = before() try { base.evaluate() } finally { after() } } } fun createProjectAndUseInLoadComponentStateMode(tempDirManager: TemporaryDirectory, directoryBased: Boolean = false, task: (Project) -> Unit) { createOrLoadProject(tempDirManager, task, directoryBased = directoryBased) } fun loadAndUseProject(tempDirManager: TemporaryDirectory, projectCreator: ((VirtualFile) -> String)? = null, task: (Project) -> Unit) { createOrLoadProject(tempDirManager, task, projectCreator, false) } private fun createOrLoadProject(tempDirManager: TemporaryDirectory, task: (Project) -> Unit, projectCreator: ((VirtualFile) -> String)? = null, directoryBased: Boolean) { runInEdtAndWait { val filePath = if (projectCreator == null) { tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}", refreshVfs = true).systemIndependentPath } else { runUndoTransparentWriteAction { projectCreator(tempDirManager.newVirtualDirectory()) } } val project = if (projectCreator == null) createHeavyProject(filePath, true) else ProjectManagerEx.getInstanceEx().loadProject(filePath)!! project.runInLoadComponentStateMode { project.use(task) } } } fun ComponentManager.saveStore() { stateStore.save(SmartList()) }
apache-2.0
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/screens/events/ScreenWillAppearEvent.kt
2
680
package abi44_0_0.host.exp.exponent.modules.api.screens.events import abi44_0_0.com.facebook.react.bridge.Arguments import abi44_0_0.com.facebook.react.uimanager.events.Event import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter class ScreenWillAppearEvent(viewId: Int) : Event<ScreenWillAppearEvent>(viewId) { override fun getEventName() = EVENT_NAME // All events for a given view can be coalesced. override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) { rctEventEmitter.receiveEvent(viewTag, eventName, Arguments.createMap()) } companion object { const val EVENT_NAME = "topWillAppear" } }
bsd-3-clause
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt
1
16594
package info.nightscout.androidaps.plugins.general.actions import android.content.Context import android.content.Intent import android.os.Bundle import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.core.content.ContextCompat import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.HistoryBrowseActivity import info.nightscout.androidaps.activities.TDDStatsActivity import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.ActionsFragmentBinding import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.events.EventCustomActionsChanged import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.events.EventTherapyEventChange import info.nightscout.androidaps.extensions.toStringMedium import info.nightscout.androidaps.extensions.toStringShort import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.interfaces.* import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.SingleClickButton import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* import javax.inject.Inject class ActionsFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var ctx: Context @Inject lateinit var rh: ResourceHelper @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var skinProvider: SkinProvider @Inject lateinit var config: Config @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @Inject lateinit var loop: Loop private var disposable: CompositeDisposable = CompositeDisposable() private val pumpCustomActions = HashMap<String, CustomAction>() private val pumpCustomButtons = ArrayList<SingleClickButton>() private lateinit var dm: DisplayMetrics private var _binding: ActionsFragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { //check screen width dm = DisplayMetrics() if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { @Suppress("DEPRECATION") activity?.display?.getRealMetrics(dm) } else { @Suppress("DEPRECATION") activity?.windowManager?.defaultDisplay?.getMetrics(dm) } _binding = ActionsFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) skinProvider.activeSkin().preProcessLandscapeActionsLayout(dm, binding) binding.profileSwitch.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { ProfileSwitchDialog().show(childFragmentManager, "ProfileSwitchDialog")}) } } binding.tempTarget.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { TempTargetDialog().show(childFragmentManager, "Actions") }) } } binding.extendedBolus.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { OKDialog.showConfirmation( activity, rh.gs(R.string.extended_bolus), rh.gs(R.string.ebstopsloop), Runnable { ExtendedBolusDialog().show(childFragmentManager, "Actions") }, null ) }) } } binding.extendedBolusCancel.setOnClickListener { if (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { uel.log(Action.CANCEL_EXTENDED_BOLUS, Sources.Actions) commandQueue.cancelExtended(object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror) } } }) } } binding.setTempBasal.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { TempBasalDialog().show(childFragmentManager, "Actions") }) } } binding.cancelTempBasal.setOnClickListener { if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) != null) { uel.log(Action.CANCEL_TEMP_BASAL, Sources.Actions) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) } } }) } } binding.fill.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { FillDialog().show(childFragmentManager, "FillDialog") }) } } binding.historyBrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) } binding.tddStats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } binding.bgCheck.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.BGCHECK, R.string.careportal_bgcheck).show(childFragmentManager, "Actions") } binding.cgmSensorInsert.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.SENSOR_INSERT, R.string.careportal_cgmsensorinsert).show(childFragmentManager, "Actions") } binding.pumpBatteryChange.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.BATTERY_CHANGE, R.string.careportal_pumpbatterychange).show(childFragmentManager, "Actions") } binding.note.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.NOTE, R.string.careportal_note).show(childFragmentManager, "Actions") } binding.exercise.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions") } binding.question.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.QUESTION, R.string.careportal_question).show(childFragmentManager, "Actions") } binding.announcement.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.ANNOUNCEMENT, R.string.careportal_announcement).show(childFragmentManager, "Actions") } sp.putBoolean(R.string.key_objectiveuseactions, true) } @Synchronized override fun onResume() { super.onResume() disposable += rxBus .toObservable(EventInitializationChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventCustomActionsChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTherapyEventChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } override fun onDestroyView() { super.onDestroyView() _binding = null } @Synchronized fun updateGui() { val profile = profileFunction.getProfile() val pump = activePlugin.activePump binding.profileSwitch.visibility = ( activePlugin.activeProfileSource.profile != null && pump.pumpDescription.isSetBasalProfileCapable && pump.isInitialized() && !pump.isSuspended() && !loop.isDisconnected).toVisibility() if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || loop.isDisconnected || pump.isFakingTempsByExtendedBoluses || config.NSCLIENT) { binding.extendedBolus.visibility = View.GONE binding.extendedBolusCancel.visibility = View.GONE } else { val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet() if (activeExtendedBolus is ValueWrapper.Existing) { binding.extendedBolus.visibility = View.GONE binding.extendedBolusCancel.visibility = View.VISIBLE @Suppress("SetTextI18n") binding.extendedBolusCancel.text = rh.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil) } else { binding.extendedBolus.visibility = View.VISIBLE binding.extendedBolusCancel.visibility = View.GONE } } if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized() || pump.isSuspended() || loop.isDisconnected || config.NSCLIENT) { binding.setTempBasal.visibility = View.GONE binding.cancelTempBasal.visibility = View.GONE } else { val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()) if (activeTemp != null) { binding.setTempBasal.visibility = View.GONE binding.cancelTempBasal.visibility = View.VISIBLE @Suppress("SetTextI18n") binding.cancelTempBasal.text = rh.gs(R.string.cancel) + " " + activeTemp.toStringShort() } else { binding.setTempBasal.visibility = View.VISIBLE binding.cancelTempBasal.visibility = View.GONE } } val activeBgSource = activePlugin.activeBgSource binding.historyBrowser.visibility = (profile != null).toVisibility() binding.fill.visibility = (pump.pumpDescription.isRefillingCapable && pump.isInitialized() && !pump.isSuspended()).toVisibility() binding.pumpBatteryChange.visibility = (pump.pumpDescription.isBatteryReplaceable || pump.isBatteryChangeLoggingEnabled()).toVisibility() binding.tempTarget.visibility = (profile != null && !loop.isDisconnected).toVisibility() binding.tddStats.visibility = pump.pumpDescription.supportsTDDs.toVisibility() val isPatchPump = pump.pumpDescription.isPatchPump binding.status.apply { cannulaOrPatch.text = if (isPatchPump) rh.gs(R.string.patch_pump) else rh.gs(R.string.cannula) val imageResource = if (isPatchPump) R.drawable.ic_patch_pump_outline else R.drawable.ic_cp_age_cannula cannulaOrPatch.setCompoundDrawablesWithIntrinsicBounds(imageResource, 0, 0, 0) batteryLayout.visibility = (!isPatchPump || pump.pumpDescription.useHardwareLink).toVisibility() if (!config.NSCLIENT) { statusLightHandler.updateStatusLights(cannulaAge, insulinAge, reservoirLevel, sensorAge, sensorLevel, pbAge, batteryLevel) sensorLevelLabel.text = if (activeBgSource.sensorBatteryLevel == -1) "" else rh.gs(R.string.careportal_level_label) } else { statusLightHandler.updateStatusLights(cannulaAge, insulinAge, null, sensorAge, null, pbAge, null) sensorLevelLabel.text = "" insulinLevelLabel.text = "" pbLevelLabel.text = "" } } checkPumpCustomActions() } private fun checkPumpCustomActions() { val activePump = activePlugin.activePump val customActions = activePump.getCustomActions() ?: return val currentContext = context ?: return removePumpCustomActions() for (customAction in customActions) { if (!customAction.isEnabled) continue val btn = SingleClickButton(currentContext, null, R.attr.customBtnStyle) btn.text = rh.gs(customAction.name) val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f ) layoutParams.setMargins(20, 8, 20, 8) // 10,3,10,3 btn.layoutParams = layoutParams btn.setOnClickListener { v -> val b = v as SingleClickButton this.pumpCustomActions[b.text.toString()]?.let { activePlugin.activePump.executeCustomAction(it.customActionType) } } val top = activity?.let { ContextCompat.getDrawable(it, customAction.iconResourceId) } btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null) binding.buttonsLayout.addView(btn) this.pumpCustomActions[rh.gs(customAction.name)] = customAction this.pumpCustomButtons.add(btn) } } private fun removePumpCustomActions() { for (customButton in pumpCustomButtons) binding.buttonsLayout.removeView(customButton) pumpCustomButtons.clear() } }
agpl-3.0
DevJake/SaltBot-2.0
src/test/kotlin/me/salt/SimpleRGBColourTest.kt
1
5735
/* * Copyright 2017 DevJake * * 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 me.salt import com.winterbe.expekt.should import me.salt.utilities.util.SimpleRGBColour import me.salt.utilities.exception.ColourValueException import me.salt.utilities.exception.ExceptionHandler import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.* class SimpleRGBColourTest : Spek({ ExceptionHandler.isTesting = true context("updating and requesting values") { given("an instance of SimpleRGBColour") { describe("with red, green and blue set to zero") { var subject = SimpleRGBColour(0, 0, 0) on("requesting the value of red") { it("should return zero") { subject.red.should.equal(0) } } on("requesting the value of green") { it("should return zero") { subject.green.should.equal(0) } } on("requesting the value of blue") { it("should return zero") { subject.blue.should.equal(0) } } on("updating and requesting the value of red to 200") { it("should return 200") { subject.red = 200 subject.red.should.equal(200) } } on("updating and requesting the value of blue to 150") { it("should return 150") { subject.red = 150 subject.red.should.equal(150) } } on("updating and requesting the value of green to 400") { it("should throw a ColourValueException") { subject.green = 400 ExceptionHandler.latestException.should.be.instanceof(ColourValueException::class.java) } } on("updating and requesting the value of green to -10") { it("should throw a ColourValueException") { subject.red = -10 ExceptionHandler.latestException.should.be.an.instanceof(ColourValueException::class.java) } } on("providing a valid value for transparency (200)") { it("should return the value of 200 for transparency") { subject.transparency = 200 subject.transparency.should.equal(200) } } on("providing an invalid value for transparency (-10)") { it("should throw a ColourValueException") { subject.transparency = -10 ExceptionHandler.latestException.should.be.an.instanceof(ColourValueException::class.java) } it("should throw a ColourValueException with a set message") { subject.transparency = -10 ExceptionHandler.latestException?.message.should.equal("The value for transparency must be between 0 and 255") } } } } context("creating instances with incorrect values") { given("an instance of SimpleRGBColour") { on("providing incorrect values and no transparency as parameters") { it("should throw a ColourValueException") { SimpleRGBColour(0, 0, 400) ExceptionHandler.latestException.should.be.instanceof(ColourValueException::class.java) } } on("providing an incorrect value for the transparency parameter") { it("should throw a ColourValueException") { SimpleRGBColour(0, 0, 100, 400) ExceptionHandler.latestException.should.be.instanceof(ColourValueException::class.java) } } } } context("creating instances with valid parameters") { given("an instance of SimpleRGBColour") { on("passing valid red, green and blue parameters, excluding transparency") { it("should not throw any exception") { SimpleRGBColour(40, 30, 80) ExceptionHandler.latestException.should.not.be.instanceof(ColourValueException::class.java) } } on("passing valid red, green, blue and transparency parameters") { it("should not throw any exception") { SimpleRGBColour(40, 30, 80, 60) ExceptionHandler.latestException.should.not.be.instanceof(ColourValueException::class.java) } } } } } })
apache-2.0
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt
1
5782
@file:Suppress("DEPRECATION") package info.nightscout.androidaps.watchfaces import android.annotation.SuppressLint import android.view.LayoutInflater import androidx.core.content.ContextCompat import androidx.viewbinding.ViewBinding import com.ustwo.clockwise.common.WatchMode import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.ActivityBigchartBinding import info.nightscout.androidaps.databinding.ActivityBigchartSmallBinding import info.nightscout.androidaps.watchfaces.utils.BaseWatchFace import info.nightscout.androidaps.watchfaces.utils.WatchfaceViewAdapter class BigChartWatchface : BaseWatchFace() { private lateinit var binding: WatchfaceViewAdapter override fun inflateLayout(inflater: LayoutInflater): ViewBinding { if (resources.displayMetrics.widthPixels < SCREEN_SIZE_SMALL || resources.displayMetrics.heightPixels < SCREEN_SIZE_SMALL) { val layoutBinding = ActivityBigchartSmallBinding.inflate(inflater) binding = WatchfaceViewAdapter.getBinding(layoutBinding) return layoutBinding } val layoutBinding = ActivityBigchartBinding.inflate(inflater) binding = WatchfaceViewAdapter.getBinding(layoutBinding) return layoutBinding } @SuppressLint("SetTextI18n") override fun setDataFields() { super.setDataFields() binding.status?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" } override fun setColorLowRes() { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) binding.sgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.delta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.timestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) highColor = ContextCompat.getColor(this, R.color.dark_midColor) lowColor = ContextCompat.getColor(this, R.color.dark_midColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark_lowres) basalCenterColor = ContextCompat.getColor(this, R.color.basal_light_lowres) pointSize = 2 setupCharts() } override fun setColorDark() { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) val color = when (singleBg.sgvLevel) { 1L -> R.color.dark_highColor 0L -> R.color.dark_midColor -1L -> R.color.dark_lowColor else -> R.color.dark_midColor } binding.sgv?.setTextColor(ContextCompat.getColor(this, color)) binding.delta?.setTextColor(ContextCompat.getColor(this, color)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, color)) val colorTime = if (ageLevel == 1) R.color.dark_Timestamp else R.color.dark_TimestampOld binding.timestamp.setTextColor(ContextCompat.getColor(this, colorTime)) highColor = ContextCompat.getColor(this, R.color.dark_highColor) lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) pointSize = 2 setupCharts() } override fun setColorBright() { if (currentWatchMode == WatchMode.INTERACTIVE) { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) val color = when (singleBg.sgvLevel) { 1L -> R.color.light_highColor 0L -> R.color.light_midColor -1L -> R.color.light_lowColor else -> R.color.light_midColor } binding.sgv?.setTextColor(ContextCompat.getColor(this, color)) binding.delta?.setTextColor(ContextCompat.getColor(this, color)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, color)) val colorTime = if (ageLevel == 1) R.color.light_mTimestamp1 else R.color.light_mTimestamp binding.timestamp.setTextColor(ContextCompat.getColor(this, colorTime)) highColor = ContextCompat.getColor(this, R.color.light_highColor) lowColor = ContextCompat.getColor(this, R.color.light_lowColor) midColor = ContextCompat.getColor(this, R.color.light_midColor) gridColor = ContextCompat.getColor(this, R.color.light_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_light) basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) pointSize = 2 setupCharts() } else { setColorDark() } } }
agpl-3.0
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/extensions/RadioGroupExtension.kt
1
512
package info.nightscout.androidaps.utils.extensions import android.widget.RadioGroup import androidx.appcompat.widget.AppCompatRadioButton import androidx.core.view.forEach val RadioGroup.selectedItemPosition: Int get() = this.indexOfChild(this.findViewById(this.checkedRadioButtonId)) fun RadioGroup.setSelection(index: Int) { (this.getChildAt(index) as AppCompatRadioButton).isChecked = true } fun RadioGroup.setEnableForChildren(state : Boolean) { forEach { child -> child.isEnabled = state} }
agpl-3.0
cyclestreets/android
libraries/cyclestreets-core/src/main/java/net/cyclestreets/util/Html.kt
1
440
package net.cyclestreets.util import android.os.Build import android.text.Html import android.text.Spanned fun fromHtml(string: String): Spanned { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) return Html.fromHtml(string, Html.FROM_HTML_MODE_LEGACY) else return fromHtmlPreNougat(string) } @Suppress("deprecation") private fun fromHtmlPreNougat(string: String): Spanned { return Html.fromHtml(string) }
gpl-3.0
anthonycr/Mezzanine
mezzanine-compiler/src/main/java/com/anthonycr/mezzanine/extensions/FunctionExtensions.kt
1
264
package com.anthonycr.mezzanine.extensions /** * Allows for arbitrary execution in the middle of a stream based on a value. */ inline fun <T> Sequence<T>.doOnNext(predicate: (T) -> Unit): Sequence<T> { this.forEach { predicate.invoke(it) } return this }
apache-2.0
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/databind/RedditModelAdapterFactory.kt
1
9768
package net.dean.jraw.databind import com.squareup.moshi.* import net.dean.jraw.models.KindConstants import net.dean.jraw.models.Listing import net.dean.jraw.models.internal.RedditModelEnvelope import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Creates JsonAdapters for a class annotated with [RedditModel]. * * This class assumes that the data is encapsulated in an envelope like this: * * ```json * { * "kind": "<kind>", * "data": { ... } * } * ``` * * The [Enveloped] annotation must be specified in order for this adapter factory to produce anything. * * ```kt * val adapter = moshi.adapter<Something>(Something::class.java, Enveloped::class.java) * val something = adapter.fromJson(json) * ``` * * If the target type does NOT have the `@RedditModel` annotation, it will be deserialized dynamically. For example, if * the JSON contains either a `Foo` or a `Bar`, we can specify their closest comment parent instead of either `Foo` or * `Bar`. * * ```kt * // Get an adapter that can deserialize boths Foos and Bars * moshi.adapter<Parent>(Parent::class.java, Enveloped::class.java) * ``` * * Dynamic deserialization works like this: * * 1. Write the JSON value into a "simple" type (e.g. a Map) * 2. Lookup the value of the "kind" node * 3. Determine the correct concrete class by looking up the kind in the [registry] * 4. Transform the intermediate JSON (the Map) into an instance of that class * * Keep in mind that dynamic deserialization is a bit hacky and is probably slower than static deserialization. */ class RedditModelAdapterFactory( /** * A Map of kinds (the value of the 'kind' node) to the concrete classes they represent. Not necessary if only * deserializing statically. Adding [Listing] to this class may cause problems. */ private val registry: Map<String, Class<*>> ) : JsonAdapter.Factory { /** @inheritDoc */ override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? { // Require @Enveloped val delegateAnnotations = Types.nextAnnotations(annotations, Enveloped::class.java) ?: return null val rawType = Types.getRawType(type) // Special handling for Listings if (rawType == Listing::class.java) { val childType = (type as ParameterizedType).actualTypeArguments.first() // Assume children are enveloped val delegate = moshi.adapter<Any>(childType, Enveloped::class.java).nullSafe() return ListingAdapter(delegate) } val isRedditModel = rawType.isAnnotationPresent(RedditModel::class.java) return if (isRedditModel) { // Static JsonAdapter val enveloped = rawType.getAnnotation(RedditModel::class.java).enveloped return if (enveloped) { val actualType = Types.newParameterizedType(RedditModelEnvelope::class.java, type) val delegate = moshi.adapter<RedditModelEnvelope<*>>(actualType).nullSafe() StaticAdapter(registry, delegate) } else { moshi.nextAdapter<Any>(this, type, delegateAnnotations).nullSafe() } } else { // Dynamic JsonAdapter DynamicNonGenericModelAdapter(registry, moshi, rawType) } } /** * Statically (normally) deserializes some JSON value into a concrete class. All generic types must be resolved * beforehand. */ private class StaticAdapter( private val registry: Map<String, Class<*>>, private val delegate: JsonAdapter<RedditModelEnvelope<*>> ) : JsonAdapter<Any>() { override fun toJson(writer: JsonWriter, value: Any?) { if (value == null) { writer.nullValue() return } // Reverse lookup the actual value of 'kind' from the registry var actualKind: String? = null for ((kind, clazz) in registry) if (clazz == value.javaClass) actualKind = kind if (actualKind == null) throw IllegalArgumentException("No registered kind for Class '${value.javaClass}'") delegate.toJson(writer, RedditModelEnvelope.create(actualKind, value)) } override fun fromJson(reader: JsonReader): Any? { return delegate.fromJson(reader)?.data ?: return null } } private abstract class DynamicAdapter<T>( protected val registry: Map<String, Class<*>>, protected val moshi: Moshi, protected val upperBound: Class<*> ) : JsonAdapter<T>() { override fun toJson(writer: JsonWriter?, value: T?) { throw UnsupportedOperationException("Serializing dynamic models aren't supported right now") } /** * Asserts that the given object is not null and the same class or a subclass of [upperBound]. Returns the value * after the check. */ protected fun ensureInBounds(obj: Any?): Any { if (!upperBound.isAssignableFrom(obj!!.javaClass)) throw IllegalArgumentException("Expected ${upperBound.name} to be assignable from $obj") return obj } } private class DynamicNonGenericModelAdapter(registry: Map<String, Class<*>>, moshi: Moshi, upperBound: Class<*>) : DynamicAdapter<Any>(registry, moshi, upperBound) { override fun fromJson(reader: JsonReader): Any? { val json = expectType<Map<String, Any>>(reader.readJsonValue(), "<root>") val kind = expectType<String>(json["kind"], "kind") val clazz = registry[kind] ?: throw IllegalArgumentException("No registered class for kind '$kind'") val envelopeType = Types.newParameterizedType(RedditModelEnvelope::class.java, clazz) val adapter = moshi.adapter<RedditModelEnvelope<*>>(envelopeType) val result = adapter.fromJsonValue(json)!! return ensureInBounds(result.data) } } private class ListingAdapter(val childrenDelegate: JsonAdapter<Any>) : JsonAdapter<Listing<Any>>() { override fun fromJson(reader: JsonReader): Listing<Any>? { // Assume that the JSON is enveloped, we have to strip that away and then parse the listing reader.beginObject() var listing: Listing<Any>? = null while (reader.hasNext()) { when (reader.selectName(envelopeOptions)) { 0 -> { // "kind" if (reader.nextString() != KindConstants.LISTING) throw IllegalArgumentException("Expecting kind to be listing at ${reader.path}") } 1 -> { // "data" listing = readListing(reader) } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return listing } private fun readListing(reader: JsonReader): Listing<Any> { var after: String? = null val children: MutableList<Any> = ArrayList() reader.beginObject() while (reader.hasNext()) { when (reader.selectName(listingOptions)) { 0 -> { // "after" after = if (reader.peek() == JsonReader.Token.NULL) reader.nextNull() else reader.nextString() } 1 -> { // "data" reader.beginArray() while (reader.hasNext()) children.add(childrenDelegate.fromJson(reader)!!) reader.endArray() } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return Listing.create(after, children) } override fun toJson(writer: JsonWriter, value: Listing<Any>?) { if (value == null) { writer.nullValue() return } writer.beginObject() writer.name("kind") writer.value(KindConstants.LISTING) writer.name("data") writeListing(writer, value) writer.endObject() } private fun writeListing(writer: JsonWriter, value: Listing<Any>) { writer.beginObject() writer.name("after") writer.value(value.nextName) writer.name("children") writer.beginArray() for (child in value.children) childrenDelegate.toJson(writer, child) writer.endArray() writer.endObject() } companion object { private val envelopeOptions = JsonReader.Options.of("kind", "data") private val listingOptions = JsonReader.Options.of("after", "children") } } /** */ companion object { private inline fun <reified T> expectType(obj: Any?, name: String): T { if (obj == null) throw IllegalArgumentException("Expected $name to be non-null") return obj as? T ?: throw IllegalArgumentException("Expected $name to be a ${T::class.java.name}, was ${obj::class.java.name}") } } }
mit
PolymerLabs/arcs
javatests/arcs/core/storage/util/TokenGeneratorTest.kt
1
879
package arcs.core.storage.util import com.google.common.truth.Truth.assertThat import kotlin.random.Random import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class TokenGeneratorTest { @Test fun randomTokenGenerator_invokedWithExistingSetOfTokens_returnsNewUniqueValue() { val random = FakeRandom() val tokenGenerator = RandomTokenGenerator( "test", random ) val used = setOf( "0::test".hashCode(), "1::test".hashCode(), "2::test".hashCode() ) val expected = "3::test".hashCode() val actual = tokenGenerator(used) assertThat(actual).isEqualTo(expected) } private open class FakeRandom : Random() { var nextIntValue: Int = 0 override fun nextBits(bitCount: Int): Int = nextIntValue++ override fun nextInt(): Int = nextIntValue++ } }
bsd-3-clause
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/FloatingToolbarProvider.kt
1
1129
// 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.openapi.editor.toolbar.floating import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.extensions.ExtensionPointName import org.jetbrains.annotations.ApiStatus interface FloatingToolbarProvider { @get:ApiStatus.ScheduledForRemoval @get:Deprecated("Use [order] option in plugin.xml") val priority: Int get() = 0 val autoHideable: Boolean val actionGroup: ActionGroup @JvmDefault fun isApplicable(dataContext: DataContext): Boolean = true fun register(dataContext: DataContext, component: FloatingToolbarComponent, parentDisposable: Disposable) {} companion object { val EP_NAME = ExtensionPointName.create<FloatingToolbarProvider>("com.intellij.editorFloatingToolbarProvider") inline fun <reified T : FloatingToolbarProvider> getProvider(): T { return EP_NAME.findExtensionOrFail(T::class.java) } } }
apache-2.0
k9mail/k-9
app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/AttachmentPresenterTest.kt
2
6997
package com.fsck.k9.activity.compose import android.net.Uri import androidx.loader.app.LoaderManager import androidx.loader.app.LoaderManager.LoaderCallbacks import androidx.test.core.app.ApplicationProvider import com.fsck.k9.K9RobolectricTest import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentMvpView import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentsChangedListener import com.fsck.k9.activity.misc.Attachment import com.fsck.k9.mail.internet.MimeHeader import com.fsck.k9.mail.internet.MimeMessage import com.fsck.k9.mail.internet.MimeMessageHelper import com.fsck.k9.mail.internet.TextBody import com.fsck.k9.mailstore.AttachmentResolver import com.fsck.k9.mailstore.AttachmentViewInfo import com.fsck.k9.mailstore.LocalBodyPart import com.fsck.k9.mailstore.MessageViewInfo import com.google.common.truth.Truth.assertThat import java.util.function.Supplier import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.doAnswer import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever private val attachmentMvpView = mock<AttachmentMvpView>() private val loaderManager = mock<LoaderManager>() private val listener = mock<AttachmentsChangedListener>() private val attachmentResolver = mock<AttachmentResolver>() private const val ACCOUNT_UUID = "uuid" private const val SUBJECT = "subject" private const val TEXT = "text" private const val EXTRA_TEXT = "extra text" private const val ATTACHMENT_NAME = "1x1.png" private const val MESSAGE_ID = 1L private const val PATH_TO_FILE = "path/to/file.png" private const val MIME_TYPE = "image/png" private val URI = Uri.Builder().scheme("content://").build() class AttachmentPresenterTest : K9RobolectricTest() { lateinit var attachmentPresenter: AttachmentPresenter @Before fun setUp() { attachmentPresenter = AttachmentPresenter( ApplicationProvider.getApplicationContext(), attachmentMvpView, loaderManager, listener ) } @Test fun loadNonInlineAttachments_normalAttachment() { val size = 42L val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val attachmentViewInfo = AttachmentViewInfo( MIME_TYPE, ATTACHMENT_NAME, size, URI, false, LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), true ) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) mockLoaderManager({ attachmentPresenter.attachments.get(0) as Attachment }) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isTrue() assertThat(attachmentPresenter.attachments).hasSize(1) assertThat(attachmentPresenter.inlineAttachments).isEmpty() val attachment = attachmentPresenter.attachments.get(0) assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) assertThat(attachment?.size).isEqualTo(size) assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) } @Test fun loadNonInlineAttachments_normalAttachmentNotAvailable() { val size = 42L val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val attachmentViewInfo = AttachmentViewInfo( MIME_TYPE, ATTACHMENT_NAME, size, URI, false, LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), false ) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isFalse() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).isEmpty() } @Test fun loadNonInlineAttachments_inlineAttachment() { val size = 42L val contentId = "xyz" val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, true) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) mockLoaderManager({ attachmentPresenter.inlineAttachments.get(contentId) as Attachment }) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isTrue() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).hasSize(1) val attachment = attachmentPresenter.inlineAttachments.get(contentId) assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) assertThat(attachment?.size).isEqualTo(size) assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) } @Test fun loadNonInlineAttachments_inlineAttachmentNotAvailable() { val size = 42L val contentId = "xyz" val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, false) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isFalse() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).isEmpty() } private fun mockLoaderManager(attachmentSupplier: Supplier<Attachment>) { doAnswer { val loaderCallbacks = it.getArgument<LoaderCallbacks<Attachment>>(2) loaderCallbacks.onLoadFinished(mock(), attachmentSupplier.get().deriveWithLoadComplete(PATH_TO_FILE)) null }.whenever(loaderManager).initLoader(anyInt(), any(), any<LoaderCallbacks<Attachment>>()) } }
apache-2.0
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/HorizontalTabBarBuilder.kt
1
1913
package org.hexworks.zircon.api.builder.fragment import org.hexworks.zircon.api.Beta import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.fragment.TabBar import org.hexworks.zircon.api.fragment.builder.FragmentBuilder import org.hexworks.zircon.internal.fragment.impl.DefaultHorizontalTabBar import org.hexworks.zircon.internal.fragment.impl.TabBarBuilder import kotlin.jvm.JvmStatic @Beta class HorizontalTabBarBuilder private constructor( size: Size = Size.unknown(), defaultSelected: String? = null, tabs: List<TabBuilder> = listOf(), position: Position = Position.zero() ) : TabBarBuilder( size = size, defaultSelected = defaultSelected, tabs = tabs, position = position ), FragmentBuilder<TabBar, HorizontalTabBarBuilder> { fun HorizontalTabBarBuilder.tab(init: TabBuilder.() -> Unit) { tabs = tabs + TabBuilder.newBuilder().apply(init) } val contentSize: Size get() = size.withRelativeHeight(-3) override fun withPosition(position: Position) = also { this.position = position } override fun createCopy() = HorizontalTabBarBuilder( size = size, defaultSelected = defaultSelected, tabs = tabs, position = position ) override fun build(): TabBar { checkCommonProperties() val finalTabs = tabs.map { it.build() } require(finalTabs.fold(0) { acc, next -> acc + next.tab.tabButton.width } <= size.width) { "There is not enough space to display all the tabs" } return DefaultHorizontalTabBar( size = size, defaultSelected = defaultSelected ?: finalTabs.first().tab.key, tabs = finalTabs ) } companion object { @JvmStatic fun newBuilder(): HorizontalTabBarBuilder = HorizontalTabBarBuilder() } }
apache-2.0
android/renderscript-intrinsics-replacement-toolkit
test-app/src/main/java/com/google/android/renderscript_test/ReferenceLut3d.kt
1
2934
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.renderscript_test import com.google.android.renderscript.Range2d import com.google.android.renderscript.Rgba3dArray /** * Reference implementation of a 3D LookUpTable operation. */ @ExperimentalUnsignedTypes fun referenceLut3d( inputArray: ByteArray, sizeX: Int, sizeY: Int, cube: Rgba3dArray, restriction: Range2d? ): ByteArray { val input = Vector2dArray(inputArray.asUByteArray(), 4, sizeX, sizeY) val output = input.createSameSized() input.forEach(restriction) { x, y -> output[x, y] = lookup(input[x, y], cube) } return output.values.asByteArray() } @ExperimentalUnsignedTypes private fun lookup(input: UByteArray, cube: Rgba3dArray): UByteArray { // Calculate the two points at opposite edges of the size 1 // cube that contains our point. val maxIndex = Int4(cube.sizeX - 1, cube.sizeY - 1, cube.sizeZ - 1, 0) val baseCoordinate: Float4 = input.toFloat4() * maxIndex.toFloat4() / 255f val point1: Int4 = baseCoordinate.intFloor() val point2: Int4 = min(point1 + 1, maxIndex) val fractionAwayFromPoint1: Float4 = baseCoordinate - point1.toFloat4() // Get the RGBA values at each of the four corners of the size 1 cube. val v000 = cube[point1.x, point1.y, point1.z].toFloat4() val v100 = cube[point2.x, point1.y, point1.z].toFloat4() val v010 = cube[point1.x, point2.y, point1.z].toFloat4() val v110 = cube[point2.x, point2.y, point1.z].toFloat4() val v001 = cube[point1.x, point1.y, point2.z].toFloat4() val v101 = cube[point2.x, point1.y, point2.z].toFloat4() val v011 = cube[point1.x, point2.y, point2.z].toFloat4() val v111 = cube[point2.x, point2.y, point2.z].toFloat4() // Do the linear mixing of these eight values. val yz00 = mix(v000, v100, fractionAwayFromPoint1.x) val yz10 = mix(v010, v110, fractionAwayFromPoint1.x) val yz01 = mix(v001, v101, fractionAwayFromPoint1.x) val yz11 = mix(v011, v111, fractionAwayFromPoint1.x) val z0 = mix(yz00, yz10, fractionAwayFromPoint1.y) val z1 = mix(yz01, yz11, fractionAwayFromPoint1.y) val v = mix(z0, z1, fractionAwayFromPoint1.z) // Preserve the alpha of the original value return ubyteArrayOf(v.x.clampToUByte(), v.y.clampToUByte(), v.z.clampToUByte(), input[3]) }
apache-2.0
pyamsoft/pydroid
billing/src/main/java/com/pyamsoft/pydroid/billing/store/PlayBillingSku.kt
1
1239
/* * Copyright 2022 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pydroid.billing.store import com.android.billingclient.api.ProductDetails import com.pyamsoft.pydroid.billing.BillingSku import com.pyamsoft.pydroid.core.requireNotNull internal data class PlayBillingSku internal constructor(internal val sku: ProductDetails) : BillingSku { private val product = sku.oneTimePurchaseOfferDetails.requireNotNull() override val id: String = sku.productId override val displayPrice: String = product.formattedPrice override val price: Long = product.priceAmountMicros override val title: String = sku.title override val description: String = sku.description }
apache-2.0
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/ex/implementation/commands/DeleteMarksCommandTest.kt
1
4771
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.ex.implementation.commands import com.intellij.openapi.editor.LogicalPosition import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.mark.Mark import com.maddyhome.idea.vim.newapi.vim import org.jetbrains.plugins.ideavim.VimTestCase import kotlin.test.assertNotNull import kotlin.test.assertNull /** * @author Jørgen Granseth */ class DeleteMarksCommandTest : VimTestCase() { private fun setUpMarks(marks: String) { configureByText( """I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. The features it combines mark it as new to science: shape and shade -- the special tinge, akin to moonlight, tempering its blue, the dingy underside, the checquered fringe. My needles have teased out its sculpted sex; corroded tissues could no longer hide that priceless mote now dimpling the convex and limpid teardrop on a lighted slide. """.trimMargin() ) marks.forEachIndexed { index, c -> VimPlugin.getMark() .setMark(myFixture.editor.vim, c, myFixture.editor.logicalPositionToOffset(LogicalPosition(index, 0))) } } private fun getMark(ch: Char): Mark? { return VimPlugin.getMark().getMark(myFixture.editor.vim, ch) } fun `test delete single mark`() { setUpMarks("a") typeText(commandToKeys("delmarks a")) assertNull(getMark('a'), "Mark was not deleted") } fun `test delete multiple marks`() { setUpMarks("abAB") typeText(commandToKeys("delmarks Ab")) arrayOf('A', 'b') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('a', 'B') .forEach { ch -> assertNotNull(getMark(ch), "Mark $ch was unexpectedly deleted") } } fun `test delete ranges (inclusive)`() { setUpMarks("abcde") typeText(commandToKeys("delmarks b-d")) arrayOf('b', 'c', 'd') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('a', 'e') .forEach { ch -> assertNotNull(getMark(ch), "Mark $ch was unexpectedly deleted") } } fun `test delete multiple ranges and marks with whitespace`() { setUpMarks("abcdeABCDE") typeText(commandToKeys("delmarks b-dC-E a")) arrayOf('a', 'b', 'c', 'd', 'C', 'D', 'E', 'a') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('e', 'A', 'B') .forEach { ch -> assertNotNull(getMark(ch), "Mark $ch was unexpectedly deleted") } } fun `test invalid range throws exception without deleting any marks`() { setUpMarks("a") typeText(commandToKeys("delmarks a-C")) assertPluginError(true) assertNotNull(getMark('a'), "Mark was deleted despite invalid command given") } fun `test invalid characters throws exception`() { setUpMarks("a") typeText(commandToKeys("delmarks bca# foo")) assertPluginError(true) assertNotNull(getMark('a'), "Mark was deleted despite invalid command given") } fun `test delmarks! with trailing spaces`() { setUpMarks("aBcAbC") typeText(commandToKeys("delmarks!")) arrayOf('a', 'b', 'c') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('A', 'B', 'C') .forEach { ch -> assertNotNull(getMark(ch), "Global mark $ch was deleted by delmarks!") } } fun `test delmarks! with other arguments fails`() { setUpMarks("aBcAbC") typeText(commandToKeys("delmarks!a")) assertPluginError(true) arrayOf('a', 'b', 'c', 'A', 'B', 'C') .forEach { ch -> assertNotNull(getMark(ch), "Mark $ch was deleted despite invalid command given") } } fun `test trailing spaces ignored`() { setUpMarks("aBcAbC") typeText(commandToKeys("delmarks! ")) arrayOf('a', 'b', 'c') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('A', 'B', 'C') .forEach { ch -> assertNotNull(getMark(ch), "Global mark $ch was deleted by delmarks!") } } fun `test alias (delm)`() { setUpMarks("a") typeText(commandToKeys("delm a")) assertNull(getMark('a'), "Mark was not deleted") setUpMarks("aBcAbC") typeText(commandToKeys("delm!")) arrayOf('a', 'b', 'c') .forEach { ch -> assertNull(getMark(ch), "Mark $ch was not deleted") } arrayOf('A', 'B', 'C') .forEach { ch -> assertNotNull(getMark(ch), "Global mark $ch was deleted by delm!") } } }
mit
Hexworks/zircon
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/uievent/impl/UIEventToComponentDispatcherTest.kt
1
6311
package org.hexworks.zircon.internal.uievent.impl import org.assertj.core.api.Assertions.assertThat import org.hexworks.cobalt.events.api.EventBus import org.hexworks.zircon.api.uievent.* import org.hexworks.zircon.internal.behavior.ComponentFocusOrderList import org.hexworks.zircon.internal.component.InternalContainer import org.hexworks.zircon.internal.component.impl.RootContainer import org.hexworks.zircon.internal.event.ZirconScope import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule import org.mockito.kotlin.* import org.mockito.quality.Strictness import kotlin.contracts.ExperimentalContracts @Suppress("TestFunctionName") @ExperimentalContracts class UIEventToComponentDispatcherTest { @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS) lateinit var target: UIEventToComponentDispatcher @Mock lateinit var rootMock: RootContainer @Mock lateinit var child0Mock: InternalContainer @Mock lateinit var child1Mock: InternalContainer @Mock lateinit var focusOrderListMock: ComponentFocusOrderList @Before fun setUp() { val eventBus = EventBus.create() val eventScope = ZirconScope() whenever(rootMock.calculatePathTo(anyOrNull())).thenReturn(listOf(rootMock)) whenever(rootMock.eventScope).thenReturn(eventScope) whenever(rootMock.eventBus).thenReturn(eventBus) target = UIEventToComponentDispatcher(rootMock, focusOrderListMock) } @Test fun dispatchShouldReturnPassWhenThereIsNoTarget() { whenever(focusOrderListMock.focusedComponent).thenReturn(rootMock) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) val result = target.dispatch(KEY_A_PRESSED_EVENT) assertThat(result).isEqualTo(Pass) } @Test fun dispatchShouldReturnProcessedWhenTargetsDefaultIsRun() { whenever(focusOrderListMock.focusedComponent).thenReturn(rootMock) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Processed) val result = target.dispatch(KEY_A_PRESSED_EVENT) assertThat(result).isEqualTo(Processed) } @Test fun dispatchShouldReturnPreventDefaultWhenChildPreventedDefault() { whenever(focusOrderListMock.focusedComponent).thenReturn(child1Mock) whenever(rootMock.calculatePathTo(child1Mock)).thenReturn(listOf(rootMock, child0Mock, child1Mock)) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(PreventDefault) whenever(child1Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE)).thenReturn(Pass) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE)).thenReturn(Pass) val result = target.dispatch(KEY_A_PRESSED_EVENT) // Child mock 0 shouldn't be called with key pressed in the capture phase verify(child0Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE) // Child mock 1 shouldn't be called with key pressed in the target phase verify(child1Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET) // Root mock shouldn't be called with key pressed in the bubble phase verify(rootMock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) assertThat(result).isEqualTo(PreventDefault) } @Test fun dispatchShouldReturnStopPropagationWhenFirstChildStoppedPropagation() { whenever(focusOrderListMock.focusedComponent).thenReturn(child1Mock) whenever(rootMock.calculatePathTo(child1Mock)).thenReturn(listOf(rootMock, child0Mock, child1Mock)) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(StopPropagation) val result = target.dispatch(KEY_A_PRESSED_EVENT) // Child mock 1 shouldn't be called with process in the target phase verify(child1Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET) // Child mock 0 shouldn't be called with process in the bubble phase verify(child0Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) // Root mock shouldn't be called with process in the bubble phase verify(rootMock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) assertThat(result).isEqualTo(StopPropagation) } @Test fun When_a_child_stops_propagation_of_the_tab_key_Then_component_events_shouldnt_be_performed() { whenever(focusOrderListMock.focusedComponent).thenReturn(child0Mock) whenever(rootMock.calculatePathTo(child0Mock)).thenReturn(listOf(rootMock, child0Mock)) whenever(rootMock.process(TAB_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(TAB_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(TAB_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(StopPropagation) val result = target.dispatch(TAB_PRESSED_EVENT) verify(child0Mock, never()).focusGiven() assertThat(result).isEqualTo(StopPropagation) } companion object { val KEY_A_PRESSED_EVENT = KeyboardEvent( type = KeyboardEventType.KEY_PRESSED, key = "a", code = KeyCode.KEY_A ) val TAB_PRESSED_EVENT = KeyboardEvent( type = KeyboardEventType.KEY_PRESSED, code = KeyCode.TAB, key = "\t" ) } }
apache-2.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/compose/components/ButtonsColumn.kt
1
804
package org.wordpress.android.ui.main.jetpack.migration.compose.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import org.wordpress.android.R.color @Composable fun ButtonsColumn( modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit ) { Column( modifier = modifier.padding(bottom = 50.dp) ) { Divider( color = colorResource(color.gray_10), thickness = 0.5.dp, ) content() } }
gpl-2.0
ingokegel/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt
4
2147
// 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.tools.projectWizard.wizard.ui.components import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JComponent class TextFieldComponent( context: Context, labelText: String? = null, description: String? = null, initialValue: String? = null, validator: SettingValidator<String>? = null, onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> } ) : UIComponent<String>( context, labelText, validator, onValueUpdate ) { private var isDisabled: Boolean = false private var cachedValueWhenDisabled: String? = null @Suppress("HardCodedStringLiteral") private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated) override val alignTarget: JComponent get() = textField override val uiComponent = componentWithCommentAtBottom(textField, description) override fun updateUiValue(newValue: String) = safeUpdateUi { textField.text = newValue } fun onUserType(action: () -> Unit) { textField.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent?) = action() }) } fun disable(@Nls message: String) { cachedValueWhenDisabled = getUiValue() textField.isEditable = false textField.foreground = UIUtil.getLabelDisabledForeground() isDisabled = true updateUiValue(message) } override fun validate(value: String) { if (isDisabled) return super.validate(value) } override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/constructors/secondaryConstructorsInInnerClass.kt
7
870
internal class Outer { private inner class Inner1() { constructor(a: Int) : this() protected constructor(c: Char) : this() private constructor(b: Boolean) : this() } protected inner class Inner2() { constructor(a: Int) : this() protected constructor(c: Char) : this() private constructor(b: Boolean) : this() } internal inner class Inner3() { constructor(a: Int) : this() protected constructor(c: Char) : this() private constructor(b: Boolean) : this() } inner class Inner4() { constructor(a: Int) : this() protected constructor(c: Char) : this() private constructor(b: Boolean) : this() } fun foo() { val inner1 = Inner1(1) val inner2 = Inner2(2) val inner3 = Inner3(3) val inner4 = Inner4(4) } }
apache-2.0
TheCoinTosser/Kotlin-Koans---Solutions
src/v_builders/n37StringAndMapBuilders.kt
1
1102
package v_builders import util.TODO fun buildStringExample(): String { fun buildString(build: StringBuilder.() -> Unit): String { val stringBuilder = StringBuilder() stringBuilder.build() return stringBuilder.toString() } return buildString { this.append("Numbers: ") for (i in 1..10) { // 'this' can be omitted append(i) } } } fun todoTask37(): Nothing = TODO( """ Task 37. Uncomment the commented code and make it compile. Add and implement function 'buildMap' with one parameter (of type extension function) creating a new HashMap, building it and returning it as a result. """ ) //The official solution is better than mine. Make sure to check that! =) fun buildMap(populate: MutableMap<Int, String>.() -> Unit): Map<Int, String> { val map = mutableMapOf<Int, String>() map.populate() return map.toMap() } fun task37(): Map<Int, String> { return buildMap { put(0, "0") for (i in 1..10) { put(i, "$i") } } }
mit
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/registry/SubsystemsRegistry.kt
1
484
package org.snakeskin.registry import org.snakeskin.subsystem.Subsystem /** * @author Cameron Earle * @version 7/16/17 * * The subsystem registry, which all subsystems that need to be loaded should be added to */ object SubsystemsRegistry: Registry<Subsystem>() { @JvmStatic internal fun initAll() { registry.forEach { it.init() } } @JvmStatic fun testAll() { registry.forEach { it.checkSubsystem() } } }
gpl-3.0
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/JsonRegistrationHandler.kt
1
3080
package jetbrains.buildServer.nuget.feed.server.json import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedFactory import jetbrains.buildServer.serverSide.TeamCityProperties import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class JsonRegistrationHandler(private val feedFactory: NuGetFeedFactory, private val packageSourceFactory: JsonPackageSourceFactory, private val adapterFactory: JsonPackageAdapterFactory) : NuGetFeedHandler { override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { val matchResult = REGISTRATION_URL.find(request.pathInfo) if (matchResult != null) { val (id, resource) = matchResult.destructured val feed = feedFactory.createFeed(feedData) val context = JsonNuGetFeedContext(feed, request) if (resource == "index") { if (DispatcherUtils.isAsyncEnabled()) { DispatcherUtils.dispatchGetRegistrations(request, response, context, id) } else { getAllRegistrations(response, context, id) } } else { if (DispatcherUtils.isAsyncEnabled()) { DispatcherUtils.dispatchGetRegistration(request, response, context, id, resource) } else { getRegistration(response, context, id, resource) } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Requested resource not found") } } private fun getRegistration(response: HttpServletResponse, context: JsonNuGetFeedContext, id: String, version: String) { val packageSource = packageSourceFactory.create(context.feed) val results = packageSource.getPackages(id) if (!results.isEmpty()) { val adapter = adapterFactory.create(context) response.writeJson(adapter.createPackagesResponse(id, results)) } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Package $id:$version not found") } } private fun getAllRegistrations(response: HttpServletResponse, context: JsonNuGetFeedContext,id: String) { val packageSource = packageSourceFactory.create(context.feed) val results = packageSource.getPackages(id) if (!results.isEmpty()) { val adapter = adapterFactory.create(context) response.writeJson(adapter.createPackagesResponse(id, results)) } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Package $id not found") } } companion object { private val REGISTRATION_URL = Regex("\\/registration1\\/([^\\/]+)\\/([^\\/]+)\\.json") } }
apache-2.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/achievement/list/AchievementListViewState.kt
1
1554
package io.ipoli.android.achievement.list import io.ipoli.android.achievement.usecase.CreateAchievementItemsUseCase import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState /** * Created by Venelin Valkov <[email protected]> * on 06/09/2018. */ sealed class AchievementListAction : Action { object Load : AchievementListAction() } object AchievementListReducer : BaseViewStateReducer<AchievementListViewState>() { override val stateKey = key<AchievementListViewState>() override fun reduce( state: AppState, subState: AchievementListViewState, action: Action ) = when (action) { is DataLoadedAction.AchievementItemsChanged -> { subState.copy( type = AchievementListViewState.StateType.ACHIEVEMENTS_LOADED, achievementListItems = action.achievementListItems ) } else -> subState } override fun defaultState() = AchievementListViewState( type = AchievementListViewState.StateType.LOADING, achievementListItems = emptyList() ) } data class AchievementListViewState( val type: StateType, val achievementListItems: List<CreateAchievementItemsUseCase.AchievementListItem> ) : BaseViewState() { enum class StateType { LOADING, ACHIEVEMENTS_LOADED } }
gpl-3.0
mobilesolutionworks/works-controller-android
library/src/main/kotlin/com/mobilesolutionworks/android/app/controller/WorksController.kt
1
3882
package com.mobilesolutionworks.android.app.controller import android.content.Context import android.content.res.Configuration import android.os.Bundle import android.support.annotation.StringRes /** * The main class of this library. * * * Created by yunarta on 16/11/15. */ open class WorksController(val mManager: WorksControllerManager) { // /** // * Reference to manager. // */ // private var mManager: WorksControllerManager? = null // /** // * Set controller manager, called by manager. // // * @param manager the controller manager. // */ // internal fun setControllerManager(manager: WorksControllerManager) { // mManager = manager // } /** * Get application context from controller. * @return application context. */ val context: Context get() = mManager.context /** * Get string from context */ fun getString(@StringRes id: Int): String { return mManager.context.getString(id) } /** * Called when manager is creating this controller. * * * This is not related to Activity or Fragment onCreate. * @param arguments arguments that is supplied in [WorksControllerManager.initController] */ open fun onCreate(arguments: Bundle?) { // Lifecycle event called when controller is created } internal fun dispatchOnPaused() = onPaused() /** * Called when host enters paused state. */ protected fun onPaused() { // Lifecycle event called when host is paused } /** * Called when host enters resumed state */ protected fun onResume() { // Lifecycle event called when host is resumed } internal fun dispatchOnResume() = onResume() /** * Called when manager destroy the controller. */ open fun onDestroy() { // Lifecycle event called when controlled is destroyed } /** * Called when after host re-creation. * @param state contains stated that you store in onSaveInstanceState. */ open fun onRestoreInstanceState(state: Bundle) { // Lifecycle event called when host is view state is restored } internal fun dispatchOnRestoreInstanceState(state: Bundle) = onRestoreInstanceState(state) /** * Called when host enter re-creation state. * * * In certain state, the controller might get release along with host * but usually what you store in state is still preserved after creation. * @param outState bundle for storing information if required. */ open fun onSaveInstanceState(outState: Bundle) { // Lifecycle event called when host is want to save instance state } internal fun dispatchOnSaveInstanceState(outState: Bundle) = onSaveInstanceState(outState) /** * Called when host receive onConfigurationChanged. * @param config new configuration. */ open fun onConfigurationChanged(config: Configuration) { // Lifecycle event called when host has configuration changed } /** * Executes the specified runnable after application enter resumed state. * @param runnable runnable object. */ fun runWhenUiIsReady(runnable: Runnable) { mManager.mainScheduler.runWhenUiIsReady(runnable) } /** * Executes the specified runnable immediately in main thread. * @param runnable runnable object. */ fun runOnMainThread(runnable: Runnable) { mManager.mainScheduler.runOnMainThread(runnable) } /** * Executes the specified runnable delayed in main thread. * @param runnable runnable object. * * * @param delay time to delay in milliseconds. */ fun runOnMainThreadDelayed(runnable: Runnable, delay: Long) { mManager.mainScheduler.runOnMainThreadDelayed(runnable, delay) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/imports/ImportsUtils.kt
8
2434
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ImportsUtils") package org.jetbrains.kotlin.idea.imports import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.types.KotlinType val DeclarationDescriptor.importableFqName: FqName? get() { if (!canBeReferencedViaImport()) return null return getImportableDescriptor().fqNameSafe } fun DeclarationDescriptor.canBeReferencedViaImport(): Boolean { if (this is PackageViewDescriptor || DescriptorUtils.isTopLevelDeclaration(this) || this is CallableDescriptor && DescriptorUtils.isStaticDeclaration(this) ) { return !name.isSpecial } //Both TypeAliasDescriptor and ClassDescriptor val parentClassifier = containingDeclaration as? ClassifierDescriptorWithTypeParameters ?: return false if (!parentClassifier.canBeReferencedViaImport()) return false return when (this) { is ConstructorDescriptor -> !parentClassifier.isInner // inner class constructors can't be referenced via import is ClassDescriptor, is TypeAliasDescriptor -> true else -> parentClassifier is ClassDescriptor && parentClassifier.kind == ClassKind.OBJECT } } fun DeclarationDescriptor.canBeAddedToImport(): Boolean = this !is PackageViewDescriptor && canBeReferencedViaImport() fun KotlinType.canBeReferencedViaImport(): Boolean { val descriptor = constructor.declarationDescriptor return descriptor != null && descriptor.canBeReferencedViaImport() } // for cases when class qualifier refers companion object treats it like reference to class itself fun KtReferenceExpression.getImportableTargets(bindingContext: BindingContext): Collection<DeclarationDescriptor> { val targets = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, this]?.let { listOf(it) } ?: getReferenceTargets(bindingContext) return targets.map { it.getImportableDescriptor() }.toSet() }
apache-2.0
GunoH/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/tests/testData/symbolicId/before/entity.kt
2
1005
package com.intellij.workspaceModel.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityWithSymbolicId interface SimpleSymbolicIdEntity : WorkspaceEntityWithSymbolicId { val version: Int val name: String val related: SimpleId val sealedClassWithLinks: SealedClassWithLinks override val symbolicId: SimpleId get() = SimpleId(name) } data class SimpleId(val name: String) : SymbolicEntityId<SimpleSymbolicIdEntity> { override val presentableName: String get() = name } sealed class SealedClassWithLinks { object Nothing : SealedClassWithLinks() data class Single(val id: SimpleId) : SealedClassWithLinks() sealed class Many() : SealedClassWithLinks() { data class Ordered(val list: List<SimpleId>) : Many() data class Unordered(val set: Set<SimpleId>) : Many() } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUImplicitReturnExpression.kt
4
880
// 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.uast.kotlin import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UReturnExpression import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement @ApiStatus.Internal class KotlinUImplicitReturnExpression( givenParent: UElement?, ) : KotlinAbstractUExpression(givenParent), UReturnExpression, KotlinUElementWithType, KotlinFakeUElement { override val psi: PsiElement? get() = null override lateinit var returnExpression: UExpression override fun unwrapToSourcePsi(): List<PsiElement> { return returnExpression.toSourcePsiFakeAware() } }
apache-2.0
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/ToolWindowUtils.kt
2
3311
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataProvider import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithToolWindowActionsPanel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithTwoToolbarsPanel import org.jetbrains.annotations.Nls import javax.swing.JComponent internal fun PackageSearchPanelBase.initialize(contentFactory: ContentFactory): Content { val panelContent = content // should be executed before toolbars val toolbar = toolbar val topToolbar = topToolbar val gearActions = gearActions val titleActions = titleActions return if (topToolbar == null) { createSimpleToolWindowWithToolWindowActionsPanel( title = title, content = panelContent, toolbar = toolbar, gearActions = gearActions, titleActions = titleActions, contentFactory = contentFactory, provider = this ) } else { contentFactory.createContent( toolbar?.let { SimpleToolWindowWithTwoToolbarsPanel( it, topToolbar, gearActions, titleActions, panelContent ) }, title, false ).apply { isCloseable = false } } } internal fun createSimpleToolWindowWithToolWindowActionsPanel( @Nls title: String, content: JComponent, toolbar: JComponent?, gearActions: ActionGroup?, titleActions: List<AnAction>, contentFactory: ContentFactory, provider: DataProvider ): Content { val createContent = contentFactory.createContent(null, title, false) val actionsPanel = SimpleToolWindowWithToolWindowActionsPanel( gearActions = gearActions, titleActions = titleActions, vertical = false, provider = provider ) actionsPanel.setProvideQuickActions(true) actionsPanel.setContent(content) toolbar?.let { actionsPanel.toolbar = it } createContent.component = actionsPanel createContent.isCloseable = false return createContent }
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/smartStepInto/inlinedFunLiteral.kt
4
122
fun foo() { <caret>f1() { } } inline fun f1(f: () -> Unit) {} // EXISTS: f1(() -> Unit), f1: f.invoke() // IGNORE_K2
apache-2.0
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/Agreements.kt
2
4512
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Agreements") package com.intellij.ide.gdpr import com.intellij.diagnostic.LoadingState import com.intellij.idea.AppExitCodes import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.AppUIUtil import java.util.* import kotlin.system.exitProcess fun showEndUserAndDataSharingAgreements(agreement: EndUserAgreement.Document) { val ui = AgreementUi.create(agreement.text) applyUserAgreement(ui, agreement).pack().show() } internal fun showDataSharingAgreement() { val ui = AgreementUi.create() applyDataSharing(ui, ResourceBundle.getBundle("messages.AgreementsBundle")).pack().show() } private fun applyUserAgreement(ui: AgreementUi, agreement: EndUserAgreement.Document): AgreementUi { val isPrivacyPolicy = agreement.isPrivacyPolicy val bundle = ResourceBundle.getBundle("messages.AgreementsBundle") val commonUserAgreement = ui .setTitle( if (isPrivacyPolicy) ApplicationInfoImpl.getShadowInstance().shortCompanyName + " " + bundle.getString("userAgreement.dialog.privacyPolicy.title") else ApplicationNamesInfo.getInstance().fullProductName + " " + bundle.getString("userAgreement.dialog.userAgreement.title")) .setDeclineButton(bundle.getString("userAgreement.dialog.exit")) { if (LoadingState.COMPONENTS_REGISTERED.isOccurred) { ApplicationManager.getApplication().exit(true, true, false) } else { exitProcess(AppExitCodes.PRIVACY_POLICY_REJECTION) } } .addCheckBox(bundle.getString("userAgreement.dialog.checkBox")) { checkBox -> ui.enableAcceptButton(checkBox.isSelected) if (checkBox.isSelected) ui.focusToAcceptButton() } if (ApplicationInfoImpl.getShadowInstance().isEAP) { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } .addEapPanel(isPrivacyPolicy) } else { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) if (ConsentOptions.needToShowUsageStatsConsent()) { applyDataSharing(ui, bundle) } else { dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } } } return ui } private fun applyDataSharing(ui: AgreementUi, bundle: ResourceBundle): AgreementUi { val dataSharingConsent = ConsentOptions.getInstance().getConsents(ConsentOptions.condUsageStatsConsent()).first[0] ui.setContent(prepareConsentsHtml(dataSharingConsent, bundle)) .setTitle(bundle.getString("dataSharing.dialog.title")) .clearBottomPanel() .focusToText() .setAcceptButton(bundle.getString("dataSharing.dialog.accept")) { AppUIUtil.saveConsents(listOf(dataSharingConsent.derive(true))) it.close(DialogWrapper.OK_EXIT_CODE) } .setDeclineButton(bundle.getString("dataSharing.dialog.decline")) { AppUIUtil.saveConsents(listOf(dataSharingConsent.derive(false))) it.close(DialogWrapper.CANCEL_EXIT_CODE) } return ui } private fun prepareConsentsHtml(consent: Consent, bundle: ResourceBundle): HtmlChunk { val allProductChunk = if (!ConsentOptions.getInstance().isEAP) { val hint = bundle.getString("dataSharing.applyToAll.hint").replace("{0}", ApplicationInfoImpl.getShadowInstance().shortCompanyName) HtmlChunk.text(hint).wrapWith("hint").wrapWith("p") } else HtmlChunk.empty() val preferencesHint = bundle.getString("dataSharing.revoke.hint").replace("{0}", ShowSettingsUtil.getSettingsMenuName()) val preferencesChunk = HtmlChunk.text(preferencesHint).wrapWith("hint").wrapWith("p") val title = HtmlChunk.text(bundle.getString("dataSharing.consents.title")).wrapWith("h1") return HtmlBuilder() .append(title) .append(HtmlChunk.p().addRaw(consent.text)) .append(allProductChunk) .append(preferencesChunk) .wrapWithHtmlBody() }
apache-2.0
jk1/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/ssi/SsiProcessor.kt
3
14607
// 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.builtInWebServer.ssi import com.intellij.openapi.diagnostic.Logger import com.intellij.util.SmartList import com.intellij.util.io.inputStream import com.intellij.util.io.lastModified import com.intellij.util.io.readChars import com.intellij.util.io.size import com.intellij.util.text.CharArrayUtil import gnu.trove.THashMap import io.netty.buffer.ByteBufUtf8Writer import java.io.IOException import java.nio.file.Path import java.util.* internal val LOG = Logger.getInstance(SsiProcessor::class.java) internal val COMMAND_START = "<!--#" internal val COMMAND_END = "-->" class SsiStopProcessingException : RuntimeException() class SsiProcessor(allowExec: Boolean) { private val commands: MutableMap<String, SsiCommand> = THashMap() init { commands.put("config", SsiCommand { state, _, paramNames, paramValues, writer -> for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] val substitutedValue = state.substituteVariables(paramValue) when { paramName.equals("errmsg", ignoreCase = true) -> state.configErrorMessage = substitutedValue paramName.equals("sizefmt", ignoreCase = true) -> state.configSizeFmt = substitutedValue paramName.equals("timefmt", ignoreCase = true) -> state.setConfigTimeFormat(substitutedValue, false) else -> { LOG.info("#config--Invalid attribute: $paramName") // We need to fetch this value each time, since it may change during the loop writer.write(state.configErrorMessage) } } } 0 }) commands.put("echo", SsiCommand { state, _, paramNames, paramValues, writer -> var encoding = "entity" var originalValue: String? = null val errorMessage = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] if (paramName.equals("var", ignoreCase = true)) { originalValue = paramValue } else if (paramName.equals("encoding", ignoreCase = true)) { if (paramValue.equals("url", ignoreCase = true) || paramValue.equals("entity", ignoreCase = true) || paramValue.equals("none", ignoreCase = true)) { encoding = paramValue } else { LOG.info("#echo--Invalid encoding: $paramValue") writer.write(errorMessage) } } else { LOG.info("#echo--Invalid attribute: $paramName") writer.write(errorMessage) } } val variableValue = state.getVariableValue(originalValue!!, encoding) writer.write(variableValue ?: "(none)") System.currentTimeMillis() }) //noinspection StatementWithEmptyBody if (allowExec) { // commands.put("exec", new SsiExec()); } commands.put("include", SsiCommand { state, commandName, paramNames, paramValues, writer -> var lastModified: Long = 0 val configErrorMessage = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] if (paramName.equals("file", ignoreCase = true) || paramName.equals("virtual", ignoreCase = true)) { val substitutedValue = state.substituteVariables(paramValues[i]) try { val virtual = paramName.equals("virtual", ignoreCase = true) lastModified = state.ssiExternalResolver.getFileLastModified(substitutedValue, virtual) val file = state.ssiExternalResolver.findFile(substitutedValue, virtual) if (file == null) { LOG.warn("#include-- Couldn't find file: $substitutedValue") return@SsiCommand 0 } file.inputStream().use { writer.write(it, file.size().toInt()) } } catch (e: IOException) { LOG.warn("#include--Couldn't include file: $substitutedValue", e) writer.write(configErrorMessage) } } else { LOG.info("#include--Invalid attribute: $paramName") writer.write(configErrorMessage) } } lastModified }) commands.put("flastmod", SsiCommand { state, _, paramNames, paramValues, writer -> var lastModified: Long = 0 val configErrMsg = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] val substitutedValue = state.substituteVariables(paramValue) if (paramName.equals("file", ignoreCase = true) || paramName.equals("virtual", ignoreCase = true)) { val virtual = paramName.equals("virtual", ignoreCase = true) lastModified = state.ssiExternalResolver.getFileLastModified(substitutedValue, virtual) val strftime = Strftime(state.configTimeFmt, Locale.US) writer.write(strftime.format(Date(lastModified))) } else { LOG.info("#flastmod--Invalid attribute: $paramName") writer.write(configErrMsg) } } lastModified }) commands.put("fsize", SsiFsize()) commands.put("printenv", SsiCommand { state, _, paramNames, _, writer -> var lastModified: Long = 0 // any arguments should produce an error if (paramNames.isEmpty()) { val variableNames = LinkedHashSet<String>() //These built-in variables are supplied by the mediator ( if not over-written by the user ) and always exist variableNames.add("DATE_GMT") variableNames.add("DATE_LOCAL") variableNames.add("LAST_MODIFIED") state.ssiExternalResolver.addVariableNames(variableNames) for (variableName in variableNames) { var variableValue: String? = state.getVariableValue(variableName) // This shouldn't happen, since all the variable names must have values if (variableValue == null) { variableValue = "(none)" } writer.append(variableName).append('=').append(variableValue).append('\n') lastModified = System.currentTimeMillis() } } else { writer.write(state.configErrorMessage) } lastModified }) commands.put("set", SsiCommand { state, _, paramNames, paramValues, writer -> var lastModified: Long = 0 val errorMessage = state.configErrorMessage var variableName: String? = null for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] if (paramName.equals("var", ignoreCase = true)) { variableName = paramValue } else if (paramName.equals("value", ignoreCase = true)) { if (variableName != null) { val substitutedValue = state.substituteVariables(paramValue) state.ssiExternalResolver.setVariableValue(variableName, substitutedValue) lastModified = System.currentTimeMillis() } else { LOG.info("#set--no variable specified") writer.write(errorMessage) throw SsiStopProcessingException() } } else { LOG.info("#set--Invalid attribute: $paramName") writer.write(errorMessage) throw SsiStopProcessingException() } } lastModified }) val ssiConditional = SsiConditional() commands.put("if", ssiConditional) commands.put("elif", ssiConditional) commands.put("endif", ssiConditional) commands.put("else", ssiConditional) } /** * @return the most current modified date resulting from any SSI commands */ fun process(ssiExternalResolver: SsiExternalResolver, file: Path, writer: ByteBufUtf8Writer): Long { val fileContents = file.readChars() var lastModifiedDate = file.lastModified().toMillis() val ssiProcessingState = SsiProcessingState(ssiExternalResolver, lastModifiedDate) var index = 0 var inside = false val command = StringBuilder() writer.ensureWritable(file.size().toInt()) try { while (index < fileContents.length) { val c = fileContents[index] if (inside) { if (c == COMMAND_END[0] && charCmp(fileContents, index, COMMAND_END)) { inside = false index += COMMAND_END.length val commandName = parseCommand(command) if (LOG.isDebugEnabled) { LOG.debug("SSIProcessor.process -- processing command: $commandName") } val paramNames = parseParamNames(command, commandName.length) val paramValues = parseParamValues(command, commandName.length, paramNames.size) // We need to fetch this value each time, since it may change during the loop val configErrMsg = ssiProcessingState.configErrorMessage val ssiCommand = commands[commandName.toLowerCase(Locale.ENGLISH)] var errorMessage: String? = null if (ssiCommand == null) { errorMessage = "Unknown command: $commandName" } else if (paramValues == null) { errorMessage = "Error parsing directive parameters." } else if (paramNames.size != paramValues.size) { errorMessage = "Parameter names count does not match parameter values count on command: $commandName" } else { // don't process the command if we are processing conditional commands only and the command is not conditional if (!ssiProcessingState.conditionalState.processConditionalCommandsOnly || ssiCommand is SsiConditional) { val newLastModified = ssiCommand.process(ssiProcessingState, commandName, paramNames, paramValues, writer) if (newLastModified > lastModifiedDate) { lastModifiedDate = newLastModified } } } if (errorMessage != null) { LOG.warn(errorMessage) writer.write(configErrMsg) } } else { command.append(c) index++ } } else if (c == COMMAND_START[0] && charCmp(fileContents, index, COMMAND_START)) { inside = true index += COMMAND_START.length command.setLength(0) } else { if (!ssiProcessingState.conditionalState.processConditionalCommandsOnly) { writer.append(c) } index++ } } } catch (e: SsiStopProcessingException) { //If we are here, then we have already stopped processing, so all is good } return lastModifiedDate } protected fun parseParamNames(command: StringBuilder, start: Int): List<String> { var bIdx = start val values = SmartList<String>() var inside = false val builder = StringBuilder() while (bIdx < command.length) { if (inside) { while (bIdx < command.length && command[bIdx] != '=') { builder.append(command[bIdx]) bIdx++ } values.add(builder.toString()) builder.setLength(0) inside = false var quotes = 0 var escaped = false while (bIdx < command.length && quotes != 2) { val c = command[bIdx] // Need to skip escaped characters if (c == '\\' && !escaped) { escaped = true bIdx++ continue } if (c == '"' && !escaped) { quotes++ } escaped = false bIdx++ } } else { while (bIdx < command.length && isSpace(command[bIdx])) { bIdx++ } if (bIdx >= command.length) { break } inside = true } } return values } @SuppressWarnings("AssignmentToForLoopParameter") protected fun parseParamValues(command: StringBuilder, start: Int, count: Int): Array<String>? { var valueIndex = 0 var inside = false val values = arrayOfNulls<String>(count) val builder = StringBuilder() var endQuote: Char = 0.toChar() var bIdx = start while (bIdx < command.length) { if (!inside) { while (bIdx < command.length && !isQuote(command[bIdx])) { bIdx++ } if (bIdx >= command.length) { break } inside = true endQuote = command[bIdx] } else { var escaped = false while (bIdx < command.length) { val c = command[bIdx] // Check for escapes if (c == '\\' && !escaped) { escaped = true bIdx++ continue } // If we reach the other " then stop if (c == endQuote && !escaped) { break } // Since parsing of attributes and var // substitution is done in separate places, // we need to leave escape in the string if (c == '$' && escaped) { builder.append('\\') } escaped = false builder.append(c) bIdx++ } // If we hit the end without seeing a quote // the signal an error if (bIdx == command.length) { return null } values[valueIndex++] = builder.toString() builder.setLength(0) inside = false } bIdx++ } @Suppress("CAST_NEVER_SUCCEEDS", "UNCHECKED_CAST") return values as Array<String> } private fun parseCommand(instruction: StringBuilder): String { var firstLetter = -1 var lastLetter = -1 for (i in 0..instruction.length - 1) { val c = instruction[i] if (Character.isLetter(c)) { if (firstLetter == -1) { firstLetter = i } lastLetter = i } else if (isSpace(c)) { if (lastLetter > -1) { break } } else { break } } return if (firstLetter == -1) "" else instruction.substring(firstLetter, lastLetter + 1) } protected fun charCmp(buf: CharSequence, index: Int, command: String): Boolean = CharArrayUtil.regionMatches(buf, index, index + command.length, command) protected fun isSpace(c: Char): Boolean = c == ' ' || c == '\n' || c == '\t' || c == '\r' protected fun isQuote(c: Char): Boolean = c == '\'' || c == '\"' || c == '`' }
apache-2.0
pdvrieze/kotlinsql
monadic/src/test/kotlin/io/github/pdvrieze/kotlinsql/monadic/test/TestCreateTransitiveMonadic.kt
1
13464
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.pdvrieze.kotlinsql.monadic.test import io.github.pdvrieze.jdbc.recorder.RecordingConnection import io.github.pdvrieze.jdbc.recorder.RecordingConnection.RecordingPreparedStatement import io.github.pdvrieze.jdbc.recorder.actions.* import io.github.pdvrieze.kotlinsql.direct.test.users import io.github.pdvrieze.kotlinsql.monadic.* import io.github.pdvrieze.kotlinsql.monadic.actions.transform import io.github.pdvrieze.kotlinsql.monadic.invoke import io.github.pdvrieze.kotlinsql.test.helpers.DummyConnection import io.github.pdvrieze.kotlinsql.test.helpers.DummyConnection.DummyPreparedStatement import io.github.pdvrieze.kotlinsql.test.helpers.DummyDataSource import io.github.pdvrieze.kotlinsql.test.helpers.TestActions import io.github.pdvrieze.kotlinsql.test.helpers.WebAuthDB import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.sql.Wrapper import java.util.stream.Collectors.toList class TestCreateTransitiveMonadic { @Test fun testFakeQuery() { val source = DummyDataSource(WebAuthDB) val names:List<String> = WebAuthDB(source) { SELECT(users.fullname).transform().commit() }.requireNoNulls() val expectedNames= arrayOf("Joe Blogs") val c = source.lastConnection!! val dc = c.unwrap<DummyConnection>() val q = "SELECT `fullname` FROM `users`" val expectedActions = listOf( SetAutoCommit(false), dc.DummyPreparedStatement(q), dc.DummyResultSet(q), StringAction("""ResultSet().next() -> true"""), StringAction("""ResultSet().getString(1) -> "Joe Blogs""""), StringAction("""ResultSet().next() -> false"""), ResultSetClose, StatementClose(q), Commit, ConnectionClose ) val filterText = listOf("getAutoCommit()", "isAfterLast()", "isLast()") val filteredActions = c.getFilteredActions() c.actions.filter { action -> action !is StringAction || filterText.none { t -> t in action.string } } assertEquals(expectedActions.joinToString(",\n"), filteredActions.joinToString(",\n")) assertArrayEquals(expectedActions.toTypedArray(), filteredActions.toTypedArray()) assertArrayEquals(expectedNames, names.toTypedArray()) } @Test fun testInsert() { val source = DummyDataSource(WebAuthDB) val insertCount: IntArray = WebAuthDB(source) { // transaction { INSERT(users.user, users.fullname, users.alias) .VALUES("jdoe", "John Doe", "John") .VALUES("janie", "Jane Doe", "Jane") .commit() // } } val c = source.lastConnection!! val dc = c.unwrap(DummyConnection::class.java)!! assertEquals(2, insertCount.size) val q = "INSERT INTO `users` (`user`, `fullname`, `alias`) VALUES (?, ?, ?)" val psstr = "RecordingPreparedStatement(\"$q\")" val expectedActions = listOf( SetAutoCommit.FALSE, dc.DummyPreparedStatement(q), StringAction("$psstr.setString(1, \"jdoe\")"), StringAction("$psstr.setString(2, \"John Doe\")"), StringAction("$psstr.setString(3, \"John\")"), StringAction("$psstr.addBatch()"), StringAction("$psstr.setString(1, \"janie\")"), StringAction("$psstr.setString(2, \"Jane Doe\")"), StringAction("$psstr.setString(3, \"Jane\")"), StringAction("$psstr.addBatch()"), StringAction("$psstr.executeBatch() -> [1, 1]"), StatementClose(q), Commit, ConnectionClose ) val filteredActions = c.getFilteredActions() assertEquals(expectedActions.joinToString(",\n"), filteredActions.joinToString(",\n")) assertArrayEquals(expectedActions.toTypedArray(), filteredActions.toTypedArray()) } @Test fun testCreateTransitive() { val source = DummyDataSource() source.setTables(WebAuthDB.roles) val tableNames = WebAuthDB(source) { metadata.getTables().mapEach { it.tableName } .commit() } assertEquals(listOf("roles"), tableNames) WebAuthDB(source) { ensureTables() .commit() } val filteredActions = source.lastConnection!!.getFilteredActions() val expectedActions = listOf<Action>( SetAutoCommit.FALSE, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, null, ["TABLE"]) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> true"""), StringAction("""ResultSet(getTables()).getString(3 ~> TABLE_NAME) -> "roles""""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getColumns(null, null, "roles", null) -> ResultSet(metadata.getColumns())"""), StringAction("""ResultSet(metadata.getColumns()).next() -> true"""), StringAction("""ResultSet(metadata.getColumns()).getInt(16 ~> CHAR_OCTET_LENGTH) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getInt(5 ~> DATA_TYPE) -> 12"""), StringAction("""ResultSet(metadata.getColumns()).getString(18 ~> IS_NULLABLE) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getInt(11 ~> NULLABLE) -> 1"""), StringAction("""ResultSet(metadata.getColumns()).getInt(17 ~> ORDINAL_POSITION) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(12 ~> REMARKS) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(6 ~> TYPE_NAME) -> "VARCHAR""""), StringAction("""ResultSet(metadata.getColumns()).getString(13 ~> COLUMN_DEF) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(4 ~> COLUMN_NAME) -> "role""""), StringAction("""ResultSet(metadata.getColumns()).getInt(7 ~> COLUMN_SIZE) -> 30"""), StringAction("""ResultSet(metadata.getColumns()).getInt(9 ~> DECIMAL_DIGITS) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(23 ~> IS_AUTOINCREMENT) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getString(24 ~> IS_GENERATEDCOLUMN) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getInt(10 ~> NUM_PREC_RADIX) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(1 ~> TABLE_CAT) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(3 ~> TABLE_NAME) -> "roles""""), StringAction("""ResultSet(metadata.getColumns()).getString(2 ~> TABLE_SCHEM) -> null"""), StringAction("""ResultSet(metadata.getColumns()).next() -> true"""), StringAction("""ResultSet(metadata.getColumns()).getInt(16 ~> CHAR_OCTET_LENGTH) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getInt(5 ~> DATA_TYPE) -> 12"""), StringAction("""ResultSet(metadata.getColumns()).getString(18 ~> IS_NULLABLE) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getInt(11 ~> NULLABLE) -> 1"""), StringAction("""ResultSet(metadata.getColumns()).getInt(17 ~> ORDINAL_POSITION) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(12 ~> REMARKS) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(6 ~> TYPE_NAME) -> "VARCHAR""""), StringAction("""ResultSet(metadata.getColumns()).getString(13 ~> COLUMN_DEF) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(4 ~> COLUMN_NAME) -> "description""""), StringAction("""ResultSet(metadata.getColumns()).getInt(7 ~> COLUMN_SIZE) -> 120"""), StringAction("""ResultSet(metadata.getColumns()).getInt(9 ~> DECIMAL_DIGITS) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(23 ~> IS_AUTOINCREMENT) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getString(24 ~> IS_GENERATEDCOLUMN) -> "NO""""), StringAction("""ResultSet(metadata.getColumns()).getInt(10 ~> NUM_PREC_RADIX) -> 0"""), StringAction("""ResultSet(metadata.getColumns()).getString(1 ~> TABLE_CAT) -> null"""), StringAction("""ResultSet(metadata.getColumns()).getString(3 ~> TABLE_NAME) -> "roles""""), StringAction("""ResultSet(metadata.getColumns()).getString(2 ~> TABLE_SCHEM) -> null"""), StringAction("""ResultSet(metadata.getColumns()).next() -> false"""), ResultSetClose, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "users", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_USERS, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "user_roles", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_USER_ROLES, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "pubkeys", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_PUBKEYS, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "tokens", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_TOKENS, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "app_perms", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_APP_PERMS, StringAction("""RecordingConnection(null).getMetaData() -> <metadata>"""), StringAction("""<metadata>.getTables(null, null, "challenges", null) -> ResultSet(getTables())"""), StringAction("""ResultSet(getTables()).next() -> false"""), ResultSetClose, TestActions.CREATE_CHALLENGES, Commit, ConnectionClose ) assertEquals(expectedActions.joinToString(",\n"), filteredActions.joinToString(",\n")) assertArrayEquals(expectedActions.toTypedArray(), filteredActions.toTypedArray()) // assertEquals(expectedActions, actualActions) } companion object { private fun RecordingConnection.getFilteredActions( filterText: List<String> = listOf("getAutoCommit()", "isAfterLast()", "isLast()"), ): List<Action> { return actions.filter { action -> when { action is StringAction && ( (action.string.startsWith("ResultSet") && ".findColumn" in action.string ) || filterText.any { it in action.string } ) -> false action is RecordingPreparedStatement && action.unwrap<DummyPreparedStatement>().sql.startsWith("CREATE TABLE") -> false action is StatementClose && action.query?.startsWith("CREATE TABLE") == true -> false else -> true } }.map { when { it is Wrapper && it.isWrapperFor(Action::class.java) -> it.unwrap(Action::class.java) else -> it } } } } } inline fun <reified T> Wrapper.unwrap(): T = unwrap(T::class.java)
apache-2.0
SpineEventEngine/base
testlib/src/test/kotlin/io/spine/protobuf/GoogleTypesTest.kt
1
3089
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.protobuf import com.google.common.truth.Truth.assertThat import com.google.protobuf.EnumValue import io.spine.type.KnownTypes import io.spine.type.TypeName import org.junit.jupiter.api.Test internal class GoogleTypesTest { private val protoFiles = listOf( "google/protobuf/compiler/plugin.proto", "google/protobuf/any.proto", "google/protobuf/api.proto", "google/protobuf/descriptor.proto", "google/protobuf/duration.proto", "google/protobuf/empty.proto", "google/protobuf/field_mask.proto", "google/protobuf/source_context.proto", "google/protobuf/struct.proto", "google/protobuf/timestamp.proto", "google/protobuf/type.proto", "google/protobuf/wrappers.proto" ) /** * Verifies that `EnumValue` protobuf type is known for the production JVM code. * * `io.spine.protobuf.EnumConverter` deals with `com.google.protobuf.EnumValue`, * but `google.protobuf.EnumValue` type is not used in our proto code. * * This test ensures the type is available via descriptors stored in resources. * * Since this module depends on `base` on the `implementation` level, * tests in this module see `base` as if it is used as a library. */ @Test fun `make sure 'EnumValue' is known to production code`() { val type = TypeName.of("google.protobuf.EnumValue") val cls = type.toJavaClass() assertThat(cls).isEqualTo(EnumValue::class.java) } @Test fun `all files from the Protobuf library are included`() { val protobufFiles = KnownTypes.instance().files() .filter { f -> f.name.startsWith("google/protobuf/") } .map { d -> d.name } assertThat(protobufFiles).containsAtLeastElementsIn(protoFiles) } }
apache-2.0
jk1/intellij-community
platform/diff-impl/src/com/intellij/diff/comparison/TrimUtil.kt
3
19540
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("TrimUtil") @file:Suppress("NAME_SHADOWING") package com.intellij.diff.comparison import com.intellij.diff.util.IntPair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.Range import com.intellij.openapi.util.text.StringUtil.isWhiteSpace import java.util.* fun isPunctuation(c: Char): Boolean { if (c == '_') return false val b = c.toInt() return b >= 33 && b <= 47 || // !"#$%&'()*+,-./ b >= 58 && b <= 64 || // :;<=>?@ b >= 91 && b <= 96 || // [\]^_` b >= 123 && b <= 126 // {|}~ } fun isAlpha(c: Char): Boolean { return !isWhiteSpace(c) && !isPunctuation(c) } fun trim(text: CharSequence, start: Int, end: Int): IntPair { return trim(start, end, { index -> isWhiteSpace(text[index]) }) } fun trim(start: Int, end: Int, ignored: BitSet): IntPair { return trim(start, end, { index -> ignored[index] }) } fun trimStart(text: CharSequence, start: Int, end: Int): Int { return trimStart(start, end, { index -> isWhiteSpace(text[index]) }) } fun trimEnd(text: CharSequence, start: Int, end: Int): Int { return trimEnd(start, end, { index -> isWhiteSpace(text[index]) }) } fun trim(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return trim(start1, start2, end1, end2, { index -> isWhiteSpace(text1[index]) }, { index -> isWhiteSpace(text2[index]) }) } fun trim(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): MergeRange { return trim(start1, start2, start3, end1, end2, end3, { index -> isWhiteSpace(text1[index]) }, { index -> isWhiteSpace(text2[index]) }, { index -> isWhiteSpace(text3[index]) }) } fun expand(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandForward(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandBackward(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun <T> expand(text1: List<T>, text2: List<T>, start1: Int, start2: Int, end1: Int, end2: Int, equals: (T, T) -> Boolean): Range { return expand(start1, start2, end1, end2, { index1, index2 -> equals(text1[index1], text2[index2]) }) } fun expand(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandForward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandBackward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expandIgnored(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesForward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandIgnoredForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesBackward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandIgnoredBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): MergeRange { return expandIgnored(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesForward(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): Int { return expandIgnoredForward(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesBackward(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): Int { return expandIgnoredBackward(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun <T> trimExpandRange(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { return trimExpand(start1, start2, end1, end2, { index1, index2 -> equals(index1, index2) }, { index -> ignored1(index) }, { index -> ignored2(index) }) } fun trimExpandText(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int, ignored1: BitSet, ignored2: BitSet): Range { return trimExpand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> ignored1[index] }, { index -> ignored2[index] }) } fun trim(text1: CharSequence, text2: CharSequence, range: Range): Range { return trim(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun trim(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): MergeRange { return trim(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3) } fun expand(text1: CharSequence, text2: CharSequence, range: Range): Range { return expand(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, range: Range): Range { return expandWhitespaces(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): MergeRange { return expandWhitespaces(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3) } fun isEquals(text1: CharSequence, text2: CharSequence, range: Range): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) return ComparisonUtil.isEquals(sequence1, sequence2, ComparisonPolicy.DEFAULT) } fun isEqualsIgnoreWhitespaces(text1: CharSequence, text2: CharSequence, range: Range): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) return ComparisonUtil.isEquals(sequence1, sequence2, ComparisonPolicy.IGNORE_WHITESPACES) } fun isEquals(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) val sequence3 = text3.subSequence(range.start3, range.end3) return ComparisonUtil.isEquals(sequence2, sequence1, ComparisonPolicy.DEFAULT) && ComparisonUtil.isEquals(sequence2, sequence3, ComparisonPolicy.DEFAULT) } fun isEqualsIgnoreWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) val sequence3 = text3.subSequence(range.start3, range.end3) return ComparisonUtil.isEquals(sequence2, sequence1, ComparisonPolicy.IGNORE_WHITESPACES) && ComparisonUtil.isEquals(sequence2, sequence3, ComparisonPolicy.IGNORE_WHITESPACES) } // // Trim // private inline fun trim(start1: Int, start2: Int, end1: Int, end2: Int, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 start1 = trimStart(start1, end1, ignored1) end1 = trimEnd(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) end2 = trimEnd(start2, end2, ignored2) return Range(start1, end1, start2, end2) } private inline fun trim(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean, ignored3: (Int) -> Boolean): MergeRange { var start1 = start1 var start2 = start2 var start3 = start3 var end1 = end1 var end2 = end2 var end3 = end3 start1 = trimStart(start1, end1, ignored1) end1 = trimEnd(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) end2 = trimEnd(start2, end2, ignored2) start3 = trimStart(start3, end3, ignored3) end3 = trimEnd(start3, end3, ignored3) return MergeRange(start1, end1, start2, end2, start3, end3) } private inline fun trim(start: Int, end: Int, ignored: (Int) -> Boolean): IntPair { var start = start var end = end start = trimStart(start, end, ignored) end = trimEnd(start, end, ignored) return IntPair(start, end) } private inline fun trimStart(start: Int, end: Int, ignored: (Int) -> Boolean): Int { var start = start while (start < end) { if (!ignored(start)) break start++ } return start } private inline fun trimEnd(start: Int, end: Int, ignored: (Int) -> Boolean): Int { var end = end while (start < end) { if (!ignored(end - 1)) break end-- } return end } // // Expand // private inline fun expand(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val count1 = expandForward(start1, start2, end1, end2, equals) start1 += count1 start2 += count1 val count2 = expandBackward(start1, start2, end1, end2, equals) end1 -= count2 end2 -= count2 return Range(start1, end1, start2, end2) } private inline fun expandForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Int { var start1 = start1 var start2 = start2 val oldStart1 = start1 while (start1 < end1 && start2 < end2) { if (!equals(start1, start2)) break start1++ start2++ } return start1 - oldStart1 } private inline fun expandBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Int { var end1 = end1 var end2 = end2 val oldEnd1 = end1 while (start1 < end1 && start2 < end2) { if (!equals(end1 - 1, end2 - 1)) break end1-- end2-- } return oldEnd1 - end1 } // // Expand Ignored // private inline fun expandIgnored(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val count1 = expandIgnoredForward(start1, start2, end1, end2, equals, ignored1) start1 += count1 start2 += count1 val count2 = expandIgnoredBackward(start1, start2, end1, end2, equals, ignored1) end1 -= count2 end2 -= count2 return Range(start1, end1, start2, end2) } private inline fun expandIgnoredForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var start1 = start1 var start2 = start2 val oldStart1 = start1 while (start1 < end1 && start2 < end2) { if (!equals(start1, start2)) break if (!ignored1(start1)) break start1++ start2++ } return start1 - oldStart1 } private inline fun expandIgnoredBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var end1 = end1 var end2 = end2 val oldEnd1 = end1 while (start1 < end1 && start2 < end2) { if (!equals(end1 - 1, end2 - 1)) break if (!ignored1(end1 - 1)) break end1-- end2-- } return oldEnd1 - end1 } private inline fun expandIgnored(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): MergeRange { var start1 = start1 var start2 = start2 var start3 = start3 var end1 = end1 var end2 = end2 var end3 = end3 val count1 = expandIgnoredForward(start1, start2, start3, end1, end2, end3, equals12, equals13, ignored1) start1 += count1 start2 += count1 start3 += count1 val count2 = expandIgnoredBackward(start1, start2, start3, end1, end2, end3, equals12, equals13, ignored1) end1 -= count2 end2 -= count2 end3 -= count2 return MergeRange(start1, end1, start2, end2, start3, end3) } private inline fun expandIgnoredForward(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var start1 = start1 var start2 = start2 var start3 = start3 val oldStart1 = start1 while (start1 < end1 && start2 < end2 && start3 < end3) { if (!equals12(start1, start2)) break if (!equals13(start1, start3)) break if (!ignored1(start1)) break start1++ start2++ start3++ } return start1 - oldStart1 } private inline fun expandIgnoredBackward(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var end1 = end1 var end2 = end2 var end3 = end3 val oldEnd1 = end1 while (start1 < end1 && start2 < end2 && start3 < end3) { if (!equals12(end1 - 1, end2 - 1)) break if (!equals13(end1 - 1, end3 - 1)) break if (!ignored1(end1 - 1)) break end1-- end2-- end3-- } return oldEnd1 - end1 } // // Trim Expand // private inline fun trimExpand(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val starts = trimExpandForward(start1, start2, end1, end2, equals, ignored1, ignored2) start1 = starts.val1 start2 = starts.val2 val ends = trimExpandBackward(start1, start2, end1, end2, equals, ignored1, ignored2) end1 = ends.val1 end2 = ends.val2 return Range(start1, end1, start2, end2) } private inline fun trimExpandForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): IntPair { var start1 = start1 var start2 = start2 while (start1 < end1 && start2 < end2) { if (equals(start1, start2)) { start1++ start2++ continue } var skipped = false if (ignored1(start1)) { skipped = true start1++ } if (ignored2(start2)) { skipped = true start2++ } if (!skipped) break } start1 = trimStart(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) return IntPair(start1, start2) } private inline fun trimExpandBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): IntPair { var end1 = end1 var end2 = end2 while (start1 < end1 && start2 < end2) { if (equals(end1 - 1, end2 - 1)) { end1-- end2-- continue } var skipped = false if (ignored1(end1 - 1)) { skipped = true end1-- } if (ignored2(end2 - 1)) { skipped = true end2-- } if (!skipped) break } end1 = trimEnd(start1, end1, ignored1) end2 = trimEnd(start2, end2, ignored2) return IntPair(end1, end2) }
apache-2.0
robnixon/ComputingTutorAndroidApp
app/src/main/java/net/computingtutor/robert/computingtutor/BaseConverterUI.kt
1
815
package net.computingtutor.robert.computingtutor import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.TextView class BaseConverterUI : BaseActivity() { var showingHelp: Boolean = false lateinit var helpTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_base_converter_ui) helpTextView = findViewById(R.id.baseConverterHelpTextView) as TextView } fun showBaseConverterHelp(view: View) { if (showingHelp) { helpTextView.visibility = View.GONE showingHelp = false } else { helpTextView.visibility = View.VISIBLE showingHelp = true } } }
mit
jaycarey/ethtrader-ticker
src/main/java/org/ethtrader/ticker/Reddit.kt
1
961
package org.ethtrader.ticker import org.jsoup.Jsoup import java.io.InputStream class Reddit(private val client: OAuthClient, val subRedditName: String) { fun uploadImage(name: String, ticker: InputStream) { val response = client.postRSubredditUpload_sr_img(subRedditName, "file" to ticker, "name" to name, "upload_type" to "img") println("Response: " + response) } fun uploadStylesheet(css: String) { val response = client.postRSubredditSubreddit_stylesheet(subRedditName, "stylesheet_contents" to css, "op" to "save") println("Response: " + response) } fun getStylesheet(): String = retry(3) { val cssPage = client.requestPlain("/r/$subRedditName/about/stylesheet/").get(String::class.java) val document = Jsoup.parse(cssPage) document.select("pre.subreddit-stylesheet-source > code").text() } }
apache-2.0
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/TachiyomiFullscreenDialog.kt
3
358
package eu.kanade.tachiyomi.widget import android.content.Context import android.view.View import androidx.appcompat.app.AppCompatDialog import eu.kanade.tachiyomi.R class TachiyomiFullscreenDialog(context: Context, view: View) : AppCompatDialog(context, R.style.ThemeOverlay_Tachiyomi_Dialog_Fullscreen) { init { setContentView(view) } }
apache-2.0
code-disaster/lwjgl3
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/EXT_hand_tracking.kt
3
10183
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val EXT_hand_tracking = "EXTHandTracking".nativeClassXR("EXT_hand_tracking", type = "instance", postfix = "EXT") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_EXT_hand_tracking">XR_EXT_hand_tracking</a> extension. This extension enables applications to locate the individual joints of hand tracking inputs. It enables applications to render hands in XR experiences and interact with virtual objects using hand joints. """ IntConstant( "The extension specification version.", "EXT_hand_tracking_SPEC_VERSION".."4" ) StringConstant( "The extension name.", "EXT_HAND_TRACKING_EXTENSION_NAME".."XR_EXT_hand_tracking" ) EnumConstant( "Extends {@code XrObjectType}.", "OBJECT_TYPE_HAND_TRACKER_EXT".."1000051000" ) EnumConstant( "Extends {@code XrStructureType}.", "TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT".."1000051000", "TYPE_HAND_TRACKER_CREATE_INFO_EXT".."1000051001", "TYPE_HAND_JOINTS_LOCATE_INFO_EXT".."1000051002", "TYPE_HAND_JOINT_LOCATIONS_EXT".."1000051003", "TYPE_HAND_JOINT_VELOCITIES_EXT".."1000051004" ) EnumConstant( """ XrHandEXT - Describes which hand the tracker is tracking. <h5>Enumerant Descriptions</h5> <ul> <li>#HAND_LEFT_EXT specifies the hand tracker will be tracking the user’s left hand.</li> <li>#HAND_RIGHT_EXT specifies the hand tracker will be tracking the user’s right hand.</li> </ul> <h5>See Also</h5> ##XrHandTrackerCreateInfoEXT """, "HAND_LEFT_EXT".."1", "HAND_RIGHT_EXT".."2" ) EnumConstant( """ XrHandJointEXT - The name of hand joints that can be tracked <h5>See Also</h5> ##XrHandCapsuleFB, ##XrHandTrackingMeshFB """, "HAND_JOINT_PALM_EXT".."0", "HAND_JOINT_WRIST_EXT".."1", "HAND_JOINT_THUMB_METACARPAL_EXT".."2", "HAND_JOINT_THUMB_PROXIMAL_EXT".."3", "HAND_JOINT_THUMB_DISTAL_EXT".."4", "HAND_JOINT_THUMB_TIP_EXT".."5", "HAND_JOINT_INDEX_METACARPAL_EXT".."6", "HAND_JOINT_INDEX_PROXIMAL_EXT".."7", "HAND_JOINT_INDEX_INTERMEDIATE_EXT".."8", "HAND_JOINT_INDEX_DISTAL_EXT".."9", "HAND_JOINT_INDEX_TIP_EXT".."10", "HAND_JOINT_MIDDLE_METACARPAL_EXT".."11", "HAND_JOINT_MIDDLE_PROXIMAL_EXT".."12", "HAND_JOINT_MIDDLE_INTERMEDIATE_EXT".."13", "HAND_JOINT_MIDDLE_DISTAL_EXT".."14", "HAND_JOINT_MIDDLE_TIP_EXT".."15", "HAND_JOINT_RING_METACARPAL_EXT".."16", "HAND_JOINT_RING_PROXIMAL_EXT".."17", "HAND_JOINT_RING_INTERMEDIATE_EXT".."18", "HAND_JOINT_RING_DISTAL_EXT".."19", "HAND_JOINT_RING_TIP_EXT".."20", "HAND_JOINT_LITTLE_METACARPAL_EXT".."21", "HAND_JOINT_LITTLE_PROXIMAL_EXT".."22", "HAND_JOINT_LITTLE_INTERMEDIATE_EXT".."23", "HAND_JOINT_LITTLE_DISTAL_EXT".."24", "HAND_JOINT_LITTLE_TIP_EXT".."25" ) EnumConstant( """ XrHandJointSetEXT - The set of hand joints to track. <h5>Enumerant Descriptions</h5> <ul> <li>#HAND_JOINT_SET_DEFAULT_EXT indicates that the created {@code XrHandTrackerEXT} tracks the set of hand joints described by {@code XrHandJointEXT} enum, i.e. the #LocateHandJointsEXT() function returns an array of joint locations with the count of #HAND_JOINT_COUNT_EXT and can be indexed using {@code XrHandJointEXT}.</li> </ul> <h5>See Also</h5> ##XrHandTrackerCreateInfoEXT """, "HAND_JOINT_SET_DEFAULT_EXT".."0" ) XrResult( "CreateHandTrackerEXT", """ Create a hand joints handle. <h5>C Specification</h5> An application can create an {@code XrHandTrackerEXT} handle using #CreateHandTrackerEXT() function. <pre><code> ￿XrResult xrCreateHandTrackerEXT( ￿ XrSession session, ￿ const XrHandTrackerCreateInfoEXT* createInfo, ￿ XrHandTrackerEXT* handTracker);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>The {@link EXTHandTracking XR_EXT_hand_tracking} extension <b>must</b> be enabled prior to calling #CreateHandTrackerEXT()</li> <li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li> <li>{@code createInfo} <b>must</b> be a pointer to a valid ##XrHandTrackerCreateInfoEXT structure</li> <li>{@code handTracker} <b>must</b> be a pointer to an {@code XrHandTrackerEXT} handle</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#SESSION_LOSS_PENDING</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_FUNCTION_UNSUPPORTED</li> <li>#ERROR_VALIDATION_FAILURE</li> <li>#ERROR_RUNTIME_FAILURE</li> <li>#ERROR_HANDLE_INVALID</li> <li>#ERROR_INSTANCE_LOST</li> <li>#ERROR_SESSION_LOST</li> <li>#ERROR_OUT_OF_MEMORY</li> <li>#ERROR_LIMIT_REACHED</li> <li>#ERROR_FEATURE_UNSUPPORTED</li> </ul></dd> </dl> If the system does not support hand tracking, runtime <b>must</b> return #ERROR_FEATURE_UNSUPPORTED from #CreateHandTrackerEXT(). In this case, the runtime <b>must</b> return #FALSE for {@code supportsHandTracking} in ##XrSystemHandTrackingPropertiesEXT when the function #GetSystemProperties() is called, so that the application <b>can</b> avoid creating a hand tracker. <h5>See Also</h5> ##XrHandTrackerCreateInfoEXT """, XrSession("session", "an {@code XrSession} in which the hand tracker will be active."), XrHandTrackerCreateInfoEXT.const.p("createInfo", "the ##XrHandTrackerCreateInfoEXT used to specify the hand tracker."), Check(1)..XrHandTrackerEXT.p("handTracker", "the returned {@code XrHandTrackerEXT} handle.") ) XrResult( "DestroyHandTrackerEXT", """ Destroy a hand joints handle. <h5>C Specification</h5> #DestroyHandTrackerEXT() function releases the {@code handTracker} and the underlying resources when finished with hand tracking experiences. <pre><code> ￿XrResult xrDestroyHandTrackerEXT( ￿ XrHandTrackerEXT handTracker);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>The {@link EXTHandTracking XR_EXT_hand_tracking} extension <b>must</b> be enabled prior to calling #DestroyHandTrackerEXT()</li> <li>{@code handTracker} <b>must</b> be a valid {@code XrHandTrackerEXT} handle</li> </ul> <h5>Thread Safety</h5> <ul> <li>Access to {@code handTracker}, and any child handles, <b>must</b> be externally synchronized</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_FUNCTION_UNSUPPORTED</li> <li>#ERROR_HANDLE_INVALID</li> </ul></dd> </dl> """, XrHandTrackerEXT("handTracker", "an {@code XrHandTrackerEXT} previously created by #CreateHandTrackerEXT().") ) XrResult( "LocateHandJointsEXT", """ Locate hand joint locations. <h5>C Specification</h5> The #LocateHandJointsEXT() function locates an array of hand joints to a base space at given time. <pre><code> ￿XrResult xrLocateHandJointsEXT( ￿ XrHandTrackerEXT handTracker, ￿ const XrHandJointsLocateInfoEXT* locateInfo, ￿ XrHandJointLocationsEXT* locations);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>The {@link EXTHandTracking XR_EXT_hand_tracking} extension <b>must</b> be enabled prior to calling #LocateHandJointsEXT()</li> <li>{@code handTracker} <b>must</b> be a valid {@code XrHandTrackerEXT} handle</li> <li>{@code locateInfo} <b>must</b> be a pointer to a valid ##XrHandJointsLocateInfoEXT structure</li> <li>{@code locations} <b>must</b> be a pointer to an ##XrHandJointLocationsEXT structure</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#SESSION_LOSS_PENDING</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_FUNCTION_UNSUPPORTED</li> <li>#ERROR_VALIDATION_FAILURE</li> <li>#ERROR_RUNTIME_FAILURE</li> <li>#ERROR_HANDLE_INVALID</li> <li>#ERROR_INSTANCE_LOST</li> <li>#ERROR_SESSION_LOST</li> <li>#ERROR_TIME_INVALID</li> </ul></dd> </dl> <h5>See Also</h5> ##XrHandJointLocationsEXT, ##XrHandJointsLocateInfoEXT """, XrHandTrackerEXT("handTracker", "an {@code XrHandTrackerEXT} previously created by #CreateHandTrackerEXT()."), XrHandJointsLocateInfoEXT.const.p("locateInfo", "a pointer to ##XrHandJointsLocateInfoEXT describing information to locate hand joints."), XrHandJointLocationsEXT.p("locations", "a pointer to ##XrHandJointLocationsEXT receiving the returned hand joint locations.") ) }
bsd-3-clause
fabioCollini/ArchitectureComponentsDemo
uirepo/src/main/java/it/codingjam/github/ui/repo/ContributorViewHolder.kt
1
633
package it.codingjam.github.ui.repo import android.view.ViewGroup import it.codingjam.github.core.Contributor import it.codingjam.github.ui.common.DataBoundViewHolder import it.codingjam.github.ui.repo.databinding.ContributorItemBinding class ContributorViewHolder(parent: ViewGroup, private val viewModel: RepoViewModel) : DataBoundViewHolder<Contributor, ContributorItemBinding>(parent, ContributorItemBinding::inflate) { init { binding.viewHolder = this } override fun bind(t: Contributor) { binding.contributor = t } fun openUserDetail() = viewModel.openUserDetail(item.login) }
apache-2.0
ayatk/biblio
infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/entity/enums/OutputOrder.kt
1
1822
/* * Copyright (c) 2016-2018 ayatk. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ayatk.biblio.infrastructure.database.entity.enums /** * 小説の出力順序 */ enum class OutputOrder(val id: String) { /** * BOOKMARK_COUNT ブックマーク数の多い順 */ BOOKMARK_COUNT("favnovelcnt"), /** * REVIEW_COUNT レビュー数の多い順 */ REVIEW_COUNT("reviewcnt"), /** * TOTAL_POINT 総合評価の高い順 */ TOTAL_POINT("hyoka"), /** * TOTAL_POINT_ASC 総合評価の低い順 */ TOTAL_POINT_ASC("hyokaasc"), /** * IMPRESSION_COUNT 感想の多い順 */ IMPRESSION_COUNT("impressioncnt"), /** * HYOKA_COUNT 評価者数の多い順 */ HYOKA_COUNT("hyokacnt"), /** * HYOKA_COUNT_ASC 評価者数の少ない順 */ HYOKA_COUNT_ASC("hyokacntasc"), /** * WEEKLY_UNIQUE_USER 週間ユニークユーザの多い順 */ WEEKLY_UNIQUE_USER("weekly"), /** * CHARACTER_LENGTH_DESC 小説本文の文字数が多い順 */ CHARACTER_LENGTH_DESC("lengthdesc"), /** * CHARACTER_LENGTH_ASC 小説本文の文字数が少ない順 */ CHARACTER_LENGTH_ASC("lengthasc"), /** * NCODE_DESC Nコードが新しい順 */ NCODE_DESC("ncodedesc"), /** * OLD 古い順 */ OLD("old"); }
apache-2.0
drakelord/wire
wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt
1
12828
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.kotlin import com.squareup.kotlinpoet.FileSpec import com.squareup.wire.schema.IdentifierSet import com.squareup.wire.schema.RepoBuilder import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class KotlinGeneratorTest { @Test fun basic() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Person { | required string name = 1; | required int32 id = 2; | optional string email = 3; | enum PhoneType { | HOME = 0; | WORK = 1; | MOBILE = 2; | } | message PhoneNumber { | required string number = 1; | optional PhoneType type = 2 [default = HOME]; | } | repeated PhoneNumber phone = 4; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Person") assertTrue(code.contains("data class Person")) assertTrue(code.contains("object : ProtoAdapter<PhoneNumber>(\n")) assertTrue(code.contains("FieldEncoding.LENGTH_DELIMITED")) assertTrue(code.contains("PhoneNumber::class.java")) assertTrue(code.contains("override fun encode(writer: ProtoWriter, value: Person)")) assertTrue(code.contains("enum class PhoneType(private val value: Int) : WireEnum")) assertTrue(code.contains("WORK(1),")) } @Test fun defaultValues() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Message { | optional int32 a = 1 [default = 10 ]; | optional int32 b = 2 [default = 0x20 ]; | optional int64 c = 3 [default = 11 ]; | optional int64 d = 4 [default = 0x21 ]; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Message") assertTrue(code.contains("val a: Int? = 10")) assertTrue(code.contains("val b: Int? = 0x20")) assertTrue(code.contains("val c: Long? = 11")) assertTrue(code.contains("val d: Long? = 0x21")) } @Test fun nameAllocatorIsUsed() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Message { | required float when = 1; | required int32 ADAPTER = 2; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Message") assertTrue(code.contains("val when_: Float")) assertTrue(code.contains("val ADAPTER_: Int")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodedSizeWithTag(1, value.when_) +")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodeWithTag(writer, 1, value.when_)")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodeWithTag(writer, 1, value.when_)")) assertTrue(code.contains("1 -> when_ = ProtoAdapter.FLOAT.decode(reader)")) } @Test fun enclosing() { val schema = RepoBuilder() .add("message.proto", """ |message A { | message B { | } | optional B b = 1; |}""".trimMargin()) .schema() val pruned = schema.prune(IdentifierSet.Builder().include("A.B").build()) val kotlinGenerator = KotlinGenerator.invoke(pruned) val typeSpec = kotlinGenerator.generateType(pruned.getType("A")) val code = FileSpec.get("", typeSpec).toString() assertTrue(code.contains("object A {")) assertTrue(code.contains("data class B(.*) : Message<B, B.Builder>".toRegex())) } @Test fun requestResponse() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/GetFeature", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun noPackage() { val expected = """ |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/RouteGuide/GetFeature", | requestAdapter = "Point#ADAPTER", | responseAdapter = "Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("RouteGuide")) } @Test fun multiDepthPackage() { val expected = """ |package routeguide.grpc | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.grpc.RouteGuide/GetFeature", | requestAdapter = "routeguide.grpc.Point#ADAPTER", | responseAdapter = "routeguide.grpc.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide.grpc; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.grpc.RouteGuide")) } @Test fun streamingRequest() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.Deferred |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/RecordRoute", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.RouteSummary#ADAPTER" | ) | suspend fun RecordRoute(): Pair<SendChannel<Point>, Deferred<RouteSummary>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc RecordRoute(stream Point) returns (RouteSummary) {} |} |$pointMessage |$routeSummaryMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun streamingResponse() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlinx.coroutines.channels.ReceiveChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/ListFeatures", | requestAdapter = "routeguide.Rectangle#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun ListFeatures(request: Rectangle): ReceiveChannel<Feature> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc ListFeatures(Rectangle) returns (stream Feature) {} |} |$rectangeMessage |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun bidirectional() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.channels.ReceiveChannel |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/RouteChat", | requestAdapter = "routeguide.RouteNote#ADAPTER", | responseAdapter = "routeguide.RouteNote#ADAPTER" | ) | suspend fun RouteChat(): Pair<SendChannel<RouteNote>, ReceiveChannel<RouteNote>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} |} |$pointMessage |$routeNoteMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun multipleRpcs() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.channels.ReceiveChannel |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/GetFeature", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature | | @WireRpc( | path = "/routeguide.RouteGuide/RouteChat", | requestAdapter = "routeguide.RouteNote#ADAPTER", | responseAdapter = "routeguide.RouteNote#ADAPTER" | ) | suspend fun RouteChat(): Pair<SendChannel<RouteNote>, ReceiveChannel<RouteNote>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} | rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} |} |$pointMessage |$featureMessage |$routeNoteMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } companion object { private val pointMessage = """ |message Point { | optional int32 latitude = 1; | optional int32 longitude = 2; |}""".trimMargin() private val rectangeMessage = """ |message Rectangle { | optional Point lo = 1; | optional Point hi = 2; |}""".trimMargin() private val featureMessage = """ |message Feature { | optional string name = 1; | optional Point location = 2; |}""".trimMargin() private val routeNoteMessage = """ |message RouteNote { | optional Point location = 1; | optional string message = 2; |}""".trimMargin() private val routeSummaryMessage = """ |message RouteSummary { | optional int32 point_count = 1; | optional int32 feature_count = 2; | optional int32 distance = 3; | optional int32 elapsed_time = 4; |}""".trimMargin() } }
apache-2.0
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/datastore/LocalDataStoreStoreIntegrationShould.kt
1
2591
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.datastore import org.hisp.dhis.android.core.data.database.ObjectWithoutUidStoreAbstractIntegrationShould import org.hisp.dhis.android.core.data.datastore.KeyValuePairSamples.keyValuePairSample import org.hisp.dhis.android.core.datastore.internal.LocalDataStoreStore.create import org.hisp.dhis.android.core.utils.integration.mock.TestDatabaseAdapterFactory import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class LocalDataStoreStoreIntegrationShould : ObjectWithoutUidStoreAbstractIntegrationShould<KeyValuePair>( create(TestDatabaseAdapterFactory.get()), LocalDataStoreTableInfo.TABLE_INFO, TestDatabaseAdapterFactory.get() ) { override fun buildObject(): KeyValuePair { return keyValuePairSample } override fun buildObjectToUpdate(): KeyValuePair { return keyValuePairSample .toBuilder() .value("value2") .build() } }
bsd-3-clause
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/regressiontests/cdata_not_filling_buffer/RssXml.kt
1
272
package com.tickaroo.tikxml.regressiontests.cdata_not_filling_buffer import com.tickaroo.tikxml.annotation.Element import com.tickaroo.tikxml.annotation.Xml @Xml(name = "rss" ) internal class RssXml { @Element(name = "channel") lateinit var detail: DetailXml }
apache-2.0
Apolline-Lille/apolline-android
app/src/main/java/science/apolline/utils/QuerySynchro.kt
1
1176
package science.apolline.utils import android.app.Activity import android.os.AsyncTask import android.os.Build import android.support.annotation.RequiresApi import science.apolline.service.database.AppDatabase import science.apolline.view.activity.SettingsActivity import java.lang.ref.WeakReference class QuerySynchro(activity: SettingsActivity.DataErasePreferenceFragment) : AsyncTask<String, Void, Long>() { //Prevent leak private val weakActivity: WeakReference<Activity> private var mActivity : SettingsActivity.DataErasePreferenceFragment init{ weakActivity = WeakReference(activity.activity) mActivity = activity } @RequiresApi(Build.VERSION_CODES.M) protected override fun doInBackground(vararg params:String):Long { val timestampModel = AppDatabase.getInstance(mActivity.context).timestampSyncDao() when(params[0]) { "getLastSync" -> return timestampModel.getLastSync() else -> return 0 } return timestampModel.getLastSync() } protected override fun onPostExecute(countSyncData:Long) { val activity = weakActivity.get() ?: return } }
gpl-3.0
dahlstrom-g/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt
4
10440
// 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.uast.java import com.intellij.psi.* import com.intellij.psi.impl.light.LightRecordCanonicalConstructor.LightRecordConstructorParameter import com.intellij.psi.impl.light.LightRecordField import com.intellij.psi.impl.source.PsiParameterImpl import com.intellij.psi.impl.source.tree.java.PsiLocalVariableImpl import com.intellij.psi.util.PsiTypesUtil import com.intellij.psi.util.parentOfType import com.intellij.util.castSafelyTo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.internal.UElementAlternative import org.jetbrains.uast.internal.accommodate import org.jetbrains.uast.internal.alternative import org.jetbrains.uast.java.internal.JavaUElementWithComments @ApiStatus.Internal abstract class AbstractJavaUVariable( givenParent: UElement? ) : JavaAbstractUElement(givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner { abstract override val javaPsi: PsiVariable @Suppress("OverridingDeprecatedMember") override val psi get() = javaPsi override val uastInitializer: UExpression? by lz { val initializer = javaPsi.initializer ?: return@lz null UastFacade.findPlugin(initializer)?.convertElement(initializer, this) as? UExpression } override val uAnnotations: List<UAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } } override val typeReference: UTypeReferenceExpression? by lz { javaPsi.typeElement?.let { UastFacade.findPlugin(it)?.convertOpt<UTypeReferenceExpression>(javaPsi.typeElement, this) } } abstract override val sourcePsi: PsiVariable? override val uastAnchor: UIdentifier? get() = sourcePsi?.let { UIdentifier(it.nameIdentifier, this) } override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && javaPsi == other.javaPsi override fun hashCode(): Int = javaPsi.hashCode() } @ApiStatus.Internal class JavaUVariable( override val javaPsi: PsiVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiVariable get() = javaPsi override val sourcePsi: PsiVariable? get() = javaPsi.takeIf { it.isPhysical || it is PsiLocalVariableImpl} companion object { fun create(psi: PsiVariable, containingElement: UElement?): UVariable { return when (psi) { is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement) is PsiLocalVariable -> JavaULocalVariable(psi, containingElement) is PsiParameter -> JavaUParameter(psi, containingElement) is PsiField -> JavaUField(psi, containingElement) else -> JavaUVariable(psi, containingElement) } } } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } @ApiStatus.Internal class JavaUParameter( override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val sourcePsi: PsiParameter? get() = javaPsi.takeIf { it.isPhysical || (it is PsiParameterImpl && it.parentOfType<PsiMethod>()?.let { canBeSourcePsi(it) } == true) } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } private class JavaRecordUParameter( override val sourcePsi: PsiRecordComponent, override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val uastAnchor: UIdentifier get() = UIdentifier(sourcePsi.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } internal fun convertRecordConstructorParameterAlternatives(element: PsiElement, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>>): Sequence<UVariable> { val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent)?:return emptySequence() return when (element) { is LightRecordField -> expectedTypes.accommodate(fieldAlternative, paramAlternative) else -> expectedTypes.accommodate(paramAlternative, fieldAlternative) } } internal fun convertRecordConstructorParameterAlternatives(element: PsiElement, givenParent: UElement?, expectedType: Class<out UElement>): UVariable? { val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent)?:return null return when (element) { is LightRecordField -> expectedType.accommodate(fieldAlternative, paramAlternative) else -> expectedType.accommodate(paramAlternative, fieldAlternative) } } private fun createAlternatives(element: PsiElement, givenParent: UElement?): Pair<UElementAlternative<JavaRecordUParameter>, UElementAlternative<JavaRecordUField>>? { val (psiRecordComponent, lightRecordField, lightConstructorParameter) = when (element) { is PsiRecordComponent -> Triple(element, null, null) is LightRecordConstructorParameter -> { val lightRecordField = element.parentOfType<PsiMethod>()?.containingClass?.findFieldByName(element.name, false) ?.castSafelyTo<LightRecordField>() ?: return null Triple(lightRecordField.recordComponent, lightRecordField, element) } is LightRecordField -> Triple(element.recordComponent, element, null) else -> return null } val paramAlternative = alternative { val psiClass = psiRecordComponent.containingClass ?: return@alternative null val jvmParameter = lightConstructorParameter ?: psiClass.constructors.asSequence() .filter { !it.isPhysical } .flatMap { it.parameterList.parameters.asSequence() }.firstOrNull { it.name == psiRecordComponent.name } JavaRecordUParameter(psiRecordComponent, jvmParameter ?: return@alternative null, givenParent) } val fieldAlternative = alternative { val psiField = lightRecordField ?: psiRecordComponent.containingClass?.findFieldByName(psiRecordComponent.name, false) ?: return@alternative null JavaRecordUField(psiRecordComponent, psiField, givenParent) } return Pair(paramAlternative, fieldAlternative) } @ApiStatus.Internal class JavaUField( override val sourcePsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val javaPsi: PsiField = unwrap<UField, PsiField>(sourcePsi) override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } private class JavaRecordUField( private val psiRecord: PsiRecordComponent, override val javaPsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val sourcePsi: PsiVariable? get() = null override val uastAnchor: UIdentifier get() = UIdentifier(psiRecord.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } @ApiStatus.Internal class JavaULocalVariable( override val sourcePsi: PsiLocalVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiLocalVariable get() = javaPsi override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(sourcePsi) override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceList -> it.parent else -> it } } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } @ApiStatus.Internal class JavaUEnumConstant( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpression, PsiEnumConstant by sourcePsi, UMultiResolvable { override val initializingClass: UClass? by lz { UastFacade.findPlugin(sourcePsi)?.convertOpt(sourcePsi.initializingClass, this) } @Suppress("OverridingDeprecatedMember") override val psi: PsiEnumConstant get() = javaPsi override val javaPsi: PsiEnumConstant get() = sourcePsi override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression get() = JavaEnumConstantClassReference(sourcePsi, this) override val typeArgumentCount: Int get() = 0 override val typeArguments: List<PsiType> get() = emptyList() override val valueArgumentCount: Int get() = sourcePsi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { sourcePsi.argumentList?.expressions?.map { UastFacade.findPlugin(it)?.convertElement(it, this) as? UExpression ?: UastEmptyExpression(this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val returnType: PsiType get() = sourcePsi.type override fun resolve(): PsiMethod? = sourcePsi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(sourcePsi.resolveMethodGenerics()) override val methodName: String? get() = null private class JavaEnumConstantClassReference( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve() = sourcePsi.containingClass override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() }) override val resolvedName: String? get() = sourcePsi.containingClass?.name override val identifier: String get() = sourcePsi.containingClass?.name ?: "<error>" } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
apache-2.0
chrhsmt/Sishen
app/src/main/java/com/chrhsmt/sisheng/network/RaspberryPi.kt
1
483
package com.chrhsmt.sisheng.network import com.chrhsmt.sisheng.Settings import okhttp3.* import java.io.IOException /** * Created by chihiro on 2017/10/10. */ class RaspberryPi { fun send(callback: Callback) { val url = String.format("http://%s%s", Settings.raspberrypiHost, Settings.raspberrypiPath) val request: Request = Request.Builder() .url(url) .build() OkHttpClient().newCall(request).enqueue(callback) } }
mit
dahlstrom-g/intellij-community
plugins/kotlin/grazie/src/org/jetbrains/kotlin/idea/grazie/KotlinTextExtractor.kt
5
2997
// 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.grazie import com.intellij.grazie.text.TextContent import com.intellij.grazie.text.TextContent.TextDomain.* import com.intellij.grazie.text.TextContentBuilder import com.intellij.grazie.text.TextExtractor import com.intellij.grazie.utils.Text import com.intellij.grazie.utils.getNotSoDistantSimilarSiblings import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.PsiCommentImpl import com.intellij.psi.util.elementType import org.jetbrains.kotlin.kdoc.lexer.KDocTokens import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression import org.jetbrains.kotlin.psi.KtStringTemplateExpression import java.util.regex.Pattern internal class KotlinTextExtractor : TextExtractor() { private val kdocBuilder = TextContentBuilder.FromPsi .withUnknown { e -> e.elementType == KDocTokens.MARKDOWN_LINK && e.text.startsWith("[") } .excluding { e -> e.elementType == KDocTokens.MARKDOWN_LINK && !e.text.startsWith("[") } .excluding { e -> e.elementType == KDocTokens.LEADING_ASTERISK } .removingIndents(" \t").removingLineSuffixes(" \t") public override fun buildTextContent(root: PsiElement, allowedDomains: Set<TextContent.TextDomain>): TextContent? { if (DOCUMENTATION in allowedDomains) { if (root is KDocSection) { return kdocBuilder.excluding { e -> e is KDocTag && e != root }.build(root, DOCUMENTATION)?.removeCode() } if (root is KDocTag) { return kdocBuilder.excluding { e -> e.elementType == KDocTokens.TAG_NAME }.build(root, DOCUMENTATION)?.removeCode() } } if (COMMENTS in allowedDomains && root is PsiCommentImpl) { val roots = getNotSoDistantSimilarSiblings(root) { it == root || root.elementType == KtTokens.EOL_COMMENT && it.elementType == KtTokens.EOL_COMMENT } return TextContent.joinWithWhitespace('\n', roots.mapNotNull { TextContentBuilder.FromPsi.removingIndents(" \t*/").removingLineSuffixes(" \t").build(it, COMMENTS) }) } if (LITERALS in allowedDomains && root is KtStringTemplateExpression) { // For multiline strings, we want to treat `'|'` as an indentation because it is commonly used with [String.trimMargin]. return TextContentBuilder.FromPsi .withUnknown { it is KtStringTemplateEntryWithExpression } .removingIndents(" \t|").removingLineSuffixes(" \t") .build(root, LITERALS) } return null } private val codeFragments = Pattern.compile("(?s)```.+?```|`.+?`") private fun TextContent.removeCode(): TextContent? = excludeRanges(Text.allOccurrences(codeFragments, this).map { TextContent.Exclusion.markUnknown(it) }) }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/NamedAndDefaultParameter.kt
3
685
// IGNORE_FIR open class A(x: Int) { fun m(x: Int) = 1 fun m(x: Int, y: Boolean = true, z: Long = 12345678901234, u: String = "abc\n", u0: String = "" + "123", uu: String = "$u", v: Char = '\u0000', vv: String = "asdfsdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf") = 2 fun d(x: Int) { m(<caret>y = false, x = 1) } } /* Text: (<highlight>[y: Boolean = true]</highlight>, [x: Int], [z: Long = 12345678901234], [u: String = "abc\n"], [u0: String = "" + "123"], [uu: String = "$u"], [v: Char = '\u0000'], [vv: String = "..."]), Disabled: false, Strikeout: false, Green: true Text: ([x: Int]), Disabled: true, Strikeout: false, Green: false */
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/BinaryOperatorReferenceSearcher.kt
6
2286
// 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.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class BinaryOperatorReferenceSearcher( targetFunction: PsiElement, private val operationTokens: List<KtSingleValueToken>, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtBinaryExpression>( targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = operationTokens.map { it.value }) { override fun processPossibleReceiverExpression(expression: KtExpression) { val binaryExpression = expression.parent as? KtBinaryExpression ?: return if (binaryExpression.operationToken !in operationTokens) return if (expression != binaryExpression.left) return processReferenceElement(binaryExpression) } override fun isReferenceToCheck(ref: PsiReference): Boolean { if (ref !is KtSimpleNameReference) return false val element = ref.element if (element.parent !is KtBinaryExpression) return false return element.getReferencedNameElementType() in operationTokens } override fun extractReference(element: KtElement): PsiReference? { val binaryExpression = element as? KtBinaryExpression ?: return null if (binaryExpression.operationToken !in operationTokens) return null return binaryExpression.operationReference.references.firstIsInstance<KtSimpleNameReference>() } }
apache-2.0
kingargyle/serenity-android
serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/recyclerview/FocusableLinearLayoutManager.kt
2
1779
package us.nineworlds.serenity.ui.recyclerview /** * The MIT License (MIT) * Copyright (c) 2018 David Carver * 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: * <p> * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * <p> * 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. */ import android.content.Context import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class FocusableLinearLayoutManager(val context: Context) : androidx.recyclerview.widget.LinearLayoutManager(context) { override fun smoothScrollToPosition(recyclerView: androidx.recyclerview.widget.RecyclerView?, state: androidx.recyclerview.widget.RecyclerView.State?, position: Int) { val smoothScroller = FocusableLinearSmoothScroller(context) smoothScroller.targetPosition = position startSmoothScroll(smoothScroller) } }
mit
dahlstrom-g/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/docComments/inlineTagsInDocComment.kt
26
25
/** * `A<B` */ class C
apache-2.0
TheMrMilchmann/lwjgl3
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_rgb8_rgba8.kt
4
605
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val OES_rgb8_rgba8 = "OESRGB8RGBA8".nativeClassGLES("OES_rgb8_rgba8", postfix = OES) { documentation = """ Native bindings to the $registryLink extension. This extension enables RGB8 and RGBA8 renderbuffer storage formats. """ IntConstant( "Accepted by the {@code internalformat} parameter of RenderbufferStorageOES.", "RGB8_OES"..0x8051, "RGBA8_OES"..0x8058 ) }
bsd-3-clause
airbnb/epoxy
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/TestModel5.kt
1
522
package com.airbnb.epoxy.sample.models import android.view.View import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.sample.R @EpoxyModelClass(layout = R.layout.model_color) abstract class TestModel5 : EpoxyModel<View>() { @EpoxyAttribute var num: Int = 0 @EpoxyAttribute var num2: Int = 0 @EpoxyAttribute var num3: Int = 0 @EpoxyAttribute var num4: Int = 0 @EpoxyAttribute var num5: Int = 0 }
apache-2.0
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/adapter/SchedulePagerAdapter.kt
1
587
package com.mgaetan89.showsrage.adapter import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentStatePagerAdapter import com.mgaetan89.showsrage.fragment.ScheduleSectionFragment class SchedulePagerAdapter(fragmentManager: FragmentManager, private val ids: List<String>, private val labels: List<String>) : FragmentStatePagerAdapter(fragmentManager) { override fun getCount() = this.ids.size override fun getItem(position: Int) = ScheduleSectionFragment.newInstance(this.ids[position]) override fun getPageTitle(position: Int) = this.labels[position] }
apache-2.0
paplorinc/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/controlStructures/JavaUWhileExpression.kt
6
1342
/* * 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 org.jetbrains.uast.java import com.intellij.psi.PsiWhileStatement import com.intellij.psi.impl.source.tree.ChildRole import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UIdentifier import org.jetbrains.uast.UWhileExpression class JavaUWhileExpression( override val psi: PsiWhileStatement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UWhileExpression { override val condition: UExpression by lz { JavaConverter.convertOrEmpty(psi.condition, this) } override val body: UExpression by lz { JavaConverter.convertOrEmpty(psi.body, this) } override val whileIdentifier: UIdentifier get() = UIdentifier(psi.getChildByRole(ChildRole.WHILE_KEYWORD), this) }
apache-2.0
antlr/grammars-v4
kotlin/kotlin-formal/examples/fuzzer/inlineTryCatch.kt329001800.kt_minimized.kt
1
169
inline fun <T> tryOrElse(f1: (() -> T), f2: (() -> T)): T { try { return (f1)!!() }catch(e: Exception) { return f2() } } fun testIt() = "abc" + tryOrElse({}, {}) + "ghi"
mit
akhbulatov/wordkeeper
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/main/MainModule.kt
1
393
package com.akhbulatov.wordkeeper.presentation.ui.main import androidx.lifecycle.ViewModel import com.akhbulatov.wordkeeper.di.ViewModelKey import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class MainModule { @Binds @IntoMap @ViewModelKey(MainViewModel::class) abstract fun bindMainViewModel(viewModel: MainViewModel): ViewModel }
apache-2.0
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/psi/mixins/impl/AtClassNameImplMixin.kt
1
851
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at.psi.mixins.impl import com.demonwav.mcdev.platform.mcp.at.AtElementFactory import com.demonwav.mcdev.platform.mcp.at.psi.mixins.AtClassNameMixin import com.demonwav.mcdev.util.findQualifiedClass import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode abstract class AtClassNameImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), AtClassNameMixin { override val classNameValue get() = findQualifiedClass(project, classNameText) override val classNameText: String get() = classNameElement.text override fun setClassName(className: String) { replace(AtElementFactory.createClassName(project, className)) } }
mit
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/fpsthrottle/FpsThrottle.kt
1
836
package org.runestar.client.plugins.fpsthrottle import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XRasterProvider import org.runestar.client.api.plugins.PluginSettings class FpsThrottle : DisposablePlugin<FpsThrottle.Settings>() { override val defaultSettings = Settings() override val name = "FPS Throttle" override fun onStart() { if (settings.sleepTimeMs <= 0) return add(XRasterProvider.drawFull0.exit.subscribe { if (!CLIENT.canvas.isFocusOwner || !settings.onlyWhenUnfocused) { Thread.sleep(settings.sleepTimeMs) } }) } data class Settings( val onlyWhenUnfocused: Boolean = true, val sleepTimeMs: Long = 50L ) : PluginSettings() }
mit
StephenVinouze/AdvancedRecyclerView
sample/src/main/java/com/github/stephenvinouze/advancedrecyclerview/sample/activities/MainActivity.kt
1
3342
package com.github.stephenvinouze.advancedrecyclerview.sample.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.github.stephenvinouze.advancedrecyclerview.sample.R import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.GestureRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.GestureSectionRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.MultipleChoiceRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.PaginationRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.SectionRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.SingleChoiceRecyclerFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) displaySingleChoiceRecyclerFragment() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.single_choice_action -> displaySingleChoiceRecyclerFragment() R.id.multiple_choice_action -> displayMultipleChoiceRecyclerFragment() R.id.section_action -> displaySectionRecyclerFragment() R.id.gesture_action -> displayGestureRecyclerFragment() R.id.gesture_section_action -> displayGestureSectionRecyclerFragment() R.id.pagination_action -> displayPaginationRecyclerFragment() } return super.onOptionsItemSelected(item) } private fun displaySingleChoiceRecyclerFragment() { title = getString(R.string.single_choice_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, SingleChoiceRecyclerFragment()).commit() } private fun displayMultipleChoiceRecyclerFragment() { title = getString(R.string.multiple_choice_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, MultipleChoiceRecyclerFragment()).commit() } private fun displaySectionRecyclerFragment() { title = getString(R.string.section_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, SectionRecyclerFragment()).commit() } private fun displayGestureRecyclerFragment() { title = getString(R.string.gesture_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, GestureRecyclerFragment()).commit() } private fun displayGestureSectionRecyclerFragment() { title = getString(R.string.gesture_sections_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, GestureSectionRecyclerFragment()).commit() } private fun displayPaginationRecyclerFragment() { title = getString(R.string.pagination_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, PaginationRecyclerFragment()).commit() } }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinDataClassComponentUsage.kt
1
873
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSimpleNameExpression class KotlinDataClassComponentUsage( calleeExpression: KtSimpleNameExpression, private val newName: String ) : KotlinUsageInfo<KtSimpleNameExpression>(calleeExpression) { override fun processUsage(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression, allUsages: Array<out UsageInfo>): Boolean { element.replace(KtPsiFactory(element.project).createExpression(newName)) return true } }
apache-2.0
StephaneBg/ScoreIt
core/src/main/kotlin/com/sbgapps/scoreit/core/widget/BaseViewHolder.kt
1
871
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.core.widget import android.content.Context import android.view.View import androidx.recyclerview.widget.RecyclerView class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val context: Context get() = itemView.context }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InlineTypeParameterFix.kt
1
3456
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext class InlineTypeParameterFix(val typeReference: KtTypeReference) : KotlinQuickFixAction<KtTypeReference>(typeReference) { override fun invoke(project: Project, editor: Editor?, file: KtFile) { val parameterListOwner = typeReference.getStrictParentOfType<KtTypeParameterListOwner>() ?: return val parameterList = parameterListOwner.typeParameterList ?: return val (parameter, bound, constraint) = when (val parent = typeReference.parent) { is KtTypeParameter -> { val bound = parent.extendsBound ?: return Triple(parent, bound, null) } is KtTypeConstraint -> { val subjectTypeParameterName = parent.subjectTypeParameterName?.text ?: return val parameter = parameterList.parameters.firstOrNull { it.name == subjectTypeParameterName } ?: return val bound = parent.boundTypeReference ?: return Triple(parameter, bound, parent) } else -> return } val context = parameterListOwner.analyzeWithContent() val parameterDescriptor = context[BindingContext.TYPE_PARAMETER, parameter] ?: return parameterListOwner.forEachDescendantOfType<KtTypeReference> { typeReference -> val typeElement = typeReference.typeElement val type = context[BindingContext.TYPE, typeReference] if (typeElement != null && type != null && type.constructor.declarationDescriptor == parameterDescriptor) { typeReference.replace(bound) } } if (parameterList.parameters.size == 1) { parameterList.delete() val constraintList = parameterListOwner.typeConstraintList if (constraintList != null) { constraintList.siblings(forward = false).firstOrNull { it.elementType == KtTokens.WHERE_KEYWORD }?.delete() constraintList.delete() } } else { EditCommaSeparatedListHelper.removeItem(parameter) if (constraint != null) { EditCommaSeparatedListHelper.removeItem(constraint) } } } override fun getText() = KotlinBundle.message("inline.type.parameter") override fun getFamilyName() = text companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = InlineTypeParameterFix(Errors.FINAL_UPPER_BOUND.cast(diagnostic).psiElement) } }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt
1
10448
// 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.intentions import com.intellij.codeInsight.CodeInsightUtil import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiFile import com.intellij.refactoring.rename.PsiElementRenameHandler import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile import org.jetbrains.kotlin.idea.refactoring.ui.CreateKotlinClassDialog import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiFactory.ClassHeaderBuilder import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.ModifiersChecker private const val IMPL_SUFFIX = "Impl" class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("create.kotlin.subclass") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.name == null || element.getParentOfType<KtFunction>(true) != null) { // Local / anonymous classes are not supported return null } if (!element.isInterface() && !element.isSealed() && !element.isAbstract() && !element.hasModifier(KtTokens.OPEN_KEYWORD)) { return null } val primaryConstructor = element.primaryConstructor if (!element.isInterface() && primaryConstructor != null) { val constructors = element.secondaryConstructors + primaryConstructor if (constructors.none { !it.isPrivate() && it.valueParameters.all { parameter -> parameter.hasDefaultValue() } }) { // At this moment we require non-private default constructor // TODO: handle non-private constructors with parameters return null } } setTextGetter(getImplementTitle(element)) return TextRange(element.startOffset, element.body?.lBrace?.startOffset ?: element.endOffset) } private fun getImplementTitle(baseClass: KtClass) = when { baseClass.isInterface() -> KotlinBundle.lazyMessage("implement.interface") baseClass.isAbstract() -> KotlinBundle.lazyMessage("implement.abstract.class") baseClass.isSealed() -> KotlinBundle.lazyMessage("implement.sealed.class") else /* open class */ -> KotlinBundle.lazyMessage("create.subclass") } override fun startInWriteAction() = false override fun checkFile(file: PsiFile): Boolean { return true } override fun preparePsiElementForWriteIfNeeded(target: KtClass): Boolean { return true } override fun applyTo(element: KtClass, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val name = element.name ?: throw IllegalStateException("This intention should not be applied to anonymous classes") if (element.isSealed() && !element.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) { createNestedSubclass(element, name, editor) } else { createExternalSubclass(element, name, editor) } } private fun defaultTargetName(baseName: String) = "$baseName$IMPL_SUFFIX" private fun KtClassOrObject.hasSameDeclaration(name: String) = declarations.any { it is KtNamedDeclaration && it.name == name } private fun targetNameWithoutConflicts(baseName: String, container: KtClassOrObject?) = Fe10KotlinNameSuggester.suggestNameByName(defaultTargetName(baseName)) { container?.hasSameDeclaration(it) != true } private fun createNestedSubclass(sealedClass: KtClass, sealedName: String, editor: Editor) { if (!super.preparePsiElementForWriteIfNeeded(sealedClass)) return val project = sealedClass.project val klass = runWriteAction { val builder = buildClassHeader(targetNameWithoutConflicts(sealedName, sealedClass), sealedClass, sealedName) val classFromText = KtPsiFactory(project).createClass(builder.asString()) val body = sealedClass.getOrCreateBody() body.addBefore(classFromText, body.rBrace) as KtClass } runInteractiveRename(klass, project, sealedClass, editor) chooseAndImplementMethods(project, klass, editor) } private fun createExternalSubclass(baseClass: KtClass, baseName: String, editor: Editor) { var container: KtClassOrObject = baseClass var name = baseName var visibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) while (!container.isPrivate() && !container.isProtected() && !(container is KtClass && container.isInner())) { val parent = container.containingClassOrObject if (parent != null) { val parentName = parent.name if (parentName != null) { container = parent name = "$parentName.$name" val parentVisibility = ModifiersChecker.resolveVisibilityFromModifiers(parent, visibility) if ((DescriptorVisibilities.compare(parentVisibility, visibility) ?: 0) < 0) { visibility = parentVisibility } } } if (container != parent) { break } } val project = baseClass.project val factory = KtPsiFactory(project) if (container.containingClassOrObject == null && !isUnitTestMode()) { val dlg = chooseSubclassToCreate(baseClass, baseName) ?: return val targetName = dlg.className val (file, klass) = runWriteAction { val file = getOrCreateKotlinFile("$targetName.kt", dlg.targetDirectory!!)!! val builder = buildClassHeader(targetName, baseClass, baseClass.fqName!!.asString()) file.add(factory.createClass(builder.asString())) val klass = file.getChildOfType<KtClass>()!! ShortenReferences.DEFAULT.process(klass) file to klass } chooseAndImplementMethods(project, klass, CodeInsightUtil.positionCursor(project, file, klass) ?: editor) } else { if (!super.preparePsiElementForWriteIfNeeded(baseClass)) return val klass = runWriteAction { val builder = buildClassHeader( targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), baseClass, name, visibility ) val classFromText = factory.createClass(builder.asString()) container.parent.addAfter(classFromText, container) as KtClass } runInteractiveRename(klass, project, container, editor) chooseAndImplementMethods(project, klass, editor) } } private fun runInteractiveRename(klass: KtClass, project: Project, container: KtClassOrObject, editor: Editor) { if (isUnitTestMode()) return PsiElementRenameHandler.rename(klass, project, container, editor) } private fun chooseSubclassToCreate(baseClass: KtClass, baseName: String): CreateKotlinClassDialog? { val sourceDir = baseClass.containingFile.containingDirectory val aPackage = JavaDirectoryService.getInstance().getPackage(sourceDir) val dialog = object : CreateKotlinClassDialog( baseClass.project, text, targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), aPackage?.qualifiedName ?: "", CreateClassKind.CLASS, true, ModuleUtilCore.findModuleForPsiElement(baseClass), baseClass.isSealed() ) { override fun getBaseDir(packageName: String?) = sourceDir override fun reportBaseInTestSelectionInSource() = true } return if (!dialog.showAndGet() || dialog.targetDirectory == null) null else dialog } private fun buildClassHeader( targetName: String, baseClass: KtClass, baseName: String, defaultVisibility: DescriptorVisibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) ): ClassHeaderBuilder { return ClassHeaderBuilder().apply { if (!baseClass.isInterface()) { if (defaultVisibility != DescriptorVisibilities.PUBLIC) { modifier(defaultVisibility.name) } if (baseClass.isInner()) { modifier(KtTokens.INNER_KEYWORD.value) } } name(targetName) val typeParameters = baseClass.typeParameterList?.parameters typeParameters(typeParameters?.map { it.text }.orEmpty()) baseClass(baseName, typeParameters?.map { it.name ?: "" }.orEmpty(), baseClass.isInterface()) typeConstraints(baseClass.typeConstraintList?.constraints?.map { it.text }.orEmpty()) } } private fun chooseAndImplementMethods(project: Project, targetClass: KtClass, editor: Editor) { editor.caretModel.moveToOffset(targetClass.textRange.startOffset) ImplementMembersHandler().invoke(project, editor, targetClass.containingFile) } }
apache-2.0