repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dahlstrom-g/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/common/ContextSimilarityUtil.kt
9
1161
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.common import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import com.intellij.textMatching.SimilarityScorer object ContextSimilarityUtil { val LINE_SIMILARITY_SCORER_KEY: Key<SimilarityScorer> = Key.create("LINE_SIMILARITY_SCORER") val PARENT_SIMILARITY_SCORER_KEY: Key<SimilarityScorer> = Key.create("PARENT_SIMILARITY_SCORER") fun createLineSimilarityScorer(line: String): SimilarityScorer = SimilarityScorer(StringUtil.getWordsIn(line)) fun createParentSimilarityScorer(element: PsiElement?): SimilarityScorer { var curElement = element val parents = mutableListOf<String>() while (curElement != null && curElement !is PsiFile) { if (curElement is PsiNamedElement) { curElement.name?.let { parents.add(it) } } curElement = curElement.parent } return SimilarityScorer(parents) } }
apache-2.0
14d9c7b40a36dea65a2e6da1db845536
40.464286
140
0.768303
4.073684
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/ui/adapter/NewsAdapter.kt
1
4478
/* * Copyright 2019 Eduard Scarlat * * 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 ro.edi.novelty.ui.adapter import android.app.Activity import android.app.ActivityOptions import android.content.Intent import android.view.View import androidx.core.content.ContextCompat import androidx.databinding.ViewDataBinding import androidx.lifecycle.ViewModel import androidx.recyclerview.widget.DiffUtil import ro.edi.novelty.R import ro.edi.novelty.databinding.NewsItemBinding import ro.edi.novelty.model.News import ro.edi.novelty.ui.NewsInfoActivity import ro.edi.novelty.ui.viewmodel.NewsViewModel class NewsAdapter(private val activity: Activity?, private val newsModel: NewsViewModel) : BaseAdapter<News>(NewsDiffCallback()) { companion object { const val NEWS_PUB_DATE = "news_pub_date" const val NEWS_FEED_TITLE = "news_feed_title" const val NEWS_TITLE = "news_title" const val NEWS_STATE = "news_state" } override fun getModel(): ViewModel { return newsModel } override fun getItemId(position: Int): Long { return getItem(position).id.toLong() } override fun getItemLayoutId(position: Int): Int { return R.layout.news_item } override fun onItemClick(itemView: View, position: Int) { newsModel.setIsRead(position, true) val i = Intent(activity, NewsInfoActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP i.putExtra(NewsInfoActivity.EXTRA_NEWS_ID, getItem(position).id) val options = ActivityOptions.makeSceneTransitionAnimation( activity, itemView, "shared_news_container" ) activity?.startActivity(i, options.toBundle()) } override fun bind(binding: ViewDataBinding, position: Int, payloads: MutableList<Any>) { val b = binding as NewsItemBinding val payload = payloads.first() as Set<*> payload.forEach { when (it) { NEWS_PUB_DATE -> b.date.text = newsModel.getDisplayDate(position) NEWS_FEED_TITLE -> b.feed.text = getItem(position).feedTitle NEWS_TITLE -> b.title.text = getItem(position).title NEWS_STATE -> { val colorInfo = ContextCompat.getColor( binding.root.context, newsModel.getInfoTextColorRes(binding.root.context, position) ) val colorTitle = ContextCompat.getColor( binding.root.context, newsModel.getTitleTextColorRes(binding.root.context, position) ) b.feed.setTextColor(colorInfo) b.title.setTextColor(colorTitle) b.date.setTextColor(colorInfo) } } } } class NewsDiffCallback : DiffUtil.ItemCallback<News>() { override fun areItemsTheSame(oldItem: News, newItem: News): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: News, newItem: News): Boolean { return false // we do this because we want the shown date to always be updated } override fun getChangePayload(oldItem: News, newItem: News): Any? { val payload = mutableSetOf<String>() payload.add(NEWS_PUB_DATE) // always add this (because we show the relative date/time in the UI) if (oldItem.feedTitle != newItem.feedTitle) { payload.add(NEWS_FEED_TITLE) } if (oldItem.title != newItem.title) { payload.add(NEWS_TITLE) } if (oldItem.isRead != newItem.isRead || oldItem.isStarred != newItem.isStarred) { payload.add(NEWS_STATE) } if (payload.isEmpty()) { return null } return payload } } }
apache-2.0
68b98441f2618544bd83719bf1ccd466
34.832
108
0.629969
4.61174
false
false
false
false
MarkusAmshove/Kluent
jvm/src/test/kotlin/org/amshove/kluent/tests/mocking/Mocking.kt
1
3393
package org.amshove.kluent import com.nhaarman.mockitokotlin2.* import org.mockito.AdditionalAnswers.* import org.mockito.Mockito.`when` import org.mockito.internal.util.MockUtil import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import org.mockito.stubbing.OngoingStubbing import kotlin.reflect.KClass @Suppress("UNUSED_PARAMETER") // Backward compatibility inline fun <reified T : Any> mock(targetClass: KClass<out T>): T = mock() inline fun <reified T : Any> mock(): T = com.nhaarman.mockitokotlin2.mock() infix fun VerifyKeyword.times(numInvocations: Int) = OngoingVerification(numInvocations) infix fun <T> OngoingVerification.on(mock: T) = verify(mock, times(numInvocations)) infix fun <T> VerifyKeyword.on(mock: T) = verify(mock) infix fun <T> VerifyNotCalledKeyword.on(mock: T) = verify(mock, never()) infix fun <T> T.that(mock: T): T { ensureMock(this) return this.apply { mock.run { Unit } } } infix fun <T : Any> VerifyNoInteractionsKeyword.on(mock: T) = verifyZeroInteractions(mock) infix fun <T> VerifyNoFurtherInteractionsKeyword.on(mock: T) = verifyNoMoreInteractions(mock) infix fun <T> T.was(n: CalledKeyword) = n @Suppress("UNUSED_PARAMETER") // Backward compatibility inline fun <reified T : Any> any(kClass: KClass<T>): T = any() inline fun <reified T : Any> any(): T = com.nhaarman.mockitokotlin2.any() infix fun <T> WhenKeyword.calling(methodCall: T): OngoingStubbing<T> = `when`(methodCall) infix fun <T> OngoingStubbing<T>.itReturns(value: T): OngoingStubbing<T> = this.thenReturn(value) infix fun <T> OngoingStubbing<T>.itThrows(value: Throwable): OngoingStubbing<T> = this.thenThrow(value) infix fun <T> OngoingStubbing<T>.itAnswers(value: (InvocationOnMock) -> T): OngoingStubbing<T> = this.thenAnswer(value) infix fun <T> OngoingStubbing<T>.itAnswers(value: Answer<T>): OngoingStubbing<T> = this.thenAnswer(value) /** * Returns the parameter of an invocation at the given position. * @param position Location of the parameter to return, zero based. * @see [returnsArgAt] */ fun <T> withArgAt(position: Int): Answer<T> = returnsArgAt(position) fun <T> withFirstArg(): Answer<T> = returnsFirstArg() fun <T> withSecondArg(): Answer<T> = returnsSecondArg() fun <T> withThirdArg(): Answer<T> = withArgAt(2) fun <T> withFourthArg(): Answer<T> = withArgAt(3) fun <T> withLastArg(): Answer<T> = returnsLastArg() private fun <T> ensureMock(obj: T) { if (!MockUtil.isMock(obj)) { throw Exception( """ $obj is no mock. Ensure to always determine the mock with the `on` method. Example: Verify on myMock that myMock.getPerson() was called /\ -------- """ ) } } val When = WhenKeyword() val Verify = VerifyKeyword() val VerifyNotCalled = VerifyNotCalledKeyword() val called = CalledKeyword() val VerifyNoInteractions = VerifyNoInteractionsKeyword() val VerifyNoFurtherInteractions = VerifyNoFurtherInteractionsKeyword() class VerifyKeyword internal constructor() class VerifyNotCalledKeyword internal constructor() class CalledKeyword internal constructor() class WhenKeyword internal constructor() class VerifyNoInteractionsKeyword internal constructor() class VerifyNoFurtherInteractionsKeyword internal constructor() class OngoingVerification(val numInvocations: Int)
mit
312e2672411f4037670cf3c7be89560d
34.726316
119
0.728854
3.895522
false
false
false
false
tommyli/nem12-manager
fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/domain/IntervalDay.kt
1
5419
// Tommy Li ([email protected]), 2017-03-10 package co.firefire.fenergy.nem12.domain import java.math.BigDecimal import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.util.* import javax.persistence.CascadeType import javax.persistence.Embedded import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.MapKey import javax.persistence.OneToMany import javax.persistence.OrderBy import org.hibernate.annotations.GenericGenerator as HbmGenericGenerator import org.hibernate.annotations.Parameter as HbmParameter import javax.persistence.Transient as JpaTransient val MINUTES_IN_DAY: Int = Duration.ofDays(1).toMinutes().toInt() @Entity data class IntervalDay( @ManyToOne(optional = false) @JoinColumn(name = "nmi_meter_register", referencedColumnName = "id", nullable = false) var nmiMeterRegister: NmiMeterRegister = NmiMeterRegister(), var intervalDate: LocalDate = LocalDate.MIN, @Embedded var intervalQuality: IntervalQuality = IntervalQuality(Quality.A) ) { @Id @HbmGenericGenerator( name = "IntervalDayIdSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = arrayOf( HbmParameter(name = "sequence_name", value = "interval_day_id_seq"), HbmParameter(name = "initial_value", value = "1000"), HbmParameter(name = "increment_size", value = "50") ) ) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IntervalDayIdSeq") var id: Long? = null var version: Int? = 0 var updateDateTime: LocalDateTime? = null var msatsLoadDateTime: LocalDateTime? = null @JpaTransient @Transient var intervalEvents: MutableMap<IntRange, IntervalEvent> = mutableMapOf() @OneToMany(mappedBy = "id.intervalDay", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true, fetch = FetchType.EAGER) @MapKey(name = "id.interval") @OrderBy("id.interval") var intervalValues: SortedMap<Int, IntervalValue> = TreeMap() fun getTotal(): BigDecimal { return intervalValues.values.sumByBigDecimal { it.value } } fun applyIntervalEvents() { assert(intervalValues.all { it.value.intervalQuality.quality != Quality.V }, { "Individual values should never have V quality." }) if (intervalQuality.quality == Quality.V) { intervalValues = TreeMap(intervalValues.mapValues { (interval, intervalValue) -> val newQuality = intervalEvents.values.find { it.intervalRange.contains(interval) }?.intervalQuality ?: IntervalQuality(Quality.A) IntervalValue(this, interval, intervalValue.value, newQuality) }) } } fun addIntervalValue(newIntervalValue: IntervalValue) { newIntervalValue.id = IntervalKey(this, newIntervalValue.interval) intervalValues.put(newIntervalValue.interval, newIntervalValue) } fun replaceIntervalValues(newIntervalValues: Map<Int, IntervalValue>) { newIntervalValues.forEach { interval: Int, newIntervalValue: IntervalValue -> val existingIntervalValue = intervalValues.get(interval) if (existingIntervalValue == null) { addIntervalValue(newIntervalValue) } else { existingIntervalValue.value = newIntervalValue.value existingIntervalValue.intervalQuality = newIntervalValue.intervalQuality } } } fun mergeNewIntervalValues(newIntervalValues: Map<Int, IntervalValue>, newUpdateDateTime: LocalDateTime?, newMsatsLoadDateTime: LocalDateTime?) { val existingDateTime = updateDateTime ?: msatsLoadDateTime ?: LocalDateTime.now() val newDateTime = newUpdateDateTime ?: newMsatsLoadDateTime ?: LocalDateTime.now() validateIntervalValueQuality(intervalValues) validateIntervalValueQuality(newIntervalValues) newIntervalValues.forEach { newInterval: Int, newIntervalValue: IntervalValue -> intervalValues.merge(newInterval, newIntervalValue, { existing: IntervalValue, new: IntervalValue -> val existingQuality = TimestampedQuality(existing.intervalQuality.quality, existingDateTime) val newQuality = TimestampedQuality(new.intervalQuality.quality, newDateTime) if (newQuality >= existingQuality) { existing.value = new.value existing.intervalQuality = new.intervalQuality existing } else { existing } }) } } fun appendIntervalEvent(intervalEvent: IntervalEvent) { intervalEvents.put(intervalEvent.intervalRange, intervalEvent) } override fun toString(): String { return "IntervalDay(id=$id, nmiMeterRegister=$nmiMeterRegister, intervalDate=$intervalDate)" } private fun validateIntervalValueQuality(intervalValues: Map<Int, IntervalValue>) { assert(intervalValues.all { it.value.intervalQuality.quality != Quality.V }, { "Individual values should never have V quality." }) } }
apache-2.0
3915a6b6c7314b59d636e76721fc2c9f
39.440299
149
0.694962
5.064486
false
false
false
false
taumechanica/ml
src/main/kotlin/ml/Metrics.kt
1
2788
// Use of this source code is governed by The MIT License // that can be found in the LICENSE file. package taumechanica.ml import kotlin.math.* import taumechanica.ml.data.* fun accuracy(frame: DataFrame, model: Predictor): Double { var total = 0 var correct = 0 val domain = (frame.target as NominalAttribute).domain for (i in 0 until frame.samples.size) if (frame.subset[i]) { val sample = frame.samples[i] val scores = model.predict(sample.values) val decision = argmax(domain, scores) if (decision == sample.values[frame.target.index]) correct++ total++ } return 100.0 * correct / total } fun rmsle(frame: DataFrame, model: Predictor): Double { var total = 0 var sum = 0.0 for (i in 0 until frame.samples.size) if (frame.subset[i]) { val sample = frame.samples[i] val prediction = model.predict(sample.values)[0] sum += (ln(prediction + 1.0) - ln(sample.values[frame.target.index] + 1.0)).pow(2.0) total++ } return (sum / total).pow(0.5) } fun logloss(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double { var total = 0 var logloss = 0.0 for (i in 0 until frame.samples.size) if (frame.subset[i]) { val sample = frame.samples[i] val scores = model.predict(sample.values) val probabilities = if (calibrate) prob(scores) else scores for ((k, p) in probabilities.withIndex()) { logloss += 0.5 * (sample.actual[k] + 1.0) * ln(max(min(p, 1.0 - 1E-15), 1E-15)) } total++ } return logloss / -total } fun gini(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double { val domain = (frame.target as NominalAttribute).domain if (domain.size != 2) { throw Exception("Could not calculate") } val values = mutableListOf<DoubleArray>() for (i in 0 until frame.samples.size) if (frame.subset[i]) { val sample = frame.samples[i] val scores = model.predict(sample.values) val probabilities = if (calibrate) prob(scores) else scores values.add(doubleArrayOf(probabilities[0], 0.5 * (sample.actual[0] + 1.0), i.toDouble())) } val g: (Int) -> Double = { by -> var losses = 0.0 val sorted = values.sortedWith(compareBy({ -it[by] }, { it[2] })) for (row in sorted) losses += row[1] var cum = 0.0 var sum = 0.0 for (row in sorted) { cum += row[1] / losses sum += cum } sum -= (sorted.size + 1.0) / 2.0 sum / sorted.size } return max(0.0, g(0) / g(1)) } fun auc(frame: DataFrame, model: Predictor, calibrate: Boolean = true): Double { return 0.5 * (gini(frame, model, calibrate) + 1.0) }
mit
2178dba937527ebe3673318117a7d8ad
31.418605
97
0.599354
3.379394
false
false
false
false
erikeelde/Granter
app/src/main/java/se/eelde/granter/app/RegularPermissionActivity.kt
1
4000
package se.eelde.granter.app import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_regular_permission.* class RegularPermissionActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_regular_permission) regular_permission_button.setOnClickListener { checkPermissions() } } private fun moveToNextStep() { supportFragmentManager .beginTransaction() .replace(fragment_container.id, DummyFragment.newInstance()) .commit() } private fun checkPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { AlertDialog.Builder(this) .setTitle("title") .setMessage("message") .setPositiveButton("ok") { _, _ -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION_RATIONALE) } .setNegativeButton("nah", null) .create() .show() } else { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION) } } else { moveToNextStep() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { REQUEST_PERMISSION_LOCATION -> { run { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { moveToNextStep() } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { AlertDialog.Builder(this) .setTitle("title") .setMessage("settings") .setPositiveButton("ok", null) .setNegativeButton("nah", null) .create() .show() } } run { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { moveToNextStep() } } run { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } REQUEST_PERMISSION_LOCATION_RATIONALE -> { run { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { moveToNextStep() } } run { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } else -> { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } companion object { private const val REQUEST_PERMISSION_LOCATION_RATIONALE = 213 private const val REQUEST_PERMISSION_LOCATION = 212 fun start(context: Context) { context.startActivity(Intent(context, RegularPermissionActivity::class.java)) } } }
mit
cff4722fd1fb27047f0307b7c41ba70b
40.666667
190
0.583
5.943536
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/NullableVFUEntityImpl.kt
1
7221
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class NullableVFUEntityImpl(val dataSource: NullableVFUEntityData) : NullableVFUEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val fileProperty: VirtualFileUrl? get() = dataSource.fileProperty override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: NullableVFUEntityData?) : ModifiableWorkspaceEntityBase<NullableVFUEntity>(), NullableVFUEntity.Builder { constructor() : this(NullableVFUEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity NullableVFUEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() index(this, "fileProperty", this.fileProperty) // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field NullableVFUEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as NullableVFUEntity this.entitySource = dataSource.entitySource this.data = dataSource.data this.fileProperty = dataSource.fileProperty if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var fileProperty: VirtualFileUrl? get() = getEntityData().fileProperty set(value) { checkModificationAllowed() getEntityData().fileProperty = value changedProperty.add("fileProperty") val _diff = diff if (_diff != null) index(this, "fileProperty", value) } override fun getEntityData(): NullableVFUEntityData = result ?: super.getEntityData() as NullableVFUEntityData override fun getEntityClass(): Class<NullableVFUEntity> = NullableVFUEntity::class.java } } class NullableVFUEntityData : WorkspaceEntityData<NullableVFUEntity>() { lateinit var data: String var fileProperty: VirtualFileUrl? = null fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<NullableVFUEntity> { val modifiable = NullableVFUEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): NullableVFUEntity { return getCached(snapshot) { val entity = NullableVFUEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return NullableVFUEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return NullableVFUEntity(data, entitySource) { this.fileProperty = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as NullableVFUEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false if (this.fileProperty != other.fileProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as NullableVFUEntityData if (this.data != other.data) return false if (this.fileProperty != other.fileProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() result = 31 * result + fileProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() result = 31 * result + fileProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.fileProperty?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
e64d3ba6d370e2fe3d138cbedc4bb96f
32.123853
133
0.730924
5.408989
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/JdkUtils.kt
6
1850
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.io.URLUtil import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.jps.model.JpsGlobal import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsOrderRootType import java.io.File import java.nio.file.Path import java.util.* import kotlin.io.path.exists import kotlin.io.path.inputStream object JdkUtils { fun defineJdk(global: JpsGlobal, jdkName: String, jdkHomePath: String, messages: BuildMessages) { val sdk = JpsJavaExtensionService.getInstance().addJavaSdk(global, jdkName, jdkHomePath) val toolsJar = File(jdkHomePath, "lib/tools.jar") if (toolsJar.exists()) { sdk.addRoot(toolsJar, JpsOrderRootType.COMPILED) } messages.info("'$jdkName' Java SDK set to $jdkHomePath") } /** * Code is copied from com.intellij.openapi.projectRoots.impl.JavaSdkImpl#findClasses(java.io.File, boolean) */ fun readModulesFromReleaseFile(jbrBaseDir: Path): List<String> { val releaseFile = jbrBaseDir.resolve("release") if (!releaseFile.exists()) { throw IllegalStateException("JRE release file is missing: $releaseFile") } releaseFile.inputStream().use { stream -> val p = Properties() p.load(stream) val jbrBaseUrl = "${URLUtil.JRT_PROTOCOL}${URLUtil.SCHEME_SEPARATOR}${FileUtilRt.toSystemIndependentName(jbrBaseDir.toAbsolutePath().toString())}${URLUtil.JAR_SEPARATOR}" val modules = p.getProperty("MODULES") ?: return emptyList() return StringUtilRt.unquoteString(modules).split(' ').map { jbrBaseUrl + it } } } }
apache-2.0
3995eff982acef8dcfc7d148205d9122
41.045455
176
0.748649
4.065934
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/feature/barcode/camera/CameraSource.kt
2
22658
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package quickbeer.android.feature.barcode.camera import android.content.Context import android.graphics.ImageFormat import android.hardware.Camera import android.hardware.Camera.CameraInfo import android.hardware.Camera.Parameters import android.view.Surface import android.view.SurfaceHolder import android.view.WindowManager import com.google.android.gms.common.images.Size import java.io.IOException import java.nio.ByteBuffer import java.util.IdentityHashMap import kotlin.math.abs import kotlin.math.ceil import quickbeer.android.feature.barcode.detection.FrameMetadata import quickbeer.android.feature.barcode.detection.FrameProcessor import quickbeer.android.feature.barcode.graphic.GraphicOverlay import quickbeer.android.feature.barcode.utils.ScannerUtils import timber.log.Timber /** * Manages the camera and allows UI updates on top of it (e.g. overlaying extra Graphics). This * receives preview frames from the camera at a specified rate, sends those frames to detector as * fast as it is able to process. * * * This camera source makes a best effort to manage processing on preview frames as fast as * possible, while at the same time minimizing lag. As such, frames may be dropped if the detector * is unable to keep up with the rate of frames generated by the camera. */ @Suppress("DEPRECATION") class CameraSource(private val graphicOverlay: GraphicOverlay) { internal var camera: Camera? = null internal var rotationDegrees: Int = 0 /** Returns the preview size that is currently in use by the underlying camera. */ internal var previewSize: Size? = null private set /** * Dedicated thread and associated runnable for calling into the detector with frames, as the * frames become available from the camera. */ private var processingThread: Thread? = null private val processingRunnable = FrameProcessingRunnable() internal val processorLock = Object() internal var frameProcessor: FrameProcessor? = null /** * Map to convert between a byte array, received from the camera, and its associated byte * buffer. We use byte buffers internally because this is a more efficient way to call into * native code later (avoids a potential copy). * * * **Note:** uses IdentityHashMap here instead of HashMap because the behavior of an array's * equals, hashCode and toString methods is both useless and unexpected. IdentityHashMap * enforces identity ('==') check on the keys. */ internal val bytesToByteBuffer = IdentityHashMap<ByteArray, ByteBuffer>() internal val context: Context = graphicOverlay.context /** * Opens the camera and starts sending preview frames to the underlying detector. The supplied * surface holder is used for the preview so frames can be displayed to the user. * * @param surfaceHolder the surface holder to use for the preview frames. * @throws IOException if the supplied surface holder could not be used as the preview display. */ @Synchronized @Throws(IOException::class) internal fun start(surfaceHolder: SurfaceHolder) { if (camera != null) return camera = createCamera().apply { setPreviewDisplay(surfaceHolder) startPreview() } processingThread = Thread(processingRunnable).apply { processingRunnable.setActive(true) start() } } /** * Closes the camera and stops sending frames to the underlying frame detector. * * This camera source may be restarted again by calling [.start]. * * Call [.release] instead to completely shut down this camera source and release the * resources of the underlying detector. */ @Synchronized internal fun stop() { processingRunnable.setActive(false) processingThread?.let { try { // Waits for the thread to complete to ensure that we can't have multiple threads // executing at the same time (i.e., which would happen if we called start too // quickly after stop). it.join() } catch (e: InterruptedException) { Timber.e("Frame processing thread interrupted on stop.") } processingThread = null } camera?.let { it.stopPreview() it.setPreviewCallbackWithBuffer(null) try { it.setPreviewDisplay(null) } catch (e: IOException) { Timber.e(e, "Failed to clear camera preview") } it.release() camera = null } // Release the reference to any image buffers, since these will no longer be in use. bytesToByteBuffer.clear() } /** Stops the camera and releases the resources of the camera and underlying detector. */ fun release() { graphicOverlay.clear() synchronized(processorLock) { stop() frameProcessor?.stop() } } fun setFrameProcessor(processor: FrameProcessor) { graphicOverlay.clear() synchronized(processorLock) { frameProcessor?.stop() frameProcessor = processor } } fun updateFlashMode(mode: String) { camera?.parameters = camera?.parameters?.apply { flashMode = mode } } /** * Opens the camera and applies the user settings. * * @throws IOException if camera cannot be found or preview cannot be processed. */ @Throws(IOException::class) private fun createCamera(): Camera { val camera = Camera.open() ?: throw IOException("There is no back-facing camera.") val parameters = camera.parameters setPreviewAndPictureSize(camera, parameters) setRotation(camera, parameters) val previewFpsRange = selectPreviewFpsRange(camera) ?: throw IOException("Could not find suitable preview frames per second range.") parameters.setPreviewFpsRange( previewFpsRange[Parameters.PREVIEW_FPS_MIN_INDEX], previewFpsRange[Parameters.PREVIEW_FPS_MAX_INDEX] ) parameters.previewFormat = IMAGE_FORMAT if (parameters.supportedFocusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { parameters.focusMode = Parameters.FOCUS_MODE_CONTINUOUS_VIDEO } else { Timber.i("Camera auto focus is not supported on this device.") } camera.parameters = parameters camera.setPreviewCallbackWithBuffer(processingRunnable::setNextFrame) // Four frame buffers are needed for working with the camera: // // one for the frame that is currently being executed upon in doing detection // one for the next pending frame to process immediately upon completing detection // two for the frames that the camera uses to populate future preview images // // Through trial and error it appears that two free buffers, in addition to the two buffers // used in this code, are needed for the camera to work properly. Perhaps the camera has one // thread for acquiring images, and another thread for calling into user code. If only three // buffers are used, then the camera will spew thousands of warning messages when detection // takes a non-trivial amount of time. previewSize?.let { camera.addCallbackBuffer(createPreviewBuffer(it)) camera.addCallbackBuffer(createPreviewBuffer(it)) camera.addCallbackBuffer(createPreviewBuffer(it)) camera.addCallbackBuffer(createPreviewBuffer(it)) } return camera } @Throws(IOException::class) private fun setPreviewAndPictureSize(camera: Camera, parameters: Parameters) { // Camera preview size is based on the landscape mode, so we need to also use the aspect // ration of display in the same mode for comparison. val displayAspectRatioInLandscape: Float = if (ScannerUtils.isPortraitMode(graphicOverlay.context)) { graphicOverlay.height.toFloat() / graphicOverlay.width } else { graphicOverlay.width.toFloat() / graphicOverlay.height } // Gives priority to the preview size specified by the user if exists. val sizePair = selectSizePair(camera, displayAspectRatioInLandscape) ?: throw IOException("Could not find suitable preview size") previewSize = sizePair.preview.also { Timber.v("Camera preview size: $it") parameters.setPreviewSize(it.width, it.height) } sizePair.picture?.let { pictureSize -> Timber.v("Camera picture size: $pictureSize") parameters.setPictureSize(pictureSize.width, pictureSize.height) } } /** * Calculates the correct rotation for the given camera id and sets the rotation in the * parameters. It also sets the camera's display orientation and rotation. * * @param parameters the camera parameters for which to set the rotation. */ @Suppress("MagicNumber") private fun setRotation(camera: Camera, parameters: Parameters) { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val degrees = when (val deviceRotation = windowManager.defaultDisplay.rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> { Timber.e("Bad device rotation value: $deviceRotation") 0 } } val cameraInfo = CameraInfo().also { Camera.getCameraInfo(CAMERA_FACING_BACK, it) } val angle = (cameraInfo.orientation - degrees + 360) % 360 rotationDegrees = angle camera.setDisplayOrientation(angle) parameters.setRotation(angle) } /** * Creates one buffer for the camera preview callback. The size of the buffer is based off of * the camera preview size and the format of the camera image. * * @return a new preview buffer of the appropriate size for the current camera settings. */ @Suppress("MagicNumber") private fun createPreviewBuffer(previewSize: Size): ByteArray { val bitsPerPixel = ImageFormat.getBitsPerPixel(IMAGE_FORMAT) val area = previewSize.height.toLong() * previewSize.width.toLong() val sizeInBits = area * bitsPerPixel.toLong() val bufferSize = ceil(sizeInBits / 8.0).toInt() + 1 // Creating the byte array this way and wrapping it, as opposed to using .allocate(), // should guarantee that there will be an array to work with. val byteArray = ByteArray(bufferSize) val byteBuffer = ByteBuffer.wrap(byteArray) check(!(!byteBuffer.hasArray() || !byteBuffer.array().contentEquals(byteArray))) { // This should never happen. If it does, then we wouldn't be passing the preview content // to the underlying detector later. "Failed to create valid buffer for camera source." } bytesToByteBuffer[byteArray] = byteBuffer return byteArray } /** * This runnable controls access to the underlying receiver, calling it to process frames when * available from the camera. This is designed to run detection on frames as fast as possible * (i.e., without unnecessary context switching or waiting on the next frame). * * While detection is running on a frame, new frames may be received from the camera. As these * frames come in, the most recent frame is held onto as pending. As soon as detection and its * associated processing is done for the previous frame, detection on the mostly recently * received frame will immediately start on the same thread. */ private inner class FrameProcessingRunnable : Runnable { // This lock guards all of the member variables below. private val lock = Object() private var active = true // These pending variables hold the state associated with the new frame awaiting processing. private var pendingFrameData: ByteBuffer? = null /** Marks the runnable as active/not active. Signals any blocked threads to continue. */ fun setActive(active: Boolean) { synchronized(lock) { this.active = active lock.notifyAll() } } /** * Sets the frame data received from the camera. This adds the previous unused frame buffer * (if present) back to the camera, and keeps a pending reference to the frame data for * future use. */ fun setNextFrame(data: ByteArray, camera: Camera) { synchronized(lock) { pendingFrameData?.let { camera.addCallbackBuffer(it.array()) pendingFrameData = null } if (!bytesToByteBuffer.containsKey(data)) { Timber.d("Could not find ByteBuffer, skipping frame") return } pendingFrameData = bytesToByteBuffer[data] // Notify the processor thread if it is waiting on the next frame (see below). lock.notifyAll() } } /** * As long as the processing thread is active, this executes detection on frames * continuously. The next pending frame is either immediately available or hasn't been * received yet. Once it is available, we transfer the frame info to local variables and run * detection on that frame. It immediately loops back for the next frame without pausing. * * If detection takes longer than the time in between new frames from the camera, this will * mean that this loop will run without ever waiting on a frame, avoiding any context * switching or frame acquisition time latency. * * If you find that this is using more CPU than you'd like, you should probably decrease the * FPS setting above to allow for some idle time in between frames. */ override fun run() { var data: ByteBuffer? while (true) { synchronized(lock) { while (active && pendingFrameData == null) { try { // Wait for the next frame to be received from the camera, since we // don't have it yet. lock.wait() } catch (e: InterruptedException) { Timber.e(e, "Frame processing loop terminated.") return } } if (!active) { // Exit the loop once this camera source is stopped or released. We check // this here, immediately after the wait() above, to handle the case where // setActive(false) had been called, triggering termination of this loop. return } // Hold onto the frame data locally, so that we can use this for detection // below. We need to clear pendingFrameData to ensure that this buffer isn't // recycled back to the camera before we are done using that data. data = pendingFrameData pendingFrameData = null } @Suppress("TooGenericExceptionCaught") try { synchronized(processorLock) { val frameMetadata = FrameMetadata( previewSize!!.width, previewSize!!.height, rotationDegrees ) data?.let { frameProcessor?.process(it, frameMetadata, graphicOverlay) } } } catch (e: Exception) { Timber.e(e, "Exception thrown from receiver.") } finally { data?.let { camera?.addCallbackBuffer(it.array()) } } } } } companion object { const val CAMERA_FACING_BACK = CameraInfo.CAMERA_FACING_BACK private const val IMAGE_FORMAT = ImageFormat.NV21 private const val MIN_CAMERA_PREVIEW_WIDTH = 400 private const val MAX_CAMERA_PREVIEW_WIDTH = 1300 private const val DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH = 640 private const val DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT = 360 private const val REQUESTED_CAMERA_FPS = 30.0f /** * Selects the most suitable preview and picture size, given the display aspect ratio in * landscape mode. * * It's firstly trying to pick the one that has closest aspect ratio to display view with * its width be in the specified range [[.MIN_CAMERA_PREVIEW_WIDTH], * [ ][.MAX_CAMERA_PREVIEW_WIDTH]]. If there're multiple candidates, choose the one having * longest width. * * If the above looking up failed, chooses the one that has the minimum sum of the * differences between the desired values and the actual values for width and height. * * Even though we only need to find the preview size, it's necessary to find both the * preview size and the picture size of the camera together, because these need to have the * same aspect ratio. On some hardware, if you would only set the preview size, you will get * a distorted image. * * @param camera the camera to select a preview size from * @return the selected preview and picture size pair */ internal fun selectSizePair( camera: Camera, displayAspectRatioInLandscape: Float ): CameraSizePair? { val validPreviewSizes = ScannerUtils.generateValidPreviewSizeList(camera) var selectedPair: CameraSizePair? = null // Picks the preview size that has closest aspect ratio to display view. var minAspectRatioDiff = Float.MAX_VALUE for (sizePair in validPreviewSizes) { val previewSize = sizePair.preview if (previewSize.width < MIN_CAMERA_PREVIEW_WIDTH || previewSize.width > MAX_CAMERA_PREVIEW_WIDTH ) { continue } val previewAspectRatio = previewSize.width.toFloat() / previewSize.height.toFloat() val aspectRatioDiff = abs(displayAspectRatioInLandscape - previewAspectRatio) val aspectRatioFoo = abs(aspectRatioDiff - minAspectRatioDiff) if (aspectRatioFoo < ScannerUtils.ASPECT_RATIO_TOLERANCE) { if (selectedPair == null || selectedPair.preview.width < sizePair.preview.width ) { selectedPair = sizePair } } else if (aspectRatioDiff < minAspectRatioDiff) { minAspectRatioDiff = aspectRatioDiff selectedPair = sizePair } } if (selectedPair == null) { // Picks the one that has the minimum sum of the differences between the desired // values and the actual values for width and height. var minDiff = Integer.MAX_VALUE for (sizePair in validPreviewSizes) { val size = sizePair.preview val wDiff = abs(size.width - DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH) val hDiff = abs(size.height - DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT) val diff = wDiff + hDiff if (diff < minDiff) { selectedPair = sizePair minDiff = diff } } } return selectedPair } /** * Selects the most suitable preview frames per second range. * * @param camera the camera to select a frames per second range from * @return the selected preview frames per second range */ @Suppress("MagicNumber") internal fun selectPreviewFpsRange(camera: Camera): IntArray? { // The camera API uses integers scaled by a factor of 1000 instead of floating-point // frame rates. val desiredPreviewFpsScaled = (REQUESTED_CAMERA_FPS * 1000f).toInt() // The method for selecting the best range is to minimize the sum of the differences // between the desired value and the upper and lower bounds of the range. This may // select a range that the desired value is outside of, but this is often preferred. // For example, if the desired frame rate is 29.97, the range (30, 30) is probably more // desirable than the range (15, 30). var selectedFpsRange: IntArray? = null var minDiff = Integer.MAX_VALUE for (range in camera.parameters.supportedPreviewFpsRange) { val deltaMin = desiredPreviewFpsScaled - range[Parameters.PREVIEW_FPS_MIN_INDEX] val deltaMax = desiredPreviewFpsScaled - range[Parameters.PREVIEW_FPS_MAX_INDEX] val diff = abs(deltaMin) + abs(deltaMax) if (diff < minDiff) { selectedFpsRange = range minDiff = diff } } return selectedFpsRange } } }
gpl-3.0
761a36f00775bf234623768cca775555
41.831758
100
0.620884
5.297639
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaVideoActivity.kt
1
11094
package com.simplemobiletools.gallery.pro.activities import android.content.res.Configuration import android.graphics.Color import android.net.Uri import android.os.Bundle import android.os.Handler import android.view.View import android.view.Window import android.view.WindowInsetsController import android.view.WindowManager import android.widget.RelativeLayout import android.widget.SeekBar import com.google.vr.sdk.widgets.video.VrVideoEventListener import com.google.vr.sdk.widgets.video.VrVideoView import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.isRPlus import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.extensions.hasNavBar import com.simplemobiletools.gallery.pro.extensions.hideSystemUI import com.simplemobiletools.gallery.pro.extensions.showSystemUI import com.simplemobiletools.gallery.pro.helpers.MIN_SKIP_LENGTH import com.simplemobiletools.gallery.pro.helpers.PATH import kotlinx.android.synthetic.main.activity_panorama_video.* import kotlinx.android.synthetic.main.bottom_video_time_holder.* import java.io.File open class PanoramaVideoActivity : SimpleActivity(), SeekBar.OnSeekBarChangeListener { private val CARDBOARD_DISPLAY_MODE = 3 private var mIsFullscreen = false private var mIsExploreEnabled = true private var mIsRendering = false private var mIsPlaying = false private var mIsDragged = false private var mPlayOnReady = false private var mDuration = 0 private var mCurrTime = 0 private var mTimerHandler = Handler() public override fun onCreate(savedInstanceState: Bundle?) { useDynamicTheme = false requestWindowFeature(Window.FEATURE_NO_TITLE) super.onCreate(savedInstanceState) setContentView(R.layout.activity_panorama_video) checkNotchSupport() checkIntent() if (isRPlus()) { window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS) } } override fun onResume() { super.onResume() vr_video_view.resumeRendering() mIsRendering = true if (config.blackBackground) { updateStatusbarColor(Color.BLACK) } window.statusBarColor = resources.getColor(R.color.circle_black_background) if (config.maxBrightness) { val attributes = window.attributes attributes.screenBrightness = 1f window.attributes = attributes } } override fun onPause() { super.onPause() vr_video_view.pauseRendering() mIsRendering = false } override fun onDestroy() { super.onDestroy() if (mIsRendering) { vr_video_view.shutdown() } if (!isChangingConfigurations) { mTimerHandler.removeCallbacksAndMessages(null) } } private fun checkIntent() { val path = intent.getStringExtra(PATH) if (path == null) { toast(R.string.invalid_image_path) finish() return } setupButtons() intent.removeExtra(PATH) video_curr_time.setOnClickListener { skip(false) } video_duration.setOnClickListener { skip(true) } try { val options = VrVideoView.Options() options.inputType = VrVideoView.Options.TYPE_MONO val uri = if (path.startsWith("content://")) { Uri.parse(path) } else { Uri.fromFile(File(path)) } vr_video_view.apply { loadVideo(uri, options) pauseVideo() setFlingingEnabled(true) setPureTouchTracking(true) // add custom buttons so we can position them and toggle visibility as desired setFullscreenButtonEnabled(false) setInfoButtonEnabled(false) setTransitionViewEnabled(false) setStereoModeButtonEnabled(false) setOnClickListener { handleClick() } setEventListener(object : VrVideoEventListener() { override fun onClick() { handleClick() } override fun onLoadSuccess() { if (mDuration == 0) { setupDuration(duration) setupTimer() } if (mPlayOnReady || config.autoplayVideos) { mPlayOnReady = false mIsPlaying = true resumeVideo() } else { video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector) } video_toggle_play_pause.beVisible() } override fun onCompletion() { videoCompleted() } }) } video_toggle_play_pause.setOnClickListener { togglePlayPause() } } catch (e: Exception) { showErrorToast(e) } window.decorView.setOnSystemUiVisibilityChangeListener { visibility -> mIsFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0 toggleButtonVisibility() } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) setupButtons() } private fun setupDuration(duration: Long) { mDuration = (duration / 1000).toInt() video_seekbar.max = mDuration video_duration.text = mDuration.getFormattedDuration() setVideoProgress(0) } private fun setupTimer() { runOnUiThread(object : Runnable { override fun run() { if (mIsPlaying && !mIsDragged) { mCurrTime = (vr_video_view!!.currentPosition / 1000).toInt() video_seekbar.progress = mCurrTime video_curr_time.text = mCurrTime.getFormattedDuration() } mTimerHandler.postDelayed(this, 1000) } }) } private fun togglePlayPause() { mIsPlaying = !mIsPlaying if (mIsPlaying) { resumeVideo() } else { pauseVideo() } } private fun resumeVideo() { video_toggle_play_pause.setImageResource(R.drawable.ic_pause_outline_vector) if (mCurrTime == mDuration) { setVideoProgress(0) mPlayOnReady = true return } vr_video_view.playVideo() window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } private fun pauseVideo() { vr_video_view.pauseVideo() video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector) window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } private fun setVideoProgress(seconds: Int) { vr_video_view.seekTo(seconds * 1000L) video_seekbar.progress = seconds mCurrTime = seconds video_curr_time.text = seconds.getFormattedDuration() } private fun videoCompleted() { mIsPlaying = false mCurrTime = (vr_video_view.duration / 1000).toInt() video_seekbar.progress = video_seekbar.max video_curr_time.text = mDuration.getFormattedDuration() pauseVideo() } private fun setupButtons() { var right = 0 var bottom = 0 if (hasNavBar()) { if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { bottom += navigationBarHeight } else { right += navigationBarWidth bottom += navigationBarHeight } } video_time_holder.setPadding(0, 0, right, bottom) video_time_holder.background = resources.getDrawable(R.drawable.gradient_background) video_time_holder.onGlobalLayout { val newBottomMargin = video_time_holder.height - resources.getDimension(R.dimen.video_player_play_pause_size) .toInt() - resources.getDimension(R.dimen.activity_margin).toInt() (explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = newBottomMargin (cardboard.layoutParams as RelativeLayout.LayoutParams).apply { bottomMargin = newBottomMargin rightMargin = navigationBarWidth } explore.requestLayout() } video_toggle_play_pause.setImageResource(R.drawable.ic_play_outline_vector) cardboard.setOnClickListener { vr_video_view.displayMode = CARDBOARD_DISPLAY_MODE } explore.setOnClickListener { mIsExploreEnabled = !mIsExploreEnabled vr_video_view.setPureTouchTracking(mIsExploreEnabled) explore.setImageResource(if (mIsExploreEnabled) R.drawable.ic_explore_vector else R.drawable.ic_explore_off_vector) } } private fun toggleButtonVisibility() { val newAlpha = if (mIsFullscreen) 0f else 1f arrayOf(cardboard, explore).forEach { it.animate().alpha(newAlpha) } arrayOf(cardboard, explore, video_toggle_play_pause, video_curr_time, video_duration).forEach { it.isClickable = !mIsFullscreen } video_seekbar.setOnSeekBarChangeListener(if (mIsFullscreen) null else this) video_time_holder.animate().alpha(newAlpha).start() } private fun handleClick() { mIsFullscreen = !mIsFullscreen toggleButtonVisibility() if (mIsFullscreen) { hideSystemUI(false) } else { showSystemUI(false) } } private fun skip(forward: Boolean) { if (forward && mCurrTime == mDuration) { return } val curr = vr_video_view.currentPosition val twoPercents = Math.max((vr_video_view.duration / 50).toInt(), MIN_SKIP_LENGTH) val newProgress = if (forward) curr + twoPercents else curr - twoPercents val roundProgress = Math.round(newProgress / 1000f) val limitedProgress = Math.max(Math.min(vr_video_view.duration.toInt(), roundProgress), 0) setVideoProgress(limitedProgress) if (!mIsPlaying) { togglePlayPause() } } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { setVideoProgress(progress) } } override fun onStartTrackingTouch(seekBar: SeekBar?) { vr_video_view.pauseVideo() mIsDragged = true } override fun onStopTrackingTouch(seekBar: SeekBar?) { mIsPlaying = true resumeVideo() mIsDragged = false } }
gpl-3.0
3506ff299650154b9b231cbb501b3d89
32.215569
127
0.609699
5.008578
false
false
false
false
Leifzhang/AndroidRouter
RouterLib/src/main/java/com/kronos/router/model/RouterParams.kt
2
727
package com.kronos.router.model import com.kronos.router.interceptor.Interceptor /** * Created by zhangyang on 16/7/16. */ class RouterParams { var url: String = "" var weight: Int = 0 var routerOptions: RouterOptions? = null var openParams: HashMap<String, String> = hashMapOf() val interceptors = mutableListOf<Interceptor>() val realPath: String get() { try { return url.let { it.subSequence(1, it.length).toString() } } catch (e: Exception) { e.printStackTrace() } return "" } fun put(key: String, value: String?) { value?.apply { openParams[key] = this } } }
mit
8ea546877ec832e0952de9e831999fbe
22.451613
74
0.557084
4.154286
false
false
false
false
apollographql/apollo-android
apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/gqldirective.kt
1
1092
package com.apollographql.apollo3.ast fun List<GQLDirective>.findDeprecationReason() = firstOrNull { it.name == "deprecated" } ?.let { it.arguments ?.arguments ?.firstOrNull { it.name == "reason" } ?.value ?.let { value -> if (value !is GQLStringValue) { throw ConversionException("reason must be a string", it.sourceLocation) } value.value } ?: "No longer supported" } /** * @return `true` or `false` based on the `if` argument if the `optional` directive is present, `null` otherwise */ fun List<GQLDirective>.optionalValue(): Boolean? { val directive = firstOrNull { it.name == "optional" } ?: return null val argument = directive.arguments?.arguments?.firstOrNull { it.name == "if" } // "if" argument defaults to true return argument == null || argument.name == "if" && (argument.value as GQLBooleanValue).value } fun List<GQLDirective>.findNonnull() = any { it.name == "nonnull" } fun GQLDirective.isApollo() = name in listOf("optional", "nonnull")
mit
3b2f7d220b52909af243bee10fb1f73f
35.4
112
0.621795
4.089888
false
false
false
false
avram/zandy
src/main/java/com/gimranov/zandy/app/ItemDisplayUtil.kt
1
2543
package com.gimranov.zandy.app import android.os.Build import android.text.Html import com.gimranov.zandy.app.data.Item import org.json.JSONArray import org.json.JSONObject internal object ItemDisplayUtil { fun datumDisplayComponents(label: String, value: String): Pair<CharSequence, CharSequence> { /* Since the field names are the API / internal form, we * attempt to get a localized, human-readable version. */ val localizedLabel = Item.localizedStringForString(label) if ("itemType" == label) { return Pair(localizedLabel, Item.localizedStringForString(value)) } if ("creators" == label) { return Pair(localizedLabel, formatCreatorList(JSONArray(value))) } if ("title" == label || "note" == label || "abstractNote" == label) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Pair(localizedLabel, Html.fromHtml(value, Html.FROM_HTML_MODE_LEGACY)) } else { @Suppress("DEPRECATION") return Pair(localizedLabel, Html.fromHtml(value)) } } else { return Pair(localizedLabel, value) } } fun formatCreatorList(creators: JSONArray): CharSequence { /* * Creators should be labeled with role and listed nicely * This logic isn't as good as it could be. */ var creator: JSONObject val sb = StringBuilder() for (j in 0 until creators.length()) { creator = creators.getJSONObject(j) if (creator.getString("creatorType") == "author") { if (creator.has("name")) sb.append(creator.getString("name")) else sb.append(creator.getString("firstName") + " " + creator.getString("lastName")) } else { if (creator.has("name")) sb.append(creator.getString("name")) else sb.append(creator.getString("firstName") + " " + creator.getString("lastName") + " (" + Item.localizedStringForString(creator .getString("creatorType")) + ")") } if (j < creators.length() - 1) sb.append(", ") } return sb.toString() } }
agpl-3.0
932b78f60ae3f856c90c1938f5956503
35.342857
93
0.520645
4.947471
false
false
false
false
ursjoss/sipamato
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/jobs/ScipamatoItemWriter.kt
2
730
package ch.difty.scipamato.core.sync.jobs import ch.difty.scipamato.common.logger import org.jooq.DSLContext import org.springframework.batch.item.ItemWriter private val log = logger() /** * Base class for ItemWriter implementations. * * [T] the type of the entity to be written */ abstract class ScipamatoItemWriter<T> constructor( protected val dslContext: DSLContext, private val topic: String, ) : ItemWriter<T> { override fun write(items: List<T>) { var changeCount = 0 for (i in items) changeCount += executeUpdate(i) log.info("$topic-sync: Successfully synced $changeCount $topic${if (changeCount == 1) "" else "s"}") } protected abstract fun executeUpdate(i: T): Int }
gpl-3.0
c914a0aac43a338cfd11405fa0b2dadb
27.076923
108
0.70274
3.945946
false
false
false
false
allotria/intellij-community
platform/vcs-code-review/src/com/intellij/util/ui/codereview/comment/RoundedPanel.kt
2
2092
// 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.util.ui.codereview.comment import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBInsets import java.awt.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.geom.RoundRectangle2D import javax.swing.JComponent import javax.swing.JPanel fun wrapComponentUsingRoundedPanel(component: JComponent): JComponent { val wrapper = RoundedPanel(BorderLayout()) wrapper.add(component) component.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) = wrapper.dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED)) }) return wrapper } private class RoundedPanel(layout: LayoutManager?) : JPanel(layout) { private var borderLineColor: Color? = null init { isOpaque = false cursor = Cursor.getDefaultCursor() updateColors() } override fun updateUI() { super.updateUI() updateColors() } private fun updateColors() { val scheme = EditorColorsManager.getInstance().globalScheme background = scheme.defaultBackground borderLineColor = scheme.getColor(EditorColors.TEARLINE_COLOR) } override fun paintComponent(g: Graphics) { GraphicsUtil.setupRoundedBorderAntialiasing(g) val g2 = g as Graphics2D val rect = Rectangle(size) JBInsets.removeFrom(rect, insets) // 2.25 scale is a @#$!% so we adjust sizes manually val rectangle2d = RoundRectangle2D.Float(rect.x.toFloat() + 0.5f, rect.y.toFloat() + 0.5f, rect.width.toFloat() - 1f, rect.height.toFloat() - 1f, 10f, 10f) g2.color = background g2.fill(rectangle2d) borderLineColor?.let { g2.color = borderLineColor g2.draw(rectangle2d) } } }
apache-2.0
2d2d6a62313df948bafa180868d2885c
32.741935
140
0.716061
4.278119
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryTest.kt
1
11732
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.exceptions import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.intrinsics.* import org.junit.Test import java.lang.RuntimeException import java.util.concurrent.* import kotlin.concurrent.* import kotlin.coroutines.* import kotlin.test.* /* * All stacktrace validation skips line numbers */ class StackTraceRecoveryTest : TestBase() { @Test fun testAsync() = runTest { fun createDeferred(depth: Int): Deferred<*> { return if (depth == 0) { async<Unit>(coroutineContext + NonCancellable) { throw ExecutionException(null) } } else { createDeferred(depth - 1) } } val deferred = createDeferred(3) val traces = listOf( "java.util.concurrent.ExecutionException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1\$createDeferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:99)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.oneMoreNestedMethod(StackTraceRecoveryTest.kt:49)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.nestedMethod(StackTraceRecoveryTest.kt:44)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1.invokeSuspend(StackTraceRecoveryTest.kt:17)\n", "Caused by: java.util.concurrent.ExecutionException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testAsync\$1\$createDeferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:21)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n" ) nestedMethod(deferred, *traces.toTypedArray()) deferred.join() } @Test fun testCompletedAsync() = runTest { val deferred = async<Unit>(coroutineContext + NonCancellable) { throw ExecutionException(null) } deferred.join() val stacktrace = listOf( "java.util.concurrent.ExecutionException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:44)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.oneMoreNestedMethod(StackTraceRecoveryTest.kt:81)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.nestedMethod(StackTraceRecoveryTest.kt:75)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1.invokeSuspend(StackTraceRecoveryTest.kt:71)", "Caused by: java.util.concurrent.ExecutionException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCompletedAsync\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:44)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)" ) nestedMethod(deferred, *stacktrace.toTypedArray()) } private suspend fun nestedMethod(deferred: Deferred<*>, vararg traces: String) { oneMoreNestedMethod(deferred, *traces) assertTrue(true) // Prevent tail-call optimization } private suspend fun oneMoreNestedMethod(deferred: Deferred<*>, vararg traces: String) { try { deferred.await() expectUnreached() } catch (e: ExecutionException) { verifyStackTrace(e, *traces) } } @Test fun testWithContext() = runTest { val deferred = async<Unit>(NonCancellable, start = CoroutineStart.LAZY) { throw RecoverableTestException() } outerMethod(deferred, "kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.innerMethod(StackTraceRecoveryTest.kt:158)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerMethod\$2.invokeSuspend(StackTraceRecoveryTest.kt:151)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.outerMethod(StackTraceRecoveryTest.kt:150)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1.invokeSuspend(StackTraceRecoveryTest.kt:141)\n", "Caused by: kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testWithContext\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n") deferred.join() } private suspend fun outerMethod(deferred: Deferred<*>, vararg traces: String) { withContext(Dispatchers.IO) { innerMethod(deferred, *traces) } assertTrue(true) } private suspend fun innerMethod(deferred: Deferred<*>, vararg traces: String) { try { deferred.await() expectUnreached() } catch (e: RecoverableTestException) { verifyStackTrace(e, *traces) } } @Test fun testCoroutineScope() = runTest { val deferred = async<Unit>(NonCancellable, start = CoroutineStart.LAZY) { throw RecoverableTestException() } outerScopedMethod(deferred, "kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.innerMethod(StackTraceRecoveryTest.kt:158)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerScopedMethod\$2\$1.invokeSuspend(StackTraceRecoveryTest.kt:193)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$outerScopedMethod\$2.invokeSuspend(StackTraceRecoveryTest.kt:151)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1.invokeSuspend(StackTraceRecoveryTest.kt:141)\n", "Caused by: kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCoroutineScope\$1\$deferred\$1.invokeSuspend(StackTraceRecoveryTest.kt:143)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n") deferred.join() } public class TrickyException() : Throwable() { // To be sure ctor is never invoked @Suppress("UNUSED", "UNUSED_PARAMETER") private constructor(message: String, cause: Throwable): this() { error("Should never be called") } override fun initCause(cause: Throwable?): Throwable { error("Can't call initCause") } } @Test fun testThrowingInitCause() = runTest { val deferred = async<Unit>(NonCancellable) { expect(2) throw TrickyException() } try { expect(1) deferred.await() } catch (e: TrickyException) { assertNull(e.cause) finish(3) } } private suspend fun outerScopedMethod(deferred: Deferred<*>, vararg traces: String) = coroutineScope { supervisorScope { innerMethod(deferred, *traces) assertTrue(true) } assertTrue(true) } @Test fun testSelfSuppression() = runTest { try { runBlocking { val job = launch { coroutineScope<Unit> { throw RecoverableTestException() } } job.join() expectUnreached() } expectUnreached() } catch (e: RecoverableTestException) { checkCycles(e) } } private suspend fun throws() { yield() // TCE throw RecoverableTestException() } private suspend fun awaiter() { val task = GlobalScope.async(Dispatchers.Default, start = CoroutineStart.LAZY) { throws() } task.await() yield() // TCE } @Test fun testNonDispatchedRecovery() { val await = suspend { awaiter() } val barrier = CyclicBarrier(2) var exception: Throwable? = null thread { await.startCoroutineUnintercepted(Continuation(EmptyCoroutineContext) { exception = it.exceptionOrNull() barrier.await() }) } barrier.await() val e = exception assertNotNull(e) verifyStackTrace(e, "kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.throws(StackTraceRecoveryTest.kt:280)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.access\$throws(StackTraceRecoveryTest.kt:20)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$throws\$1.invokeSuspend(StackTraceRecoveryTest.kt)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.awaiter(StackTraceRecoveryTest.kt:285)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testNonDispatchedRecovery\$await\$1.invokeSuspend(StackTraceRecoveryTest.kt:291)\n" + "Caused by: kotlinx.coroutines.RecoverableTestException") } private class Callback(val cont: CancellableContinuation<*>) @Test fun testCancellableContinuation() = runTest { val channel = Channel<Callback>(1) launch { try { awaitCallback(channel) } catch (e: Throwable) { verifyStackTrace(e, "kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1.invokeSuspend(StackTraceRecoveryTest.kt:329)\n" + "\t(Coroutine boundary)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest.awaitCallback(StackTraceRecoveryTest.kt:348)\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1\$1.invokeSuspend(StackTraceRecoveryTest.kt:322)\n" + "Caused by: kotlinx.coroutines.RecoverableTestException\n" + "\tat kotlinx.coroutines.exceptions.StackTraceRecoveryTest\$testCancellableContinuation\$1.invokeSuspend(StackTraceRecoveryTest.kt:329)") } } val callback = channel.receive() callback.cont.resumeWithException(RecoverableTestException()) } private suspend fun awaitCallback(channel: Channel<Callback>) { suspendCancellableCoroutine<Unit> { cont -> channel.trySend(Callback(cont)) } yield() // nop to make sure it is not a tail call } }
apache-2.0
0a118ef59d128eb031903fe51eba6082
43.439394
167
0.642516
5.244524
false
true
false
false
smmribeiro/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/uastLiteralUtils.kt
5
7675
/* * 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. */ @file:JvmName("UastLiteralUtils") package org.jetbrains.uast import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.PsiReference import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.expressions.UInjectionHost /** * Checks if the [UElement] is a null literal. * * @return true if the receiver is a null literal, false otherwise. */ fun UElement.isNullLiteral(): Boolean = this is ULiteralExpression && this.isNull /** * Checks if the [UElement] is a boolean literal. * * @return true if the receiver is a boolean literal, false otherwise. */ fun UElement.isBooleanLiteral(): Boolean = this is ULiteralExpression && this.isBoolean /** * Checks if the [UElement] is a `true` boolean literal. * * @return true if the receiver is a `true` boolean literal, false otherwise. */ fun UElement.isTrueLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == true /** * Checks if the [UElement] is a `false` boolean literal. * * @return true if the receiver is a `false` boolean literal, false otherwise. */ fun UElement.isFalseLiteral(): Boolean = this is ULiteralExpression && this.isBoolean && this.value == false /** * Checks if the [UElement] is a [String] literal. * * @return true if the receiver is a [String] literal, false otherwise. */ @Deprecated("doesn't support UInjectionHost, most likely it is not what you want", ReplaceWith("isInjectionHost()")) fun UElement.isStringLiteral(): Boolean = this is ULiteralExpression && this.isString /** * Checks if the [UElement] is a [PsiLanguageInjectionHost] holder. * * NOTE: It is a transitional function until everything will migrate to [UInjectionHost] */ fun UElement?.isInjectionHost(): Boolean = this is UInjectionHost || (this is UExpression && this.sourceInjectionHost != null) /** * Returns the [String] literal value. * * @return literal text if the receiver is a valid [String] literal, null otherwise. */ @Deprecated("doesn't support UInjectionHost, most likely it is not what you want", ReplaceWith("UExpression.evaluateString()")) @Suppress("Deprecation") fun UElement.getValueIfStringLiteral(): String? = if (isStringLiteral()) (this as ULiteralExpression).value as String else null /** * Checks if the [UElement] is a [Number] literal (Integer, Long, Float, Double, etc.). * * @return true if the receiver is a [Number] literal, false otherwise. */ fun UElement.isNumberLiteral(): Boolean = this is ULiteralExpression && this.value is Number /** * Checks if the [UElement] is an integral literal (is an [Integer], [Long], [Short], [Char] or [Byte]). * * @return true if the receiver is an integral literal, false otherwise. */ fun UElement.isIntegralLiteral(): Boolean = this is ULiteralExpression && when (value) { is Int -> true is Long -> true is Short -> true is Char -> true is Byte -> true else -> false } /** * Returns the integral value of the literal. * * @return long representation of the literal expression value, * 0 if the receiver literal expression is not a integral one. */ fun ULiteralExpression.getLongValue(): Long = value.let { when (it) { is Long -> it is Int -> it.toLong() is Short -> it.toLong() is Char -> it.toLong() is Byte -> it.toLong() else -> 0 } } /** * @return corresponding [PsiLanguageInjectionHost] for this [UExpression] if it exists. * Tries to not return same [PsiLanguageInjectionHost] for different UElement-s, thus returns `null` if host could be obtained from * another [UExpression]. */ val UExpression.sourceInjectionHost: PsiLanguageInjectionHost? get() { (this.sourcePsi as? PsiLanguageInjectionHost)?.let { return it } // following is a handling of KT-27283 if (this !is ULiteralExpression) return null val parent = this.uastParent if (parent is UPolyadicExpression && parent.sourcePsi is PsiLanguageInjectionHost) return null (this.sourcePsi?.parent as? PsiLanguageInjectionHost)?.let { return it } return null } val UExpression.allPsiLanguageInjectionHosts: List<PsiLanguageInjectionHost> @ApiStatus.Experimental get() { sourceInjectionHost?.let { return listOf(it) } (this as? UPolyadicExpression)?.let { return this.operands.mapNotNull { it.sourceInjectionHost } } return emptyList() } @ApiStatus.Experimental fun isConcatenation(uExpression: UElement?): Boolean { if (uExpression !is UPolyadicExpression) return false if (uExpression.operator != UastBinaryOperator.PLUS) return false return true } /** * @return a non-strict parent [PsiLanguageInjectionHost] for [ULiteralExpression.sourcePsi] of given literal expression if it exists. * * NOTE: consider using [sourceInjectionHost] as more performant. Probably will be deprecated in future. */ val ULiteralExpression.psiLanguageInjectionHost: PsiLanguageInjectionHost? get() = this.sourcePsi?.let { PsiTreeUtil.getParentOfType(it, PsiLanguageInjectionHost::class.java, false) } /** * @return if given [uElement] is an [ULiteralExpression] but not a [UInjectionHost] * (which could happen because of "KotlinULiteralExpression and PsiLanguageInjectionHost mismatch", see KT-27283 ) * then tries to convert it to [UInjectionHost] and return it, * otherwise return [uElement] itself * * NOTE: when `kotlin.uast.force.uinjectionhost` flag is `true` this method is useless because there is no mismatch anymore */ @ApiStatus.Experimental fun wrapULiteral(uElement: UExpression): UExpression { if (uElement is ULiteralExpression && uElement !is UInjectionHost) { uElement.sourceInjectionHost.toUElementOfType<UInjectionHost>()?.let { return it } } return uElement } /** * @return all references injected into this [ULiteralExpression] * * Note: getting references simply from the `sourcePsi` will not work for Kotlin polyadic strings for instance */ val ULiteralExpression.injectedReferences: Iterable<PsiReference> get() { val element = this.psiLanguageInjectionHost ?: return emptyList() val references = element.references.asSequence() val innerReferences = element.children.asSequence().flatMap { e -> e.references.asSequence() } return (references + innerReferences).asIterable() } @JvmOverloads fun deepLiteralSearch(expression: UExpression, maxDepth: Int = 5): Sequence<ULiteralExpression> { val visited = HashSet<UExpression>() fun deepLiteralSearchInner(expression: UExpression, maxDepth: Int): Sequence<ULiteralExpression> { if (maxDepth <= 0 || !visited.add(expression)) return emptySequence(); return when (expression) { is ULiteralExpression -> sequenceOf(expression) is UPolyadicExpression -> expression.operands.asSequence().flatMap { deepLiteralSearchInner(it, maxDepth - 1) } is UReferenceExpression -> expression.resolve() .toUElementOfType<UVariable>() ?.uastInitializer ?.let { deepLiteralSearchInner(it, maxDepth - 1) }.orEmpty() else -> emptySequence() } } return deepLiteralSearchInner(expression, maxDepth) }
apache-2.0
9003aebc28b78d1ee26d94d7829a11d2
37.189055
134
0.735896
4.464805
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHTextActions.kt
2
1620
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.collaboration.ui.codereview.InlineIconButton import icons.CollaborationToolsIcons import org.jetbrains.plugins.github.i18n.GithubBundle import java.awt.event.ActionListener import java.util.concurrent.CompletableFuture import javax.swing.JComponent internal object GHTextActions { fun createDeleteButton(delete: () -> CompletableFuture<out Any?>): JComponent { val icon = CollaborationToolsIcons.Delete val hoverIcon = CollaborationToolsIcons.DeleteHovered val button = InlineIconButton(icon, hoverIcon, tooltip = CommonBundle.message("button.delete")) button.actionListener = ActionListener { if (MessageDialogBuilder.yesNo(GithubBundle.message("pull.request.review.comment.delete.dialog.title"), GithubBundle.message("pull.request.review.comment.delete.dialog.msg")).ask(button)) { delete() } } return button } fun createEditButton(paneHandle: GHEditableHtmlPaneHandle): JComponent { val icon = AllIcons.General.Inline_edit val hoverIcon = AllIcons.General.Inline_edit_hovered val button = InlineIconButton(icon, hoverIcon, tooltip = CommonBundle.message("button.edit")) button.actionListener = ActionListener { paneHandle.showAndFocusEditor() } return button } }
apache-2.0
ee66d0234398a2e92ce534475d9f8b5f
42.810811
140
0.762963
4.750733
false
false
false
false
smmribeiro/intellij-community
plugins/ml-local-models/java/src/com/intellij/java/ml/local/JavaFrequencyElementFeatureProvider.kt
12
2746
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.ml.local import com.intellij.codeInsight.completion.CompletionLocation import com.intellij.codeInsight.completion.ml.ContextFeatures import com.intellij.codeInsight.completion.ml.ElementFeatureProvider import com.intellij.codeInsight.completion.ml.MLFeatureValue import com.intellij.codeInsight.lookup.LookupElement import com.intellij.lang.java.JavaLanguage import com.intellij.ml.local.models.LocalModelsManager import com.intellij.ml.local.models.frequency.classes.ClassesFrequencyLocalModel import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod class JavaFrequencyElementFeatureProvider : ElementFeatureProvider { override fun getName(): String = "local" override fun calculateFeatures(element: LookupElement, location: CompletionLocation, contextFeatures: ContextFeatures): MutableMap<String, MLFeatureValue> { val features = mutableMapOf<String, MLFeatureValue>() val psi = element.psiElement val receiverClassName = contextFeatures.getUserData(JavaFrequencyContextFeatureProvider.RECEIVER_CLASS_NAME_KEY) val classFrequencies = contextFeatures.getUserData(JavaFrequencyContextFeatureProvider.RECEIVER_CLASS_FREQUENCIES_KEY) if (psi is PsiMethod && receiverClassName != null && classFrequencies != null) { psi.containingClass?.let { cls -> JavaLocalModelsUtil.getClassName(cls)?.let { className -> if (receiverClassName == className) { JavaLocalModelsUtil.getMethodName(psi)?.let { methodName -> val frequency = classFrequencies.getMethodFrequency(methodName) if (frequency > 0) { val totalUsages = classFrequencies.getTotalFrequency() features["absolute_method_frequency"] = MLFeatureValue.numerical(frequency) features["relative_method_frequency"] = MLFeatureValue.numerical(frequency.toDouble() / totalUsages) } } } } } } val classesModel = LocalModelsManager.getInstance(location.project).getModel<ClassesFrequencyLocalModel>(JavaLanguage.INSTANCE) if (psi is PsiClass && classesModel != null && classesModel.readyToUse()) { JavaLocalModelsUtil.getClassName(psi)?.let { className -> classesModel.getClass(className)?.let { features["absolute_class_frequency"] = MLFeatureValue.numerical(it) features["relative_class_frequency"] = MLFeatureValue.numerical(it.toDouble() / classesModel.totalClassesUsages()) } } } return features } }
apache-2.0
305b1f78e814055940fc19d23d31f721
51.826923
140
0.725783
5.038532
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/highlighting/PyRainbowVisitor.kt
3
5718
// 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.jetbrains.python.highlighting import com.intellij.codeInsight.daemon.RainbowVisitor import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.controlflow.ScopeOwner import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil import com.jetbrains.python.psi.* import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.TypeEvalContext class PyRainbowVisitor : RainbowVisitor() { object Holder { val IGNORED_NAMES = setOf(PyNames.NONE, PyNames.TRUE, PyNames.FALSE) val DEFAULT_HIGHLIGHTING_KEY = DefaultLanguageHighlighterColors.LOCAL_VARIABLE @JvmStatic val HIGHLIGHTING_KEYS: Set<TextAttributesKey> = setOf(PyHighlighter.PY_PARAMETER, DEFAULT_HIGHLIGHTING_KEY) } override fun suitableForFile(file: PsiFile): Boolean = file is PyFile override fun visit(element: PsiElement) { when (element) { is PyReferenceExpression -> processReference(element) is PyTargetExpression -> processTarget(element) is PyNamedParameter -> processNamedParameter(element) } } override fun clone(): PyRainbowVisitor = PyRainbowVisitor() private fun processReference(referenceExpression: PyReferenceExpression) { val context = getReferenceContext(referenceExpression, mutableSetOf()) ?: return val name = updateNameIfGlobal(context, referenceExpression.name) ?: return addInfo(context, referenceExpression, name) } private fun processTarget(targetExpression: PyTargetExpression) { val context = getTargetContext(targetExpression) ?: return val name = updateNameIfGlobal(context, targetExpression.name) ?: return addInfo(context, targetExpression, name) } private fun processNamedParameter(namedParameter: PyNamedParameter) { val context = getNamedParameterContext(namedParameter) ?: return val name = namedParameter.name ?: return val element = namedParameter.nameIdentifier ?: return addInfo(context, element, name, PyHighlighter.PY_PARAMETER) } private fun getReferenceContext(referenceExpression: PyReferenceExpression, visitedReferenceExpressions: MutableSet<PyReferenceExpression>): PsiElement? { if (referenceExpression.isQualified || referenceExpression.name in Holder.IGNORED_NAMES) return null val resolved = referenceExpression.reference.resolve() return when (resolved) { is PyTargetExpression -> getTargetContext(resolved) is PyNamedParameter -> getNamedParameterContext(resolved) is PyReferenceExpression -> { if (!visitedReferenceExpressions.add(resolved)) return getLeastCommonScope(visitedReferenceExpressions) return if (resolved.parent is PyAugAssignmentStatement) getReferenceContext(resolved, visitedReferenceExpressions) else null } else -> null } } private fun getTargetContext(targetExpression: PyTargetExpression): PsiElement? { if (targetExpression.isQualified || targetExpression.name in Holder.IGNORED_NAMES) return null val parent = targetExpression.parent if (parent is PyGlobalStatement) return targetExpression.containingFile if (parent is PyNonlocalStatement) { val outerResolved = targetExpression.reference.resolve() return if (outerResolved is PyTargetExpression) getTargetContext(outerResolved) else null } val context = TypeEvalContext.codeInsightFallback(targetExpression.project) val resolveResults = targetExpression.getReference(PyResolveContext.defaultContext(context)).multiResolve(false) val resolvesToGlobal = resolveResults .asSequence() .map { it.element } .any { it is PyTargetExpression && it.parent is PyGlobalStatement } if (resolvesToGlobal) return targetExpression.containingFile val resolvedNonLocal = resolveResults .asSequence() .map { it.element } .filterIsInstance<PyTargetExpression>() .find { it.parent is PyNonlocalStatement } if (resolvedNonLocal != null) return getTargetContext(resolvedNonLocal) val scopeOwner = ScopeUtil.getScopeOwner(targetExpression) return if (scopeOwner is PyFile || scopeOwner is PyFunction || scopeOwner is PyLambdaExpression) scopeOwner else null } private fun getNamedParameterContext(namedParameter: PyNamedParameter): PsiElement? { if (namedParameter.isSelf) return null val scopeOwner = ScopeUtil.getScopeOwner(namedParameter) return if (scopeOwner is PyLambdaExpression || scopeOwner is PyFunction) scopeOwner else null } private fun updateNameIfGlobal(context: PsiElement, name: String?) = if (context is PyFile && name != null) "global_$name" else name private fun addInfo(context: PsiElement, rainbowElement: PsiElement, name: String, key: TextAttributesKey? = Holder.DEFAULT_HIGHLIGHTING_KEY) { addInfo(getInfo(context, rainbowElement, name, key)) } private fun getLeastCommonScope(elements: Collection<PsiElement>): ScopeOwner? { var result: ScopeOwner? = null elements.forEach { val currentScopeOwner = ScopeUtil.getScopeOwner(it) if (result == null) { result = currentScopeOwner } else if (result != currentScopeOwner && currentScopeOwner != null && PsiTreeUtil.isAncestor(result, currentScopeOwner, true)) { result = currentScopeOwner } } return result } }
apache-2.0
f2f4bb273d27f96e4fc280937c9cc031
41.355556
145
0.76198
5.137466
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GuidelinesActivity.kt
1
1922
package com.habitrpg.android.habitica.ui.activities import android.os.Bundle import android.view.MenuItem import android.widget.TextView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.ui.helpers.setMarkdown import kotlinx.android.synthetic.main.activity_prefs.* import okhttp3.* import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader class GuidelinesActivity: BaseActivity() { override fun getLayoutResId(): Int = R.layout.activity_guidelines override fun injectActivity(component: UserComponent?) { /* no-on */ } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupToolbar(toolbar) val client = OkHttpClient() val request = Request.Builder().url("https://s3.amazonaws.com/habitica-assets/mobileApp/endpoint/community-guidelines.md").build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val `in` = response.body()?.byteStream() val reader = BufferedReader(InputStreamReader(`in`)) val text = reader.readText() response.body()?.close() findViewById<TextView>(R.id.text_view).post { findViewById<TextView>(R.id.text_view).setMarkdown(text) } } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } }
gpl-3.0
2c09f1e1ff882b1e209f1e14dfb03374
33.963636
138
0.644641
4.793017
false
false
false
false
ohmae/VoiceMessageBoard
app/src/main/java/net/mm2d/android/vmb/font/FontUtils.kt
1
1352
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.vmb.font import android.graphics.Typeface import android.widget.TextView import net.mm2d.android.vmb.R import net.mm2d.android.vmb.settings.Settings import net.mm2d.android.vmb.util.Toaster import net.mm2d.log.Logger import java.io.File /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object FontUtils { fun isValidFontFile(file: File): Boolean = try { Typeface.createFromFile(file) true } catch (e: Exception) { Logger.w(e) false } fun setFont(textView: TextView, settings: Settings) { if (settings.fontPathToUse.isEmpty()) { textView.typeface = Typeface.DEFAULT return } try { val typeFace = Typeface.createFromFile(settings.fontPath) if (typeFace != null) { textView.setTypeface(typeFace, Typeface.NORMAL) return } } catch (e: Exception) { } settings.useFont = false settings.fontPath = "" textView.typeface = Typeface.DEFAULT Toaster.show(textView.context, R.string.toast_failed_to_load_font) } }
mit
6f5f05585855c5ea42096499e1a11973
26.265306
74
0.615269
3.929412
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/platform/GraphicsLayerTest.kt
3
10890
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.test.InternalTestApi import androidx.compose.ui.test.junit4.DesktopScreenshotTestRule import androidx.compose.ui.unit.dp import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @OptIn(InternalTestApi::class) class GraphicsLayerTest { @get:Rule val screenshotRule = DesktopScreenshotTestRule("compose/ui/ui-desktop/platform") @Test fun scale() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer( scaleX = 2f, scaleY = 0.5f, transformOrigin = TransformOrigin(0f, 0f) ) .requiredSize(10f.dp, 10f.dp).background(Color.Red) ) Box( Modifier .graphicsLayer( translationX = 10f, translationY = 20f, scaleX = 2f, scaleY = 0.5f ) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) } screenshotRule.snap(window.surface) } @Test fun rotationZ() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer( translationX = 10f, rotationZ = 90f, scaleX = 2f, scaleY = 0.5f, transformOrigin = TransformOrigin(0f, 0f) ) .requiredSize(10f.dp, 10f.dp).background(Color.Red) ) Box( Modifier .graphicsLayer( translationX = 10f, translationY = 20f, rotationZ = 45f ) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) } screenshotRule.snap(window.surface) } @Test fun rotationX() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer(rotationX = 45f) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) Box( Modifier .graphicsLayer( translationX = 20f, transformOrigin = TransformOrigin(0f, 0f), rotationX = 45f ) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) } screenshotRule.snap(window.surface) } @Test fun rotationY() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer(rotationY = 45f) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) Box( Modifier .graphicsLayer( translationX = 20f, transformOrigin = TransformOrigin(0f, 0f), rotationY = 45f ) .requiredSize(10f.dp, 10f.dp).background(Color.Blue) ) } screenshotRule.snap(window.surface) } @Test fun `nested layer transformations`() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer(rotationZ = 45f, translationX = 10f) .requiredSize(20f.dp, 20f.dp).background(Color.Green) ) { Box( Modifier .graphicsLayer(rotationZ = 45f) .requiredSize(20f.dp, 20f.dp).background(Color.Blue) ) } } screenshotRule.snap(window.surface) } @Test fun clip() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer( translationX = 10f, translationY = 10f, transformOrigin = TransformOrigin(0f, 0f), clip = false ) .requiredSize(10f.dp, 10f.dp).background(Color.Red) ) { Box( Modifier .graphicsLayer( transformOrigin = TransformOrigin(0f, 0f), clip = false ) .requiredSize(20f.dp, 2f.dp) .background(Color.Blue) ) } Box( Modifier .graphicsLayer( translationX = 10f, translationY = 30f, transformOrigin = TransformOrigin(0f, 0f), clip = true ) .requiredSize(10f.dp, 10f.dp).background(Color.Red) ) { Box( Modifier .graphicsLayer( transformOrigin = TransformOrigin(0f, 0f), clip = false ) .requiredSize(20f.dp, 2f.dp) .background(Color.Blue) ) } Box( Modifier .graphicsLayer( translationX = 30f, translationY = 10f, transformOrigin = TransformOrigin(0f, 0f), clip = true, shape = RoundedCornerShape(5.dp) ) .requiredSize(10f.dp, 10f.dp).background(Color.Red) ) { Box( Modifier .graphicsLayer( transformOrigin = TransformOrigin(0f, 0f), clip = false ) .requiredSize(20f.dp, 2f.dp) .background(Color.Blue) ) } } screenshotRule.snap(window.surface) } @Test fun alpha() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .padding(start = 5.dp) .graphicsLayer( translationX = -5f, translationY = 5f, transformOrigin = TransformOrigin(0f, 0f), alpha = 0.5f ) .requiredSize(10f.dp, 10f.dp) .background(Color.Green) ) { // This box will be clipped (because if we use alpha, we draw into // intermediate buffer) Box( Modifier .requiredSize(30f.dp, 30f.dp) .background(Color.Blue) ) } Box( Modifier .padding(start = 15.dp) .graphicsLayer(alpha = 0.5f) .requiredSize(15f.dp, 15f.dp) .background(Color.Red) ) { Box( Modifier .graphicsLayer(alpha = 0.5f) .requiredSize(10f.dp, 10f.dp) .background(Color.Blue) ) } Box( Modifier .graphicsLayer( alpha = 0f ) .requiredSize(10f.dp, 10f.dp) .background(Color.Blue) ) } screenshotRule.snap(window.surface) } @Test fun elevation() { val window = TestComposeWindow(width = 40, height = 40) window.setContent { Box( Modifier .graphicsLayer(shadowElevation = 5f) .requiredSize(20f.dp, 20f.dp) ) Box( Modifier .graphicsLayer(translationX = 20f, shadowElevation = 5f) .requiredSize(20f.dp, 20f.dp) ) { Box( Modifier .requiredSize(20f.dp, 20f.dp) .background(Color.Blue) ) } Box( Modifier .graphicsLayer(translationY = 20f, alpha = 0.8f, shadowElevation = 5f) .requiredSize(20f.dp, 20f.dp) ) { Box( Modifier .requiredSize(20f.dp, 20f.dp) .background(Color.Red) ) } Box( Modifier .graphicsLayer( translationX = 20f, translationY = 20f, shadowElevation = 5f, alpha = 0.8f ) .requiredSize(20f.dp, 20f.dp) ) } screenshotRule.snap(window.surface) } }
apache-2.0
c1b16eeb5d56b60663f681ac6ffd79a9
32.204268
90
0.44169
5.383094
false
true
false
false
androidx/androidx
compose/animation/animation-graphics/src/commonMain/kotlin/androidx/compose/animation/graphics/vector/AnimatorAnimationSpecs.kt
3
5571
/* * 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.compose.animation.graphics.vector import androidx.compose.animation.core.AnimationVector import androidx.compose.animation.core.AnimationVector1D import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.AnimationVector3D import androidx.compose.animation.core.AnimationVector4D import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.TwoWayConverter import androidx.compose.animation.core.VectorizedFiniteAnimationSpec private const val MillisToNanos = 1_000_000L /** * Returns this [FiniteAnimationSpec] reversed. */ internal fun <T> FiniteAnimationSpec<T>.reversed(durationMillis: Int): FiniteAnimationSpec<T> { return ReversedSpec(this, durationMillis) } private class ReversedSpec<T>( private val spec: FiniteAnimationSpec<T>, private val durationMillis: Int ) : FiniteAnimationSpec<T> { override fun <V : AnimationVector> vectorize( converter: TwoWayConverter<T, V> ): VectorizedFiniteAnimationSpec<V> { return VectorizedReversedSpec(spec.vectorize(converter), durationMillis * MillisToNanos) } } private class VectorizedReversedSpec<V : AnimationVector>( private val animation: VectorizedFiniteAnimationSpec<V>, private val durationNanos: Long ) : VectorizedFiniteAnimationSpec<V> { override fun getValueFromNanos( playTimeNanos: Long, initialValue: V, targetValue: V, initialVelocity: V ): V { return animation.getValueFromNanos( durationNanos - playTimeNanos, targetValue, initialValue, initialVelocity ) } override fun getVelocityFromNanos( playTimeNanos: Long, initialValue: V, targetValue: V, initialVelocity: V ): V { return animation.getVelocityFromNanos( durationNanos - playTimeNanos, targetValue, initialValue, initialVelocity ).reversed() } override fun getDurationNanos(initialValue: V, targetValue: V, initialVelocity: V): Long { return durationNanos } } /** * Creates a [FiniteAnimationSpec] that combine and run multiple [specs] based on the start time * (in milliseconds) specified as the first half of the pairs. */ internal fun <T> combined( specs: List<Pair<Int, FiniteAnimationSpec<T>>> ): FiniteAnimationSpec<T> { return CombinedSpec(specs) } private class CombinedSpec<T>( private val specs: List<Pair<Int, FiniteAnimationSpec<T>>> ) : FiniteAnimationSpec<T> { override fun <V : AnimationVector> vectorize( converter: TwoWayConverter<T, V> ): VectorizedFiniteAnimationSpec<V> { return VectorizedCombinedSpec( specs.map { (timeMillis, spec) -> timeMillis * MillisToNanos to spec.vectorize(converter) } ) } } private class VectorizedCombinedSpec<V : AnimationVector>( private val animations: List<Pair<Long, VectorizedFiniteAnimationSpec<V>>> ) : VectorizedFiniteAnimationSpec<V> { private fun chooseAnimation(playTimeNanos: Long): Pair<Long, VectorizedFiniteAnimationSpec<V>> { return animations.lastOrNull { (timeNanos, _) -> timeNanos <= playTimeNanos } ?: animations.first() } override fun getValueFromNanos( playTimeNanos: Long, initialValue: V, targetValue: V, initialVelocity: V ): V { val (timeNanos, animation) = chooseAnimation(playTimeNanos) val internalPlayTimeNanos = playTimeNanos - timeNanos return animation.getValueFromNanos( internalPlayTimeNanos, initialValue, targetValue, initialVelocity ) } override fun getVelocityFromNanos( playTimeNanos: Long, initialValue: V, targetValue: V, initialVelocity: V ): V { val (timeNanos, animation) = chooseAnimation(playTimeNanos) return animation.getVelocityFromNanos( playTimeNanos - timeNanos, initialValue, targetValue, initialVelocity ) } override fun getDurationNanos(initialValue: V, targetValue: V, initialVelocity: V): Long { val (timeNanos, animation) = animations.last() return timeNanos + animation.getDurationNanos(initialValue, targetValue, initialVelocity) } } private fun <V : AnimationVector> V.reversed(): V { @Suppress("UNCHECKED_CAST") return when (this) { is AnimationVector1D -> AnimationVector1D(value * -1) as V is AnimationVector2D -> AnimationVector2D(v1 * -1, v2 * -1) as V is AnimationVector3D -> AnimationVector3D(v1 * -1, v2 * -1, v3 * -1) as V is AnimationVector4D -> AnimationVector4D(v1 * -1, v2 * -1, v3 * -1, v4 * -1) as V else -> throw RuntimeException("Unknown AnimationVector: $this") } }
apache-2.0
dd4522358c9862ebc07fc1fe6730bd65
32.359281
100
0.68336
4.773779
false
false
false
false
androidx/androidx
compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/settings/DecorFitsSystemWindowsSetting.kt
3
2680
/* * 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.compose.integration.demos.settings import android.content.Context import android.view.View import android.view.Window import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat.setDecorFitsSystemWindows import androidx.core.view.WindowInsetsCompat import androidx.preference.CheckBoxPreference /** * Setting that determines whether [setDecorFitsSystemWindows] is called with true or false for the * demo activity's window. */ internal object DecorFitsSystemWindowsSetting : DemoSetting<Boolean> { private const val Key = "decorFitsSystemWindows" private const val DefaultValue = true override fun createPreference(context: Context) = CheckBoxPreference(context).apply { title = "Decor fits system windows" key = Key summaryOff = "The framework will not fit the content view to the insets and will just pass through" + " the WindowInsetsCompat to the content view." summaryOn = "The framework will fit the content view to the insets. WindowInsets APIs " + "must be used to add necessary padding. Insets will be animated." setDefaultValue(DefaultValue) } @Composable fun asState() = preferenceAsState(Key) { getBoolean(Key, DefaultValue) } } /** * Sets the window's [decorFitsSystemWindow][setDecorFitsSystemWindows] property to * [decorFitsSystemWindows] as long as this function is composed. */ @Composable internal fun DecorFitsSystemWindowsEffect( decorFitsSystemWindows: Boolean, view: View, window: Window ) { DisposableEffect(decorFitsSystemWindows, window) { setDecorFitsSystemWindows(window, decorFitsSystemWindows) ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets -> if (!decorFitsSystemWindows) WindowInsetsCompat.CONSUMED else insets } onDispose { setDecorFitsSystemWindows(window, true) } } }
apache-2.0
38b6fd33f2ced3809ea28d35a92bfa1d
35.22973
100
0.732836
4.972171
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/live-templates-k1/src/org/jetbrains/kotlin/idea/liveTemplates/k1/macro/Fe10AbstractKotlinVariableMacro.kt
4
4400
// 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.liveTemplates.k1.macro import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.template.Expression import com.intellij.codeInsight.template.ExpressionContext import com.intellij.codeInsight.template.Result import com.intellij.codeInsight.template.TextResult import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.completion.BasicLookupElementFactory import org.jetbrains.kotlin.idea.completion.InsertHandlerProvider import org.jetbrains.kotlin.idea.core.NotPropertiesService import org.jetbrains.kotlin.idea.core.isVisible import org.jetbrains.kotlin.idea.liveTemplates.macro.KotlinMacro import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter abstract class Fe10AbstractKotlinVariableMacro<State> : KotlinMacro() { private fun getVariables(params: Array<Expression>, context: ExpressionContext): Collection<VariableDescriptor> { if (params.isNotEmpty()) { return emptyList() } val project = context.project val psiDocumentManager = PsiDocumentManager.getInstance(project) psiDocumentManager.commitAllDocuments() val document = context.editor?.document ?: return emptyList() val psiFile = psiDocumentManager.getPsiFile(document) as? KtFile ?: return emptyList() val contextElement = psiFile.findElementAt(context.startOffset)?.getNonStrictParentOfType<KtElement>() ?: return emptyList() val resolutionFacade = psiFile.getResolutionFacade() val bindingContext = resolutionFacade.analyze(contextElement, BodyResolveMode.PARTIAL_FOR_COMPLETION) fun isVisible(descriptor: DeclarationDescriptor): Boolean { return descriptor !is DeclarationDescriptorWithVisibility || descriptor.isVisible( contextElement, null, bindingContext, resolutionFacade ) } val state = initState(contextElement, bindingContext) val helper = ReferenceVariantsHelper( bindingContext, resolutionFacade, resolutionFacade.moduleDescriptor, ::isVisible, NotPropertiesService.getNotProperties(contextElement) ) return helper .getReferenceVariants(contextElement, CallTypeAndReceiver.DEFAULT, DescriptorKindFilter.VARIABLES, { true }) .map { it as VariableDescriptor } .filter { isSuitable(it, project, state) } } protected abstract fun initState(contextElement: KtElement, bindingContext: BindingContext): State protected abstract fun isSuitable( variableDescriptor: VariableDescriptor, project: Project, state: State ): Boolean override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? { val vars = getVariables(params, context) if (vars.isEmpty()) return null return vars.firstOrNull()?.let { TextResult(it.name.render()) } } override fun calculateLookupItems(params: Array<Expression>, context: ExpressionContext): Array<LookupElement>? { val vars = getVariables(params, context) if (vars.size < 2) return null val lookupElementFactory = BasicLookupElementFactory(context.project, InsertHandlerProvider(CallType.DEFAULT, editor = context.editor!!) { emptyList() }) return vars.map { lookupElementFactory.createLookupElement(it) }.toTypedArray() } }
apache-2.0
043ed6fc1490cdb0b73a7ab6b665e8b3
44.833333
161
0.754091
5.346294
false
false
false
false
GunoH/intellij-community
platform/execution-impl/src/com/intellij/execution/target/TargetEnvironmentDetailsConfigurable.kt
4
3034
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.target import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.NamedConfigurable import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.panels.VerticalLayout import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.util.function.Supplier import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel internal class TargetEnvironmentDetailsConfigurable( private val project: Project, private val config: TargetEnvironmentConfiguration, defaultLanguage: LanguageRuntimeType<*>?, treeUpdate: Runnable ) : NamedConfigurable<TargetEnvironmentConfiguration>(true, treeUpdate) { private val targetConfigurable: Configurable = config.getTargetType() .createConfigurable(project, config, defaultLanguage, this) private var languagesPanel: TargetEnvironmentLanguagesPanel? = null override fun getBannerSlogan(): String = config.displayName override fun getIcon(expanded: Boolean): Icon = config.getTargetType().icon override fun isModified(): Boolean = targetConfigurable.isModified || languagesPanel?.isModified == true override fun getDisplayName(): String = config.displayName override fun apply() { targetConfigurable.apply() languagesPanel?.applyAll() } override fun reset() { targetConfigurable.reset() languagesPanel?.reset() } override fun setDisplayName(name: String) { config.displayName = name } override fun disposeUIResources() { super.disposeUIResources() targetConfigurable.disposeUIResources() languagesPanel?.disposeUIResources() } override fun getEditableObject() = config override fun createOptionsPanel(): JComponent { val panel = JPanel(VerticalLayout(UIUtil.DEFAULT_VGAP)) panel.border = JBUI.Borders.empty(0, 10, 10, 10) panel.add(targetConfigurable.createComponent() ?: throw IllegalStateException()) val targetSupplier: Supplier<TargetEnvironmentConfiguration> if (targetConfigurable is BrowsableTargetEnvironmentType.ConfigurableCurrentConfigurationProvider) targetSupplier = Supplier<TargetEnvironmentConfiguration>(targetConfigurable::getCurrentConfiguration) else { targetSupplier = Supplier<TargetEnvironmentConfiguration> { config } } languagesPanel = TargetEnvironmentLanguagesPanel(project, config.getTargetType(), targetSupplier, config.runtimes) { forceRefreshUI() } panel.add(languagesPanel!!.component) return JBScrollPane(panel).also { it.border = JBUI.Borders.empty() } } override fun resetOptionsPanel() { languagesPanel?.disposeUIResources() languagesPanel = null super.resetOptionsPanel() } private fun forceRefreshUI() { createComponent()?.let { it.revalidate() it.repaint() } } }
apache-2.0
004861f0f0092617be8331e603cf41a6
31.287234
140
0.765985
5.107744
false
true
false
false
chemouna/Nearby
app/src/main/kotlin/com/mounacheikhna/nearby/ui/DividerItemDecoration.kt
1
3478
package com.mounacheikhna.nearby.ui import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v4.view.ViewCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View /** * A divider for items in a {@link RecyclerView}. */ class DividerItemDecoration(context: Context, orientation: Int, paddingStart: Float, private val rtl: Boolean) : RecyclerView.ItemDecoration() { private val divider: Drawable private var orientation: Int = 0 private var paddingStart: Float = 0.toFloat() init { val a = context.obtainStyledAttributes(ATTRS) divider = a.getDrawable(0) a.recycle() setOrientation(orientation) setPaddingStart(paddingStart) } fun setOrientation(orientation: Int) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw IllegalArgumentException("invalid orientation") } this.orientation = orientation } fun setPaddingStart(paddingStart: Float) { if (paddingStart < 0) { throw IllegalArgumentException("paddingStart < 0") } this.paddingStart = paddingStart } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { if (orientation == VERTICAL_LIST) { drawVertical(c, parent) } else { drawHorizontal(c, parent) } } fun drawVertical(c: Canvas, parent: RecyclerView) { val left = (parent.paddingLeft + (if (rtl) 0 else paddingStart.toInt())) val right = (parent.width - parent.paddingRight + (if (rtl) paddingStart.toInt() else 0)).toInt() val childCount = parent.childCount for (i in 0..childCount - 1) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin + Math.round( ViewCompat.getTranslationY(child)) val bottom = top + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } fun drawHorizontal(c: Canvas, parent: RecyclerView) { val top = parent.paddingTop val bottom = parent.height - parent.paddingBottom val childCount = parent.childCount for (i in 0..childCount - 1) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val left = child.right + params.rightMargin + Math.round( ViewCompat.getTranslationX(child)) val right = left + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { if (orientation == VERTICAL_LIST) { outRect.set(0, 0, 0, divider.intrinsicHeight) } else { outRect.set(0, 0, divider.intrinsicWidth, 0) } } companion object { private val ATTRS = intArrayOf(android.R.attr.listDivider) val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL val VERTICAL_LIST = LinearLayoutManager.VERTICAL } }
apache-2.0
0c7ac1c2d273b50e3f3b5df7ef223fe5
34.489796
105
0.635135
4.797241
false
false
false
false
jwren/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitBeforeAfterInspection.kt
1
3653
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInsight.AnnotationUtil import com.intellij.codeInspection.* import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.createModifierActions import com.intellij.lang.jvm.actions.modifierRequest import com.intellij.psi.PsiModifier.ModifierConstant import com.intellij.psi.PsiType import org.jetbrains.uast.UMethod class JUnitBeforeAfterInspection : AbstractBaseUastLocalInspectionTool() { override fun checkMethod(method: UMethod, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor> { val javaMethod = method.javaPsi val annotation = ANNOTATIONS.firstOrNull { AnnotationUtil.isAnnotated(javaMethod, it, AnnotationUtil.CHECK_HIERARCHY) } ?: return emptyArray() val returnType = method.returnType ?: return emptyArray() val parameterList = method.uastParameters if ((parameterList.isNotEmpty() || returnType != PsiType.VOID || javaMethod.hasModifier(JvmModifier.STATIC)) || (isJUnit4(annotation) && !javaMethod.hasModifier(JvmModifier.PUBLIC)) ) return makeStaticVoidFix(method, manager, isOnTheFly, annotation, if (isJUnit4(annotation)) JvmModifier.PUBLIC else null) if (isJUnit5(annotation) && javaMethod.hasModifier(JvmModifier.PRIVATE)) { return removePrivateModifierFix(method, manager, isOnTheFly, annotation) } return emptyArray() } private fun makeStaticVoidFix( method: UMethod, manager: InspectionManager, isOnTheFly: Boolean, annotation: String, @ModifierConstant modifier: JvmModifier? // null means unchanged ): Array<ProblemDescriptor> { val message = JvmAnalysisBundle.message("jvm.inspections.before.after.descriptor", annotation) val fixes = arrayOf(MakeNoArgVoidFix(method.name, false, modifier)) val place = method.uastAnchor?.sourcePsi ?: return emptyArray() val problemDescriptor = manager.createProblemDescriptor( place, message, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) return arrayOf(problemDescriptor) } private fun removePrivateModifierFix( method: UMethod, manager: InspectionManager, isOnTheFly: Boolean, annotation: String, ): Array<ProblemDescriptor> { val message = JvmAnalysisBundle.message("jvm.inspections.before.after.descriptor", annotation) val containingFile = method.sourcePsi?.containingFile ?: return emptyArray() val fixes = IntentionWrapper.wrapToQuickFixes( createModifierActions(method, modifierRequest(JvmModifier.PRIVATE, false)), containingFile ).toTypedArray() val place = method.uastAnchor?.sourcePsi ?: return emptyArray() val problemDescriptor = manager.createProblemDescriptor( place, message, isOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) return arrayOf(problemDescriptor) } private fun isJUnit4(annotation: String) = annotation.endsWith(BEFORE) || annotation.endsWith(AFTER) private fun isJUnit5(annotation: String) = annotation.endsWith(BEFORE_EACH) || annotation.endsWith(AFTER_EACH) companion object { // JUnit 4 classes private const val BEFORE = "org.junit.Before" private const val AFTER = "org.junit.After" // JUnit 5 classes private const val BEFORE_EACH = "org.junit.jupiter.api.BeforeEach" private const val AFTER_EACH = "org.junit.jupiter.api.AfterEach" private val ANNOTATIONS = arrayOf(BEFORE, AFTER, BEFORE_EACH, AFTER_EACH) } }
apache-2.0
680ecab6a8e02a26578b0bff97cb2d7f
44.675
127
0.763482
4.781414
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/getSourceModuleDependencies.kt
1
4960
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.project import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import org.jetbrains.kotlin.idea.configuration.BuildSystemType import org.jetbrains.kotlin.idea.configuration.getBuildSystemType import org.jetbrains.kotlin.idea.project.isHMPPEnabled import org.jetbrains.kotlin.platform.TargetPlatform fun Module.getSourceModuleDependencies( forProduction: Boolean, platform: TargetPlatform, includeTransitiveDependencies: Boolean = true, ): List<IdeaModuleInfo> { // Use StringBuilder so that all lines are written into the log atomically (otherwise // logs of call to getIdeaModelDependencies for several different modules interleave, leading // to unreadable mess) val debugString: StringBuilder? = if (LOG.isDebugEnabled) StringBuilder() else null debugString?.appendLine("Building idea model dependencies for module ${this}, platform=${platform}, forProduction=$forProduction") val allIdeaModuleInfoDependencies = resolveDependenciesFromOrderEntries(debugString, forProduction, includeTransitiveDependencies) val supportedModuleInfoDependencies = filterSourceModuleDependencies(debugString, platform, allIdeaModuleInfoDependencies) LOG.debug(debugString?.toString()) return supportedModuleInfoDependencies.toList() } private fun Module.resolveDependenciesFromOrderEntries( debugString: StringBuilder?, forProduction: Boolean, includeTransitiveDependencies: Boolean, ): Set<IdeaModuleInfo> { //NOTE: lib dependencies can be processed several times during recursive traversal val result = LinkedHashSet<IdeaModuleInfo>() val dependencyEnumerator = ModuleRootManager.getInstance(this).orderEntries().compileOnly() if (includeTransitiveDependencies) { dependencyEnumerator.recursively().exportedOnly() } if (forProduction && getBuildSystemType() == BuildSystemType.JPS) { dependencyEnumerator.productionOnly() } debugString?.append(" IDEA dependencies: [") dependencyEnumerator.forEach { orderEntry -> debugString?.append("${orderEntry.presentableName} ") if (orderEntry.acceptAsDependency(forProduction)) { result.addAll(orderEntryToModuleInfo(project, orderEntry, forProduction)) debugString?.append("OK; ") } else { debugString?.append("SKIP; ") } true } debugString?.appendLine("]") return result.toSet() } private fun Module.filterSourceModuleDependencies( debugString: StringBuilder?, platform: TargetPlatform, dependencies: Set<IdeaModuleInfo> ): Set<IdeaModuleInfo> { val dependencyFilter = if (isHMPPEnabled) HmppSourceModuleDependencyFilter(platform) else NonHmppSourceModuleDependenciesFilter(platform) val supportedDependencies = dependencies.filter { dependency -> dependencyFilter.isSupportedDependency(dependency) }.toSet() debugString?.appendLine( " Corrected result (Supported dependencies): ${ supportedDependencies.joinToString( prefix = "[", postfix = "]", separator = ";" ) { it.displayedName } }" ) return supportedDependencies } private fun OrderEntry.acceptAsDependency(forProduction: Boolean): Boolean { return this !is ExportableOrderEntry || !forProduction // this is needed for Maven/Gradle projects with "production-on-test" dependency || this is ModuleOrderEntry && isProductionOnTestDependency || scope.isForProductionCompile } private fun orderEntryToModuleInfo(project: Project, orderEntry: OrderEntry, forProduction: Boolean): List<IdeaModuleInfo> { fun Module.toInfos() = correspondingModuleInfos().filter { !forProduction || it is ModuleProductionSourceInfo } if (!orderEntry.isValid) return emptyList() return when (orderEntry) { is ModuleSourceOrderEntry -> { orderEntry.getOwnerModule().toInfos() } is ModuleOrderEntry -> { val module = orderEntry.module ?: return emptyList() if (forProduction && orderEntry.isProductionOnTestDependency) { listOfNotNull(module.testSourceInfo()) } else { module.toInfos() } } is LibraryOrderEntry -> { val library = orderEntry.library ?: return listOf() createLibraryInfo(project, library) } is JdkOrderEntry -> { val sdk = orderEntry.jdk ?: return listOf() listOfNotNull(SdkInfo(project, sdk)) } else -> { throw IllegalStateException("Unexpected order entry $orderEntry") } } }
apache-2.0
c03a5e0581f6c371d7e8911d28ad1808
39.655738
158
0.706452
5.504994
false
false
false
false
smmribeiro/intellij-community
platform/core-api/src/com/intellij/codeWithMe/ClientId.kt
1
10242
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeWithMe import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.trace import com.intellij.openapi.util.Disposer import com.intellij.util.Processor import kotlinx.coroutines.ThreadContextElement import org.jetbrains.annotations.ApiStatus import java.util.concurrent.Callable import java.util.function.BiConsumer import java.util.function.Function import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext /** * ClientId is a global context class that is used to distinguish the originator of an action in multi-client systems * In such systems, each client has their own ClientId. Current process also can have its own ClientId, with this class providing methods to distinguish local actions from remote ones. * * It's up to the application to preserve and propagate the current value across background threads and asynchronous activities. */ data class ClientId(val value: String) { enum class AbsenceBehavior { /** * Return localId if ClientId is not set */ RETURN_LOCAL, /** * Throw an exception if ClientId is not set */ THROW } companion object { private val LOG = Logger.getInstance(ClientId::class.java) fun getClientIdLogger() = LOG /** * Default client id for local application */ val defaultLocalId: ClientId = ClientId("Host") /** * Specifies behavior for [ClientId.current] */ var AbsenceBehaviorValue: AbsenceBehavior = AbsenceBehavior.RETURN_LOCAL /** * Controls propagation behavior. When false, decorateRunnable does nothing. */ @JvmStatic var propagateAcrossThreads: Boolean = false /** * The ID considered local to this process. All other IDs (except for null) are considered remote */ @JvmStatic var localId: ClientId = defaultLocalId private set /** * True if and only if the current [ClientId] is local to this process */ @JvmStatic val isCurrentlyUnderLocalId: Boolean get() { val clientIdValue = getCachedService()?.clientIdValue return clientIdValue == null || clientIdValue == localId.value } /** * Gets the current [ClientId]. Subject to [AbsenceBehaviorValue] */ @JvmStatic val current: ClientId get() = when (AbsenceBehaviorValue) { AbsenceBehavior.RETURN_LOCAL -> currentOrNull ?: localId AbsenceBehavior.THROW -> currentOrNull ?: throw NullPointerException("ClientId not set") } @JvmStatic @ApiStatus.Internal // optimization method for avoiding allocating ClientId in the hot path fun getCurrentValue(): String { val service = getCachedService() return if (service == null) localId.value else service.clientIdValue ?: localId.value } /** * Gets the current [ClientId]. Can be null if none was set. */ @JvmStatic val currentOrNull: ClientId? get() = getCachedService()?.clientIdValue?.let(::ClientId) /** * Overrides the ID that is considered to be local to this process. Can be only invoked once. */ @JvmStatic fun overrideLocalId(newId: ClientId) { require(localId == defaultLocalId) localId = newId } /** * Returns true if and only if the given ID is considered to be local to this process */ @JvmStatic @Deprecated("Use ClientId.isLocal", ReplaceWith("clientId.isLocal", "com.intellij.codeWithMe.ClientId.Companion.isLocal")) fun isLocalId(clientId: ClientId?): Boolean { return clientId.isLocal } /** * Is true if and only if the given ID is considered to be local to this process */ @JvmStatic val ClientId?.isLocal: Boolean get() = this == null || this == localId /** * Returns true if the given ID is local or a client is still in the session. * Consider subscribing to a proper lifetime instead of this check. */ @JvmStatic @Deprecated("Use ClientId.isValid", ReplaceWith("clientId.isValid", "com.intellij.codeWithMe.ClientId.Companion.isValid")) fun isValidId(clientId: ClientId?): Boolean { return clientId.isValid } /** * Is true if the given ID is local or a client is still in the session. * Consider subscribing to a proper lifetime instead of this check */ @JvmStatic val ClientId?.isValid: Boolean get() = getCachedService()?.isValid(this) ?: true /** * Returns a disposable object associated with the given ID. * Consider using a lifetime that is usually passed along with the ID */ @JvmStatic fun ClientId?.toDisposable(): Disposable { return getCachedService()?.toDisposable(this) ?: Disposer.newDisposable() } /** * Invokes a runnable under the given [ClientId] */ @JvmStatic @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Consider using an overload that returns a AccessToken to follow java try-with-resources pattern") fun withClientId(clientId: ClientId?, action: Runnable): Unit = withClientId(clientId) { action.run() } /** * Computes a value under given [ClientId] */ @JvmStatic @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Consider using an overload that returns an AccessToken to follow java try-with-resources pattern") fun <T> withClientId(clientId: ClientId?, action: Callable<T>): T = withClientId(clientId) { action.call() } /** * Computes a value under given [ClientId] */ @JvmStatic inline fun <T> withClientId(clientId: ClientId?, action: () -> T): T { val service = ClientIdService.tryGetInstance() ?: return action() val newClientIdValue = if (!service.isValid(clientId)) { getClientIdLogger().trace { "Invalid ClientId $clientId replaced with null at ${Throwable().fillInStackTrace()}" } null } else { clientId?.value } val oldClientIdValue = service.clientIdValue try { service.clientIdValue = newClientIdValue return action() } finally { service.clientIdValue = oldClientIdValue } } class ClientIdAccessToken(val oldClientIdValue: String?) : AccessToken() { override fun finish() { getCachedService()?.clientIdValue = oldClientIdValue } } @JvmStatic fun withClientId(clientId: ClientId?): AccessToken { if (clientId == null) return AccessToken.EMPTY_ACCESS_TOKEN return withClientId(clientId.value) } @JvmStatic fun withClientId(clientIdValue: String): AccessToken { val service = getCachedService() val oldClientIdValue: String? oldClientIdValue = service?.clientIdValue if (service == null || clientIdValue == oldClientIdValue) return AccessToken.EMPTY_ACCESS_TOKEN val newClientIdValue = if (service.isValid(ClientId(clientIdValue))) clientIdValue else { LOG.trace { "Invalid ClientId $clientIdValue replaced with null at ${Throwable().fillInStackTrace()}" } null } service.clientIdValue = newClientIdValue return ClientIdAccessToken(oldClientIdValue) } private var service:ClientIdService? = null private fun getCachedService(): ClientIdService? { var cached = service if (cached != null) return cached cached = ClientIdService.tryGetInstance() if (cached != null) { service = cached } return cached } @JvmStatic fun <T> decorateFunction(action: () -> T): () -> T { if (propagateAcrossThreads) return action val currentId = currentOrNull return { withClientId(currentId) { return@withClientId action() } } } @JvmStatic fun decorateRunnable(runnable: Runnable): Runnable { if (!propagateAcrossThreads) { return runnable } val currentId = currentOrNull return Runnable { withClientId(currentId) { runnable.run() } } } @JvmStatic fun <T> decorateCallable(callable: Callable<T>): Callable<T> { if (!propagateAcrossThreads) return callable val currentId = currentOrNull return Callable { withClientId(currentId, callable) } } @JvmStatic fun <T, R> decorateFunction(function: Function<T, R>): Function<T, R> { if (!propagateAcrossThreads) return function val currentId = currentOrNull return Function { withClientId(currentId) { function.apply(it) } } } @JvmStatic fun <T, U> decorateBiConsumer(biConsumer: BiConsumer<T, U>): BiConsumer<T, U> { if (!propagateAcrossThreads) return biConsumer val currentId = currentOrNull return BiConsumer { t, u -> withClientId(currentId) { biConsumer.accept(t, u) } } } @JvmStatic fun <T> decorateProcessor(processor: Processor<T>): Processor<T> { if (!propagateAcrossThreads) return processor val currentId = currentOrNull return Processor { withClientId(currentId) { processor.process(it) } } } fun coroutineContext(): CoroutineContext = currentOrNull?.asContextElement() ?: EmptyCoroutineContext } } fun isForeignClientOnServer(): Boolean { return !ClientId.isCurrentlyUnderLocalId && ClientId.localId == ClientId.defaultLocalId } fun isOnGuest(): Boolean { return ClientId.localId != ClientId.defaultLocalId } fun ClientId.asContextElement(): CoroutineContext.Element = ClientIdElement(this) private object ClientIdElementKey : CoroutineContext.Key<ClientIdElement> private class ClientIdElement(private val clientId: ClientId) : ThreadContextElement<AccessToken> { override val key: CoroutineContext.Key<*> get() = ClientIdElementKey override fun updateThreadContext(context: CoroutineContext): AccessToken { return ClientId.withClientId(clientId) } override fun restoreThreadContext(context: CoroutineContext, oldState: AccessToken): Unit { oldState.finish() } }
apache-2.0
dac3225ae2d20f6cf6e17405624b3f51
32.361564
184
0.68717
4.976676
false
false
false
false
MediaArea/MediaInfo
Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/SubscribeActivity.kt
1
3211
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ package net.mediaarea.mediainfo import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import com.android.billingclient.api.SkuDetails import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingFlowParams import android.app.Activity import android.os.Bundle import android.view.Gravity import android.view.MenuItem import android.view.View import kotlinx.android.synthetic.main.activity_subscribe.* class SubscribeActivity : AppCompatActivity() { private lateinit var subscriptionManager: SubscriptionManager private lateinit var subscriptionDetails: SkuDetails private lateinit var lifetimeSubscriptionDetails: SkuDetails override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_subscribe) subscriptionManager = SubscriptionManager.getInstance(application) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) subscriptionManager.details.observe (this, Observer { subscriptionDetails = it subscribe_button.isEnabled = true subscribe_button.text = subscribe_button.text.toString() .replace("%PRICE%", subscriptionDetails.price) subscription_detail_text.visibility= View.VISIBLE subscription_detail_text.gravity=Gravity.CENTER_HORIZONTAL }) subscriptionManager.lifetimeDetails.observe (this, Observer { lifetimeSubscriptionDetails = it lifetime_subscribe_button.isEnabled = true lifetime_subscribe_button.text = lifetime_subscribe_button.text.toString() .replace("%PRICE%", lifetimeSubscriptionDetails.price) }) subscribe_button.setOnClickListener { if (::subscriptionDetails.isInitialized) { val request = BillingFlowParams.newBuilder() .setSkuDetails(subscriptionDetails) .build() if (subscriptionManager.launchBillingFlow(this, request) == BillingClient.BillingResponseCode.OK) { finish() } } } lifetime_subscribe_button.setOnClickListener { if (::lifetimeSubscriptionDetails.isInitialized) { val request = BillingFlowParams.newBuilder() .setSkuDetails(lifetimeSubscriptionDetails) .build() if (subscriptionManager.launchBillingFlow(this, request) == BillingClient.BillingResponseCode.OK) { setResult(Activity.RESULT_OK) finish() } } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { setResult(Activity.RESULT_CANCELED) finish() } return super.onOptionsItemSelected(item) } }
bsd-2-clause
1f21ec9159afc9bddbf36fc1af5ddc42
36.337209
115
0.668016
5.498288
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/ColorType.kt
1
2345
package ch.rmy.android.http_shortcuts.variables.types import android.content.Context import android.graphics.Color import ch.rmy.android.framework.extensions.showOrElse import ch.rmy.android.framework.extensions.toLocalizable import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository import ch.rmy.android.http_shortcuts.data.models.VariableModel import ch.rmy.android.http_shortcuts.utils.ActivityProvider import ch.rmy.android.http_shortcuts.utils.ColorPickerFactory import ch.rmy.android.http_shortcuts.utils.ColorUtil.colorIntToHexString import ch.rmy.android.http_shortcuts.utils.ColorUtil.hexStringToColorInt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import javax.inject.Inject import kotlin.coroutines.resume class ColorType : BaseVariableType() { @Inject lateinit var variablesRepository: VariableRepository @Inject lateinit var activityProvider: ActivityProvider @Inject lateinit var colorPickerFactory: ColorPickerFactory override fun inject(applicationComponent: ApplicationComponent) { applicationComponent.inject(this) } override suspend fun resolveValue(context: Context, variable: VariableModel): String { val value = withContext(Dispatchers.Main) { suspendCancellableCoroutine<String> { continuation -> colorPickerFactory.createColorPicker( onColorPicked = { color -> continuation.resume(color.colorIntToHexString()) }, onDismissed = { continuation.cancel() }, title = variable.title.toLocalizable(), initialColor = getInitialColor(variable), ) .showOrElse { continuation.cancel() } } } if (variable.rememberValue) { variablesRepository.setVariableValue(variable.id, value) } return value } private fun getInitialColor(variable: VariableModel): Int = variable.takeIf { it.rememberValue }?.value?.hexStringToColorInt() ?: Color.BLACK }
mit
52a36fad59a2b49f8cab557714feca46
36.822581
90
0.689126
5.281532
false
false
false
false
juzraai/ted-xml-model
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/coded/RefOjs.kt
1
483
package hu.juzraai.ted.xml.model.tedexport.coded import hu.juzraai.ted.xml.model.tedexport.coded.refojs.NoOj import org.simpleframework.xml.Element import org.simpleframework.xml.Root /** * Model of REF_OJS element. * * @author Zsolt Jurányi */ @Root(name = "REF_OJS") data class RefOjs( @field:Element(name = "COLL_OJ") var collOj: String = "", @field:Element(name = "NO_OJ") var noOj: NoOj = NoOj(), @field:Element(name = "DATE_PUB") var datePub: String = "" )
apache-2.0
3e8c79c701926cce6030ded5023806e7
20.954545
59
0.692946
2.648352
false
false
false
false
sksamuel/ktest
kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/date/matchers.kt
1
94291
package io.kotest.matchers.date import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNot import io.kotest.matchers.shouldNotBe import java.time.DayOfWeek import java.time.LocalDate import java.time.LocalDateTime import java.time.Month import java.time.OffsetDateTime import java.time.Period import java.time.ZonedDateTime import java.time.temporal.TemporalAmount /** * Asserts that this year is the same as [date]'s year * * Verifies that this year is the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 has the same year as 10/03/1998, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldNotHaveSameYearAs] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 10) * * firstDate shouldHaveSameYearAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(2018, 2, 9) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998 ``` */ infix fun LocalDate.shouldHaveSameYearAs(date: LocalDate) = this should haveSameYear(date) /** * Asserts that this year is NOT the same as [date]'s year * * Verifies that this year isn't the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 doesn't have the same year as 09/02/2018, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldHaveSameYearAs] * * ``` * val firstDate = LocalDate.of(2018, 2, 9) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 10) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference * ``` */ infix fun LocalDate.shouldNotHaveSameYearAs(date: LocalDate) = this shouldNot haveSameYear(date) /** * Matcher that compares years of LocalDates * * Verifies that two dates have exactly the same year, ignoring any other fields. * For example, 09/02/1998 has the same year as 10/03/1998, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 10) * * firstDate should haveSameYear(secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 2, 9) * * firstDate shouldNot haveSameYear(secondDate) // Assertion passes * ``` * * @see [LocalDate.shouldHaveSameYearAs] * @see [LocalDate.shouldNotHaveSameYearAs] */ fun haveSameYear(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult = MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}") } /** * Asserts that this year is the same as [date]'s year * * Verifies that this year is the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same year as 10/03/1998 11:30:30, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldNotHaveSameYearAs] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30) * * firstDate shouldHaveSameYearAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * * firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998 * ``` */ infix fun LocalDateTime.shouldHaveSameYearAs(date: LocalDateTime) = this should haveSameYear(date) /** * Asserts that this year is NOT the same as [date]'s year * * Verifies that this year isn't the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 doesn't have the same year as 09/02/2018 10:00:00, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldHaveSameYearAs] * * ``` * val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 10, 1, 30, 30) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference * ``` */ infix fun LocalDateTime.shouldNotHaveSameYearAs(date: LocalDateTime) = this shouldNot haveSameYear(date) /** * Matcher that compares years of LocalDateTimes * * Verifies that two DateTimes have exactly the same year, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same year as 10/03/1998 11:30:30, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30) * * firstDate should haveSameYear(secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0) * * firstDate shouldNot haveSameYear(secondDate) // Assertion passes * ``` * * @see [LocalDateTime.shouldHaveSameYearAs] * @see [LocalDateTime.shouldNotHaveSameYearAs] */ fun haveSameYear(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult = MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}") } /** * Asserts that this year is the same as [date]'s year * * Verifies that this year is the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same year as 10/03/1998 11:30:30 -05:00 America/Chicago, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldNotHaveSameYearAs] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldHaveSameYearAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998 * ``` */ infix fun ZonedDateTime.shouldHaveSameYearAs(date: ZonedDateTime) = this should haveSameYear(date) /** * Asserts that this year is NOT the same as [date]'s year * * Verifies that this year isn't the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same year as 09/02/2018 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldHaveSameYearAs] * * ``` * val firstDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 19, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 10, 1, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference * ``` */ infix fun ZonedDateTime.shouldNotHaveSameYearAs(date: ZonedDateTime) = this shouldNot haveSameYear(date) /** * Matcher that compares years of ZonedDateTimes * * Verifies that two ZonedDateTimes have exactly the same year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same year as 10/03/1998 11:30:30 -05:00 America/Chicago, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate should haveSameYear(secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNot haveSameYear(secondDate) // Assertion passes * ``` * * @see [ZonedDateTime.shouldHaveSameYearAs] * @see [ZonedDateTime.shouldNotHaveSameYearAs] */ fun haveSameYear(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}") } /** * Asserts that this year is the same as [date]'s year * * Verifies that this year is the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the same year as 10/03/1998 11:30:30 -05:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldNotHaveSameYearAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldHaveSameYearAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldHaveSameYearAs secondDate // Assertion fails, 2018 != 1998 * ``` */ infix fun OffsetDateTime.shouldHaveSameYearAs(date: OffsetDateTime) = this should haveSameYear(date) /** * Asserts that this year is NOT the same as [date]'s year * * Verifies that this year isn't the same as [date]'s year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 doesn't have the same year as 09/02/2018 10:00:00 -03:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldHaveSameYearAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1999, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * firstDate shouldNotHaveSameYearAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 10, 11, 30, 30, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998 and we expected a difference * * ``` */ infix fun OffsetDateTime.shouldNotHaveSameYearAs(date: OffsetDateTime) = this shouldNot haveSameYear(date) /** * Matcher that compares years of OffsetDateTimes * * Verifies that two ZonedDateTimes have exactly the same year, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the same year as 10/03/1998 11:30:30 -05:00, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = OffsetDateTime.of(2018, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 19, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 10, 1, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldNotHaveSameYearAs secondDate // Assertion fails, 1998 == 1998, and we expected a difference * ``` * * @see [OffsetDateTime.shouldHaveSameYearAs] * @see [OffsetDateTime.shouldNotHaveSameYearAs] */ fun haveSameYear(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult = MatcherResult(value.year == date.year, "$value should have year ${date.year}", "$value should not have year ${date.year}") } /** * Asserts that this month is the same as [date]'s month * * Verifies that month year is the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 has the same month as 10/02/2018, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldNotHaveSameMonthAs] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 10) * * firstDate should haveSameYear(secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 2, 9) * * firstDate shouldNot haveSameYear(secondDate) // Assertion passes * ``` */ infix fun LocalDate.shouldHaveSameMonthAs(date: LocalDate) = this should haveSameMonth(date) /** * Asserts that this month is NOT the same as [date]'s month * * Verifies that this month isn't the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 doesn't have the same month as 09/03/1998, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldHaveSameMonthAs] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 2, 10) * * firstDate shouldHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 9) * * firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3 * ``` */ infix fun LocalDate.shouldNotHaveSameMonthAs(date: LocalDate) = this shouldNot haveSameMonth(date) /** * Matcher that compares months of LocalDates * * Verifies that two dates have exactly the same month, ignoring any other fields. * For example, 09/02/1998 has the same month as 10/02/2018, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 3, 9) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 2, 10) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference * ``` * * @see [LocalDate.shouldHaveSameMonthAs] * @see [LocalDate.shouldNotHaveSameMonthAs] */ fun haveSameMonth(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult = MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}") } /** * Asserts that this month is the same as [date]'s month * * Verifies that this month is the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same month as 10/02/2018 11:30:30, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldNotHaveSameMonthAs] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(2018, 2, 10, 10, 0, 0) * * firstDate should haveSameMonth(secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 9, 10, 0, 0) * * firstDate shouldNot haveSameMonth(secondDate) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveSameMonthAs(date: LocalDateTime) = this should haveSameMonth(date) /** * Asserts that this month is NOT the same as [date]'s month * * Verifies that this month isn't the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 doesn't have the same month as 09/03/1998 10:00:00, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldHaveSameMonthAs] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(2018, 2, 10, 11, 30, 30) * * firstDate shouldHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 9, 10, 0, 0) * * firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3 * ``` */ infix fun LocalDateTime.shouldNotHaveSameMonthAs(date: LocalDateTime) = this shouldNot haveSameMonth(date) /** * Matcher that compares months of LocalDateTimes * * Verifies that two DateTimes have exactly the same month, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same month as 10/02/2018 11:30:30, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 10, 11, 30, 30) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 1, 30, 30) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference * ``` * * @see [LocalDateTime.shouldHaveSameMonthAs] * @see [LocalDateTime.shouldNotHaveSameMonthAs] */ fun haveSameMonth(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult = MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}") } /** * Asserts that this month is the same as [date]'s month * * Verifies that this month is the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same month as 10/02/2018 11:30:30 -05:00 America/Chicago, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldNotHaveSameMonthAs] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 2, 10, 11, 30, 30, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate should haveSameMonth(secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNot haveSameMonth(secondDate) // Assertion passes * ``` */ infix fun ZonedDateTime.shouldHaveSameMonthAs(date: ZonedDateTime) = this should haveSameMonth(date) /** * Asserts that this month is NOT the same as [date]'s month * * Verifies that this month isn't the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same month as 09/03/1998 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldHaveSameMonthAs] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3 * ``` */ infix fun ZonedDateTime.shouldNotHaveSameMonthAs(date: ZonedDateTime) = this shouldNot haveSameMonth(date) /** * Matcher that compares months of ZonedDateTimes * * Verifies that two ZonedDateTimes have exactly the same month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same month as 10/02/2018 11:30:30 -05:00 America/Chicago, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 3, 9, 19, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 2, 10, 1, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference * ``` * * @see [ZonedDateTime.shouldHaveSameMonthAs] * @see [ZonedDateTime.shouldNotHaveSameMonthAs] */ fun haveSameMonth(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}") } /** * Asserts that this month is the same as [date]'s month * * Verifies that this month is the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the same month as 10/02/2018 11:30:30 -05:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldNotHaveSameMonthAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldHaveSameMonthAs secondDate // Assertion fails, 2 != 3 * ``` */ infix fun OffsetDateTime.shouldHaveSameMonthAs(date: OffsetDateTime) = this should haveSameMonth(date) /** * Asserts that this month is NOT the same as [date]'s month * * Verifies that this month isn't the same as [date]'s month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 doesn't have the same month as 09/03/1998 10:00:00 -03:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldHaveSameMonthAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 9, 19, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 2, 10, 1, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldNotHaveSameMonthAs secondDate // Assertion fails, 2 == 2, and we expected a difference * ``` */ infix fun OffsetDateTime.shouldNotHaveSameMonthAs(date: OffsetDateTime) = this shouldNot haveSameMonth(date) /** * Matcher that compares months of OffsetDateTimes * * Verifies that two ZonedDateTimes have exactly the same month, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the same month as 10/02/1998 11:30:30 -05:00, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 2, 10, 11, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate should haveSameMonth(secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 3, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNot haveSameMonth(secondDate) // Assertion passes * ``` * * @see [OffsetDateTime.shouldHaveSameMonthAs] * @see [OffsetDateTime.shouldNotHaveSameMonthAs] */ fun haveSameMonth(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult = MatcherResult(value.month == date.month, "$value should have month ${date.month}", "$value should not have month ${date.month}") } /** * Asserts that this day is the same as [date]'s day * * Verifies that this day is the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 has the same day as 09/03/2018, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldNotHaveSameDayAs] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 3, 9) * * firstDate shouldHaveSameDayAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10 * ``` */ infix fun LocalDate.shouldHaveSameDayAs(date: LocalDate) = this should haveSameDay(date) /** * Asserts that this day is NOT the same as [date]'s day * * Verifies that this day isn't the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 doesn't have the same day as 10/02/1998, and this assertion should pass for this comparison * * Opposite of [LocalDate.shouldHaveSameDayAs] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 3, 9) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference * ``` */ infix fun LocalDate.shouldNotHaveSameDayAs(date: LocalDate) = this shouldNot haveSameDay(date) /** * Matcher that compares days of LocalDates * * Verifies that two dates have exactly the same day, ignoring any other fields. * For example, 09/02/1998 has the same day as 09/03/2018, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(2018, 3, 9) * * firstDate should haveSameDay(secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldNot haveSameDay(secondDate) // Assertion passes * ``` * * @see [LocalDate.shouldHaveSameDayAs] * @see [LocalDate.shouldNotHaveSameDayAs] */ fun haveSameDay(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult = MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}") } /** * Asserts that this day is the same as [date]'s day * * Verifies that this day is the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same day as 09/03/2018 11:30:30, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldNotHaveSameDayAs] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 9, 11, 30, 30) * * firstDate shouldHaveSameDayAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10 * ``` */ infix fun LocalDateTime.shouldHaveSameDayAs(date: LocalDateTime) = this should haveSameDay(date) /** * Asserts that this day is NOT the same as [date]'s day * * Verifies that this year isn't the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 doesn't have the same day as 10/02/1998 10:00:00, and this assertion should pass for this comparison * * Opposite of [LocalDateTime.shouldHaveSameDayAs] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(2018, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 3, 9, 11, 30, 30) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference * ``` */ infix fun LocalDateTime.shouldNotHaveSameDayAs(date: LocalDateTime) = this shouldNot haveSameDay(date) /** * Matcher that compares days of LocalDateTimes * * Verifies that two DateTimes have exactly the same day, ignoring any other fields. * For example, 09/02/1998 10:00:00 has the same day as 09/03/2018 11:30:30, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(2018, 3, 9, 11, 30, 30) * * firstDate should haveSameDay(secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldNot haveSameDay(secondDate) // Assertion passes * ``` * * @see [LocalDateTime.shouldHaveSameDayAs] * @see [LocalDateTime.shouldNotHaveSameDayAs] */ fun haveSameDay(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult = MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}") } /** * Asserts that this day is the same as [date]'s day * * Verifies that this day is the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same day as 09/03/2018 11:30:30 -05:00 America/Chicago, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldNotHaveSameDayAs] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldHaveSameDayAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 10 * ``` */ infix fun ZonedDateTime.shouldHaveSameDayAs(date: ZonedDateTime) = this should haveSameDay(date) /** * Asserts that this day is NOT the same as [date]'s day * * Verifies that this day isn't the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo doesn't have the same day as 10/02/1998 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison * * Opposite of [ZonedDateTime.shouldHaveSameDayAs] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference * ``` */ infix fun ZonedDateTime.shouldNotHaveSameDayAs(date: ZonedDateTime) = this shouldNot haveSameDay(date) /** * Matcher that compares days of ZonedDateTimes * * Verifies that two ZonedDateTimes have exactly the same day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo has the same day as 09/03/2018 11:30:30 -05:00 America/Chicago, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneId.of("America/Chicago")) * * firstDate should haveSameDay(secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNot haveSameDay(secondDate) // Assertion passes * ``` * * @see [ZonedDateTime.shouldHaveSameDayAs] * @see [ZonedDateTime.shouldNotHaveSameDayAs] */ fun haveSameDay(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}") } /** * Asserts that this day is the same as [date]'s day * * Verifies that this day is the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the day year as 09/02/1998 11:30:30 -05:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldNotHaveSameDayAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldHaveSameDayAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldHaveSameDayAs secondDate // Assertion fails, 9 != 12 * ``` */ infix fun OffsetDateTime.shouldHaveSameDayAs(date: OffsetDateTime) = this should haveSameDay(date) /** * Asserts that this day is NOT the same as [date]'s day * * Verifies that this day isn't the same as [date]'s day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 doesn't have the same day as 10/02/1998 10:00:00 -03:00, * and this assertion should pass for this comparison * * Opposite of [OffsetDateTime.shouldHaveSameDayAs] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 19, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 3, 9, 1, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate shouldNotHaveSameDayAs secondDate // Assertion fails, 9 == 9, and we expected a difference * ``` */ infix fun OffsetDateTime.shouldNotHaveSameDayAs(date: OffsetDateTime) = this shouldNot haveSameDay(date) /** * Matcher that compares days of OffsetDateTimes * * Verifies that two ZonedDateTimes have exactly the same day, ignoring any other fields. * For example, 09/02/1998 10:00:00 -03:00 has the same day as 09/03/2018 11:30:30 -05:00, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2018, 3, 9, 11, 30, 30, 30, ZoneOffset.ofHours(-5)) * * firstDate should haveSameDay(secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNot haveSameDay(secondDate) // Assertion passes * ``` * * @see [OffsetDateTime.shouldHaveSameDayAs] * @see [OffsetDateTime.shouldNotHaveSameDayAs] */ fun haveSameDay(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult = MatcherResult(value.dayOfMonth == date.dayOfMonth, "$value should have day ${date.dayOfMonth} but had ${value.dayOfMonth}", "$value should not have day ${date.dayOfMonth}") } /** * Asserts that this is before [date] * * Verifies that this is before [date], comparing year, month and day. * For example, 09/02/1998 is before 10/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldNotBeBefore] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldBeBefore secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 10) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldBeBefore secondDate // Assertion fails, 10/02/1998 is not before 09/02/1998 as expected. * ``` * * @see LocalDate.shouldNotBeAfter */ infix fun LocalDate.shouldBeBefore(date: LocalDate) = this should before(date) /** * Asserts that this is NOT before [date] * * Verifies that this is not before [date], comparing year, month and day. * For example, 10/02/1998 is not before 09/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldBeBefore] * * ``` * val firstDate = LocalDate.of(1998, 2, 10) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldNotBeBefore secondDate // Assertion passes * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldNotBeBefore secondDate // Assertion fails, 09/02/1998 is before 10/02/1998, and we expected the opposite. * ``` * * @see LocalDate.shouldBeAfter */ infix fun LocalDate.shouldNotBeBefore(date: LocalDate) = this shouldNot before(date) /** * Matcher that compares two LocalDates and checks whether one is before the other * * Verifies that two LocalDates occurs in a certain order, checking that one happened before the other. * For example, 09/02/1998 is before 10/02/1998, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldBe before(secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 10) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldNotBe before(secondDate) // Assertion passes * ``` * * @see LocalDate.shouldBeBefore * @see LocalDate.shouldNotBeBefore */ fun before(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult = MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date") } /** * Asserts that this is before [date] * * Verifies that this is before [date], comparing every field in the LocalDateTime. * For example, 09/02/1998 00:00:00 is before 09/02/1998 00:00:01, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldNotBeBefore] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * * firstDate shouldBeBefore secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * * firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate * ``` * * @see LocalDateTime.shouldNotBeAfter */ infix fun LocalDateTime.shouldBeBefore(date: LocalDateTime) = this should before(date) /** * Asserts that this is NOT before [date] * * Verifies that this is not before [date], comparing every field in the LocalDateTime. * For example, 09/02/1998 00:00:01 is not before 09/02/1998 00:00:00, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldBeBefore] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * * firstDate shouldNotBeBefore secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * * firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it * ``` * * @see LocalDateTime.shouldBeAfter */ infix fun LocalDateTime.shouldNotBeBefore(date: LocalDateTime) = this shouldNot before(date) /** * Matcher that compares two LocalDateTimes and checks whether one is before the other * * Verifies that two LocalDateTimes occurs in a certain order, checking that one happened before the other. * For example, 09/02/1998 00:00:00 is before 09/02/1998 00:00:01, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * * firstDate shouldBe before(secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 0, 0, 1) * val secondDate = LocalDateTime.of(1998, 2, 9, 0, 0, 0) * * firstDate shouldNotBe before(secondDate) // Assertion passes * ``` * * @see LocalDateTime.shouldBeBefore * @see LocalDateTime.shouldNotBeBefore */ fun before(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult = MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date") } /** * Asserts that this is before [date] * * Verifies that this is before [date], comparing every field in the ZonedDateTime. * For example, 09/02/1998 00:00:00 -03:00 America/Sao_Paulo is before 09/02/1998 00:00:01 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldNotBeBefore] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBeBefore secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate * ``` * * @see ZonedDateTime.shouldNotBeAfter */ infix fun ZonedDateTime.shouldBeBefore(date: ZonedDateTime) = this should before(date) /** * Asserts that this is NOT before [date] * * Verifies that this is not before [date], comparing every field in the ZonedDateTime. * For example, 09/02/1998 00:00:01 -03:00 America/Sao_Paulo is not before 09/02/1998 00:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldBeBefore] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBeBefore secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it * ``` * * @see ZonedDateTime.shouldBeAfter */ infix fun ZonedDateTime.shouldNotBeBefore(date: ZonedDateTime) = this shouldNot before(date) /** * Matcher that compares two ZonedDateTimes and checks whether one is before the other * * Verifies that two ZonedDateTimes occurs in a certain order, checking that one happened before the other. * For example, 09/02/1998 00:00:00 -03:00 America/Sao_Paulo is before 09/02/1998 00:00:01 -03:00 America/Sao_Paulo, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBe before(secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBe before(secondDate) // Assertion passes * ``` * * @see ZonedDateTime.shouldBeBefore * @see ZonedDateTime.shouldNotBeBefore */ fun before(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date") } /** * Asserts that this is before [date] * * Verifies that this is before [date], comparing every field in the OffsetDateTime. * For example, 09/02/1998 00:00:00 -03:00 is before 09/02/1998 00:00:01 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldNotBeBefore] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBeBefore secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBeBefore secondDate // Assertion fails, firstDate is one second after secondDate * ``` * * @see OffsetDateTime.shouldNotBeAfter */ infix fun OffsetDateTime.shouldBeBefore(date: OffsetDateTime) = this should before(date) /** * Asserts that this is NOT before [date] * * Verifies that this is not before [date], comparing every field in the OffsetDateTime. * For example, 09/02/1998 00:00:01 -03:00 is not before 09/02/1998 00:00:00 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldBeBefore] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBeBefore secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBeBefore secondDate // Assertion fails, firstDate is one second before secondDate and we didn't expect it * ``` * * @see OffsetDateTime.shouldBeAfter */ infix fun OffsetDateTime.shouldNotBeBefore(date: OffsetDateTime) = this shouldNot before(date) /** * Matcher that compares two OffsetDateTimes and checks whether one is before the other * * Verifies that two OffsetDateTimes occurs in a certain order, checking that one happened before the other. * For example, 09/02/1998 00:00:00 -03:00 is before 09/02/1998 00:00:01 -03:00, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBe before(secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 1, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 0, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBe before(secondDate) // Assertion passes * ``` * * @see OffsetDateTime.shouldBeBefore * @see OffsetDateTime.shouldNotBeBefore */ fun before(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult = MatcherResult(value.isBefore(date), "$value should be before $date", "$value should not be before $date") } /** * Asserts that this is after [date] * * Verifies that this is after [date], comparing year, month and day. * For example, 09/02/1998 is after 08/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldNotBeAfter] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 8) * * firstDate shouldBeAfter secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate * ``` * * @see LocalDate.shouldNotBeBefore */ infix fun LocalDate.shouldBeAfter(date: LocalDate) = this should after(date) /** * Asserts that this is NOT after [date] * * Verifies that this is not after [date], comparing year, month and day. * For example, 09/02/1998 is not after 10/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldBeAfter] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldNotBeAfter secondDate // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 10) * val secondDate = LocalDate.of(1998, 2, 9) * * firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate * ``` * * @see LocalDate.shouldBeBefore */ infix fun LocalDate.shouldNotBeAfter(date: LocalDate) = this shouldNot after(date) /** * Matcher that compares two LocalDates and checks whether one is after the other * * Verifies that two LocalDates occurs in a certain order, checking that one happened after the other. * For example, 10/02/1998 is after 09/02/1998, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 8) * * firstDate shouldBe after(secondDate ) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldNotBe after(secondDate) // Assertion passes * ``` * * @see LocalDate.shouldBeAfter * @see LocalDate.shouldNotBeAfter */ fun after(date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult = MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date") } /** * Asserts that this is after [date] * * Verifies that this is after [date], comparing all fields in LocalDateTime. * For example, 09/02/1998 10:00:00 is after 09/02/1998 09:00:00, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldNotBeAfter] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 8, 10, 0, 0) * * firstDate shouldBeAfter secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate * ``` * * @see LocalDateTime.shouldNotBeBefore */ infix fun LocalDateTime.shouldBeAfter(date: LocalDateTime) = this should after(date) /** * Asserts that this is NOT after [date] * * Verifies that this is not after [date], comparing all fields in LocalDateTime. * For example, 09/02/1998 09:00:00 is not after 09/02/1998 10:00:00, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldBeAfter] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldNotBeAfter secondDate // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * * firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate * ``` * * @see LocalDateTime.shouldBeBefore */ infix fun LocalDateTime.shouldNotBeAfter(date: LocalDateTime) = this shouldNot after(date) /** * Matcher that compares two LocalDateTimes and checks whether one is after the other * * Verifies that two LocalDateTimes occurs in a certain order, checking that one happened after the other. * For example, 09/02/1998 10:00:00 is after 09/02/1998 09:00:00, and the matcher will have a positive result for this comparison * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 8, 10, 0, 0) * * firstDate shouldBe after(secondDate ) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldNotBe after(secondDate) // Assertion passes * ``` * * @see LocalDateTime.shouldBeAfter * @see LocalDateTime.shouldNotBeAfter */ fun after(date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult = MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date") } /** * Asserts that this is after [date] * * Verifies that this is after [date], comparing all fields in ZonedDateTime. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is after 09/02/1998 09:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldNotBeAfter] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBeAfter secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate * ``` * * @see ZonedDateTime.shouldNotBeBefore */ infix fun ZonedDateTime.shouldBeAfter(date: ZonedDateTime) = this should after(date) /** * Asserts that this is NOT after [date] * * Verifies that this is not after [date], comparing all fields in ZonedDateTime. * For example, 09/02/1998 09:00:00 -03:00 America/Sao_Paulo is not after 09/02/1998 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldBeAfter] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBeAfter secondDate // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate * ``` * * @see ZonedDateTime.shouldBeBefore */ infix fun ZonedDateTime.shouldNotBeAfter(date: ZonedDateTime) = this shouldNot after(date) /** * Matcher that compares two ZonedDateTimes and checks whether one is after the other * * Verifies that two ZonedDateTimes occurs in a certain order, checking that one happened after the other. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is after 09/02/1998 09:00:00 -03:00 America/Sao_Paulo, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldBe after(secondDate ) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * firstDate shouldNotBe after(secondDate) // Assertion passes * ``` * * @see ZonedDateTime.shouldBeAfter * @see ZonedDateTime.shouldNotBeAfter */ fun after(date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date") } /** * Asserts that this is after [date] * * Verifies that this is after [date], comparing all fields in OffsetDateTime. * For example, 09/02/1998 10:00:00 -03:00 is after 09/02/1998 09:00:00 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldNotBeAfter] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBeAfter secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBeAfter secondDate // Assertion fails, firstDate is NOT after secondDate * ``` * * @see OffsetDateTime.shouldNotBeBefore */ infix fun OffsetDateTime.shouldBeAfter(date: OffsetDateTime) = this should after(date) /** * Asserts that this is NOT after [date] * * Verifies that this is not after [date], comparing all fields in OffsetDateTime. * For example, 09/02/1998 09:00:00 -03:00 is not after 09/02/1998 10:00:00 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldBeAfter] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBeAfter secondDate // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBeAfter secondDate // Assertion fails, first date IS after secondDate * ``` * * @see OffsetDateTime.shouldBeBefore */ infix fun OffsetDateTime.shouldNotBeAfter(date: OffsetDateTime) = this shouldNot after(date) /** * Matcher that compares two OffsetDateTimes and checks whether one is after the other * * Verifies that two OffsetDateTimes occurs in a certain order, checking that one happened after the other. * For example, 09/02/1998 10:00:00 -03:00 is after 09/02/1998 09:00:00 -03:00, * and the matcher will have a positive result for this comparison * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 8, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBe after(secondDate ) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldNotBe after(secondDate) // Assertion passes * ``` * * @see OffsetDateTime.shouldBeAfter * @see OffsetDateTime.shouldNotBeAfter */ fun after(date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult = MatcherResult(value.isAfter(date), "$value should be after $date", "$value should not be after $date") } /** * Asserts that this is within [period] of [date] * * Verifies that this is within [period] of [date]. * For example, 09/02/1998 is within 3 days of 10/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldNotBeWithin] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 25) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate * ``` */ fun LocalDate.shouldBeWithin(period: Period, date: LocalDate) = this should within(period, date) /** * Asserts that this is NOT within [period] of [date] * * Verifies that this is not within [period] of [date]. * For example, 09/02/1998 is not within 3 days of 25/02/1998, and this assertion should pass for this comparison. * * Opposite of [LocalDate.shouldBeWithin] * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 25) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to * ``` */ fun LocalDate.shouldNotBeWithin(period: Period, date: LocalDate) = this shouldNot within(period, date) /** * Matcher that compares two LocalDates and checks whether one is within [period] of the other * * Verifies that two LocalDates are within a certain period. * For example, 09/02/1998 is within 3 days of 10/02/1998, and the matcher will have a positive result for this comparison. * * * ``` * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 10) * * firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDate.of(1998, 2, 9) * val secondDate = LocalDate.of(1998, 2, 25) * firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes * ``` * * @see [LocalDate.shouldBeWithin] * @see [LocalDate.shouldNotBeWithin] */ fun within(period: Period, date: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult { val start = date.minus(period) val end = date.plus(period) val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value) return MatcherResult(passed, "$value should be within $period of $date", "$value should not be within $period of $date") } } /** * Asserts that this is within [temporalAmount] of [date] * * Verifies that this is within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 is within 3 days of 10/02/1998 10:00:00, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldNotBeWithin] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate * ``` */ fun LocalDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: LocalDateTime) = this should within(temporalAmount, date) /** * Asserts that this is NOT within [temporalAmount] of [date] * * Verifies that this is not within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 is not within 3 days of 25/02/1998 10:00:00, and this assertion should pass for this comparison. * * Opposite of [LocalDateTime.shouldBeWithin] * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to * ``` */ fun LocalDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: LocalDateTime) = this shouldNot within(temporalAmount, date) /** * Matcher that compares two LocalDateTimes and checks whether one is within [temporalAmount] of the other * * Verifies that two LocalDateTimes are within a certain period. * For example, 09/02/1998 10:00:00 is within 3 days of 10/02/1998 10:00:00, * and the matcher will have a positive result for this comparison. * * * ``` * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 10, 10, 0, 0) * * firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = LocalDateTime.of(1998, 2, 9, 10, 0, 0) * val secondDate = LocalDateTime.of(1998, 2, 25, 10, 0, 0) * firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes * ``` * * @see [LocalDateTime.shouldBeWithin] * @see [LocalDateTime.shouldNotBeWithin] */ fun within(temporalAmount: TemporalAmount, date: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult { val start = date.minus(temporalAmount) val end = date.plus(temporalAmount) val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value) return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date") } } /** * Asserts that this is within [temporalAmount] of [date] * * Verifies that this is within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is within 3 days of 10/02/1998 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldNotBeWithin] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate * ``` */ fun ZonedDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: ZonedDateTime) = this should within(temporalAmount, date) /** * Asserts that this is NOT within [temporalAmount] of [date] * * Verifies that this is not within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is not within 3 days of 25/02/1998 10:00:00 -03:00 America/Sao_Paulo, * and this assertion should pass for this comparison. * * Opposite of [ZonedDateTime.shouldBeWithin] * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to * ``` */ fun ZonedDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: ZonedDateTime) = this shouldNot within(temporalAmount, date) /** * Matcher that compares two ZonedDateTimes and checks whether one is within [temporalAmount] of the other * * Verifies that two ZonedDateTimes are within a certain period. * For example, 09/02/1998 10:00:00 -03:00 America/Sao_Paulo is within 3 days of 10/02/1998 10:00:00 -03:00 America/Sao_Paulo, * and the matcher will have a positive result for this comparison. * * * ``` * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * * firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = ZonedDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * val secondDate = ZonedDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneId.of("America/Sao_Paulo)) * firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes * ``` * * @see [ZonedDateTime.shouldBeWithin] * @see [ZonedDateTime.shouldNotBeWithin] */ fun within(temporalAmount: TemporalAmount, date: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult { val start = date.minus(temporalAmount) val end = date.plus(temporalAmount) val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value) return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date") } } /** * Asserts that this is within [temporalAmount] of [date] * * Verifies that this is within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 -03:00 is within 3 days of 10/02/1998 10:00:00 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldNotBeWithin] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate.shouldBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is not within 3 days of secondDate * ``` */ fun OffsetDateTime.shouldBeWithin(temporalAmount: TemporalAmount, date: OffsetDateTime) = this should within(temporalAmount, date) /** * Asserts that this is NOT within [temporalAmount] of [date] * * Verifies that this is not within [temporalAmount] of [date]. * For example, 09/02/1998 10:00:00 -03:00 is not within 3 days of 25/02/1998 10:00:00 -03:00, * and this assertion should pass for this comparison. * * Opposite of [OffsetDateTime.shouldBeWithin] * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate.shouldNotBeWithin(Period.ofDays(3), secondDate) // Assertion fails, firstDate is within 3 days of secondDate, and we expected not to * ``` */ fun OffsetDateTime.shouldNotBeWithin(temporalAmount: TemporalAmount, date: OffsetDateTime) = this shouldNot within(temporalAmount, date) /** * Matcher that compares two OffsetDateTimes and checks whether one is within [temporalAmount] of the other * * Verifies that two OffsetDateTimes are within a certain period. * For example, 09/02/1998 10:00:00 -03:00 is within 3 days of 10/02/1998 10:00:00 -03:00, * and the matcher will have a positive result for this comparison. * * * ``` * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 10, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * * firstDate shouldBe within(Period.ofDays(3), secondDate) // Assertion passes * * * val firstDate = OffsetDateTime.of(1998, 2, 9, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(1998, 2, 25, 10, 0, 0, 0, ZoneOffset.ofHours(-3)) * firstDate shouldNotBe within(Period.ofDays(3), secondDate) // Assertion passes * ``` * * @see [OffsetDateTime.shouldBeWithin] * @see [OffsetDateTime.shouldNotBeWithin] */ fun within(temporalAmount: TemporalAmount, date: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult { val start = date.minus(temporalAmount) val end = date.plus(temporalAmount) val passed = start == value || end == value || start.isBefore(value) && end.isAfter(value) return MatcherResult(passed, "$value should be within $temporalAmount of $date", "$value should not be within $temporalAmount of $date") } } /** * Asserts that this is between [a] and [b] * * Verifies that this is after [a] and before [b], comparing year, month and day. * * Opposite of [LocalDate.shouldNotBeBetween] * * ``` * val date = LocalDate.of(2019, 2, 16) * val firstDate = LocalDate.of(2019, 2, 15) * val secondDate = LocalDate.of(2019, 2, 17) * * date.shouldBeBetween(firstDate, secondDate) // Assertion passes * * * val date = LocalDate.of(2019, 2, 15) * val firstDate = LocalDate.of(2019, 2, 16) * val secondDate = LocalDate.of(2019, 2, 17) * * date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate * ``` * * @see LocalDate.shouldNotBeBetween */ fun LocalDate.shouldBeBetween(a: LocalDate, b: LocalDate) = this shouldBe between(a, b) /** * Asserts that this is NOT between [a] and [b] * * Verifies that this is not after [a] and before [b], comparing year, month and day. * * Opposite of [LocalDate.shouldBeBetween] * * ``` * val date = LocalDate.of(2019, 2, 15) * val firstDate = LocalDate.of(2019, 2, 16) * val secondDate = LocalDate.of(2019, 2, 17) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes * * * val date = LocalDate.of(2019, 2, 16) * val firstDate = LocalDate.of(2019, 2, 15) * val secondDate = LocalDate.of(2019, 2, 17) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate * ``` * * @see LocalDate.shouldBeBetween */ fun LocalDate.shouldNotBeBetween(a: LocalDate, b: LocalDate) = this shouldNotBe between(a, b) /** * Matcher that checks if LocalDate is between two other LocalDates * * Verifies that LocalDate is after the first LocalDate and before the second LocalDate * For example, 20/03/2019 is between 19/03/2019 and 21/03/2019, and the matcher will have a positive result for this comparison * * ``` * val date = LocalDate.of(2019, 2, 16) * val firstDate = LocalDate.of(2019, 2, 15) * val secondDate = LocalDate.of(2019, 2, 17) * * date shouldBe after(firstDate, secondDate) // Assertion passes * * * val date = LocalDate.of(2019, 2, 15) * val firstDate = LocalDate.of(2019, 2, 16) * val secondDate = LocalDate.of(2019, 2, 17) * * date shouldNotBe between(firstDate, secondDate) // Assertion passes * ``` * * @see LocalDate.shouldBeBetween * @see LocalDate.shouldNotBeBetween */ fun between(a: LocalDate, b: LocalDate): Matcher<LocalDate> = object : Matcher<LocalDate> { override fun test(value: LocalDate): MatcherResult { val passed = value.isAfter(a) && value.isBefore(b) return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b") } } /** * Asserts that this is between [a] and [b] * * Verifies that this is after [a] and before [b], comparing all fields in LocalDateTime. * * Opposite of [LocalDateTime.shouldNotBeBetween] * * ``` * val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date.shouldBeBetween(firstDate, secondDate) // Assertion passes * * * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate * ``` * * @see LocalDateTime.shouldNotBeBetween */ fun LocalDateTime.shouldBeBetween(a: LocalDateTime, b: LocalDateTime) = this shouldBe between(a, b) /** * Asserts that this is NOT between [a] and [b] * * Verifies that this is not after [a] and before [b], comparing all fields in LocalDateTime. * * Opposite of [LocalDateTime.shouldBeBetween] * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes * * * val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate * ``` * * @see LocalDateTime.shouldBeBetween */ fun LocalDateTime.shouldNotBeBetween(a: LocalDateTime, b: LocalDateTime) = this shouldNotBe between(a, b) /** * Matcher that checks if LocalDateTime is between two other LocalDateTimes * * Verifies that LocalDateTime is after the first LocalDateTime and before the second LocalDateTime * For example, 20/03/2019 10:00:00 is between 19/03/2019 10:00:00 and 21/03/2019 10:00:00, and the matcher will have a positive result for this comparison * * ``` * val date = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date shouldBe after(firstDate, secondDate) // Assertion passes * * * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0) * val firstDate = LocalDateTime.of(2019, 2, 16, 12, 0, 0) * val secondDate = LocalDateTime.of(2019, 2, 17, 12, 0, 0) * * date shouldNotBe between(firstDate, secondDate) // Assertion passes * ``` * * @see LocalDateTime.shouldBeBetween * @see LocalDateTime.shouldNotBeBetween */ fun between(a: LocalDateTime, b: LocalDateTime): Matcher<LocalDateTime> = object : Matcher<LocalDateTime> { override fun test(value: LocalDateTime): MatcherResult { val passed = value.isAfter(a) && value.isBefore(b) return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b") } } /** * Asserts that this is between [a] and [b] * * Verifies that this is after [a] and before [b], comparing all fields in ZonedDateTime. * * Opposite of [ZonedDateTime.shouldNotBeBetween] * * ``` * val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date.shouldBeBetween(firstDate, secondDate) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate * ``` * * @see ZonedDateTime.shouldNotBeBetween */ fun ZonedDateTime.shouldBeBetween(a: ZonedDateTime, b: ZonedDateTime) = this shouldBe between(a, b) /** * Asserts that this is NOT between [a] and [b] * * Verifies that this is not after [a] and before [b], comparing all fields in ZonedDateTime. * * Opposite of [ZonedDateTime.shouldBeBetween] * * ``` * val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate * ``` * * @see ZonedDateTime.shouldBeBetween */ fun ZonedDateTime.shouldNotBeBetween(a: ZonedDateTime, b: ZonedDateTime) = this shouldNotBe between(a, b) /** * Matcher that checks if ZonedDateTime is between two other ZonedDateTimes * * Verifies that ZonedDateTime is after the first ZonedDateTime and before the second ZonedDateTime * For example, 20/03/2019 10:00:00 -03:00 America/Sao_Paulo is between 19/03/2019 10:00:00 -03:00 America/Sao_Paulo * and 21/03/2019 10:00:00 -03:00 America/Sao_Paulo, and the matcher will have a positive result for this comparison * * ``` * val date = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date shouldBe after(firstDate, secondDate) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val firstDate = ZonedDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * val secondDate = ZonedDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneId.of("America/Sao_Paulo")) * * date shouldNotBe between(firstDate, secondDate) // Assertion passes * ``` * * @see ZonedDateTime.shouldBeBetween * @see ZonedDateTime.shouldNotBeBetween */ fun between(a: ZonedDateTime, b: ZonedDateTime): Matcher<ZonedDateTime> = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult { val passed = value.isAfter(a) && value.isBefore(b) return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b") } } /** * Asserts that this is between [a] and [b] * * Verifies that this is after [a] and before [b], comparing all fields in ZonedDateTime. * * Opposite of [OffsetDateTime.shouldNotBeBetween] * * ``` * val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldBeBetween(firstDate, secondDate) // Assertion passes * * * val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldBeBetween(firstDate, secondDate) // Assertion fails, date is NOT between firstDate and secondDate * ``` * * @see OffsetDateTime.shouldNotBeBetween */ fun OffsetDateTime.shouldBeBetween(a: OffsetDateTime, b: OffsetDateTime) = this shouldBe between(a, b) /** * Asserts that this is NOT between [a] and [b] * * Verifies that this is not after [a] and before [b], comparing all fields in ZonedDateTime. * * Opposite of [OffsetDateTime.shouldBeBetween] * * ``` * val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion passes * * * val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldNotBeBetween(firstDate, secondDate) // Assertion fails, date IS between firstDate and secondDate * ``` * * @see OffsetDateTime.shouldBeBetween */ fun OffsetDateTime.shouldNotBeBetween(a: OffsetDateTime, b: OffsetDateTime) = this shouldNotBe between(a, b) /** * Matcher that checks if OffsetDateTime is between two other OffsetDateTimes * * Verifies that OffsetDateTime is after the first OffsetDateTime and before the second OffsetDateTime * For example, 20/03/2019 10:00:00 -03:00 is between 19/03/2019 10:00:00 -03:00 and 21/03/2019 10:00:00 -03:00, * and the matcher will have a positive result for this comparison * * ``` * val date = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date shouldBe after(firstDate, secondDate) // Assertion passes * * * val date = OffsetDateTime.of(2019, 2, 15, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val firstDate = OffsetDateTime.of(2019, 2, 16, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * val secondDate = OffsetDateTime.of(2019, 2, 17, 12, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date shouldNotBe between(firstDate, secondDate) // Assertion passes * ``` * * @see OffsetDateTime.shouldBeBetween * @see OffsetDateTime.shouldNotBeBetween */ fun between(a: OffsetDateTime, b: OffsetDateTime): Matcher<OffsetDateTime> = object : Matcher<OffsetDateTime> { override fun test(value: OffsetDateTime): MatcherResult { val passed = value.isAfter(a) && value.isBefore(b) return MatcherResult(passed, "$value should be after $a and before $b", "$value should not be be after $a and before $b") } } /** * Asserts that the day of month inputted is equaled the date day * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0) * * date.shouldHaveDayOfMonth(15) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveDayOfMonth(day: Int) = this.dayOfMonth shouldBe day /** * Asserts that the day of year inputted is equaled the date day * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0) * * date.shouldHaveDayOfYear(46) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveDayOfYear(day: Int) = this.dayOfYear shouldBe day /** * Asserts that the day of year inputted is equaled the date day * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0) * * date.shouldHaveDayOfWeek(FRIDAY) // Assertion passes * date.shouldHaveDayOfWeek(5) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveDayOfWeek(day: Int) = this.dayOfWeek.value shouldBe day infix fun LocalDateTime.shouldHaveDayOfWeek(day: DayOfWeek) = this.dayOfWeek shouldBe day /** * Asserts that the month inputted is equaled the date month * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 0, 0, 0) * * date.shouldHaveMonth(2) // Assertion passes * date.shouldHaveMonth(FEBRUARY) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveMonth(month: Int) = this.month.value shouldBe month infix fun LocalDateTime.shouldHaveMonth(month: Month) = this.month shouldBe month /** * Asserts that the hour inputted is equaled the date time hour * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 0) * * date.shouldHaveHour(12) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveHour(hour: Int) = this.hour shouldBe hour /** * Asserts that the minute inputted is equaled the date time minute * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 0) * * date.shouldHaveMinute(10) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveMinute(minute: Int) = this.minute shouldBe minute /** * Asserts that the second inputted is equaled the date time second * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 10, 11, 0) * * date.shouldHaveSecond(11) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveSecond(second: Int) = this.second shouldBe second /** * Asserts that the nano inputted is equaled the date time nano * * ``` * val date = LocalDateTime.of(2019, 2, 15, 12, 10, 0, 12) * * date.shouldHaveNano(10) // Assertion passes * ``` */ infix fun LocalDateTime.shouldHaveNano(nano: Int) = this.nano shouldBe nano /** * Asserts that this is equal to [other] using the [ChronoZonedDateTime.isEqual] * * Opposite of [ZonedDateTime.shouldNotHaveSameInstantAs] * * ``` * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldHaveSameInstantAs(other) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldHaveSameInstantAs(other) // Assertion fails, date is NOT equal to the other date * ``` * * @see ZonedDateTime.shouldNotHaveSameInstant */ infix fun ZonedDateTime.shouldHaveSameInstantAs(other: ZonedDateTime) = this should haveSameInstantAs(other) /** * Asserts that this is NOT equal to [other] using the [ChronoZonedDateTime.isEqual] * * Opposite of [ZonedDateTime.shouldHaveSameInstantAs] * * ``` * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldNotHaveSameInstantAs(other) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.shouldNotHaveSameInstantAs(other) // Assertion fails, date is equal to the other date * ``` * * @see ZonedDateTime.shouldHaveSameInstantAs */ infix fun ZonedDateTime.shouldNotHaveSameInstantAs(other: ZonedDateTime) = this shouldNot haveSameInstantAs(other) /** * Matcher that checks if ZonedDateTime is equal to another ZonedDateTime using the * [ChronoZonedDateTime.isEqual] * * * ``` * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 9, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.haveSameInstantAs(other) // Assertion passes * * * val date = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-1)) * val other = ZonedDateTime.of(2019, 2, 16, 11, 0, 0, 0, ZoneOffset.ofHours(-3)) * * date.haveSameInstantAs(other) // Assertion fails, date is NOT equal to the other date * ``` * * @see ZonedDateTime.shouldHaveSameInstantAs * @see ZonedDateTime.shouldNotHaveSameInstantAs */ fun haveSameInstantAs(other: ZonedDateTime) = object : Matcher<ZonedDateTime> { override fun test(value: ZonedDateTime): MatcherResult = MatcherResult( passed = value.isEqual(other), failureMessage = "$value should be equal to $other", negatedFailureMessage = "$value should not be equal to $other" ) }
mit
9fbcabe312356f67c45dfa432b57a86f
39.021647
178
0.689822
3.629928
false
false
false
false
mapzen/eraser-map
app/src/main/kotlin/com/mapzen/erasermap/view/TimeView.kt
1
1080
package com.mapzen.erasermap.view import android.content.Context import android.util.AttributeSet import android.widget.TextView import com.mapzen.erasermap.R /** * Formats time for display. Examples: <1 min, 45 mins, 2 hrs 1 min, 5 hrs 27 mins. */ public class TimeView(context: Context, attrs: AttributeSet) : TextView(context, attrs) { public var timeInMinutes: Int = 0 set (value) { if (value < 1) { text = context.getString(R.string.less_than_one_minute) } else { formatTime(value) } } private fun formatTime(value: Int) { val hours = value / 60 val minutes = value % 60 val hourText = context.resources.getQuantityString(R.plurals.hours, hours, hours) val minuteText = context.resources.getQuantityString(R.plurals.minutes, minutes, minutes) if (hours == 0) { text = minuteText } else if (minutes == 0) { text = hourText } else { text = hourText + " " + minuteText } } }
gpl-3.0
f336f0aa062f70f031197d166d50fa8e
29
97
0.597222
4.106464
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/archive/ArchiveItem.kt
1
2147
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.archive import java.io.OutputStream import java.nio.file.Path /** * Abstraction to represent archive and its files as a one thing before and after transformation * together with information if any changes happened during the transformation. */ interface ArchiveItem { /** * Relative path of the item according to its location in the archive. * * Files in a nested archive have a path relative to that archive not to the parent of * the archive. The root archive has the file system path set as its relative path. */ val relativePath: Path /** * Name of the file. */ val fileName: String /** * Whether the item's content or its children were changed by Jetifier. This determines * whether the parent archive is going to be marked as changed thus having a dependency on * support. */ val wasChanged: Boolean /** * Accepts visitor. */ fun accept(visitor: ArchiveItemVisitor) /** * Writes its internal data (or other nested files) into the given output stream. */ fun writeSelfTo(outputStream: OutputStream) fun isPomFile() = fileName.equals("pom.xml", ignoreCase = true) || fileName.endsWith(".pom", ignoreCase = true) fun isClassFile() = fileName.endsWith(".class", ignoreCase = true) fun isXmlFile() = fileName.endsWith(".xml", ignoreCase = true) fun isProGuardFile () = fileName.equals("proguard.txt", ignoreCase = true) }
apache-2.0
e4459519230c38e1b3d2950abc17a0e0
31.545455
96
0.698184
4.463617
false
false
false
false
SDILogin/RouteTracker
app/src/main/java/me/sdidev/simpleroutetracker/base/GeoPositionTrackerService.kt
1
3266
package me.sdidev.simpleroutetracker.base import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.location.Location import android.os.Binder import android.os.Bundle import android.os.IBinder import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.common.api.PendingResult import com.google.android.gms.common.api.Status import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import me.sdidev.simpleroutetracker.App import me.sdidev.simpleroutetracker.BuildConfig import me.sdidev.simpleroutetracker.LocationUpdateManager import me.sdidev.simpleroutetracker.util.positionFromLocation import org.slf4j.LoggerFactory import javax.inject.Inject class GeoPositionTrackerService : Service() { private val logger = LoggerFactory.getLogger(GeoPositionTrackerService::class.java) private val binder: LocalBinder = LocalBinder() private var googleApiClient: GoogleApiClient? = null private var pendingResult: PendingResult<Status>? = null @Inject lateinit var locationUpdateManager: LocationUpdateManager override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return START_STICKY_COMPATIBILITY } override fun onCreate() { super.onCreate() App.applicationComponent.resolve(this) googleApiClient = GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(p0: Bundle?) { logger.info("connected to google api") startGoogleApiLocationListening() } override fun onConnectionSuspended(p0: Int) { logger.info("connection suspended") } }) .addOnConnectionFailedListener { error -> logger.warn("google api connection failure: $error") } .build() googleApiClient?.connect() } override fun onDestroy() { googleApiClient?.disconnect() pendingResult?.cancel() super.onDestroy() } override fun onBind(intent: Intent?): IBinder { return binder } @SuppressLint("MissingPermission") private fun startGoogleApiLocationListening() { val lastLocation: Location? = LocationServices.FusedLocationApi.getLastLocation(googleApiClient) if (lastLocation != null) { locationUpdateManager.update(positionFromLocation(lastLocation)) } val locationRequest = LocationRequest() locationRequest.interval = BuildConfig.UPDATE_INTERVAL locationRequest.smallestDisplacement = BuildConfig.MINIMAL_UPDATE_DISTANCE pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest ) { location -> logger.info("user position: (${location.latitude}, ${location.longitude})") locationUpdateManager.update(positionFromLocation(location)) } } private class LocalBinder : Binder() }
mit
04dd80fc9f7844908787b6fdeb4234e0
33.744681
112
0.695346
5.516892
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/views/richtext/RichText.kt
1
9294
package com.orgzly.android.ui.views.richtext import android.content.Context import android.content.res.TypedArray import android.graphics.Typeface import android.text.InputType import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextUtils import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.View import android.widget.FrameLayout import android.widget.TextView import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.ui.ImageLoader import com.orgzly.android.ui.main.MainActivity import com.orgzly.android.ui.util.styledAttributes import com.orgzly.android.ui.views.style.CheckboxSpan import com.orgzly.android.ui.views.style.DrawerMarkerSpan import com.orgzly.android.ui.views.style.DrawerSpan import com.orgzly.android.util.LogUtils import com.orgzly.android.util.OrgFormatter class RichText(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs), ActionableRichTextView { fun interface OnUserTextChangeListener { fun onUserTextChange(str: String) } data class Listeners( var onUserTextChange: OnUserTextChangeListener? = null) private val listeners = Listeners() fun setOnUserTextChangeListener(listener: OnUserTextChangeListener) { listeners.onUserTextChange = listener } private val sourceBackgroundColor: Int by lazy { context.styledAttributes(intArrayOf(R.attr.colorSecondaryContainer)) { typedArray -> typedArray.getColor(0, 0) } } data class Attributes( val viewId: Int = 0, val editId: Int = 0, val parseCheckboxes: Boolean = true, val linkify: Boolean = true, val editable: Boolean = true, val inputType: Int = InputType.TYPE_NULL, val imeOptions: Int = 0, val hint: String? = null, val textSize: Int = 0, val paddingHorizontal: Int = 0, val paddingVertical: Int = 0 ) private lateinit var attributes: Attributes private val richTextEdit: RichTextEdit private val richTextView: RichTextView init { parseAttrs(attrs) inflate(getContext(), R.layout.rich_text, this) richTextEdit = findViewById(R.id.rich_text_edit) richTextView = findViewById(R.id.rich_text_view) // TODO: if editable richTextEdit.apply { if (attributes.editId != 0) { id = attributes.editId } setCommonAttributes(this) inputType = attributes.inputType imeOptions = attributes.imeOptions // Wrap lines when editing. Doesn't work when set in XML? setHorizontallyScrolling(false) maxLines = Integer.MAX_VALUE if (AppPreferences.highlightEditedRichText(context)) { setBackgroundColor(sourceBackgroundColor) } else { setBackgroundColor(0) } // If RichTextEdit loses the focus, switch to view mode setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) { toViewMode(true) } } } richTextView.apply { if (attributes.viewId != 0) { id = attributes.viewId } setCommonAttributes(this) if (attributes.editable) { setTextIsSelectable(true) } setOnTapUpListener { _, _, charOffset -> if (attributes.editable) { toEditMode(charOffset) } } setOnActionListener(this@RichText) } } private fun parseAttrs(attrs: AttributeSet?) { if (attrs != null) { context.styledAttributes(attrs, R.styleable.RichText) { typedArray -> readAttributes(typedArray) } } } private fun readAttributes(typedArray: TypedArray) { typedArray.run { attributes = Attributes( getResourceId(R.styleable.RichText_view_id, 0), getResourceId(R.styleable.RichText_edit_id, 0), getBoolean(R.styleable.RichText_parse_checkboxes, true), getBoolean(R.styleable.RichText_linkify, true), getBoolean(R.styleable.RichText_editable, true), getInteger(R.styleable.RichText_android_inputType, InputType.TYPE_NULL), getInteger(R.styleable.RichText_android_imeOptions, 0), getString(R.styleable.RichText_android_hint), getDimensionPixelSize(R.styleable.RichText_android_textSize, 0), getDimensionPixelSize(R.styleable.RichText_paddingHorizontal, 0), getDimensionPixelSize(R.styleable.RichText_paddingVertical, 0), ) } } private fun setCommonAttributes(view: TextView) { view.hint = attributes.hint if (attributes.textSize > 0) { view.setTextSize(TypedValue.COMPLEX_UNIT_PX, attributes.textSize.toFloat()) } if (attributes.paddingHorizontal > 0 || attributes.paddingVertical > 0) { view.setPadding( attributes.paddingHorizontal, attributes.paddingVertical, attributes.paddingHorizontal, attributes.paddingVertical) } } fun setSourceText(text: CharSequence?) { richTextEdit.setText(text) if (richTextView.visibility == View.VISIBLE) { parseAndSetViewText() } } fun getSourceText(): CharSequence? { return richTextEdit.text } fun setVisibleText(text: CharSequence) { richTextView.text = text } fun toEditMode(charOffset: Int) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "editable:${attributes.editable}", charOffset) richTextEdit.activate(charOffset) richTextView.deactivate() } private fun toViewMode(reparseSource: Boolean = false) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "reparseSource:$reparseSource") if (reparseSource) { parseAndSetViewText() } richTextView.activate() richTextEdit.deactivate() } private fun parseAndSetViewText() { val source = richTextEdit.text if (source != null) { val parsed = OrgFormatter.parse( source, context, attributes.linkify, attributes.parseCheckboxes) richTextView.setText(parsed, TextView.BufferType.SPANNABLE) ImageLoader.loadImages(richTextView) } else { richTextView.text = null } } fun setTypeface(typeface: Typeface) { richTextView.typeface = typeface richTextEdit.typeface = typeface } fun setMaxLines(lines: Int) { if (lines < Integer.MAX_VALUE) { richTextView.maxLines = lines richTextView.ellipsize = TextUtils.TruncateAt.END } else { richTextView.maxLines = Integer.MAX_VALUE richTextView.ellipsize = null } } fun setOnEditorActionListener(any: TextView.OnEditorActionListener) { richTextEdit.setOnEditorActionListener(any) } override fun toggleDrawer(markerSpan: DrawerMarkerSpan) { val textSpanned = richTextView.text as Spanned // Find a drawer at the place of the clicked span val pos = textSpanned.getSpanStart(markerSpan) val drawerSpan = textSpanned.getSpans(pos, pos, DrawerSpan::class.java).firstOrNull() if (drawerSpan == null) { Log.w(TAG, "No DrawerSpan found at the place of $markerSpan ($pos)") return } val drawerStart = textSpanned.getSpanStart(drawerSpan) val drawerEnd = textSpanned.getSpanEnd(drawerSpan) val builder = SpannableStringBuilder(textSpanned) val replacement = OrgFormatter.drawerSpanned( drawerSpan.name, drawerSpan.content, isFolded = !drawerSpan.isFolded) builder.removeSpan(drawerSpan) builder.removeSpan(markerSpan) builder.replace(drawerStart, drawerEnd, replacement) richTextView.text = builder } override fun toggleCheckbox(checkboxSpan: CheckboxSpan) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, checkboxSpan) val content = if (checkboxSpan.isChecked()) "[ ]" else "[X]" val replacement = OrgFormatter.checkboxSpanned( content, checkboxSpan.rawStart, checkboxSpan.rawEnd) val newSource = richTextEdit.text ?.replaceRange(checkboxSpan.rawStart, checkboxSpan.rawEnd, replacement) ?.toString() .orEmpty() listeners.onUserTextChange?.onUserTextChange(newSource) } // TODO: Consider getting MainActivity's *ViewModel* here instead override fun followLinkToNoteWithProperty(name: String, value: String) { MainActivity.followLinkToNoteWithProperty(name, value) } override fun followLinkToFile(path: String) { MainActivity.followLinkToFile(path) } companion object { val TAG: String = RichText::class.java.name } }
gpl-3.0
6fb29fd1dd7546b11a567e6588b254f0
30.723549
97
0.638692
4.920064
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/locations/ReverseGeocoder.kt
1
5520
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.locations import android.content.Context import android.location.Geocoder import androidx.annotation.WorkerThread import com.mapbox.mapboxsdk.geometry.LatLng import de.grobox.transportr.utils.hasLocation import de.schildbach.pte.dto.Location import de.schildbach.pte.dto.LocationType.ADDRESS import de.schildbach.pte.dto.Point import okhttp3.* import org.json.JSONException import org.json.JSONObject import java.io.IOException import java.util.* import kotlin.concurrent.thread class ReverseGeocoder(private val context: Context, private val callback: ReverseGeocoderCallback) { fun findLocation(location: Location) { if (!location.hasLocation()) return findLocation(location.latAsDouble, location.lonAsDouble) } fun findLocation(location: android.location.Location) { if (location.latitude == 0.0 && location.latitude == 0.0) return findLocation(location.latitude, location.longitude) } private fun findLocation(lat: Double, lon: Double) { if (Geocoder.isPresent()) { findLocationWithGeocoder(lat, lon) } else { findLocationWithOsm(lat, lon) } } private fun findLocationWithGeocoder(lat: Double, lon: Double) { thread(start = true) { try { val geoCoder = Geocoder(context, Locale.getDefault()) val addresses = geoCoder.getFromLocation(lat, lon, 1) if (addresses == null || addresses.size == 0) throw IOException("No results") val address = addresses[0] var name: String? = address.thoroughfare ?: throw IOException("Empty Address") if (address.featureName != null) name += " " + address.featureName val place = address.locality val point = Point.fromDouble(lat, lon) val l = Location(ADDRESS, null, point, place, name) callback.onLocationRetrieved(WrapLocation(l)) } catch (e: IOException) { if (e.message != "Service not Available") { e.printStackTrace() } findLocationWithOsm(lat, lon) } } } private fun findLocationWithOsm(lat: Double, lon: Double) { val client = OkHttpClient() // https://nominatim.openstreetmap.org/reverse?lat=52.5217&lon=13.4324&format=json val url = StringBuilder("https://nominatim.openstreetmap.org/reverse?") url.append("lat=").append(lat).append("&") url.append("lon=").append(lon).append("&") url.append("format=json") val request = Request.Builder() .header("User-Agent", "Transportr (https://transportr.app)") .url(url.toString()) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() callback.onLocationRetrieved(getWrapLocation(lat, lon)) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val body = response.body() if (!response.isSuccessful || body == null) { callback.onLocationRetrieved(getWrapLocation(lat, lon)) return } val result = body.string() body.close() try { val data = JSONObject(result) val address = data.getJSONObject("address") var name = address.optString("road") if (name.isNotEmpty()) { val number = address.optString("house_number") if (number.isNotEmpty()) name += " $number" } else { name = data.getString("display_name").split(",")[0] } var place = address.optString("city") if (place.isEmpty()) place = address.optString("state") val point = Point.fromDouble(lat, lon) val l = Location(ADDRESS, null, point, place, name) callback.onLocationRetrieved(WrapLocation(l)) } catch (e: JSONException) { callback.onLocationRetrieved(getWrapLocation(lat, lon)) throw IOException(e) } } }) } private fun getWrapLocation(lat: Double, lon: Double): WrapLocation { return WrapLocation(LatLng(lat, lon)) } interface ReverseGeocoderCallback { @WorkerThread fun onLocationRetrieved(location: WrapLocation) } }
gpl-3.0
4e7316b0a7a0387b62a21d78558bcfc2
36.04698
100
0.594565
4.766839
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/compat/jei/fluxgen/FluxGenRecipeMaker.kt
1
1295
package szewek.mcflux.compat.jei.fluxgen import mezz.jei.api.IGuiHelper import mezz.jei.api.IJeiHelpers import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidStack import szewek.mcflux.recipes.FluxGenRecipes import szewek.mcflux.recipes.RecipeFluxGen import java.util.* object FluxGenRecipeMaker { fun getFluxGenRecipes(hlp: IJeiHelpers): List<FluxGenRecipeJEI> { val igh = hlp.guiHelper val catalysts = FluxGenRecipes.catalysts val hotFluids = FluxGenRecipes.hotFluids val cleanFluids = FluxGenRecipes.cleanFluids val recipes = ArrayList<FluxGenRecipeJEI>(catalysts.size + hotFluids.size + cleanFluids.size) for (e in catalysts.entries) { val ri = e.key val rfg = e.value val stk = ri.makeItemStack() if (rfg.usage > 0) stk.count = rfg.usage.toInt() recipes.add(FluxGenRecipeJEI(igh, stk, null, rfg.factor.toInt(), 1)) } addFluids(igh, recipes, hotFluids, 0) addFluids(igh, recipes, cleanFluids, 1) return recipes } private fun addFluids(igh: IGuiHelper, l: MutableList<FluxGenRecipeJEI>, m: Map<FluidStack, RecipeFluxGen>, s: Int) { for ((key, rfg) in m) { val fs = key.copy() fs.amount = (if (rfg.usage > 0) rfg.usage else 1).toInt() l.add(FluxGenRecipeJEI(igh, ItemStack.EMPTY, fs, rfg.factor.toInt(), s)) } } }
mit
16bc5b558cd8ba2aa9149aace308706c
33.078947
118
0.738224
3.150852
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/codegen/GradleApiExtensionsTest.kt
2
20285
/* * Copyright 2018 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.gradle.kotlin.dsl.codegen import com.nhaarman.mockito_kotlin.atMost import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import org.gradle.api.internal.file.pattern.PatternMatcher import org.gradle.api.internal.file.temp.DefaultTemporaryFileProvider import org.gradle.internal.hash.Hashing import org.gradle.kotlin.dsl.accessors.TestWithClassPath import org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType import org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.slf4j.Logger import java.io.File import java.util.Properties import java.util.function.Consumer import java.util.jar.Attributes import java.util.jar.JarEntry import java.util.jar.JarOutputStream import java.util.jar.Manifest import kotlin.reflect.KClass @LeaksFileHandles("embedded Kotlin compiler environment keepalive") class GradleApiExtensionsTest : TestWithClassPath() { @Test fun `gradle-api-extensions generated jar is reproducible`() { apiKotlinExtensionsGenerationFor( ClassToKClass::class, ClassToKClassParameterizedType::class, GroovyNamedArguments::class, ClassAndGroovyNamedArguments::class ) { assertGeneratedJarHash("6236f057767b0bf27131a299c9128997") } } @Test fun `maps java-lang-Class to kotlin-reflect-KClass`() { apiKotlinExtensionsGenerationFor(ClassToKClass::class) { assertGeneratedExtensions( """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`rawClass`(`type`: kotlin.reflect.KClass<*>): Unit = `rawClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`unknownClass`(`type`: kotlin.reflect.KClass<*>): Unit = `unknownClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`invariantClass`(`type`: kotlin.reflect.KClass<kotlin.Number>): Unit = `invariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantClass`(`type`: kotlin.reflect.KClass<out kotlin.Number>): Unit = `covariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`contravariantClass`(`type`: kotlin.reflect.KClass<in Int>): Unit = `contravariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`varargOfClasses`(vararg `types`: kotlin.reflect.KClass<*>): Unit = `varargOfClasses`(*`types`.map { it.java }.toTypedArray()) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`arrayOfClasses`(`types`: kotlin.Array<kotlin.reflect.KClass<*>>): Unit = `arrayOfClasses`(`types`.map { it.java }.toTypedArray()) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`collectionOfClasses`(`types`: kotlin.collections.Collection<kotlin.reflect.KClass<out kotlin.Number>>): Unit = `collectionOfClasses`(`types`.map { it.java }) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T = `methodParameterizedClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T = `covariantMethodParameterizedClass`(`type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T = `methodParameterizedCovariantClass`(`type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T = `methodParameterizedContravariantClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T = `covariantMethodParameterizedCovariantClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T = `covariantMethodParameterizedContravariantClass`(`type`.java) """ ) assertUsageCompilation( """ import kotlin.reflect.* fun classToKClass(subject: ClassToKClass) { subject.rawClass(type = String::class) subject.unknownClass(type = String::class) subject.invariantClass(type = Number::class) subject.covariantClass(type = Int::class) subject.contravariantClass(type = Number::class) subject.varargOfClasses(Number::class, Int::class) subject.arrayOfClasses(types = arrayOf(Number::class, Int::class)) subject.collectionOfClasses(listOf(Number::class, Int::class)) subject.methodParameterizedClass(type = Int::class) subject.covariantMethodParameterizedClass(type = Int::class) subject.methodParameterizedCovariantClass(type = Int::class) subject.methodParameterizedContravariantClass(type = Int::class) subject.covariantMethodParameterizedCovariantClass(type = Int::class) subject.covariantMethodParameterizedContravariantClass(type = Int::class) } """ ) } } @Test fun `maps Groovy named arguments to Kotlin vararg of Pair`() { apiKotlinExtensionsGenerationFor(GroovyNamedArguments::class, Consumer::class) { assertGeneratedExtensions( """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`rawMap`(vararg `args`: Pair<String, Any?>): Unit = `rawMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringUnknownMap`(vararg `args`: Pair<String, Any?>): Unit = `stringUnknownMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringObjectMap`(vararg `args`: Pair<String, Any?>): Unit = `stringObjectMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithOtherParameters`(`foo`: String, `bar`: Int, vararg `args`: Pair<String, Any?>): Unit = `mapWithOtherParameters`(mapOf(*`args`), `foo`, `bar`) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithLastSamAndOtherParameters`(`foo`: String, vararg `args`: Pair<String, Any?>, `bar`: java.util.function.Consumer<String>): Unit = `mapWithLastSamAndOtherParameters`(mapOf(*`args`), `foo`, `bar`) """ ) assertUsageCompilation( """ import java.util.function.Consumer fun usage(subject: GroovyNamedArguments) { subject.rawMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.stringUnknownMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.stringObjectMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.mapWithOtherParameters(foo = "foo", bar = 42) subject.mapWithOtherParameters("foo", 42, "bar" to 23L, "bazar" to "cathedral") subject.mapWithLastSamAndOtherParameters(foo = "foo") { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters("foo", "bar" to 23L, "bazar" to "cathedral") { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters("foo", *arrayOf("bar" to 23L, "bazar" to "cathedral")) { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer { println(it.toUpperCase()) }) subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer<String> { println(it.toUpperCase()) }) } """ ) } } @Test fun `maps mixed java-lang-Class and Groovy named arguments`() { apiKotlinExtensionsGenerationFor(ClassAndGroovyNamedArguments::class, Consumer::class) { assertGeneratedExtensions( """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClass`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>): Unit = `mapAndClass`(mapOf(*`args`), `type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndVarargs`(`type`: kotlin.reflect.KClass<out T>, `options`: kotlin.Array<String>, vararg `args`: Pair<String, Any?>): Unit = `mapAndClassAndVarargs`(mapOf(*`args`), `type`.java, *`options`) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndSAM`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>, `action`: java.util.function.Consumer<in T>): Unit = `mapAndClassAndSAM`(mapOf(*`args`), `type`.java, `action`) """ ) assertUsageCompilation( """ import java.util.function.Consumer fun usage(subject: ClassAndGroovyNamedArguments) { subject.mapAndClass<Number>(Int::class) subject.mapAndClass<Number>(Int::class, "foo" to 42, "bar" to "bazar") subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar")) subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar"), "bazar" to "cathedral") } """ ) } } @Test fun `maps target type, mapped function and parameters generics`() { apiKotlinExtensionsGenerationFor(ClassToKClassParameterizedType::class) { assertGeneratedExtensions( """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`invariantClass`(`type`: kotlin.reflect.KClass<T>, `list`: kotlin.collections.List<T>): T = `invariantClass`(`type`.java, `list`) """, """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantClass`(`type`: kotlin.reflect.KClass<out T>, `list`: kotlin.collections.List<T>): T = `covariantClass`(`type`.java, `list`) """, """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`contravariantClass`(`type`: kotlin.reflect.KClass<in T>, `list`: kotlin.collections.List<T>): T = `contravariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedInvariantClass`(`type`: kotlin.reflect.KClass<V>, `list`: kotlin.collections.List<V>): V = `covariantMethodParameterizedInvariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out V>, `list`: kotlin.collections.List<out V>): V = `covariantMethodParameterizedCovariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in V>, `list`: kotlin.collections.List<out V>): V = `covariantMethodParameterizedContravariantClass`(`type`.java, `list`) """ ) assertUsageCompilation( """ import java.io.Serializable fun usage(subject: ClassToKClassParameterizedType<Number>) { subject.invariantClass(Number::class, emptyList()) subject.covariantClass(Int::class, emptyList()) subject.contravariantClass(Serializable::class, emptyList()) subject.covariantMethodParameterizedInvariantClass(Number::class, emptyList()) subject.covariantMethodParameterizedCovariantClass(Int::class, emptyList()) subject.covariantMethodParameterizedContravariantClass(Serializable::class, emptyList()) } """ ) } } private fun apiKotlinExtensionsGenerationFor(vararg classes: KClass<*>, action: ApiKotlinExtensionsGeneration.() -> Unit) = ApiKotlinExtensionsGeneration(apiJarsWith(*classes), fixturesApiMetadataJar()).apply(action) private data class ApiKotlinExtensionsGeneration(val apiJars: List<File>, val apiMetadataJar: File) { lateinit var generatedSourceFiles: List<File> } private fun ApiKotlinExtensionsGeneration.assertGeneratedExtensions(vararg expectedExtensions: String) { generatedSourceFiles = generateKotlinDslApiExtensionsSourceTo( file("src").also { it.mkdirs() }, "org.gradle.kotlin.dsl", "SourceBaseName", apiJars, emptyList(), PatternMatcher.MATCH_ALL, fixtureParameterNamesSupplier ) val generatedSourceCode = generatedSourceFiles.joinToString("") { it.readText().substringAfter("package org.gradle.kotlin.dsl\n\n") } println(generatedSourceCode) expectedExtensions.forEach { expectedExtension -> assertThat(generatedSourceCode, containsString(expectedExtension.trimIndent())) } } private fun ApiKotlinExtensionsGeneration.assertUsageCompilation(vararg extensionsUsages: String) { val useDir = file("use").also { it.mkdirs() } val usageFiles = extensionsUsages.mapIndexed { idx, usage -> useDir.resolve("usage$idx.kt").also { it.writeText( """ import org.gradle.kotlin.dsl.fixtures.codegen.* import org.gradle.kotlin.dsl.* $usage """.trimIndent() ) } } val logger = mock<Logger> { on { isTraceEnabled } doReturn false on { isDebugEnabled } doReturn false } compileKotlinApiExtensionsTo( file("out").also { it.mkdirs() }, generatedSourceFiles + usageFiles, apiJars, logger ) // Assert no warnings were emitted verify(logger, atMost(1)).isTraceEnabled verify(logger, atMost(1)).isDebugEnabled verifyNoMoreInteractions(logger) } private fun GradleApiExtensionsTest.ApiKotlinExtensionsGeneration.assertGeneratedJarHash(hash: String) = file("api-extensions.jar").let { generatedJar -> generateApiExtensionsJar( DefaultTemporaryFileProvider { newFolder("tmp") }, generatedJar, apiJars, apiMetadataJar ) {} assertThat( Hashing.md5().hashFile(generatedJar).toZeroPaddedString(32), equalTo(hash) ) } private fun apiJarsWith(vararg classes: KClass<*>): List<File> = jarClassPathWith("gradle-api.jar", *classes, org.gradle.api.Generated::class).asFiles private fun fixturesApiMetadataJar(): File = file("gradle-api-metadata.jar").also { file -> JarOutputStream( file.outputStream().buffered(), Manifest().apply { mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" } ).use { output -> output.putNextEntry(JarEntry("gradle-api-declaration.properties")) Properties().apply { setProperty("includes", "org/gradle/kotlin/dsl/fixtures/codegen/**") setProperty("excludes", "**/internal/**") store(output, null) } } } } private val fixtureParameterNamesSupplier = { key: String -> when { key.startsWith("${ClassToKClass::class.qualifiedName}.") -> when { key.contains("Class(") -> listOf("type") key.contains("Classes(") -> listOf("types") else -> null } key.startsWith("${GroovyNamedArguments::class.qualifiedName}.") -> when { key.contains("Map(") -> listOf("args") key.contains("Parameters(") -> listOf("args", "foo", "bar") else -> null } key.startsWith("${ClassAndGroovyNamedArguments::class.qualifiedName}.") -> when { key.contains("mapAndClass(") -> listOf("args", "type") key.contains("mapAndClassAndVarargs(") -> listOf("args", "type", "options") key.contains("mapAndClassAndSAM(") -> listOf("args", "type", "action") else -> null } key.startsWith("${ClassToKClassParameterizedType::class.qualifiedName}.") -> when { key.contains("Class(") -> listOf("type", "list") else -> null } else -> null } }
apache-2.0
850b4a9fa7f79a099714a895ea2cc4a0
46.729412
264
0.59931
5.207959
false
false
false
false
jayrave/falkon
falkon-engine-android-sqlite/src/main/kotlin/com/jayrave/falkon/engine/android/sqlite/CompiledQuery.kt
1
3013
package com.jayrave.falkon.engine.android.sqlite import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteDatabase import com.jayrave.falkon.engine.CompiledStatement import com.jayrave.falkon.engine.Source import com.jayrave.falkon.engine.Type import java.sql.SQLException import java.util.* /** * This isn't actually a compiled statement as there is no way (that Jay could find) in Android * to compile a SELECT statement!! This class just stores the sql & the bind args, and when * [execute] is called, send them off to the database * * *CAUTION: * This class is not thread-safe */ internal class CompiledQuery(override val sql: String, private val database: SupportSQLiteDatabase) : CompiledStatement<Source> { private var bindArgs: MutableMap<Int, Any?> = newArgsMap() override var isClosed = false private set override fun execute(): Source { throwIfClosed() return CursorBackedSource(database.query( SimpleSQLiteQuery( sql, Array<Any?>(bindArgs.size) { null }.also { arr -> bindArgs.forEach { (index, value) -> arr[index - 1] = value } } ) )) } override fun bindShort(index: Int, value: Short): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindInt(index: Int, value: Int): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindLong(index: Int, value: Long): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindFloat(index: Int, value: Float): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindDouble(index: Int, value: Double): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindString(index: Int, value: String): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindBlob(index: Int, value: ByteArray): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindNull(index: Int, type: Type): CompiledStatement<Source> { bindArg(index, null) return this } override fun close() { isClosed = true } override fun clearBindings(): CompiledStatement<Source> { throwIfClosed() bindArgs = newArgsMap() return this } private fun bindArg(index: Int, value: Any?) { throwIfClosed() bindArgs.put(index, value) } private fun throwIfClosed() { if (isClosed) { throw SQLException("CompiledQuery has already been closed!!") } } companion object { private fun newArgsMap(): MutableMap<Int, Any?> = HashMap() } }
apache-2.0
52493d119800ab323bf8f2b38dd11296
27.980769
101
0.617325
4.700468
false
false
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionModifierListDemo.kt
2
15640
/* * 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. */ @file:OptIn(ExperimentalCoilApi::class, ExperimentalComposeUiApi::class) package com.example.constraintlayout import android.content.ContentResolver import android.content.Context import android.net.Uri import androidx.annotation.DrawableRes import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.Placeable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.constraintlayout.compose.ConstrainScope import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import androidx.constraintlayout.compose.Motion import androidx.constraintlayout.compose.layoutId import androidx.constraintlayout.compose.rememberMotionListItems import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import coil.request.ImageRequest import kotlin.math.roundToInt private val ItemHeight = 100.dp @Preview @Composable private fun ExpandableListPreview() { val durationMs = 800 val itemsData = createItemDataList(count = 10) /** * ConstraintLayout when collapsed, Column when expanded */ var collapsedOrExpanded by remember { mutableStateOf(true) } /** * Define the items that'll be present both in ConstraintLayout and Column, since the parent * node will change from one to the other we need to use [rememberMotionListItems]. */ val items = rememberMotionListItems(count = itemsData.size) { index -> CartItem( modifier = Modifier // In this case, these Dimensions do not cause conflict with ConstraintLayout .fillMaxWidth() .height(ItemHeight) .layoutId(index.toString()) // For ConstraintLayout // ignoreAxisChanges prevents animation from triggering during scroll .motion(animationSpec = tween(durationMs), ignoreAxisChanges = true) { // We may apply keyframes to modify the items during animation keyAttributes { frame(50) { scaleX = 0.7f scaleY = 0.7f } } } .zIndex((itemsData.size - index).toFloat()), item = itemsData[index] ) } Column( Modifier .fillMaxSize() .background(Color.LightGray) .verticalScroll(rememberScrollState()) ) { Column( Modifier .fillMaxWidth() ) { // Motion Composable enables the `motion` Modifier. Motion( modifier = Modifier .fillMaxWidth() .background(Color.Gray) .padding(bottom = 8.dp) .animateContentSize(tween(durationMs)) // Match the animated content ) { // Here we'll change the Layout Composable for our items based on the // `collapsedOrExpanded` state, we may use the `emit` extension function to // simplify it. if (collapsedOrExpanded) { CollapsedCartList( modifier = Modifier .fillMaxWidth(), dataSize = items.size ) { items.emit() } } else { Column( modifier = Modifier .fillMaxWidth() .padding(8.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { items.emit() } } } } Text(text = "Layout: " + if (collapsedOrExpanded) "ConstraintLayout" else "Column") Button(onClick = { collapsedOrExpanded = !collapsedOrExpanded }) { Text(text = "Toggle") } } } /** * Collapsed view using ConstraintLayout, will layout the first three items one below the other, all * other items will be stacked under each other. * * The content most have their [Modifier.layoutId] assigned from 0 to [dataSize] - 1. * * @see CollapsedCartListPreview */ @Composable private fun CollapsedCartList( modifier: Modifier = Modifier, dataSize: Int, content: @Composable () -> Unit ) { val itemIds: List<Int> = remember { List(dataSize) { index -> index } } val cSet = remember { val applyDimensions: ConstrainScope.() -> Unit = { width = Dimension.fillToConstraints height = Dimension.value(ItemHeight) } ConstraintSet { val itemRefsById = itemIds.associateWith { createRefFor(it.toString()) } itemRefsById.forEach { (id, ref) -> when (id) { 0, 1, 2 -> { // Stack the first three items below each other constrain(ref) { val lastRef = itemRefsById[id - 1] ?: parent applyDimensions() start.linkTo(lastRef.start, 8.dp) end.linkTo(lastRef.end, 8.dp) top.linkTo(lastRef.top, 16.dp) translationZ = (6 - (2 * id)).coerceAtLeast(0).dp } } else -> { // Stack/hide together all other items if (id > 0) { val lastRef = itemRefsById[2]!! constrain(ref) { applyDimensions() centerTo(lastRef) } } } } } } } ConstraintLayout( modifier = modifier, constraintSet = cSet ) { content() } } /** * Non-ConstraintLayout variant of [CollapsedCartList]. */ @Composable private fun CollapsedCartListCustom( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { val density = LocalDensity.current Layout( measurePolicy = remember { MeasurePolicy { measurables, constraints -> var count = 2 val placeables = mutableListOf<Placeable>() var maxWidth = constraints.maxWidth var itemsToWrap = 0 measurables.forEach { measurable -> if (count-- >= 0) { itemsToWrap++ maxWidth -= with(density) { 16.dp.toPx() }.roundToInt() placeables.add( measurable.measure( Constraints.fixed( maxWidth, with(density) { 100.dp.toPx() }.roundToInt() ) ) ) } else { placeables.add( measurable.measure( Constraints.fixed( maxWidth, with(density) { 100.dp.toPx() }.roundToInt() ) ) ) } } layout( width = constraints.maxWidth, height = with(density) { itemsToWrap * 16.dp.roundToPx() + 100.dp.roundToPx() } ) { count = 2 var x = 0 var y = 0 placeables.forEach { placeable -> if (count-- >= 0) { x += with(density) { 8.dp.roundToPx() } y += with(density) { 16.dp.roundToPx() } placeable.place(x, y, (count + 1).times(2).toFloat()) } else { placeable.place(x, y, 0f) } } } } }, modifier = modifier, content = content ) } @Composable private fun CartItem(modifier: Modifier = Modifier, item: ItemData) { ConstraintLayout( modifier = modifier .background(color = Color.White, shape = RoundedCornerShape(10.dp)) .padding(8.dp), constraintSet = remember { ConstraintSet { val image = createRefFor("image") val name = createRefFor("name") val id = createRefFor("id") val cost = createRefFor("cost") constrain(image) { width = Dimension.ratio("1:1") height = Dimension.fillToConstraints top.linkTo(parent.top) bottom.linkTo(parent.bottom) start.linkTo(parent.start) } constrain(cost) { end.linkTo(parent.end) bottom.linkTo(parent.bottom) } constrain(name) { width = Dimension.fillToConstraints start.linkTo(image.end, 8.dp) end.linkTo(cost.start, 8.dp) baseline.linkTo(cost.baseline) } constrain(id) { top.linkTo(parent.top) end.linkTo(parent.end) } } } ) { Image( modifier = Modifier .layoutId("image") .clip(RoundedCornerShape(10.dp)), painter = rememberImagePainter( request = ImageRequest.Builder(LocalContext.current) .data(item.thumbnailUri) .placeholder(R.drawable.pepper) .build() ), contentDescription = null ) Text(modifier = Modifier.layoutId("name"), text = item.name) Text(modifier = Modifier.layoutId("cost"), text = "$${item.cost}") Text(modifier = Modifier.layoutId("id"), text = item.id.toString()) } } @Stable private data class ItemData( val id: Int, val thumbnailUri: Uri, val name: String, val cost: Float ) /** * Returns a list of [ItemData] objects with randomly populated values. * * @param count amount of [ItemData] generated */ @Composable private fun createItemDataList(count: Int): List<ItemData> { val context = LocalContext.current return remember(count) { List(count) { index -> ItemData( id = index, thumbnailUri = context.drawableUri(R.drawable.pepper), name = itemNames.random(), cost = IntRange(5, 50).random().toFloat() + (IntRange(0, 99).random() / 100f) ) } } } @Preview @Composable private fun CollapsedCartListPreview() { val itemsData = createItemDataList(count = 5) Column(Modifier.fillMaxWidth()) { Column(Modifier.background(Color.LightGray)) { Text(text = "ConstraintLayout") CollapsedCartList( modifier = Modifier.fillMaxWidth(), dataSize = itemsData.size ) { itemsData.forEachIndexed { index, itemData -> CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp) .layoutId(index.toString()), item = itemData ) } } } Column(Modifier.background(Color.Gray)) { Text(text = "Custom Layout") CollapsedCartListCustom(modifier = Modifier.fillMaxWidth()) { itemsData.forEachIndexed { _, itemData -> CartItem(item = itemData) } } } } } @Preview @Composable private fun ExpandedCartListPreview() { val itemsData = createItemDataList(count = 5) Column( modifier = Modifier .fillMaxSize() .background(Color.LightGray), verticalArrangement = Arrangement.spacedBy(16.dp) ) { itemsData.forEach { CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp), item = it ) } } } @Preview @Composable private fun CartItemPreview() { CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp), item = ItemData( id = 0, thumbnailUri = LocalContext.current.drawableUri(R.drawable.pepper), name = "Pepper", cost = 5.56f ) ) } internal fun Context.drawableUri(@DrawableRes resourceId: Int): Uri = with(resources) { Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getResourcePackageName(resourceId)) .appendPath(getResourceTypeName(resourceId)) .appendPath(getResourceEntryName(resourceId)) .build() } private val itemNames = listOf( "Fruit", "Vegetables", "Bread", "Pet Food", "Cereal", "Milk", "Eggs", "Yogurt" )
apache-2.0
3f2472b300963b9e05b82130d6586508
33.835189
100
0.540857
5.289144
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/data/netease/result/UserDetailResultBean.kt
1
6523
package tech.summerly.quiet.data.netease.result import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/25 * desc : */ data class UserDetailResultBean( @SerializedName("profile") @Expose val profile: Profile? = null, @SerializedName("level") @Expose val level: Int? = null, @SerializedName("listenSongs") @Expose val listenSongs: Long? = null, @SerializedName("userPoint") @Expose val userPoint: UserPoint? = null, // @SerializedName("mobileSign") // @Expose // val mobileSign: Boolean? = null, // @SerializedName("pcSign") // @Expose // val pcSign: Boolean? = null, // @SerializedName("peopleCanSeeMyPlayRecord") // @Expose // val peopleCanSeeMyPlayRecord: Boolean? = null, // @SerializedName("bindings") // @Expose // val bindings: List<Binding>? = null, @SerializedName("adValid") @Expose val adValid: Boolean? = null, @SerializedName("code") @Expose val code: Long, @SerializedName("createDays") @Expose val createDays: Long? = null ) { data class Profile( @SerializedName("userId") @Expose val userId: Long? = null, @SerializedName("nickname") @Expose val nickname: String? = null, @SerializedName("avatarUrl") @Expose val avatarUrl: String? = null, @SerializedName("backgroundUrl") @Expose val backgroundUrl: String? = null, @SerializedName("playlistCount") @Expose val playlistCount: Long? = null // @SerializedName("followed") // @Expose // val followed: Boolean? = null, // @SerializedName("djStatus") // @Expose // val djStatus: Long? = null, // @SerializedName("detailDescription") // @Expose // val detailDescription: String? = null, // @SerializedName("avatarImgIdStr") // @Expose // val avatarImgIdStr: String? = null, // @SerializedName("backgroundImgIdStr") // @Expose // val backgroundImgIdStr: String? = null, // @SerializedName("description") // @Expose // val description: String? = null, // @SerializedName("accountStatus") // @Expose // val accountStatus: Long? = null, // @SerializedName("province") // @Expose // val province: Long? = null, // @SerializedName("defaultAvatar") // @Expose // val defaultAvatar: Boolean? = null, // @SerializedName("gender") // @Expose // val gender: Long? = null, // @SerializedName("birthday") // @Expose // val birthday: Long? = null, // @SerializedName("city") // @Expose // val city: Long? = null, // @SerializedName("mutual") // @Expose // val mutual: Boolean? = null, // @SerializedName("remarkName") // @Expose // val remarkName: Any? = null, // @SerializedName("experts") // @Expose // val experts: Experts? = null, // @SerializedName("avatarImgId") // @Expose // val avatarImgId: Long? = null, // @SerializedName("backgroundImgId") // @Expose // val backgroundImgId: Long? = null, // @SerializedName("expertTags") // @Expose // val expertTags: Any? = null, // @SerializedName("vipType") // @Expose // val vipType: Long? = null, // @SerializedName("userType") // @Expose // val userType: Long? = null, // @SerializedName("authStatus") // @Expose // val authStatus: Long? = null, // @SerializedName("signature") // @Expose // val signature: String? = null, // @SerializedName("authority") // @Expose // val authority: Long? = null, // @SerializedName("followeds") // @Expose // val followeds: Long? = null, // @SerializedName("follows") // @Expose // val follows: Long? = null, // @SerializedName("blacklist") // @Expose // val blacklist: Boolean? = null, // @SerializedName("eventCount") // @Expose // val eventCount: Long? = null, // @SerializedName("playlistBeSubscribedCount") // @Expose // val playlistBeSubscribedCount: Long? = null ) // data class Binding( // // @SerializedName("expiresIn") // @Expose // val expiresIn: Long? = null, // @SerializedName("refreshTime") // @Expose // val refreshTime: Long? = null, // @SerializedName("userId") // @Expose // val userId: Long? = null, // @SerializedName("tokenJsonStr") // @Expose // val tokenJsonStr: String? = null, // @SerializedName("url") // @Expose // val url: String? = null, // @SerializedName("expired") // @Expose // val expired: Boolean? = null, // @SerializedName("id") // @Expose // val id: Long? = null, // @SerializedName("type") // @Expose // val type: Long? = null // ) data class UserPoint( @SerializedName("userId") @Expose val userId: Long? = null, @SerializedName("balance") @Expose val balance: Long? = null, @SerializedName("updateTime") @Expose val updateTime: Long? = null, @SerializedName("version") @Expose val version: Long? = null, @SerializedName("status") @Expose val status: Long? = null, @SerializedName("blockBalance") @Expose val blockBalance: Long? = null ) }
gpl-2.0
3c5e156f9c16d5b9b45b243753d0fe09
28.922018
58
0.489499
4.449523
false
false
false
false
ajalt/clikt
samples/repo/src/main/kotlin/com/github/ajalt/clikt/samples/repo/main.kt
1
5166
package com.github.ajalt.clikt.samples.repo import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.requireObject import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.output.TermUi import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.arguments.optional import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.file import java.io.File data class RepoConfig(var home: String, val config: MutableMap<String, String>, var verbose: Boolean) class Repo : CliktCommand( help = """Repo is a command line tool that showcases how to build complex command line interfaces with Clikt. This tool is supposed to look like a distributed version control system to show how something like this can be structured.""") { init { versionOption("1.0") } val repoHome: String by option(help = "Changes the repository folder location.") .default(".repo") val config: List<Pair<String, String>> by option(help = "Overrides a config key/value pair.") .pair() .multiple() val verbose: Boolean by option("-v", "--verbose", help = "Enables verbose mode.") .flag() override fun run() { val repo = RepoConfig(repoHome, HashMap(), verbose) for ((k, v) in config) { repo.config[k] = v } currentContext.obj = repo } } class Clone : CliktCommand( help = """Clones a repository. This will clone the repository at SRC into the folder DEST. If DEST is not provided this will automatically use the last path component of SRC and create that folder.""") { val repo: RepoConfig by requireObject() val src: File by argument().file() val dest: File? by argument().file().optional() val shallow: Boolean by option(help = "Makes a checkout shallow or deep. Deep by default.") .flag("--deep") val rev: String by option("--rev", "-r", help = "Clone a specific revision instead of HEAD.") .default("HEAD") override fun run() { val destName = dest?.name ?: src.name echo("Cloning repo $src to ${File(destName).absolutePath}") repo.home = destName if (shallow) { echo("Making shallow checkout") } echo("Checking out revision $rev") } } class Delete : CliktCommand( help = """Deletes a repository. This will throw away the current repository.""") { val repo: RepoConfig by requireObject() override fun run() { echo("Destroying repo ${repo.home}") echo("Deleted!") } } class SetUser : CliktCommand( name = "setuser", help = """Sets the user credentials. This will override the current user config.""") { val repo: RepoConfig by requireObject() val username: String by option(help = "The developer's shown username.") .prompt() val email: String by option(help = "The developer's email address.") .prompt(text = "E-Mail") val password: String by option(help = "The login password.") .prompt(hideInput = true, requireConfirmation = true) override fun run() { repo.config["username"] = username repo.config["email"] = email repo.config["password"] = "*".repeat(password.length) echo("Changed credentials.") } } class Commit : CliktCommand( help = """Commits outstanding changes. Commit changes to the given files into the repository. You will need to "repo push" to push up your changes to other repositories. If a list of files is omitted, all changes reported by "repo status" will be committed.""") { val repo: RepoConfig by requireObject() val message: List<String> by option("--message", "-m", help = "The commit message. If provided multiple times " + "each argument gets converted into a new line.") .multiple() val files: List<File> by argument() .file() .multiple() override fun run() { val msg: String = if (message.isNotEmpty()) { message.joinToString("\n") } else { val marker = "# Files to be committed:" val text = buildString { append("\n\n").append(marker).append("\n#") for (file in files) { append("\n# ").append(file) } } val message = TermUi.editText(text) if (message == null) { echo("Aborted!") return } message.split(marker, limit = 2)[0].trim().apply { if (this.isEmpty()) { echo("Aborting commit due to empty commit message.") return } } } echo("Files to be commited: $files") echo("Commit message:") echo(msg) } } fun main(args: Array<String>) = Repo() .subcommands(Clone(), Delete(), SetUser(), Commit()) .main(args)
apache-2.0
c72b44a3988bd2e3a9bdc50cea4d29e5
32.764706
101
0.608208
4.40785
false
true
false
false
owntracks/android
project/app/src/test/java/org/owntracks/android/services/BlockingDequeueThatAlsoSometimesPersistsThingsToDiskMaybeTest.kt
1
4513
package org.owntracks.android.services import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.owntracks.android.model.messages.MessageLocation import org.owntracks.android.support.Parser import java.io.File import java.nio.file.Files import kotlin.random.Random class BlockingDequeueThatAlsoSometimesPersistsThingsToDiskMaybeTest { private val parser = Parser(null) private val random = Random(1) private fun generateRandomMessageLocation(): MessageLocation { return MessageLocation().apply { longitude = random.nextDouble() latitude = random.nextDouble() accuracy = random.nextInt() } } @Test fun `given an empty queue when polling then null is returned`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) assertNull(queue.poll()) } @Test fun `given an empty queue when adding an item the queue size is 1`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) queue.offer(generateRandomMessageLocation()) assertEquals(1, queue.size) } @Test fun `given a non-empty queue, when pushing an item to the head then that same item is returned on poll`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) assertEquals(6, queue.size) val retrieved = queue.poll() assertEquals(headItem, retrieved) } @Test fun `given a file path, when initializing the queue the size is correct`() { val dir = Files.createTempDirectory("").toFile() val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val newQueue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(5, newQueue.size) } @Test fun `given a file path where the head slot is occupied, when initializing the queue the size is correct`() { val dir = Files.createTempDirectory("").toFile() val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) val newQueue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(6, newQueue.size) val retrieved = queue.poll() assertEquals(headItem, retrieved) } @Test fun `given a non-empty queue, when taking an item to the head then the item is returned`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) assertEquals(6, queue.size) val retrieved = queue.take() assertEquals(headItem, retrieved) } @Test fun `given a corrupt file, when initializing the queue then an empty queue is created`() { val dir = Files.createTempDirectory("").toFile() dir.resolve("messageQueue.dat").writeBytes(random.nextBytes(100)) val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(0, queue.size) } @Test fun `given an un-writable location, when initializing a queue then an in-memory empty queue is created`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, File("/"), parser ) assertEquals(0, queue.size) } }
epl-1.0
a4a3acb8a4a2edf0a6c650b4857befd2
30.124138
112
0.632617
5.585396
false
true
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/ExecutedInteractionsLogService.kt
1
3900
package net.perfectdreams.loritta.cinnamon.pudding.services import kotlinx.datetime.Instant import kotlinx.datetime.toJavaInstant import kotlinx.serialization.json.JsonObject import net.perfectdreams.loritta.common.commands.ApplicationCommandType import net.perfectdreams.loritta.common.components.ComponentType import net.perfectdreams.loritta.cinnamon.pudding.Pudding import net.perfectdreams.loritta.cinnamon.pudding.tables.ExecutedComponentsLog import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.ExecutedApplicationCommandsLog import org.jetbrains.exposed.sql.insertAndGetId import org.jetbrains.exposed.sql.select class ExecutedInteractionsLogService(private val pudding: Pudding) : Service(pudding) { suspend fun insertApplicationCommandLog( userId: Long, guildId: Long?, channelId: Long, sentAt: Instant, type: ApplicationCommandType, declaration: String, executor: String, options: JsonObject, success: Boolean, latency: Double, stacktrace: String? ): Long { return pudding.transaction { ExecutedApplicationCommandsLog.insertAndGetId { it[ExecutedApplicationCommandsLog.userId] = userId it[ExecutedApplicationCommandsLog.guildId] = guildId it[ExecutedApplicationCommandsLog.channelId] = channelId it[ExecutedApplicationCommandsLog.sentAt] = sentAt.toJavaInstant() it[ExecutedApplicationCommandsLog.type] = type it[ExecutedApplicationCommandsLog.declaration] = declaration it[ExecutedApplicationCommandsLog.executor] = executor it[ExecutedApplicationCommandsLog.options] = options.toString() it[ExecutedApplicationCommandsLog.success] = success it[ExecutedApplicationCommandsLog.latency] = latency it[ExecutedApplicationCommandsLog.stacktrace] = stacktrace } }.value } suspend fun insertComponentLog( userId: Long, guildId: Long?, channelId: Long, sentAt: Instant, type: ComponentType, declaration: String, executor: String, // options: JsonObject, success: Boolean, latency: Double, stacktrace: String? ): Long { return pudding.transaction { ExecutedComponentsLog.insertAndGetId { it[ExecutedComponentsLog.userId] = userId it[ExecutedComponentsLog.guildId] = guildId it[ExecutedComponentsLog.channelId] = channelId it[ExecutedComponentsLog.sentAt] = sentAt.toJavaInstant() it[ExecutedComponentsLog.type] = type it[ExecutedComponentsLog.declaration] = declaration it[ExecutedComponentsLog.executor] = executor // it[ExecutedApplicationCommandsLog.options] = options.toString() it[ExecutedComponentsLog.success] = success it[ExecutedComponentsLog.latency] = latency it[ExecutedComponentsLog.stacktrace] = stacktrace } }.value } suspend fun getExecutedApplicationCommands(since: Instant): Long { return pudding.transaction { return@transaction ExecutedApplicationCommandsLog.select { ExecutedApplicationCommandsLog.sentAt greaterEq since.toJavaInstant() }.count() } } suspend fun getUniqueUsersExecutedApplicationCommands(since: Instant): Long { return pudding.transaction { return@transaction ExecutedApplicationCommandsLog.slice(ExecutedApplicationCommandsLog.userId).select { ExecutedApplicationCommandsLog.sentAt greaterEq since.toJavaInstant() }.groupBy(ExecutedApplicationCommandsLog.userId).count() } } }
agpl-3.0
5b50362176b38e3f5e9e9583a526565e
42.344444
115
0.679744
6.09375
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/widgets/WidgetLMK.kt
1
4928
package com.androidvip.hebf.widgets import android.app.ActivityManager import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.lifecycle.lifecycleScope import com.androidvip.hebf.R import com.androidvip.hebf.ui.base.BaseActivity import com.androidvip.hebf.utils.Prefs import com.androidvip.hebf.utils.RootUtils import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.topjohnwu.superuser.Shell import kotlinx.coroutines.launch //TODO class WidgetLMK : BaseActivity() { private companion object { private var MODERADO = "12288,16384,20480,25088,29696,34304" private var MULTITASK = "3072,7168,11264,15360,19456,23552" private var FREE_RAM = "6144,14336,24576,32768,40960,49152" private var GAME = "4096,8192,16384,32768,49152,65536" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val profileNames = resources.getStringArray(R.array.lmk_profiles) val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? val memoryInfo = ActivityManager.MemoryInfo() lifecycleScope.launch(workerContext) { val isRooted = Shell.rootAccess() am?.getMemoryInfo(memoryInfo) val mem = memoryInfo.totalMem / 1048567 when { mem <= 512 -> { MODERADO = "6144,8192,10240,12288,14848,17408" MULTITASK = "1536,3584,5632,7680,9728,11776" FREE_RAM = "3072,7168,12288,16384,20480,24576" GAME = "2048,4096,8192,16384,24576,32768" } mem <= 768 -> { MODERADO = "9216,12288,15360,18944,22272,25600" MULTITASK = "2048,5120,8192,11264,14336,17920" FREE_RAM = "4608,10752,18432,24576,30720,36864" GAME = "3072,6144,12288,24576,36864,49152" } mem <= 1024 -> { MODERADO = "12288,16384,20480,25088,29696,34304" MULTITASK = "3072,7168,11264,15360,19456,23552" FREE_RAM = "6144,14336,24576,32768,40960,49152" GAME = "4096,8192,16384,32768,49152,65536" } mem <= 2048 -> { MODERADO = "18432,24576,30720,37632,44544,51456" MULTITASK = "4608,10752,16896,23040,29184,35328" FREE_RAM = "9216,21504,26624,36864,61440,73728" GAME = "6144,12288,24576,49152,73728,98304" } } runSafeOnUiThread { if (isRooted) { val builder = MaterialAlertDialogBuilder(this@WidgetLMK) builder.setTitle(getString(R.string.profiles)) .setSingleChoiceItems(profileNames, 1) { _, _ -> } .setPositiveButton(android.R.string.ok) { dialog, _ -> val position = (dialog as AlertDialog).listView.checkedItemPosition val prefs = Prefs(applicationContext) when (position) { 0 -> { prefs.putInt("PerfisLMK", 0) finish() } 1 -> { setProfiles(MODERADO) prefs.putInt("PerfisLMK", 1) } 2 -> { setProfiles(MULTITASK) prefs.putInt("PerfisLMK", 2) } 3 -> { setProfiles(FREE_RAM) prefs.putInt("PerfisLMK", 3) } 4 -> { setProfiles(GAME) prefs.putInt("PerfisLMK", 4) } } } .setOnDismissListener { finish() } .setNegativeButton(android.R.string.cancel) { _, _ -> finish() } builder.show() } else { Toast.makeText(this@WidgetLMK, "Only for rooted users!", Toast.LENGTH_LONG).show() finish() } } }.start() } private fun setProfiles(profile: String) { RootUtils.executeAsync("echo '$profile' > /sys/module/lowmemorykiller/parameters/minfree") Toast.makeText(this@WidgetLMK, getString(R.string.profiles_set), Toast.LENGTH_SHORT).show() } }
apache-2.0
fec57f998efa7b10a45f5e8b29a24a0f
42.236842
102
0.497362
4.869565
false
false
false
false
authzee/kotlin-guice
kotlin-guice/src/main/kotlin/dev/misfitlabs/kotlinguice4/KotlinModule.kt
1
4210
/* * Copyright (C) 2017 John Leacox * Copyright (C) 2017 Brian van de Boogaard * * 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 dev.misfitlabs.kotlinguice4 import com.google.inject.AbstractModule import com.google.inject.Binder import com.google.inject.MembersInjector import com.google.inject.Provider import com.google.inject.Scope import dev.misfitlabs.kotlinguice4.binder.KotlinAnnotatedBindingBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinAnnotatedElementBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinLinkedBindingBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinScopedBindingBuilder import dev.misfitlabs.kotlinguice4.internal.KotlinBindingBuilder import kotlin.reflect.KProperty /** * An extension of [AbstractModule] that enhances the binding DSL to allow binding using reified * type parameters. * * By using this class instead of [AbstractModule] you can replace: * ``` * class MyModule : AbstractModule() { * override fun configure() { * bind(Service::class.java).to(ServiceImpl::class.java).`in`(Singleton::class.java) * bind(object : TypeLiteral<PaymentService<CreditCard>>() {}) * .to(CreditCardPaymentService::class.java) * } * } * ``` * with * ``` * class MyModule : KotlinModule() { * override fun configure() { * bind<Service>().to<ServiceImpl>().`in`<Singleton>() * bind<PaymentService<CreditCard>>().to<CreditCardPaymentService>() * } * } * ``` * * @see KotlinBinder * @see AbstractModule * @author John Leacox * @since 1.0 */ abstract class KotlinModule : AbstractModule() { private class KotlinLazyBinder(private val delegateBinder: () -> Binder) { private val classesToSkip = arrayOf( KotlinAnnotatedBindingBuilder::class.java, KotlinAnnotatedElementBuilder::class.java, KotlinBinder::class.java, KotlinBindingBuilder::class.java, KotlinLinkedBindingBuilder::class.java, KotlinScopedBindingBuilder::class.java ) var lazyBinder = lazyInit() var currentBinder: Binder? = null operator fun getValue(thisRef: Any?, property: KProperty<*>): KotlinBinder { if (currentBinder != delegateBinder()) { currentBinder = delegateBinder() lazyBinder = lazyInit() } return lazyBinder.value } private fun lazyInit() = lazy { KotlinBinder(delegateBinder().skipSources(*classesToSkip)) } } /** Gets direct access to the underlying [KotlinBinder]. */ protected val kotlinBinder: KotlinBinder by KotlinLazyBinder { this.binder() } /** @see KotlinBinder.bindScope */ protected inline fun <reified TAnn : Annotation> bindScope(scope: Scope) { kotlinBinder.bindScope<TAnn>(scope) } /** @see KotlinBinder.bind */ protected inline fun <reified T> bind(): KotlinAnnotatedBindingBuilder<T> { return kotlinBinder.bind<T>() } /** @see KotlinBinder.requestStaticInjection */ protected inline fun <reified T> requestStaticInjection() { kotlinBinder.requestStaticInjection<T>() } /** @see AbstractModule.requireBinding */ protected inline fun <reified T> requireBinding() { requireBinding(key<T>()) } /** @see KotlinBinder.getProvider */ protected inline fun <reified T> getProvider(): Provider<T> { return kotlinBinder.getProvider<T>() } /** @see KotlinBinder.getMembersInjector */ protected inline fun <reified T> getMembersInjector(): MembersInjector<T> { return kotlinBinder.getMembersInjector<T>() } }
apache-2.0
5b7499573eab24948a00293d2542b0fb
34.677966
100
0.685273
4.636564
false
false
false
false
openbakery/gradle-xcodePlugin
libxcodetools/src/main/kotlin/org/openbakery/assemble/Archive.kt
1
5799
package org.openbakery.assemble import org.openbakery.CommandRunner import org.openbakery.bundle.ApplicationBundle import org.openbakery.tools.CommandLineTools import org.openbakery.util.FileHelper import org.openbakery.xcode.Type import org.slf4j.LoggerFactory import java.io.File /** * This class creates an .xcarchive for the application bundle * Note: The implementation is not complete. Several methods must be migrated from the XcodeBuildArchiveTask to this class * * The idea is that this class just creates the xcarchive, but has no dependency and knowledge about gradle */ class Archive(applicationBundleFile: File, archiveName: String, type: Type, simulator: Boolean, tools: CommandLineTools, watchApplicationBundleFile: File? = null) { private var applications = "Applications" private var products = "Products" companion object { val logger = LoggerFactory.getLogger("AppPackage")!! } private val applicationBundleFile: File = applicationBundleFile private val watchApplicationBundleFile: File? = watchApplicationBundleFile private val tools: CommandLineTools = tools private val fileHelper: FileHelper = FileHelper(CommandRunner()) private val archiveName: String = archiveName private val type: Type = type private val simulator: Boolean = simulator fun create(destinationDirectory: File) : ApplicationBundle { return this.create(destinationDirectory, false) } fun create(destinationDirectory: File, bitcodeEnabled: Boolean) : ApplicationBundle { val archiveDirectory = getArchiveDirectory(destinationDirectory) val applicationDirectory = copyApplication(archiveDirectory) copyOnDemandResources(archiveDirectory) copyDsyms(archiveDirectory) val applicationBundle = ApplicationBundle(applicationDirectory, type, simulator, tools.plistHelper) if (type == Type.iOS) { copyFrameworks(applicationBundle, archiveDirectory, applicationBundle.platformName, bitcodeEnabled) } if (applicationBundle.watchAppBundle != null) { copyFrameworks(applicationBundle.watchAppBundle, archiveDirectory, applicationBundle.watchAppBundle.platformName, true) } return applicationBundle } private fun copyApplication(archiveDirectory: File) : File { val applicationDirectory = File(archiveDirectory, "$products/$applications") applicationDirectory.mkdirs() fileHelper.copyTo(applicationBundleFile, applicationDirectory) return File(applicationDirectory, applicationBundleFile.name) } private fun copyOnDemandResources(archiveDirectory: File) { val onDemandResources = File(applicationBundleFile.parent, "OnDemandResources") if (onDemandResources.exists()) { val destination = File(archiveDirectory, products) fileHelper.copyTo(onDemandResources, destination) } } private fun copyDsyms(archiveDirectory: File) { val dSymDirectory = File(archiveDirectory, "dSYMs") dSymDirectory.mkdirs() copyDsyms(applicationBundleFile.parentFile, dSymDirectory) if (watchApplicationBundleFile != null) { copyDsyms(watchApplicationBundleFile, dSymDirectory) } } private fun copyDsyms(archiveDirectory: File, dSymDirectory: File) { archiveDirectory.walk().forEach { if (it.isDirectory && it.extension.toLowerCase() == "dsym") { fileHelper.copyTo(it, dSymDirectory) } } } private fun getArchiveDirectory(destinationDirectory: File): File { val archiveDirectory = File(destinationDirectory, this.archiveName + ".xcarchive") archiveDirectory.mkdirs() return archiveDirectory } private fun copyFrameworks(applicationBundle: ApplicationBundle, archiveDirectory: File, platformName: String, bitcodeEnabled: Boolean) { if (!applicationBundle.frameworksPath.exists()) { logger.debug("framework path does not exists, so we are done") return } var libNames = ArrayList<String>() applicationBundle.frameworksPath.walk().forEach { if (it.extension.toLowerCase() == "dylib") { libNames.add(it.name) } } logger.debug("swift libraries to add: {}", libNames) val swiftLibraryDirectories = getSwiftLibraryDirectories(platformName) libNames.forEach { libraryName -> val library = getSwiftLibrary(swiftLibraryDirectories, libraryName) if (library != null) { val swiftSupportDirectory = getSwiftSupportDirectory(archiveDirectory, platformName) fileHelper.copyTo(library, swiftSupportDirectory) if (!bitcodeEnabled) { val destination = File(applicationBundle.frameworksPath, library.name) val commandList = listOf("/usr/bin/xcrun", "bitcode_strip", library.absolutePath, "-r", "-o", destination.absolutePath) tools.lipo.xcodebuild.commandRunner.run(commandList) } } } } private fun getSwiftLibrary(libraryDirectories: List<File>, name: String) : File? { for (directory in libraryDirectories) { val result = getSwiftLibrary(directory, name) if (result != null) { return result } } return null } private fun getSwiftLibrary(libraryDirectory: File, name: String) : File?{ val result = File(libraryDirectory, name) if (result.exists()) { return result } return null } private fun getSwiftLibraryDirectories(platformName: String) : List<File> { var result = ArrayList<File>() val baseDirectory = File(tools.lipo.xcodebuild.toolchainDirectory, "usr/lib/") baseDirectory.listFiles().forEach { if (it.isDirectory && it.name.startsWith("swift")) { val platformDirectory = File(it, platformName) if (platformDirectory.exists()) { result.add(platformDirectory) } } } return result } private fun getSwiftSupportDirectory(archiveDirectory: File, platformName: String) : File { val swiftSupportDirectory = File(archiveDirectory, "SwiftSupport/$platformName") if (!swiftSupportDirectory.exists()) { swiftSupportDirectory.mkdirs() } return swiftSupportDirectory } }
apache-2.0
8dbfd0f048f27b062ce522be18ecbe82
33.313609
164
0.768236
4.267108
false
false
false
false
AlmasB/GroupNet
src/main/kotlin/icurves/algorithm/AStarEdgeRouter.kt
1
5168
package icurves.algorithm import icurves.algorithm.astar.AStarGrid import icurves.algorithm.astar.NodeState import icurves.diagram.Zone import icurves.guifx.SettingsController import icurves.util.Log import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.shape.Polyline import javafx.scene.shape.Rectangle import javafx.scene.shape.Shape import javafx.scene.text.Font import javafx.scene.text.Text import math.geom2d.Point2D import math.geom2d.polygon.Polygons2D import math.geom2d.polygon.SimplePolygon2D /** * * * @author Almas Baimagambetov ([email protected]) */ class AStarEdgeRouter : EdgeRouter { private val TILES = 50 override fun route(zone1: Zone, zone2: Zone): Polyline { var union = Polygons2D.union(zone1.getPolygonShape(), zone2.getPolygonShape()) val bbox = union.boundingBox() //SettingsController.debugShapes.add(Rectangle(bbox.minX, bbox.minY, bbox.width, bbox.height)) val TILE_SIZE = (Math.min(bbox.width, bbox.height) / TILES).toInt() val grid = AStarGrid(bbox.width.toInt() / TILE_SIZE, bbox.height.toInt() / TILE_SIZE) println("Grid size: ${grid.width}x${grid.height} Tile size: $TILE_SIZE") println() println(zone1.getPolygonShape().vertices()) println(zone2.getPolygonShape().vertices()) // keep only distinct vertices union = SimplePolygon2D(union.vertices().map { P(it.x().toInt(), it.y().toInt()) }.toSet().map { Point2D(it.x.toDouble(), it.y.toDouble()) }) println(union.vertices()) println() val boundary = union.boundary() // signed, so - if inside val maxDistance: Double = try { -Math.min(boundary.signedDistance(zone1.center.x, zone1.center.y), boundary.signedDistance(zone2.center.x, zone2.center.y)) } catch (e: Exception) { 1000.0 } for (y in 0 until grid.height) { for (x in 0 until grid.width) { val tileCenter = Point2D(x.toDouble() * TILE_SIZE + TILE_SIZE / 2 + bbox.minX, y.toDouble() * TILE_SIZE + TILE_SIZE / 2 + bbox.minY) val node = grid.getNode(x, y) try { if (union.contains(tileCenter)) { val dist = -boundary.signedDistance(tileCenter).toInt() if (dist < TILE_SIZE) { node.state = NodeState.NOT_WALKABLE continue } node.state = NodeState.WALKABLE //node.gCost = 100000 - dist * 1000 //node.gCost = ((2 - dist / maxDistance) * 2500).toInt() node.gCost = ((1 - dist / maxDistance) * 5000).toInt() if (node.gCost < 0) { //println("Distance: $dist, gCost: ${node.gCost}") node.gCost = 0 } // val text = Text("${node.fCost}") // text.translateX = tileCenter.x() // text.translateY = tileCenter.y() // text.font = Font.font(36.0) // // SettingsController.debugNodes.add(text) } else { node.state = NodeState.NOT_WALKABLE } } catch (e: Exception) { Log.e(e) node.state = NodeState.NOT_WALKABLE } // if (node.state == NodeState.WALKABLE) { // val circle = Circle(tileCenter.x(), tileCenter.y(), 15.0, Color.GREEN) // //SettingsController.debugNodes.add(circle) // } else { // val circle = Circle(tileCenter.x(), tileCenter.y(), 15.0, Color.RED) // //SettingsController.debugNodes.add(circle) // } } } val startX = (zone1.center.x - bbox.minX) / TILE_SIZE val startY = (zone1.center.y - bbox.minY) / TILE_SIZE val targetX = (zone2.center.x - bbox.minX) / TILE_SIZE val targetY = (zone2.center.y - bbox.minY) / TILE_SIZE println("$startX,$startY - $targetX,$targetY") val path = grid.getPath(startX.toInt(), startY.toInt(), targetX.toInt(), targetY.toInt()) if (path.isEmpty()) { println("Edge routing A* not found") } // so that start and end vertices are exactly the same as requested val points = arrayListOf<Double>(zone1.center.x, zone1.center.y) points.addAll(path.map { arrayListOf(it.x, it.y) } .flatten() .mapIndexed { index, value -> value.toDouble() * TILE_SIZE + TILE_SIZE / 2 + (if (index % 2 == 0) bbox.minX else bbox.minY) } .dropLast(2) ) // so that start and end vertices are exactly the same as requested points.add(zone2.center.x) points.add(zone2.center.y) return Polyline(*points.toDoubleArray()) } data class P(val x: Int, val y: Int) { } }
apache-2.0
31ab51f6e7b1a956b9916a743aa41949
32.348387
149
0.549729
4.078927
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/gcloud/spanner/testing/SpannerEmulator.kt
1
4812
// Copyright 2020 The Cross-Media Measurement 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.wfanet.measurement.gcloud.spanner.testing import java.net.ServerSocket import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import org.jetbrains.annotations.BlockingExecutor import org.wfanet.measurement.common.getRuntimePath private const val EMULATOR_HOSTNAME = "localhost" private const val INVALID_HOST_MESSAGE = "emulator host must be of the form $EMULATOR_HOSTNAME:<port>" /** * Wrapper for Cloud Spanner Emulator binary. * * @param port TCP port that the emulator should listen on, or 0 to allocate a port automatically * @param coroutineContext Context for operations that may block */ class SpannerEmulator( private val port: Int = 0, private val coroutineContext: @BlockingExecutor CoroutineContext = Dispatchers.IO ) : AutoCloseable { private val startMutex = Mutex() @Volatile private lateinit var emulator: Process val started: Boolean get() = this::emulator.isInitialized @Volatile private var _emulatorHost: String? = null val emulatorHost: String get() { check(started) { "Emulator not started" } return _emulatorHost!! } /** * Starts the emulator process if it has not already been started. * * This suspends until the emulator is ready. * * @returns the emulator host */ suspend fun start(): String { if (started) { return emulatorHost } return startMutex.withLock { // Double-checked locking. if (started) { return@withLock emulatorHost } return withContext(coroutineContext) { // Open a socket on `port`. This should reduce the likelihood that the port // is in use. Additionally, this will allocate a port if `port` is 0. val localPort = ServerSocket(port).use { it.localPort } val emulatorHost = "$EMULATOR_HOSTNAME:$localPort" _emulatorHost = emulatorHost emulator = ProcessBuilder(emulatorPath.toString(), "--host_port=$emulatorHost") .redirectError(ProcessBuilder.Redirect.INHERIT) .start() /** Suffix of line of emulator output that will tell us that it's ready. */ val readyLineSuffix = "Server address: $emulatorHost" emulator.inputStream.use { input -> input.bufferedReader().use { reader -> do { yield() check(emulator.isAlive) { "Emulator stopped unexpectedly" } val line = reader.readLine() } while (!line.endsWith(readyLineSuffix)) } } emulatorHost } } } override fun close() { if (started) { emulator.destroy() } } fun buildJdbcConnectionString(project: String, instance: String, database: String): String = buildJdbcConnectionString(emulatorHost, project, instance, database) companion object { private val emulatorPath: Path init { val runfilesRelativePath = Paths.get("cloud_spanner_emulator", "emulator") val runtimePath = getRuntimePath(runfilesRelativePath) check(runtimePath != null && Files.exists(runtimePath)) { "$runfilesRelativePath not found in runfiles" } check(Files.isExecutable(runtimePath)) { "$runtimePath is not executable" } emulatorPath = runtimePath } fun withHost(emulatorHost: String): SpannerEmulator { val lazyMessage: () -> String = { INVALID_HOST_MESSAGE } val parts = emulatorHost.split(':', limit = 2) require(parts.size == 2 && parts[0] == EMULATOR_HOSTNAME, lazyMessage) val port = requireNotNull(parts[1].toIntOrNull(), lazyMessage) return SpannerEmulator(port) } fun buildJdbcConnectionString( emulatorHost: String, project: String, instance: String, database: String ): String { return "jdbc:cloudspanner://$emulatorHost/projects/$project/instances/$instance/databases/" + "$database;usePlainText=true;autoConfigEmulator=true" } } }
apache-2.0
8384d1a2e419bfe2c18d8585e4a0ac6c
31.734694
99
0.689942
4.595989
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/views/LauncherPreviewView.kt
1
5977
package app.lawnchair.views import android.annotation.SuppressLint import android.appwidget.AppWidgetProviderInfo import android.content.Context import android.util.Log import android.view.ContextThemeWrapper import android.view.Gravity import android.view.View import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import androidx.annotation.UiThread import androidx.annotation.WorkerThread import com.android.launcher3.InvariantDeviceProfile import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherSettings.Favorites.* import com.android.launcher3.R import com.android.launcher3.graphics.LauncherPreviewRenderer import com.android.launcher3.model.BgDataModel import com.android.launcher3.model.GridSizeMigrationTaskV2 import com.android.launcher3.model.LoaderTask import com.android.launcher3.model.ModelDelegate import com.android.launcher3.util.ComponentKey import com.android.launcher3.util.Executors.MAIN_EXECUTOR import com.android.launcher3.util.Executors.MODEL_EXECUTOR import com.android.launcher3.util.RunnableList import com.android.launcher3.util.Themes import com.google.android.material.progressindicator.CircularProgressIndicator import kotlin.math.min @SuppressLint("ViewConstructor") class LauncherPreviewView( context: Context, private val idp: InvariantDeviceProfile, private val dummySmartspace: Boolean = false, private val dummyInsets: Boolean = false, private val appContext: Context = context.applicationContext ) : FrameLayout(context) { private val onReadyCallbacks = RunnableList() private val onDestroyCallbacks = RunnableList() private var destroyed = false private var rendererView: View? = null private val spinner = CircularProgressIndicator(context).apply { val themedContext = ContextThemeWrapper(context, Themes.getActivityThemeRes(context)) val textColor = Themes.getAttrColor(themedContext, R.attr.workspaceTextColor) isIndeterminate = true setIndicatorColor(textColor) trackCornerRadius = 1000 alpha = 0f animate() .alpha(1f) .withLayer() .setStartDelay(100) .setDuration(300) .start() } init { addView(spinner, LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { gravity = Gravity.CENTER }) loadAsync() } fun addOnReadyCallback(runnable: Runnable) { onReadyCallbacks.add(runnable) } @UiThread fun destroy() { destroyed = true onDestroyCallbacks.executeAllAndDestroy() removeAllViews() } private fun loadAsync() { MODEL_EXECUTOR.execute(this::loadModelData) } @WorkerThread private fun loadModelData() { val migrated = doGridMigrationIfNecessary() val inflationContext = ContextThemeWrapper(appContext, Themes.getActivityThemeRes(context)) if (migrated) { val previewContext = LauncherPreviewRenderer.PreviewContext(inflationContext, idp) object : LoaderTask( LauncherAppState.getInstance(previewContext), null, BgDataModel(), ModelDelegate(), null ) { override fun run() { loadWorkspace( emptyList(), PREVIEW_CONTENT_URI, "$SCREEN = 0 or $CONTAINER = $CONTAINER_HOTSEAT" ) MAIN_EXECUTOR.execute { renderView(previewContext, mBgDataModel, mWidgetProvidersMap) onDestroyCallbacks.add { previewContext.onDestroy() } } } }.run() } else { LauncherAppState.getInstance(inflationContext).model.loadAsync { dataModel -> if (dataModel != null) { MAIN_EXECUTOR.execute { renderView(inflationContext, dataModel, null) } } else { onReadyCallbacks.executeAllAndDestroy() Log.e("LauncherPreviewView", "Model loading failed") } } } } @WorkerThread private fun doGridMigrationIfNecessary(): Boolean { val needsToMigrate = GridSizeMigrationTaskV2.needsToMigrate(context, idp) if (!needsToMigrate) { return false } return GridSizeMigrationTaskV2.migrateGridIfNeeded(context, idp) } @UiThread private fun renderView( inflationContext: Context, dataModel: BgDataModel, widgetProviderInfoMap: Map<ComponentKey, AppWidgetProviderInfo>? ) { if (destroyed) { return } val renderer = LauncherPreviewRenderer(inflationContext, idp, null, dummyInsets) if (dummySmartspace) { renderer.setWorkspaceSearchContainer(R.layout.smartspace_widget_placeholder) } val view = renderer.getRenderedView(dataModel, widgetProviderInfoMap) updateScale(view) view.pivotX = if (layoutDirection == LAYOUT_DIRECTION_RTL) view.measuredWidth.toFloat() else 0f view.pivotY = 0f view.layoutParams = LayoutParams(view.measuredWidth, view.measuredHeight) removeView(spinner) rendererView = view addView(view) onReadyCallbacks.executeAllAndDestroy() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) rendererView?.let { updateScale(it) } } private fun updateScale(view: View) { // This aspect scales the view to fit in the surface and centers it val scale: Float = min( measuredWidth / view.measuredWidth.toFloat(), measuredHeight / view.measuredHeight.toFloat() ) view.scaleX = scale view.scaleY = scale } }
gpl-3.0
bdc22ccb1fad9e0c965b69cfdea4268d
34.577381
103
0.664213
5.001674
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/pages/GroovydocPackagePage.kt
1
2405
package com.eden.orchid.groovydoc.pages import com.copperleaf.groovydoc.json.models.GroovydocPackageDoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.groovydoc.GroovydocGenerator import com.eden.orchid.groovydoc.resources.PackageDocResource @Archetype(value = ConfigArchetype::class, key = "${GroovydocGenerator.GENERATOR_KEY}.packagePages") @Description(value = "Documentation for a Groovy package.", name = "Groovy Package") class GroovydocPackagePage( context: OrchidContext, val packageDoc: GroovydocPackageDoc, val classes: List<GroovydocClassPage> ) : BaseGroovydocPage(PackageDocResource(context, packageDoc), "groovydocPackage", packageDoc.name) { val innerPackages: MutableList<GroovydocPackagePage> = ArrayList() fun hasInterfaces(): Boolean { return classes.any { it.classDoc.kind == "interface" } } val interfaces: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "interface" } } fun hasTraits(): Boolean { return classes.any { it.classDoc.kind == "trait" } } val traits: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "trait" } } fun hasAnnotations(): Boolean { return classes.any { it.classDoc.kind == "@interface" } } val annotations: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "@interface" } } fun hasEnums(): Boolean { return classes.any { it.classDoc.kind == "enum" } } val enums: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "enum" } } fun hasExceptions(): Boolean { return classes.any { it.classDoc.kind == "exception" } } val exceptions: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "exception" } } fun hasOrdinaryClasses(): Boolean { return classes.any { it.classDoc.kind == "class" } } val ordinaryClasses: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "class" } } }
mit
696621aa1e088667bd1c6605d3522d76
31.066667
101
0.661123
4.404762
false
false
false
false
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/setting/adapter/FooterEditorAdapterDelegate.kt
1
3513
package net.yslibrary.monotweety.setting.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.SwitchCompat import androidx.recyclerview.widget.RecyclerView import com.hannesdorfmann.adapterdelegates4.AdapterDelegate import net.yslibrary.monotweety.R import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.base.inflate import timber.log.Timber class FooterEditorAdapterDelegate( private val listener: Listener, ) : AdapterDelegate<List<SettingAdapter.Item>>() { override fun isForViewType(items: List<SettingAdapter.Item>, position: Int): Boolean { return items[position] is Item } override fun onBindViewHolder( items: List<SettingAdapter.Item>, position: Int, holder: RecyclerView.ViewHolder, payloads: MutableList<Any>, ) { val item = items[position] as Item if (holder is ViewHolder) { val context = holder.itemView.context val res = context.resources val subTitle = if (item.checked) res.getString(R.string.sub_label_footer_on, item.footerText) else res.getString(R.string.sub_label_footer_off) holder.title.text = res.getString(R.string.label_footer) holder.subTitle.text = subTitle holder.itemView.isEnabled = item.enabled holder.itemView.setOnClickListener { onClick(context, item) } } } override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder { return ViewHolder.create(parent) } private fun onClick(context: Context, item: Item) { // show dialog val view = context.inflate(R.layout.dialog_footer_editor) val enabledSwitch = view.findById<SwitchCompat>(R.id.switch_button) val input = view.findById<EditText>(R.id.input) enabledSwitch.isChecked = item.checked input.setText(item.footerText, TextView.BufferType.EDITABLE) input.isEnabled = item.checked enabledSwitch.setOnCheckedChangeListener { _, checked -> input.isEnabled = checked } Timber.tag("Dialog").i("onClick - Edit Footer") AlertDialog.Builder(context) .setTitle(R.string.title_edit_footer) .setView(view) .setPositiveButton(R.string.label_confirm) { _, _ -> val enabled = enabledSwitch.isChecked val footerText = input.text.toString() listener.onFooterUpdated(enabled, footerText) }.show() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val title = view.findById<TextView>(R.id.title) val subTitle = view.findById<TextView>(R.id.sub_title) companion object { fun create(parent: ViewGroup): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.vh_2line_text, parent, false) return ViewHolder(view) } } } data class Item( val enabled: Boolean, val checked: Boolean, val footerText: String, override val type: SettingAdapter.ViewType, ) : SettingAdapter.Item interface Listener { fun onFooterUpdated(enabled: Boolean, footerText: String) } }
apache-2.0
f46ac5cb880d6c9bb2419385415e6cec
33.782178
92
0.664105
4.604194
false
false
false
false
mayuki/AgqrPlayer4Tv
AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/component/fragment/guidedstep/PlayerSettingGuidedStepFragment.kt
1
2370
package org.misuzilla.agqrplayer4tv.component.fragment.guidedstep import android.os.Bundle import android.support.v17.leanback.app.GuidedStepSupportFragment import android.support.v17.leanback.widget.GuidanceStylist import android.support.v17.leanback.widget.GuidedAction import org.misuzilla.agqrplayer4tv.R import org.misuzilla.agqrplayer4tv.infrastracture.extension.addCheckAction import org.misuzilla.agqrplayer4tv.model.preference.ApplicationPreference import org.misuzilla.agqrplayer4tv.model.preference.PlayerType /** * 設定: プレイヤー設定のGuidedStepクラスです。 */ class PlayerSettingGuidedStepFragment : GuidedStepSupportFragment() { override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance { return GuidanceStylist.Guidance(context!!.getString(R.string.guidedstep_player_title), context!!.getString(R.string.guidedstep_player_description), context!!.getString(R.string.guidedstep_settings_title), null) } override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) { with (actions) { addCheckAction(context!!, PlayerType.EXO_PLAYER.value, context!!.getString(R.string.guidedstep_player_type_exoplayer), context!!.getString(R.string.guidedstep_player_type_exoplayer_description), ApplicationPreference.playerType.get() == PlayerType.EXO_PLAYER) addCheckAction(context!!, PlayerType.ANDROID_DEFAULT.value, context!!.getString(R.string.guidedstep_player_type_default), context!!.getString(R.string.guidedstep_player_type_default_description), ApplicationPreference.playerType.get() == PlayerType.ANDROID_DEFAULT) addCheckAction(context!!, PlayerType.WEB_VIEW.value, context!!.getString(R.string.guidedstep_player_type_webview), context!!.getString(R.string.guidedstep_player_type_webview_description), ApplicationPreference.playerType.get() == PlayerType.WEB_VIEW) } } override fun onGuidedActionClicked(action: GuidedAction) { actions.forEach { it.isChecked = it == action } ApplicationPreference.playerType.set(PlayerType.fromInt(action.id.toInt())) fragmentManager!!.popBackStack() } }
mit
9ce04a57cb9ffb233fc30557b449cea1
53.395349
218
0.726262
4.620553
false
false
false
false
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/views/BugFixedSpinner.kt
1
4156
/* * Copyright (c) 2012-2017 Frederic Julian * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.views import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.AdapterView import android.widget.Spinner /** * A Spinner will normally call it's OnItemSelectedListener * when you use setSelection(...) in your initialization code. * This is usually unwanted behavior, and a common work-around * is to use spinner.post(...) with a Runnable to assign the * OnItemSelectedListener after layout. * * If you do not call setSelection(...) manually, the callback * may be called with the first item in the adapter you have * set. The common work-around for that is to count callbacks. * * While these workarounds usually *seem* to work, the callback * may still be called repeatedly for other reasons while the * selection hasn't actually changed. This will happen for * example, if the user has accessibility options enabled - * which is more common than you might think as several apps * use this for different purposes, like detecting which * notifications are active. * * Ideally, your OnItemSelectedListener callback should be * coded defensively so that no problem would occur even * if the callback was called repeatedly with the same values * without any user interaction, so no workarounds are needed. * * This class does that for you. It keeps track of the values * you have set with the setSelection(...) methods, and * proxies the OnItemSelectedListener callback so your callback * only gets called if the selected item's position differs * from the one you have set by code, or the first item if you * did not set it. * * This also means that if the user actually clicks the item * that was previously selected by code (or the first item * if you didn't set a selection by code), the callback will * not fire. */ class BugFixedSpinner : Spinner { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private var lastPosition = -1 private var firstTrigger = true override fun setOnItemSelectedListener(listener: OnItemSelectedListener?) { if (listener == null) { super.setOnItemSelectedListener(null) } else { firstTrigger = true super.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (firstTrigger) { firstTrigger = false lastPosition = position } else { if (position != lastPosition) { lastPosition = position listener.onItemSelected(parent, view, position, id) } } } override fun onNothingSelected(parent: AdapterView<*>?) { if (firstTrigger) { firstTrigger = false } else { if (-1 != lastPosition) { lastPosition = -1 listener.onNothingSelected(parent) } } } }) } } }
gpl-3.0
426b9cbad758154177169ce5b6ee5ce3
39.359223
112
0.653272
5.013269
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/database/models/guild/LogSettings.kt
1
791
package me.mrkirby153.KirBot.database.models.guild import com.mrkirby153.bfs.model.Model import com.mrkirby153.bfs.model.annotations.Column import com.mrkirby153.bfs.model.annotations.Table import com.mrkirby153.bfs.model.annotations.Timestamps import com.mrkirby153.bfs.model.enhancers.TimestampEnhancer import java.sql.Timestamp @Table("log_settings") @Timestamps class LogSettings : Model() { var id: String = "" @Column("server_id") var serverId: String = "" @Column("channel_id") var channelId: String = "" var included: Long = 0L var excluded: Long = 0L @TimestampEnhancer.CreatedAt @Column("created_at") var createdAt: Timestamp? = null @TimestampEnhancer.UpdatedAt @Column("updated_at") var updatedAt: Timestamp? = null }
mit
cf8873b4ec958ec1b572e7a67fbfe782
22.294118
59
0.725664
3.766667
false
false
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/DeclarationInconsistencyProcessor.kt
1
1980
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language 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 * * 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.devtools.ksp.processor import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration class DeclarationInconsistencyProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() override fun process(resolver: Resolver): List<KSAnnotated> { val numberClass = resolver.getClassDeclarationByName("kotlin.Number")!! val serializable = numberClass.superTypes.first { it.resolve().declaration.qualifiedName?.asString() == "java.io.Serializable" }.resolve().declaration as KSClassDeclaration val serizableDirect = resolver.getClassDeclarationByName("java.io.Serializable")!! results.add("via type: ${serializable.qualifiedName?.asString()}") serializable.getAllFunctions().forEach { results.add(it.simpleName.asString()) } results.add("via find declaration: ${serizableDirect.qualifiedName?.asString()}") serizableDirect.getAllFunctions().forEach { results.add(it.simpleName.asString()) } return emptyList() } override fun toResult(): List<String> { return results } }
apache-2.0
8539dd4eed85db1cbc5d20561b832681
40.25
90
0.725253
4.669811
false
false
false
false
SecUSo/privacy-friendly-app-example
app/src/main/java/org/secuso/privacyfriendlyexample/ui/BaseActivity.kt
1
7920
/* This file is part of Privacy Friendly App Example. Privacy Friendly App Example is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Privacy Friendly App Example is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Privacy Friendly App Example. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyexample.ui import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.os.Handler import android.preference.PreferenceActivity import android.preference.PreferenceManager import com.google.android.material.navigation.NavigationView import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener import androidx.core.app.TaskStackBuilder import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.MenuItem import android.view.View import org.secuso.privacyfriendlyexample.R /** * This class is a parent class of all activities that can be accessed from the * Navigation Drawer (example see MainActivity.java) * * The default NavigationDrawer functionality is implemented in this class. If you wish to inherit * the default behaviour, make sure the content view has a NavigationDrawer with the id 'nav_view', * the header should point to 'nav_header_main' and the menu should be loaded from 'main_drawer'. * * Also the main layout that holds the content of the activity should have the id 'main_content'. * This way it will automatically fade in and out every time a transition is happening. * * @author Christopher Beckmann (Kamuno), Karola Marky (yonjuni) * @version 20161225 */ abstract class BaseActivity : AppCompatActivity(), OnNavigationItemSelectedListener { companion object { // delay to launch nav drawer item, to allow close animation to play internal const val NAVDRAWER_LAUNCH_DELAY = 250 // fade in and fade out durations for the main content when switching between // different Activities of the app through the Nav Drawer internal const val MAIN_CONTENT_FADEOUT_DURATION = 150 internal const val MAIN_CONTENT_FADEIN_DURATION = 250 } // Navigation drawer: private var mDrawerLayout: DrawerLayout? = null private var mNavigationView: NavigationView? = null // Helper private val mHandler: Handler = Handler() protected val mSharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } protected abstract val navigationDrawerID: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(0, 0) } override fun onBackPressed() { val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onNavigationItemSelected(item: MenuItem): Boolean = goToNavigationItem(item.itemId) protected fun goToNavigationItem(itemId: Int): Boolean { if (itemId == navigationDrawerID) { // just close drawer because we are already in this activity mDrawerLayout?.closeDrawer(GravityCompat.START) return true } // delay transition so the drawer can close mHandler.postDelayed({ callDrawerItem(itemId) }, NAVDRAWER_LAUNCH_DELAY.toLong()) mDrawerLayout?.closeDrawer(GravityCompat.START) selectNavigationItem(itemId) // fade out the active activity val mainContent = findViewById<View>(R.id.main_content) mainContent?.animate()!!.alpha(0f).duration = MAIN_CONTENT_FADEOUT_DURATION.toLong() return true } // set active navigation item private fun selectNavigationItem(itemId: Int) { mNavigationView ?: return for (i in 0 until mNavigationView!!.menu.size()) { val b = itemId == mNavigationView!!.menu.getItem(i).itemId mNavigationView!!.menu.getItem(i).isChecked = b } } /** * Enables back navigation for activities that are launched from the NavBar. See * `AndroidManifest.xml` to find out the parent activity names for each activity. * @param intent */ private fun createBackStack(intent: Intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { val builder = TaskStackBuilder.create(this) builder.addNextIntentWithParentStack(intent) builder.startActivities() } else { startActivity(intent) finish() } } /** * This method manages the behaviour of the navigation drawer * Add your menu items (ids) to res/menu/main_drawer.xmlparam itemId Item that has been clicked by the user */ private fun callDrawerItem(itemId: Int) { val intent: Intent when (itemId) { R.id.nav_example -> { intent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } startActivity(intent) } R.id.nav_game -> { intent = Intent(this, GameActivity::class.java) createBackStack(intent) } R.id.nav_about -> { intent = Intent(this, AboutActivity::class.java) createBackStack(intent) } R.id.nav_help -> { intent = Intent(this, HelpActivity::class.java) createBackStack(intent) } R.id.nav_tutorial -> { intent = Intent(this, TutorialActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } startActivity(intent) } R.id.nav_settings -> { intent = Intent(this, SettingsActivity::class.java) intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsActivity.GeneralPreferenceFragment::class.java.name) intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true) createBackStack(intent) } } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) val toolbar = findViewById<View>(R.id.toolbar) as Toolbar if (supportActionBar == null) { setSupportActionBar(toolbar) } mDrawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout val toggle = ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) mDrawerLayout!!.addDrawerListener(toggle) toggle.syncState() mNavigationView = findViewById<View>(R.id.nav_view) as NavigationView mNavigationView!!.setNavigationItemSelectedListener(this) selectNavigationItem(navigationDrawerID) val mainContent = findViewById<View>(R.id.main_content) if (mainContent != null) { mainContent.alpha = 0f mainContent.animate().alpha(1f).duration = MAIN_CONTENT_FADEIN_DURATION.toLong() } } }
gpl-3.0
1f31fa4cdc723874dc1b9d5d1aa65cfe
38.014778
132
0.679293
4.978001
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
lib_service/src/main/java/no/nordicsemi/android/service/ServiceManager.kt
1
2728
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.service import android.bluetooth.BluetoothDevice import android.content.Context import android.content.Intent import dagger.hilt.android.qualifiers.ApplicationContext import no.nordicsemi.ui.scanner.DiscoveredBluetoothDevice import javax.inject.Inject const val DEVICE_DATA = "device-data" class ServiceManager @Inject constructor( @ApplicationContext private val context: Context ) { fun <T> startService(service: Class<T>, device: DiscoveredBluetoothDevice) { val intent = Intent(context, service).apply { putExtra(DEVICE_DATA, device) } context.startService(intent) } fun <T> startService(service: Class<T>, device: BluetoothDevice) { val intent = Intent(context, service).apply { putExtra(DEVICE_DATA, device) } context.startService(intent) } fun <T> startService(service: Class<T>) { val intent = Intent(context, service) context.startService(intent) } fun <T> stopService(service: Class<T>) { val intent = Intent(context, service) context.stopService(intent) } }
bsd-3-clause
4cdc9381fc6f056110f2be6f11faea57
37.422535
89
0.738636
4.615905
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/screen/dialog/CreateCharacterDialog.kt
1
24084
/* * The MIT License * * Copyright 2015 Nathan Templon. * * 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.jupiter.europa.screen.dialog import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener import com.badlogic.gdx.scenes.scene2d.utils.Drawable import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.jupiter.europa.EuropaGame import com.jupiter.europa.entity.EuropaEntity import com.jupiter.europa.entity.Mappers import com.jupiter.europa.entity.Party import com.jupiter.europa.entity.component.MovementResourceComponent import com.jupiter.europa.entity.effects.Effect import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.entity.stats.SkillSet.Skills import com.jupiter.europa.entity.stats.characterclass.CharacterClass import com.jupiter.europa.entity.stats.race.PlayerRaces import com.jupiter.europa.entity.stats.race.Race import com.jupiter.europa.entity.traits.EffectPool import com.jupiter.europa.entity.traits.feat.Feat import com.jupiter.europa.io.FileLocations import com.jupiter.europa.scene2d.ui.AttributeSelector import com.jupiter.europa.scene2d.ui.EuropaButton import com.jupiter.europa.scene2d.ui.EuropaButton.ClickEvent import com.jupiter.europa.scene2d.ui.MultipleNumberSelector import com.jupiter.europa.scene2d.ui.MultipleNumberSelector.MultipleNumberSelectorStyle import com.jupiter.europa.scene2d.ui.ObservableDialog import com.jupiter.europa.screen.MainMenuScreen import com.jupiter.europa.screen.MainMenuScreen.DialogExitStates import com.jupiter.ganymede.event.Listener import java.util.ArrayList import java.util.Arrays import java.util.Collections import java.util.HashSet /** * @author Nathan Templon */ public class CreateCharacterDialog : ObservableDialog(CreateCharacterDialog.DIALOG_NAME, CreateCharacterDialog.getDefaultSkin().get(javaClass<Window.WindowStyle>())) { // Enumerations public enum class CreateCharacterExitStates { OK, CANCELED } // Properties private val selectRaceClass: SelectRaceClassAttributesDialog private var selectSkills: SelectSkillsDialog? = null private var selectFeats: SelectTraitDialog<Feat>? = null private var manager: DialogManager? = null private val otherPools = ArrayList<EffectPool<out Effect>>() private val skinInternal: Skin = getDefaultSkin() public var exitState: CreateCharacterExitStates = CreateCharacterExitStates.CANCELED private set public var createdEntity: EuropaEntity? = null private set private var lastDialog: Dialog? = null private var widthInternal: Float = 0.toFloat() private var heightInternal: Float = 0.toFloat() public fun getDialogs(): Collection<ObservableDialog> { val dialogs = HashSet<ObservableDialog>(3) dialogs.add(this.selectRaceClass) dialogs.add(this.selectSkills) dialogs.add(this.selectFeats) return dialogs.filterNotNull().toSet() } init { this.selectRaceClass = SelectRaceClassAttributesDialog(skinInternal) this.selectRaceClass.addDialogListener({ args -> this.onSelectRaceClassHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.selectSkills = SelectSkillsDialog(skinInternal, 8, 4, Arrays.asList(*Skills.values())) this.selectSkills?.addDialogListener({ args -> this.onSelectSkillsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.lastDialog = this.selectRaceClass this.addDialogListener({ args -> this.onShown(args) }, ObservableDialog.DialogEvents.SHOWN) } // Public Methods override fun setSize(width: Float, height: Float) { super.setSize(width, height) this.getDialogs().forEach { it.setSize(width, height) } this.manager?.dialogs?.forEach { it.setSize(width, height) } this.widthInternal = width this.heightInternal = height } // Private Methods private fun onShown(args: ObservableDialog.DialogEventArgs) { val last = this.lastDialog if (last != null) { if (last is SelectTraitDialog<*>) { val manager = this.manager if (manager != null && manager.dialogs.contains(last)) { manager.index = manager.dialogs.indexOf(last) manager.start() } else { this.showDialog(last) } } else { this.showDialog(last) } } } private fun onSelectRaceClassHide(args: ObservableDialog.DialogEventArgs) { if (this.selectRaceClass.exitState === DialogExitStates.NEXT) { this.createEntity() val skills = Mappers.skills.get(this.createdEntity) val skillList = skills.classSkills val classComp = Mappers.characterClass.get(this.createdEntity) this.selectSkills = SelectSkillsDialog(this.skinInternal, classComp.characterClass.availableSkillPoints - skills.getSkillPointsSpent(), classComp.characterClass.maxPointsPerSkill, skillList) this.selectSkills!!.addDialogListener({ args -> this.onSelectSkillsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.showDialog(this.selectSkills) } else { this.exitState = CreateCharacterExitStates.CANCELED this.concludeDialog() } } private fun onSelectSkillsHide(args: ObservableDialog.DialogEventArgs) { if (this.selectSkills!!.exitState === DialogExitStates.NEXT) { // Debug Code this.selectFeats = SelectTraitDialog("Select Feats", this.skinInternal, Mappers.characterClass.get(this.createdEntity).characterClass.featPool) selectFeats!!.setDialogBackground(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.selectFeats!!.addDialogListener({ args -> this.onSelectFeatsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.showDialog(selectFeats) } else { this.showDialog(this.selectRaceClass) } } private fun onSelectFeatsHide(args: ObservableDialog.DialogEventArgs) { if (this.selectFeats!!.exitState === DialogExitStates.NEXT) { this.selectFeats!!.applyChanges() val charClass = Mappers.characterClass.get(this.createdEntity).characterClass this.otherPools.clear() this.otherPools.addAll(charClass.abilityPools .filter { it != charClass.featPool } .toList()) val dialogs = this.otherPools.map { pool -> SelectTraitDialog("Select " + pool.name, this.skinInternal, pool) as SelectTraitDialog<*> // Unnecessary cast due to java-kotlin interop quirk }.toList() // Switch to a DialogManager that can handle the "back" button if (dialogs.size() > 0) { for (dialog in dialogs) { dialog.setDialogBackground(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) } val manager = DialogManager(dialogs, { dialog -> this.showDialog(dialog) }) manager.onForward = { this.exitState = CreateCharacterExitStates.OK this.concludeDialog() } manager.onBack = { // Going back one dialog this.showDialog(this.selectFeats) } manager.start() this.manager = manager } else { this.exitState = CreateCharacterExitStates.OK this.concludeDialog() } } else { // Going back one dialog this.showDialog(this.selectSkills) } } private fun showDialog(dialog: Dialog?) { if (dialog != null) { dialog.show(this.getStage()) dialog.setSize(this.widthInternal, this.heightInternal) this.lastDialog = dialog } } private fun concludeDialog() { if (this.createdEntity != null) { val comp = Mappers.skills.get(this.createdEntity) if (comp != null) { val skills = comp.skills val skillLevels = this.selectSkills!!.getSelectedSkills() for ((skill, value) in skillLevels) { skills.setSkill(skill, value) } } for (dialog in this.manager?.dialogs ?: listOf()) { dialog.applyChanges() } } this.hide() } private fun createEntity() { this.createdEntity = Party.createPlayer(this.selectRaceClass.getCharacterName(), CharacterClass.CLASS_LOOKUP.get(this.selectRaceClass.getSelectedClass())!!, this.selectRaceClass.getSelectedRace(), this.selectRaceClass.getAttributes()) } // Nested Classes private class SelectRaceClassAttributesDialog(private val skinInternal: Skin) : ObservableDialog(CreateCharacterDialog.SelectRaceClassAttributesDialog.DIALOG_NAME, skinInternal.get(javaClass<Window.WindowStyle>())) { private var mainTable: Table? = null private var selectBoxTable: Table? = null private var nameTable: Table? = null private var nameLabel: Label? = null private var nameField: TextField? = null private var raceSelectBox: SelectBox<Race>? = null private var classSelectBox: SelectBox<String>? = null private var titleLabelInternal: Label? = null private var raceLabel: Label? = null private var classLabel: Label? = null private var raceClassPreview: Image? = null private var backButton: EuropaButton? = null private var nextButton: EuropaButton? = null private var attributeSelector: AttributeSelector? = null public var exitState: DialogExitStates = DialogExitStates.BACK private set public fun getSelectedClass(): String { return this.classSelectBox!!.getSelected() } public fun getSelectedRace(): Race { return this.raceSelectBox!!.getSelected() } public fun getCharacterPortrait(): Drawable { return this.raceClassPreview!!.getDrawable() } public fun getCharacterName(): String { return this.nameField!!.getText() } public fun getAttributes(): AttributeSet { return this.attributeSelector!!.getAttributes() } init { this.initComponents() this.addDialogListener({ args -> this.nextButton?.setChecked(false) this.backButton?.setChecked(false) }, ObservableDialog.DialogEvents.SHOWN) } // Private Methods private fun initComponents() { this.titleLabelInternal = Label(TITLE, skinInternal.get(javaClass<LabelStyle>())) this.raceLabel = Label("Race: ", skinInternal.get(javaClass<LabelStyle>())) this.classLabel = Label("Class: ", skinInternal.get(javaClass<LabelStyle>())) this.nameLabel = Label("Name: ", skinInternal.get(javaClass<LabelStyle>())) this.nameField = TextField("default", skinInternal.get(javaClass<TextFieldStyle>())) this.raceClassPreview = Image(EuropaGame.game.assetManager!!.get(FileLocations.SPRITES_DIRECTORY.resolve("CharacterSprites.atlas").toString(), javaClass<TextureAtlas>()).findRegion(PlayerRaces.Human.textureString + "-champion-" + MovementResourceComponent.FRONT_STAND_TEXTURE_NAME)) this.raceClassPreview?.setScale(IMAGE_SCALE.toFloat()) this.raceSelectBox = SelectBox<Race>(skinInternal.get(javaClass<SelectBox.SelectBoxStyle>())) this.raceSelectBox?.setItems(*PlayerRaces.values()) this.raceSelectBox?.addListener(object : ChangeListener() { override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) { [email protected]() } }) this.classSelectBox = SelectBox<String>(skinInternal.get(javaClass<SelectBox.SelectBoxStyle>())) this.classSelectBox?.setItems(*CharacterClass.AVAILABLE_CLASSES.toTypedArray()) this.classSelectBox?.addListener(object : ChangeListener() { override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) { [email protected]() } }) this.backButton = EuropaButton("Back", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.backButton?.addClickListener({ args -> this.onRaceClassBackButton(args) }) this.nextButton = EuropaButton("Next", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.nextButton!!.addClickListener({ args -> this.onRaceClassNextButton(args) }) this.attributeSelector = AttributeSelector(50, skinInternal.get(javaClass<MultipleNumberSelectorStyle>()), 2) this.nameTable = Table() this.nameTable!!.add<Label>(this.nameLabel).left().space(MainMenuScreen.COMPONENT_SPACING.toFloat()) this.nameTable!!.add<TextField>(this.nameField).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).padTop(10f).expandX().fillX() this.mainTable = Table() this.selectBoxTable = Table() this.selectBoxTable!!.add<Label>(this.raceLabel).fillX().space(MainMenuScreen.COMPONENT_SPACING.toFloat()) this.selectBoxTable!!.add<Label>(this.classLabel).fillX().space(MainMenuScreen.COMPONENT_SPACING.toFloat()).spaceLeft((5 * MainMenuScreen.COMPONENT_SPACING).toFloat()) this.selectBoxTable!!.row() this.selectBoxTable!!.add<SelectBox<Race>>(this.raceSelectBox).minWidth(MainMenuScreen.TITLE_BUTTON_WIDTH.toFloat()).fillX() this.selectBoxTable!!.add<SelectBox<String>>(this.classSelectBox).minWidth(MainMenuScreen.TITLE_BUTTON_WIDTH.toFloat()).fillX().spaceLeft((5 * MainMenuScreen.COMPONENT_SPACING).toFloat()) this.selectBoxTable!!.row() this.mainTable!!.add<Label>(this.titleLabelInternal).center().colspan(2) this.mainTable!!.row() this.mainTable!!.add(Image()).expandY().fillY() this.mainTable!!.row() this.mainTable!!.add<Table>(this.nameTable).colspan(2).expandX().fillX().bottom() this.mainTable!!.row() this.mainTable!!.add<Table>(this.selectBoxTable).left() this.mainTable!!.add<Image>(this.raceClassPreview).center() this.mainTable!!.row() this.mainTable!!.add<AttributeSelector>(this.attributeSelector).colspan(2).center().top().padTop(40f) this.mainTable!!.row() this.mainTable!!.add(Image()).expandY().fillY() this.mainTable!!.row() val buttonTable = Table() buttonTable.add<EuropaButton>(this.backButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() buttonTable.add<EuropaButton>(this.nextButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.add(buttonTable).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right().colspan(2).expandX().fillX() this.mainTable!!.row() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.background(skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).expand().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun updateNewCharacterPreview() { val race = this.raceSelectBox?.getSelected() val charClass = CharacterClass.CLASS_LOOKUP.get(this.classSelectBox?.getSelected()) try { val classInstance = charClass?.newInstance() val textureClassString = classInstance?.textureSetName val texture = race?.textureString + "-" + textureClassString + "-" + MovementResourceComponent.FRONT_STAND_TEXTURE_NAME val drawable = TextureRegionDrawable(EuropaGame.game.assetManager!!.get(FileLocations.SPRITES_DIRECTORY.resolve("CharacterSprites.atlas").toString(), javaClass<TextureAtlas>()).findRegion(texture)) this.raceClassPreview!!.setDrawable(drawable) } catch (ex: IllegalAccessException) { } catch (ex: InstantiationException) { } } private fun onRaceClassBackButton(event: ClickEvent) { this.exitState = DialogExitStates.BACK this.hide() } private fun onRaceClassNextButton(event: ClickEvent) { this.exitState = DialogExitStates.NEXT this.hide() } companion object { // Constants private val DIALOG_NAME = "" private val TITLE = "Select a Race and Class" private val IMAGE_SCALE = 4 } } private class SelectSkillsDialog(private val skinInternal: Skin, private val skillPointsAvailable: Int, public val maxPointsPerSkill: Int, private val selectableSkills: List<Skills>) : ObservableDialog(CreateCharacterDialog.SelectSkillsDialog.DIALOG_TITLE, skinInternal.get(javaClass<Window.WindowStyle>())) { private var mainTable: Table? = null private var titleLabelInternal: Label? = null private var skillSelector: MultipleNumberSelector? = null private var buttonTableInternal: Table? = null private var nextButton: EuropaButton? = null private var backButton: EuropaButton? = null public var exitState: DialogExitStates? = null private set public fun getSelectedSkills(): Map<Skills, Int> = this.skillSelector?.getValues()?.map { entry -> val skill = Skills.getByDisplayName(entry.getKey()) if (skill != null) { Pair(skill, entry.getValue()) } else { null } }?.filterNotNull()?.toMap() ?: mapOf() init { this.initComponent() } // Private Methods private fun initComponent() { this.titleLabelInternal = Label(TITLE, skinInternal.get(javaClass<LabelStyle>())) this.mainTable = Table() // Create Attribute Selector val skillNames = this.selectableSkills.map { skill -> skill.displayName }.toList() this.skillSelector = MultipleNumberSelector(this.skillPointsAvailable, this.skinInternal.get(javaClass<MultipleNumberSelectorStyle>()), Collections.unmodifiableList<String>(skillNames), 2) this.skillSelector?.setUseMaximumNumber(true) this.skillSelector?.maximumNumber = this.maxPointsPerSkill this.skillSelector?.setIncrement(5) this.nextButton = EuropaButton("Next", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.nextButton?.addClickListener { args -> this.onNextButton(args) } this.backButton = EuropaButton("Back", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.backButton!!.addClickListener { args -> this.onBackButton(args) } this.buttonTableInternal = Table() this.buttonTableInternal!!.add<EuropaButton>(this.backButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() this.buttonTableInternal!!.add<EuropaButton>(this.nextButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.add<Label>(this.titleLabelInternal).center().top() this.mainTable!!.row() this.mainTable!!.add<MultipleNumberSelector>(this.skillSelector).expandY().center().top() this.mainTable!!.row() this.mainTable!!.add<Table>(buttonTableInternal).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).bottom().right().expandX().fillX() this.mainTable!!.row() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.background(skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).expand().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun onNextButton(event: ClickEvent) { this.exitState = DialogExitStates.NEXT this.hide() } private fun onBackButton(event: ClickEvent) { this.exitState = DialogExitStates.BACK this.hide() } companion object { // Constants private val DIALOG_TITLE = "" private val TITLE = "Select Skills" } }// Properties private class DialogManager(internal val dialogs: List<SelectTraitDialog<*>>, private val show: (ObservableDialog) -> Unit) : Listener<ObservableDialog.DialogEventArgs> { internal var index: Int = 0 public var onForward: () -> Unit = {} public var onBack: () -> Unit = {} public fun start() { if (dialogs.size() > 0) { this.show(this.index) } else { this.onForward() } } private fun show(index: Int) { val dialog = this.dialogs[index] dialog.addDialogListener(this, ObservableDialog.DialogEvents.HIDDEN) this.show(dialog) } override fun handle(args: ObservableDialog.DialogEventArgs) { this.dialogs[this.index].removeDialogListener(this) when (this.dialogs[this.index].exitState) { DialogExitStates.BACK -> this.index-- DialogExitStates.NEXT -> this.index++ } if (this.index <= 0) { this.onBack() } else if (this.index >= this.dialogs.size()) { this.onForward() } else { this.show(this.index) } } } companion object { // Constants public val DIALOG_NAME: String = "Create a Character" // Static Methods private fun getDefaultSkin(): Skin { return MainMenuScreen.createMainMenuSkin() } } }
mit
2b232abde7df576e35fe6a0a209108ec
42.630435
313
0.65994
5.062855
false
false
false
false
cyrillrx/android_libraries
core/src/main/java/com/cyrillrx/utils/Security.kt
1
1246
package com.cyrillrx.utils import android.util.Base64 import java.math.BigInteger import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec /** * @author Cyril Leroux * Created on 20/09/2018 */ /** Keyed-Hash Message Authentication Code (HMAC) key using SHA-512 as the hash. */ private const val ALGORITHM_HMAC_SHA512 = "HmacSHA512" /** Maximum length of the new `BigInteger` in bits. */ private const val NUM_BITS = 130 /** Radix base to be used for the string representation. */ private const val RADIX = 32 fun String.base64Encode(): String? = try { val byteArray = toByteArray(Charsets.UTF_8) Base64.encodeToString(byteArray, Base64.NO_WRAP) } catch (e: Exception) { null } fun String.signature(secret: String): String? = try { val key = SecretKeySpec(secret.toByteArray(Charsets.UTF_8), ALGORITHM_HMAC_SHA512) val hMacSha512 = Mac.getInstance(ALGORITHM_HMAC_SHA512) hMacSha512.init(key) val byteArray = toByteArray(Charsets.UTF_8) val macData = hMacSha512.doFinal(byteArray) Base64.encodeToString(macData, Base64.NO_WRAP) } catch (e: Exception) { null } fun buildNonce(): String = BigInteger(NUM_BITS, SecureRandom()).toString(RADIX)
mit
f27ac2dbd6890d43f57e78f7c518a7cf
25.531915
86
0.725522
3.461111
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/model/Term.kt
1
5022
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.model import android.content.Context import android.database.Cursor import android.os.Parcel import android.os.Parcelable import co.timetableapp.data.TimetableDbHelper import co.timetableapp.data.handler.DataNotFoundException import co.timetableapp.data.schema.TermsSchema import org.threeten.bp.LocalDate /** * Represents a term (or semester) in a student's timetable. * * A `Term` does not have any links with classes, assignments, exams, or any other model except * from the [Timetable] to which it belongs to. This means that [Class]es must set their own start * and end dates. * * @property timetableId the identifier of the [Timetable] this term belongs to * @property name the name for this term (e.g. First Semester, Summer Term, etc.) * @property startDate the start date of this term * @property endDate the end date of this term */ data class Term( override val id: Int, override val timetableId: Int, val name: String, val startDate: LocalDate, val endDate: LocalDate ) : TimetableItem, Comparable<Term> { init { if (startDate.isAfter(endDate)) { throw IllegalArgumentException("the start date cannot be after the end date") } } companion object { /** * Constructs a [Term] using column values from the cursor provided * * @param cursor a query of the terms table * @see [TermsSchema] */ @JvmStatic fun from(cursor: Cursor): Term { val startDate = LocalDate.of( cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_YEAR)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_MONTH)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_DAY_OF_MONTH))) val endDate = LocalDate.of( cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_YEAR)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_MONTH)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_DAY_OF_MONTH))) return Term( cursor.getInt(cursor.getColumnIndex(TermsSchema._ID)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_TIMETABLE_ID)), cursor.getString(cursor.getColumnIndex(TermsSchema.COL_NAME)), startDate, endDate) } /** * Creates a [Term] from the [termId] and corresponding data in the database. * * @throws DataNotFoundException if the database query returns no results * @see from */ @JvmStatic @Throws(DataNotFoundException::class) fun create(context: Context, termId: Int): Term { val db = TimetableDbHelper.getInstance(context).readableDatabase val cursor = db.query( TermsSchema.TABLE_NAME, null, "${TermsSchema._ID}=?", arrayOf(termId.toString()), null, null, null) if (cursor.count == 0) { cursor.close() throw DataNotFoundException(this::class.java, termId) } cursor.moveToFirst() val term = Term.from(cursor) cursor.close() return term } @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<Term> = object : Parcelable.Creator<Term> { override fun createFromParcel(source: Parcel): Term = Term(source) override fun newArray(size: Int): Array<Term?> = arrayOfNulls(size) } } private constructor(source: Parcel) : this( source.readInt(), source.readInt(), source.readString(), source.readSerializable() as LocalDate, source.readSerializable() as LocalDate ) override fun compareTo(other: Term): Int { return startDate.compareTo(other.startDate) } override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(id) dest?.writeInt(timetableId) dest?.writeString(name) dest?.writeSerializable(startDate) dest?.writeSerializable(endDate) } }
apache-2.0
772fb461b101498fb5868f541d1def0f
35.129496
98
0.626444
4.728814
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/datatypes/LoanProductBundle.kt
1
2070
/* * Copyright (c) 2019. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.test.loanOrigination.datatypes import kotlinx.serialization.Serializable @Serializable open class LoanProductBundle(val name: String, val id: String) { fun withPrice(customerId: String, amount: Double, price: Double): PricedLoanProductBundle { return PricedLoanProductBundle( name, id, customerId, amount, price, false ) } override fun toString(): String { return "LoanProductBundle(name='$name', id='$id')" } } @Serializable class PricedLoanProductBundle : LoanProductBundle { val customerId: String val price: Double val approvedOffer: Boolean val amount: Double constructor(name: String, id: String, customerId: String, amount: Double, price: Double, approvedOffer: Boolean) : super(name, id) { this.customerId = customerId this.price = price this.approvedOffer = approvedOffer this.amount = amount } fun approve(): PricedLoanProductBundle { return PricedLoanProductBundle(name, id, customerId, amount, price, true) } override fun toString(): String { return "PricedLoanProductBundle(name='$name', id='$id', customerId='$customerId', price=$price, approvedOffer=$approvedOffer, amount=$amount)" } }
lgpl-3.0
6962c7855d6c57bc7475963275ab2d1a
30.846154
150
0.678744
4.715262
false
false
false
false
googlecodelabs/android-dagger
app/src/main/java/com/example/android/dagger/login/LoginViewModel.kt
1
1491
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.android.dagger.user.UserManager /** * LoginViewModel is the ViewModel that [LoginActivity] uses to * obtain information of what to show on the screen and handle complex logic. */ class LoginViewModel(private val userManager: UserManager) { private val _loginState = MutableLiveData<LoginViewState>() val loginState: LiveData<LoginViewState> get() = _loginState fun login(username: String, password: String) { if (userManager.loginUser(username, password)) { _loginState.value = LoginSuccess } else { _loginState.value = LoginError } } fun unregister() { userManager.unregister() } fun getUsername(): String = userManager.username }
apache-2.0
60f3a7cf773edb85a25c9e8c4d9d850d
31.413043
77
0.716298
4.518182
false
false
false
false
aleksey-zhidkov/jeb-k
src/main/kotlin/jeb/jeb.kt
1
3568
package jeb import jeb.util.Try import java.io.BufferedReader import java.io.File import java.nio.file.Paths import java.time.LocalDateTime val usage = "Usage: jeb-k <init|backup [--force] <dir>>" fun main(args: Array<String>) { when { args.size == 0 -> println(usage) args[0] == "init" -> init() args[0] == "backup" -> { val force = args[1] == "--force" val dir = if (force) { args[2] } else { args[1] } backup(File(dir), LocalDateTime.now(), force) } else -> println(usage) } } fun init() { val currentDir = System.getProperty("user.dir").withTailingSlash() val sourceDirs = readSourceDirs(currentDir) val backupDirDefault = if (sourceDirs.contains(currentDir)) null else currentDir val backupDir = readLine("Backups directory", backupDirDefault) val disksCount = readLine("Backups count", "10").toInt() val state = State(backupDir, sourceDirs.map(::Source), Hanoi(disksCount)) State.saveState(File(backupDir, "jeb.json"), state) } private fun backup(backupDir: File, time: LocalDateTime, force: Boolean) { var config = File(backupDir, "jeb.json") if (!config.exists()) { config = backupDir } if (!config.exists()) { println("jeb-k config is not found at ${config.absolutePath}") return } val state = State.loadState(config) when (state) { is Try.Success -> doBackup(config, state.result, time, force) is Try.Failure -> println(state.reason.message) } } private fun doBackup(config: File, state: State, time: LocalDateTime, force: Boolean) { try { var excludesFile = Paths.get(state.backupsDir, "excludes.txt") if (!excludesFile.toFile().exists()) { excludesFile = Paths.get(config.parent, "excludes.txt") if (!excludesFile.toFile().exists()) { excludesFile = null } } val newState = Backuper(Storage(), time).doBackup(state, force, excludesFile) when (newState) { is Try.Success -> newState.result?.let { State.saveState(config, it) } is Try.Failure -> log.error(newState.reason) } } catch(e: JebExecException) { log.error(e) } } private fun readSourceDirs(currentDir: String): List<String> { val sources = arrayListOf<String>() var defaultSourceDir: String? = currentDir do { val invitation = if (sources.size == 0) "Source directory (add trailing slash to backup directory content or leave it blank to backup directory)\n" else "Source directory" val source = readLine(invitation, defaultSourceDir) if (source == defaultSourceDir) { defaultSourceDir = null } sources.add(source) } while (readLine("Add another source? [yes/No]", "no").toLowerCase() == "yes") return sources } // Hack for tests: do not recreate buffered reader on each call var inReader: BufferedReader? = null get() { if (field == null) field = System.`in`.bufferedReader() return field } private fun readLine(invitation: String, default: String?): String { val defaultMsg = if (default != null) " [Leave empty to use $default]" else "" print("$invitation$defaultMsg:") val line = inReader!!.readLine() return if (line.length > 0 || default == null) line else default } private fun String.withTailingSlash() = if (this.endsWith("/")) this else this + "/"
apache-2.0
be4585d2e8391faf5ade1df49b6310f0
32.345794
155
0.613509
4.04077
false
true
false
false
strykeforce/thirdcoast
src/main/kotlin/org/strykeforce/telemetry/grapher/ClientHandler.kt
1
1645
package org.strykeforce.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private const val PERIOD = 5L // milliseconds private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the `Measurable` items specified in the subscription. * * @param subscription items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, PERIOD, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } }
mit
dff31c2fae2401ff63b81151ed29146d
30.634615
80
0.685714
4.795918
false
false
false
false
pdvrieze/ProcessManager
darwin/src/commonMain/kotlin/net/devrieze/util/util.kt
1
1706
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ /** * Generic utility methods for use in kotlin */ package net.devrieze.util inline fun <T> T?.valIfNot(alternate:T, condition:T.()->Boolean):T = if (this!=null && condition()) this else alternate inline fun <T> T.valIf(alternate:T, condition:T.()->Boolean):T = if (condition()) alternate else this inline fun <T> T?.valIfNullOr(alternate:T, condition:T.()->Boolean):T = if (this==null || condition()) alternate else this inline fun <T> T?. nullIfNot(condition:T.()->Boolean):T? = if (this?.condition() == true) this else null interface __Override__<T> { infix fun by(alternative:T):T } class __Override__T<T> : __Override__<T> { override infix fun by(alternative: T):T { return alternative } } class __Override__F<T>(val value:T):__Override__<T> { override infix fun by(alternative: T):T { return value } } inline fun <T> T?.overrideIf(crossinline condition: T.() -> Boolean): __Override__<T> { return if (this==null || condition()) __Override__T() else __Override__F(this) }
lgpl-3.0
85a673c26dd8964c88d394d372ac2944
31.188679
112
0.689332
3.660944
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/index/stub/BibtexEntryStubElementType.kt
1
1641
package nl.hannahsten.texifyidea.index.stub import com.intellij.psi.stubs.* import nl.hannahsten.texifyidea.BibtexLanguage import nl.hannahsten.texifyidea.index.BibtexEntryIndex import nl.hannahsten.texifyidea.psi.BibtexEntry import nl.hannahsten.texifyidea.psi.impl.BibtexEntryImpl open class BibtexEntryStubElementType(debugName: String) : IStubElementType<BibtexEntryStub, BibtexEntry>(debugName, BibtexLanguage) { override fun createPsi(stub: BibtexEntryStub): BibtexEntry { return BibtexEntryImpl(stub, this) } override fun serialize(stub: BibtexEntryStub, dataStream: StubOutputStream) { dataStream.writeName(stub.identifier) dataStream.writeName(stub.title) dataStream.writeName(stub.authors.joinToString(";")) dataStream.writeName(stub.year) } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): BibtexEntryStub { val name = dataStream.readName()?.string ?: "" val title = dataStream.readName()?.string ?: "" val authors = (dataStream.readName()?.string ?: "").split(";") val year = dataStream.readName()?.string ?: "" return BibtexEntryStubImpl(parentStub, this, name, authors, year, title) } override fun createStub(entry: BibtexEntry, parentStub: StubElement<*>?): BibtexEntryStub { return BibtexEntryStubImpl(parentStub, this, entry.identifier, entry.authors, entry.year, entry.title) } override fun getExternalId() = "ENTRY" override fun indexStub(stub: BibtexEntryStub, sink: IndexSink) { sink.occurrence(BibtexEntryIndex.key, stub.name ?: "") } }
mit
58da0175c0ddfe043688f263e47bb25d
41.102564
134
0.725168
4.898507
false
false
false
false
lightem90/Sismic
app/src/main/java/com/polito/sismic/Presenters/ReportActivity/NoteActivity.kt
1
1217
package com.polito.sismic.Presenters.ReportActivity import android.app.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import com.polito.sismic.R import kotlinx.android.synthetic.main.activity_note.* //Custom activity to take a note class NoteActivity : AppCompatActivity() { private lateinit var mUserName : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_note) mUserName = intent.getStringExtra("username") note_save.setOnClickListener { exitWithSuccess() } } private fun exitWithSuccess() { val intent = Intent() intent.putExtra("note", note.text.toString()) setResult(Activity.RESULT_OK, intent) finish() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { val intent = Intent() intent.putExtra("username", mUserName) setResult(Activity.RESULT_CANCELED, intent) finish() return true } return false } }
mit
df6efccf0973971a2d4075aa8f185e75
27.97619
66
0.678718
4.680769
false
false
false
false
Devexperts/usages
api/src/main/kotlin/com/devexperts/usages/api/Model.kt
1
7319
/** * Copyright (C) 2017 Devexperts LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. */ package com.devexperts.usages.api import com.fasterxml.jackson.annotation.JsonProperty import java.util.* data class Member( @JsonProperty("memberName") val qualifiedMemberName: String, @JsonProperty("paramTypes") val parameterTypes: List<String>, @JsonProperty("type") val type: MemberType ) { fun packageName(): String { if (type == MemberType.PACKAGE) return qualifiedMemberName; val className = className(); val lastDotIndex = className.lastIndexOf('.') return if (lastDotIndex == -1) qualifiedMemberName else qualifiedMemberName.substring(0, lastDotIndex) } fun className() = when (type) { MemberType.PACKAGE -> throw IllegalStateException("Cannot return class name for package member") MemberType.CLASS -> qualifiedMemberName else -> qualifiedMemberName.substring(0, qualifiedMemberName.indexOf('#')) } fun simpleClassName() = simpleNonPackageName(className()) fun simpleName(): String { if (type == MemberType.PACKAGE) return qualifiedMemberName var simpleName = simpleNonPackageName(qualifiedMemberName) if (type == MemberType.METHOD) simpleName += "(${simpleParameters()})" return simpleName } fun simpleMemberName(): String { if (type == MemberType.PACKAGE || type == MemberType.CLASS) throw IllegalStateException("Simple member name is allowed for fields and methods only, current member is $this") var simpleMemberName = qualifiedMemberName.substring(qualifiedMemberName.indexOf("#") + 1) if (type == MemberType.METHOD && !parameterTypes.isEmpty()) simpleMemberName += "(${simpleParameters()})" return simpleMemberName } private fun simpleNonPackageName(qualifiedName: String): String { val lastDotIndex = qualifiedName.lastIndexOf('.') return if (lastDotIndex < 0) qualifiedName else qualifiedName.substring(lastDotIndex + 1) } private fun simpleParameters(): String { val paramsJoiner = StringJoiner(", ") for (p in parameterTypes) { paramsJoiner.add(simpleNonPackageName(p)) } return paramsJoiner.toString() } override fun toString(): String { var res = qualifiedMemberName if (type == MemberType.METHOD) { res = "$res(${simpleParameters()})" } return res } override fun hashCode(): Int { var result = qualifiedMemberName.hashCode() result = 31 * result + parameterTypes.hashCode() result = 31 * result + type.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Member if (qualifiedMemberName != other.qualifiedMemberName) return false if (parameterTypes != other.parameterTypes) return false if (type != other.type) return false return true } companion object { fun fromPackage(packageName: String) = Member(packageName, emptyList(), MemberType.PACKAGE) fun fromClass(className: String) = Member(className, emptyList(), MemberType.CLASS) fun fromField(className: String, fieldName: String) = Member( "$className#$fieldName", emptyList(), MemberType.FIELD) fun fromMethod(className: String, methodName: String, parameterTypes: List<String>) = Member( "$className#$methodName", parameterTypes, MemberType.METHOD) } } enum class MemberType constructor(val typeName: String) { PACKAGE("package"), CLASS("class"), METHOD("method"), FIELD("field"); override fun toString(): String { return typeName } } data class MemberUsage( @JsonProperty("member") val member: Member, @JsonProperty("usageKind") val usageKind: UsageKind, @JsonProperty("location") val location: Location ) data class Location( @JsonProperty("artifact") val artifact: Artifact, @JsonProperty("member") val member: Member, // class or method @JsonProperty("file") val file: String?, // content file, do not use it for equals and hashCode! @JsonProperty("line") val lineNumber: Int? // line number of usage in the file ) { init { // if (member.type != MemberType.CLASS && member.type != MemberType.METHOD) // throw IllegalArgumentException("Only methods and classes could be used as location, current member $member") } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Location if (artifact != other.artifact) return false if (member != other.member) return false if (lineNumber != other.lineNumber) return false return true } override fun hashCode(): Int { var result = artifact.hashCode() result = 31 * result + member.hashCode() if (lineNumber != null) result = 31 * result + lineNumber return result } } data class Artifact( @JsonProperty("groupId") val groupId: String, @JsonProperty("artifactId") val artifactId: String, @JsonProperty("version") val version: String, @JsonProperty("type") val type: String?, @JsonProperty("classifier") val classifier: String? ) { override fun toString() = "$groupId:$artifactId:${type ?: ""}:${classifier ?: ""}:$version" } // Do not rename enum values for backwards compatibility enum class UsageKind constructor(val description: String) { UNCLASSIFIED("Unclassified"), SIGNATURE("Signature"), CLASS_DECLARATION("Class declaration"), EXTEND_OR_IMPLEMENT("Usage in inheritance (extends or implements)"), OVERRIDE("Method overriding"), METHOD_DECLARATION("Method declaration"), METHOD_PARAMETER("Method parameter"), METHOD_RETURN("Method return type"), ANNOTATION("Annotation"), THROW("Throw"), CATCH("Catch"), CONSTANT("Constant"), FIELD("Field"), ASTORE("Local variable"), NEW("New instance"), ANEWARRAY("New array"), CAST("Type cast"), GETFIELD("Read field"), PUTFIELD("Write field"), GETSTATIC("Read static field"), PUTSTATIC("Write static field"), INVOKEVIRTUAL("Invoke virtual method"), INVOKESPECIAL("Invoke special method"), INVOKESTATIC("Invoke static method"), INVOKEINTERFACE("Invoke interface method"), INVOKEDYNAMIC("Invoke dynamic") }
gpl-3.0
36c6a33ef8d70fccabf023531ab5a201
34.192308
125
0.658697
4.931941
false
false
false
false
yotkaz/thimman
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/JobOfferChallenge.kt
1
635
package yotkaz.thimman.backend.model import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR import javax.persistence.* @Entity data class JobOfferChallenge( @Id @GeneratedValue(strategy = GenerationType.TABLE) var id: Long? = null, @ManyToOne(fetch = FetchType.EAGER) var jobOffer: JobOffer?, @ManyToOne(fetch = FetchType.EAGER) var challenge: Challenge?, @Embedded var challengeAttributes: ChallengeAttributes? = null ) { @Deprecated(JPA_EMPTY_CONSTRUCTOR) constructor() : this( jobOffer = null, challenge = null ) }
apache-2.0
804cc11b79cbed58a2f37bd70ff3fd7b
20.2
60
0.64252
4.440559
false
false
false
false
benkyokai/tumpaca
app/src/main/kotlin/com/tumpaca/tp/util/DownloadUtils.kt
1
4399
package com.tumpaca.tp.util import android.app.DownloadManager import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Environment import android.util.DisplayMetrics import android.util.Log import com.tumpaca.tp.R import com.tumpaca.tp.activity.MainActivity import com.tumpaca.tp.model.TPRuntime import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.net.URL class DownloadUtils { companion object { private const val TAG = "DownloadUtils" // 外部ストレージ許可のダイアログから戻ってきたときにダウンロードを再開するために // 対象の URL をこれに保存しておく。なお、画面が回転されたりしたら復元しないがそれは諦める。 private var urlToSave: String? = null @JvmStatic fun downloadPhoto(url: String): Observable<Bitmap> { return Observable .create { emitter: ObservableEmitter<Bitmap> -> try { val photo = TPRuntime.bitMapCache.getIfNoneAndSet(url) { URL(url).openStream().use { stream -> val options = BitmapFactory.Options() options.inDensity = DisplayMetrics.DENSITY_MEDIUM BitmapFactory.decodeStream(stream, null, options) } } photo?.let { emitter.onNext(it) } emitter.onComplete() } catch (e: Exception) { Log.e("downloadPhoto", e.message.orEmpty(), e) emitter.onError(e) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } @JvmStatic fun downloadGif(url: String): Observable<ByteArray> { return Observable .create { emitter: ObservableEmitter<ByteArray> -> try { val gif = TPRuntime.gifCache.getIfNoneAndSet(url) { URL(url).openStream().use { stream -> stream.readBytes() } } gif?.let { emitter.onNext(gif) } emitter.onComplete() } catch (e: Exception) { Log.e("downloadGif", e.message.orEmpty(), e) emitter.onError(e) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } @JvmStatic fun saveImage(activity: MainActivity, url: String) { if (!activity.checkStoragePermissions()) { urlToSave = url activity.requestStoragePermissions() return } val target = Uri.parse(url) val request = DownloadManager.Request(target) val fileName = target.lastPathSegment request.setDescription(activity.resources.getString(R.string.download_image)) request.setTitle(fileName) request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) val manager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager? manager?.enqueue(request) Log.d(TAG, "startDownload started... fileName=$fileName,url=$url") } @JvmStatic fun resumeSaveImage(activity: MainActivity) { if (urlToSave != null) { val url: String = urlToSave as String urlToSave = null saveImage(activity, url) } } } }
gpl-3.0
e020ef1d0aa0c5f9c737566da38b35aa
38.971698
106
0.522068
5.453024
false
false
false
false
AoEiuV020/PaNovel
pager/src/main/java/cc/aoeiuv020/pager/PagerDrawer.kt
1
514
package cc.aoeiuv020.pager /** * * Created by AoEiuV020 on 2017.12.07-23:54:07. */ abstract class PagerDrawer : IPagerDrawer { var pager: Pager? = null protected lateinit var backgroundSize: Size protected lateinit var contentSize: Size override fun attach(pager: Pager, backgroundSize: Size, contentSize: Size) { this.pager = pager this.backgroundSize = backgroundSize this.contentSize = contentSize } override fun detach() { this.pager = null } }
gpl-3.0
7dd60cb2cf2b62bf15f4a8c3e767bcbe
23.52381
80
0.671206
4.178862
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/WidgetTestHelper.kt
1
8143
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device.datatypes class WidgetTestHelper { // TODO Fix tests companion object { /*@JvmStatic private fun newGenWidget(args: Map<String, Any>, widgetGenIndex: Int): Widget { assert(widgetGenIndex >= 1) val genArgs = args.toMutableMap() // @formatter:off genArgs["uid"] = args["uid"] ?: getIdsList(widgetGenIndex).last() genArgs["text"] = args["text"] ?: getTextsList(widgetGenIndex, (0 until widgetGenIndex).map { _ -> genArgs["uid"] as String? ?: "" }).last() genArgs["bounds"] = args["bounds"] ?: getBoundsList(widgetGenIndex).last() genArgs["className"] = args["className"] ?: getClassesList(widgetGenIndex).last() genArgs["enabled"] = args["enabled"] ?: true // @formatter:on return newWidget(genArgs) } @Suppress("UNCHECKED_CAST") @JvmStatic fun newWidgets(widgetCount: Int, packageName: String, props: Map<String, Any>, widgetIdPrefix: String = ""): List<Widget> { assert(widgetCount >= 1) val propIdsList = props["idsList"] val idsList = if ( (propIdsList == null) || (propIdsList as List<String>).isEmpty() ) getIdsList(widgetCount, widgetIdPrefix) else propIdsList val textsList = props["textsList"] as List<String>? ?: getTextsList(widgetCount, idsList) val boundsList = props["boundsList"] as List<List<Int>>? ?: getBoundsList(widgetCount) val classesList = props["classList"] as List<String>? ?: getClassesList(widgetCount) val enabledList = props["enabledList"] as List<Boolean>? ?: (0..widgetCount).map { _ -> true } assert(arrayListOf(idsList, textsList, boundsList, classesList, enabledList).all { it.size == widgetCount }) val widgets = (0 until widgetCount).map { i -> newWidget(mutableMapOf( "uid" to idsList[i], "text" to textsList[i], "bounds" to boundsList[i], "className" to classesList[i], "packageName" to packageName, "clickable" to true, "check" to false, "enabled" to enabledList[i] )) } assert(widgets.size == widgetCount) return widgets } @JvmStatic private fun getIdsList(idsCount: Int, widgetIdPrefix: String = ""): List<String> = (0 until idsCount).map { i -> getNextWidgetId(i, widgetIdPrefix) } @JvmStatic private fun getTextsList(textsCount: Int, widgetIds: List<String>): List<String> { assert(widgetIds.size == textsCount) return (0 until textsCount).map { i -> "txt:uid/${widgetIds[i]}" } } @JvmStatic private fun getClassesList(classesCount: Int): List<String> { val classesList = androidWidgetClassesForTesting return (0 until classesCount).map { index -> val classNameIndex = index % classesList.size classesList[classNameIndex] } } @JvmStatic private fun getBoundsList(boundsCount: Int): List<List<Int>> { var lowX = 5 + getBoundsListCallGen var lowY = 6 + getBoundsListCallGen getBoundsListCallGen++ var highX = lowX + 20 var highY = lowY + 30 val bounds: MutableList<List<Int>> = mutableListOf() (0 until boundsCount).forEach { _ -> bounds.update(arrayListOf(lowX, lowY, highX, highY)) lowX += 25 lowY += 35 highX = lowX + 20 highY = lowY + 30 } return bounds } @JvmStatic private var dummyNameGen = 0 @JvmStatic private var getBoundsListCallGen = 0 @JvmStatic private fun getNextWidgetId(index: Int, widgetIdPrefix: String = ""): String { return if (widgetIdPrefix.isEmpty()) "${index}_uniq${dummyNameGen++}" else "${widgetIdPrefix}_W$index" } @JvmStatic private val androidWidgetClassesForTesting = arrayListOf( "android.view.View", "android.widget.Button", "android.widget.CheckBox", "android.widget.CheckedTextView", "android.widget.CompoundButton", "android.widget.EditText", "android.widget.GridView", "android.widget.ImageButton", "android.widget.ImageView", "android.widget.LinearLayout", "android.widget.ListView", "android.widget.RadioButton", "android.widget.RadioGroup", "android.widget.Spinner", "android.widget.Switch", "android.widget.TableLayout", "android.widget.TextView", "android.widget.ToggleButton" ) @JvmStatic fun newClickableButton(args: MutableMap<String, Any> = HashMap()): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("clickable" to true, "check" to true, "enabled" to true)) } return newButton(newArgs) } @JvmStatic private fun newButton(args: Map<String, Any>): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("className" to "android.widget.Button")) } return newWidget(newArgs) } @JvmStatic @Suppress("unused") fun newTopLevelWidget(packageName: String): Widget { return newWidget(mapOf("uid" to "topLevelFrameLayout", "packageName" to packageName, "class" to "android.widget.FrameLayout", "bounds" to arrayListOf(0, 0, 800, 1205)) .toMutableMap()) } @JvmStatic fun newClickableWidget(args: MutableMap<String, Any> = HashMap(), widgetGenIndex: Int = 0): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("clickable" to true, "enabled" to true)) } return if (widgetGenIndex > 0) newWidget(newArgs) else newGenWidget(newArgs, widgetGenIndex + 1) } @Suppress("UNCHECKED_CAST") @JvmStatic private fun newWidget(args: MutableMap<String, Any>): Widget { val bounds = if (args["bounds"] != null) args["bounds"] as List<Int> else arrayListOf(10, 20, 101, 202) if (args["className"] == null) args["className"] = androidWidgetClassesForTesting[1] assert(bounds.size == 4) assert(bounds[0] < bounds[2]) assert(bounds[1] < bounds[3]) val lowX = bounds[0] val lowY = bounds[1] val highX = bounds[2] val highY = bounds[3] val xpath = "//${args["className"] as String? ?: "fix_cls"}[${(args["index"] as Int? ?: 0) + 1}]" return OldWidget(args["uid"] as String? ?: "", args["index"] as Int? ?: 0, args["text"] as String? ?: "fix_text", args["resourceId"] as String? ?: "fix_resId", args["className"] as String? ?: "fix_cls", args["packageName"] as String? ?: "fix_pkg", args["contentDesc"] as String? ?: "fix_contDesc", args["xpath"] as String? ?: xpath, args["check"] as Boolean? ?: false, args["check"] as Boolean? ?: false, args["clickable"] as Boolean? ?: false, args["enabled"] as Boolean? ?: false, args["focusable"] as Boolean? ?: false, args["focus"] as Boolean? ?: false, args["scrollable"] as Boolean? ?: false, args["longClickable"] as Boolean? ?: false, args["password"] as Boolean? ?: false, args["selected"] as Boolean? ?: false, Rectangle(lowX, lowY, highX - lowX, highY - lowY), null) // @formatter:on }*/ } }
gpl-3.0
31255b166fd889b9e0ac3b4fd1c16329
33.948498
144
0.651603
3.691296
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/structures/MultiblockHydraulicPress.kt
2
5961
package com.cout970.magneticraft.features.multiblocks.structures import com.cout970.magneticraft.misc.vector.plus import com.cout970.magneticraft.misc.vector.rotateBox import com.cout970.magneticraft.misc.vector.times import com.cout970.magneticraft.misc.vector.vec3Of import com.cout970.magneticraft.systems.multiblocks.* import com.cout970.magneticraft.systems.tilerenderers.PIXEL import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.text.ITextComponent import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks object MultiblockHydraulicPress : Multiblock() { override val name: String = "hydraulic_press" override val size: BlockPos = BlockPos(3, 5, 3) override val scheme: List<MultiblockLayer> override val center: BlockPos = BlockPos(1, 0, 0) init { val I = IgnoreBlockComponent val R = corrugatedIronBlock() val G = grateBlock() val C = copperCoilBlock() val Y = strippedBlock() val U = columnBlock(EnumFacing.UP) val H = columnBlock(EnumFacing.EAST) val M = mainBlockOf(controllerBlock) scheme = yLayers( zLayers( listOf(I, I, I), // y = 4 listOf(H, H, H), listOf(I, I, I)), zLayers( listOf(I, I, I), // y = 3 listOf(U, R, U), listOf(I, I, I)), zLayers( listOf(I, I, I), // y = 2 listOf(U, Y, U), listOf(I, I, I)), zLayers( listOf(G, G, G), // y = 1 listOf(C, R, C), listOf(G, G, G)), zLayers( listOf(G, M, G), // y = 0 listOf(G, G, G), listOf(G, G, G)) ) } override fun getControllerBlock() = Multiblocks.hydraulicPress override fun getGlobalCollisionBoxes(): List<AxisAlignedBB> = hitboxes val hitboxes = listOf( Vec3d(-14.000, 4.000, 1.000) * PIXEL to Vec3d(-3.000, 20.000, 15.000) * PIXEL, Vec3d(2.000, 16.000, 2.000) * PIXEL to Vec3d(14.000, 30.000, 14.000) * PIXEL, Vec3d(2.000, 40.000, 13.000) * PIXEL to Vec3d(14.000, 58.000, 14.000) * PIXEL, Vec3d(0.000, 40.000, 12.000) * PIXEL to Vec3d(3.000, 58.000, 13.000) * PIXEL, Vec3d(0.000, 40.000, 3.000) * PIXEL to Vec3d(3.000, 58.000, 4.000) * PIXEL, Vec3d(2.000, 40.000, 2.000) * PIXEL to Vec3d(14.000, 58.000, 3.000) * PIXEL, Vec3d(-7.000, 44.000, 12.100) * PIXEL to Vec3d(23.000, 47.000, 15.100) * PIXEL, Vec3d(-6.000, 43.000, 12.000) * PIXEL to Vec3d(-3.000, 48.000, 16.000) * PIXEL, Vec3d(-11.000, 20.000, 3.000) * PIXEL to Vec3d(-1.000, 51.000, 13.000) * PIXEL, Vec3d(15.000, 42.000, 4.000) * PIXEL to Vec3d(25.000, 70.000, 12.000) * PIXEL, Vec3d(19.000, 43.000, 12.000) * PIXEL to Vec3d(22.000, 48.000, 16.000) * PIXEL, Vec3d(19.000, 4.000, 1.000) * PIXEL to Vec3d(30.000, 20.000, 15.000) * PIXEL, Vec3d(17.000, 20.000, 3.000) * PIXEL to Vec3d(27.000, 51.000, 13.000) * PIXEL, Vec3d(-11.000, 70.000, 2.000) * PIXEL to Vec3d(27.000, 78.000, 14.000) * PIXEL, Vec3d(-9.000, 42.000, 4.000) * PIXEL to Vec3d(1.000, 70.000, 12.000) * PIXEL, Vec3d(-7.000, 44.000, 0.900) * PIXEL to Vec3d(23.000, 47.000, 3.900) * PIXEL, Vec3d(19.000, 43.000, 0.000) * PIXEL to Vec3d(22.000, 48.000, 4.000) * PIXEL, Vec3d(-6.000, 43.000, 0.000) * PIXEL to Vec3d(-3.000, 48.000, 4.000) * PIXEL, Vec3d(13.000, 40.000, 3.000) * PIXEL to Vec3d(16.000, 58.000, 4.000) * PIXEL, Vec3d(13.000, 40.000, 12.000) * PIXEL to Vec3d(16.000, 58.000, 13.000) * PIXEL, Vec3d(-2.000, 0.000, 3.000) * PIXEL to Vec3d(-1.000, 1.000, 13.000) * PIXEL, Vec3d(17.000, 0.000, 3.000) * PIXEL to Vec3d(18.000, 1.000, 13.000) * PIXEL, Vec3d(27.000, 18.000, 4.000) * PIXEL to Vec3d(31.000, 30.000, 12.000) * PIXEL, Vec3d(31.000, 22.000, 6.000) * PIXEL to Vec3d(32.000, 26.000, 10.000) * PIXEL, Vec3d(3.000, 38.000, 3.000) * PIXEL to Vec3d(13.000, 52.000, 13.000) * PIXEL, Vec3d(6.500, 52.000, 6.500) * PIXEL to Vec3d(9.500, 80.000, 9.500) * PIXEL, Vec3d(-16.000, 0.000, -16.000) * PIXEL to Vec3d(0.000, 4.000, 32.000) * PIXEL, Vec3d(16.000, 0.000, -16.000) * PIXEL to Vec3d(32.000, 4.000, 32.000) * PIXEL, Vec3d(0.000, 12.000, -12.000) * PIXEL to Vec3d(16.000, 20.000, -4.000) * PIXEL, Vec3d(1.000, 11.460, -15.654) * PIXEL to Vec3d(15.000, 14.000, -11.593) * PIXEL, Vec3d(0.000, 0.000, -16.000) * PIXEL to Vec3d(1.000, 20.000, -12.000) * PIXEL, Vec3d(15.000, 0.000, -16.000) * PIXEL to Vec3d(16.000, 20.000, -12.000) * PIXEL, Vec3d(1.000, 19.000, -16.000) * PIXEL to Vec3d(15.000, 20.000, -12.000) * PIXEL, Vec3d(-10.000, 12.000, -11.000) * PIXEL to Vec3d(8.000, 24.000, 27.000) * PIXEL, Vec3d(8.000, 12.000, -11.000) * PIXEL to Vec3d(26.000, 24.000, 27.000) * PIXEL, Vec3d(-12.000, 0.000, -12.000) * PIXEL to Vec3d(8.000, 12.000, 8.000) * PIXEL, Vec3d(8.000, 0.000, -12.000) * PIXEL to Vec3d(28.000, 12.000, 8.000) * PIXEL, Vec3d(8.000, 0.000, 8.000) * PIXEL to Vec3d(28.000, 12.000, 28.000) * PIXEL, Vec3d(-12.000, 0.000, 8.000) * PIXEL to Vec3d(8.000, 12.000, 28.000) * PIXEL, Vec3d(-14.500, 18.000, 4.000) * PIXEL to Vec3d(-10.500, 30.000, 12.000) * PIXEL, Vec3d(-15.500, 22.000, 6.000) * PIXEL to Vec3d(-14.500, 26.000, 10.000) * PIXEL, Vec3d(0.000, 0.000, 24.000) * PIXEL to Vec3d(16.000, 15.000, 32.000) * PIXEL ).map { EnumFacing.SOUTH.rotateBox(vec3Of(0.5), it) + vec3Of(0, 0, 1) } override fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> = emptyList() }
gpl-2.0
cf616e5071bd9f2d1d80d733b276c543
52.232143
133
0.590169
2.659973
false
false
false
false
rcgroot/open-gpstracker-ng
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/gpximport/ImportTrackTypeDialogFragment.kt
1
4328
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.gpximport import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableBoolean import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProviders import nl.sogeti.android.gpstracker.utils.FragmentResultLambda import nl.sogeti.android.gpstracker.v2.sharedwear.util.observe import nl.sogeti.android.opengpstrack.ng.features.R import nl.sogeti.android.opengpstrack.ng.features.databinding.FragmentImportTracktypeDialogBinding class ImportTrackTypeDialogFragment : DialogFragment() { private lateinit var presenter: ImportTrackTypePresenter fun show(manager: androidx.fragment.app.FragmentManager, tag: String, resultLambda: (String) -> Unit) { val lambdaHolder = FragmentResultLambda<String>() lambdaHolder.resultLambda = resultLambda manager.beginTransaction().add(lambdaHolder, TAG_LAMBDA_FRAGMENT).commit() setTargetFragment(lambdaHolder, 324) super.show(manager, tag) } override fun dismiss() { fragmentManager?.let { fragmentManager -> val fragment = fragmentManager.findFragmentByTag(TAG_LAMBDA_FRAGMENT) if (fragment != null) { fragmentManager.beginTransaction() .remove(fragment) .commit() } } super.dismiss() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter = ViewModelProviders.of(this).get(ImportTrackTypePresenter::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = DataBindingUtil.inflate<FragmentImportTracktypeDialogBinding>(inflater, R.layout.fragment_import_tracktype_dialog, container, false) val importTrackTypePresenter = ViewModelProviders.of(this).get(ImportTrackTypePresenter::class.java) binding.presenter = importTrackTypePresenter binding.model = presenter.model presenter.model.dismiss.observe { sender -> if (sender is ObservableBoolean && sender.get()) { dismiss() } } binding.fragmentImporttracktypeSpinner.onItemSelectedListener = importTrackTypePresenter.onItemSelectedListener if (targetFragment is FragmentResultLambda<*>) { importTrackTypePresenter.resultLambda = (targetFragment as FragmentResultLambda<String>).resultLambda } presenter = importTrackTypePresenter return binding.root } companion object { private const val TAG_LAMBDA_FRAGMENT = "TAG_LAMBDA_FRAGMENT" } }
gpl-3.0
e74c62c286b7585f5a20fd537de7db2b
43.618557
154
0.670287
5.201923
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/ui/SCMCatalogEntryLabelProviderTest.kt
1
2003
package net.nemerosa.ontrack.extension.scm.catalog.ui import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.structure.Project import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class SCMCatalogEntryLabelProviderTest { private lateinit var catalogLinkService: CatalogLinkService private lateinit var provider: SCMCatalogEntryLabelProvider private lateinit var project: Project @Before fun init() { project = Project.of(NameDescription.nd("PRJ", "")).withId(ID.of(1)) catalogLinkService = mock() provider = SCMCatalogEntryLabelProvider(catalogLinkService) } @Test fun properties() { assertTrue(provider.isEnabled) assertEquals("SCM Catalog Entry", provider.name) } @Test fun `Label for linked project`() { whenever(catalogLinkService.getSCMCatalogEntry(project)).thenReturn(CatalogFixtures.entry()) val labels = provider.getLabelsForProject(project) assertEquals(1, labels.size) val label = labels.first() with(label) { assertEquals("scm-catalog", category) assertEquals("entry", name) assertEquals("#33cc33", color) } } @Test fun `Label for unlinked project`() { whenever(catalogLinkService.getSCMCatalogEntry(project)).thenReturn(null) val labels = provider.getLabelsForProject(project) assertEquals(1, labels.size) val label = labels.first() with(label) { assertEquals("scm-catalog", category) assertEquals("no-entry", name) assertEquals("#a9a9a9", color) } } }
mit
73f46bccccef7d923688d19d83d08a47
31.322581
100
0.702446
4.636574
false
true
false
false
SeunAdelekan/Kanary
src/main/com/iyanuadelekan/kanary/app/router/RouteManager.kt
1
5556
package com.iyanuadelekan.kanary.app.router import com.iyanuadelekan.kanary.app.RouteList import com.iyanuadelekan.kanary.app.RouterAction import com.iyanuadelekan.kanary.app.adapter.component.middleware.MiddlewareAdapter import com.iyanuadelekan.kanary.app.constant.RouteType import com.iyanuadelekan.kanary.exceptions.InvalidRouteException /** * @author Iyanu Adelekan on 18/11/2018. */ /** * Class managing the creation and addition of routes to respective route trees. */ internal class RouteManager : com.iyanuadelekan.kanary.app.framework.router.RouteManager { private val getRoutes by lazy { RouteList() } private val postRoutes by lazy { RouteList() } private val putRoutes by lazy { RouteList() } private val deleteRoutes by lazy { RouteList() } private val optionsRoutes by lazy { RouteList() } private val headRoutes by lazy { RouteList() } private val patchRoutes by lazy { RouteList() } private val linkRoutes by lazy { RouteList() } private val unlinkRoutes by lazy { RouteList() } /** * Invoked to register a new route to the router. * * @param routeType - type of route to be added. See [RouteType]. * @param path - URL path. * @param action - router action. * * @return [RouteManager] - current [RouteManager] instance. */ @Throws(InvalidRouteException::class) override fun addRoute( routeType: RouteType, path: String, action: RouterAction, middleware: List<MiddlewareAdapter>?): RouteManager { val routeList: RouteList = getRouteList(routeType) val subPaths: List<String> = path.split("/") if (!subPaths.isEmpty()) { var node = getMatchingNode(routeList, subPaths[0]) if (node == null) { node = RouteNode(subPaths[0], action) routeList.add(node) } if (subPaths.size > 1) { for (i in 1 until subPaths.size) { node = node as RouteNode val pathSegment = subPaths[i] if (!node.hasChild(pathSegment)) { val childNode = RouteNode(pathSegment) if (i == subPaths.size - 1) { childNode.action = action } if (middleware != null) { childNode.addMiddleware(middleware) } node.addChild(childNode) } else { if (i == subPaths.size - 1) { throw InvalidRouteException( "The path '$path' with method '${routeType.name}' has already been defined.") } node = node.getChild(pathSegment) } } } return this } throw InvalidRouteException("The path '$path' is an invalid route path") } /** * Invoked to resolve a corresponding RouteNode to a given URL target - if any. * * @param path - URL path (target). * @return [RouteNode] - Returns corresponding instance of [RouteNode], if one exists. Else returns null. */ override fun getRouteNode(path: String, method: RouteType): RouteNode? { val queue: ArrayList<RouteNode> = ArrayList() val urlPathSegments = path.split('/') val iterator = urlPathSegments.iterator() var currentSegment = iterator.next() getRouteList(method).forEach { if (it.path == currentSegment || it.path[0] == ':') { queue.add(it) } } while (!queue.isEmpty()) { val currentNode = queue[0] if (currentNode.path == currentSegment || currentNode.path[0] == ':') { if (!iterator.hasNext()) { return currentNode } currentSegment = iterator.next() } currentNode.getChildren().forEach { if (it.path == currentSegment || it.path[0] == ':') { queue.add(it) } } queue.removeAt(0) } return null } /** * Invoked to get a matching route node - within a given route list - for a given sub path. * * @param routeList - list of routes. * @param subPath - sub path to match. * @return [RouteNode] - returns a [RouteNode] is one exists and null otherwise. */ override fun getMatchingNode(routeList: RouteList, subPath: String): RouteNode? { var node: RouteNode? = null routeList.forEach { if (it.path == subPath) { node = it } } return node } /** * Invoked to resolve the required route list for a given route type. * * @param method - Specified [RouteType]. * @return [RouteList] - Corresponding route list. */ private fun getRouteList(method: RouteType): RouteList { return when (method) { RouteType.GET -> getRoutes RouteType.POST -> postRoutes RouteType.PUT -> putRoutes RouteType.DELETE -> deleteRoutes RouteType.OPTIONS -> optionsRoutes RouteType.HEAD -> headRoutes RouteType.PATCH -> patchRoutes RouteType.LINK -> linkRoutes RouteType.UNLINK -> unlinkRoutes } } }
apache-2.0
f3214608116f5102a956caa379e7a18a
33.73125
113
0.554356
5.009919
false
false
false
false
nemerosa/ontrack
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/subscriptions/EventSubscription.kt
1
1598
package net.nemerosa.ontrack.extension.notifications.subscriptions import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.structure.ProjectEntity /** * Subscrition to an event. * * @property projectEntity Project entity to subscribe to (`null` for global events) * @property events List of events types to subscribe to * @property keywords Optional space-separated list of tokens to look for in the events * @property channel Type of channel to send the event to * @property channelConfig Specific configuration of the channel * @property disabled If the subscription is disabled * @property origin Origin of the subscription (used for filtering) */ data class EventSubscription( val projectEntity: ProjectEntity?, @APIDescription("List of events types to subscribe to") val events: Set<String>, @APIDescription("Optional space-separated list of tokens to look for in the events") val keywords: String?, @APIDescription("Type of channel to send the event to") val channel: String, val channelConfig: JsonNode, @APIDescription("If the subscription is disabled") val disabled: Boolean, @APIDescription("Origin of the subscription (used for filtering)") val origin: String, ) { fun disabled(disabled: Boolean) = EventSubscription( projectEntity = projectEntity, events = events, keywords = keywords, channel = channel, channelConfig = channelConfig, disabled = disabled, origin = origin ) }
mit
e195910cd839b4842f482c13d851f554
38
88
0.736546
4.90184
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/McpVersionPair.kt
1
959
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp import com.demonwav.mcdev.util.SemanticVersion data class McpVersionPair(val mcpVersion: String, val mcVersion: SemanticVersion) : Comparable<McpVersionPair> { override fun compareTo(other: McpVersionPair): Int { val mcRes = mcVersion.compareTo(other.mcVersion) if (mcRes != 0) { return mcRes } val thisStable = mcpVersion.startsWith("stable") val thatStable = other.mcpVersion.startsWith("stable") return if (thisStable && !thatStable) { -1 } else if (!thisStable && thatStable) { 1 } else { val thisNum = mcpVersion.substringAfter('_') val thatNum = other.mcpVersion.substringAfter('_') thisNum.toInt().compareTo(thatNum.toInt()) } } }
mit
1945c1966d393d58a2f73d3998a5ed59
27.205882
112
0.622523
4.31982
false
false
false
false
npryce/hamkrest
src/main/kotlin/com/natpryce/hamkrest/collection_matchers.kt
1
2602
package com.natpryce.hamkrest import kotlin.reflect.KFunction1 /** * Matches an [Iterable] if any element is matched by [elementMatcher]. */ fun <T> anyElement(elementMatcher: Matcher<T>) = object : Matcher.Primitive<Iterable<T>>() { override fun invoke(actual: Iterable<T>): MatchResult = match(actual.any(elementMatcher.asPredicate())) { "was ${describe(actual)}" } override val description: String get() = "in which any element ${describe(elementMatcher)}" override val negatedDescription: String get() = "in which no element ${describe(elementMatcher)}" } /** * Matches an [Iterable] if any element is matched by [elementPredicate]. */ fun <T> anyElement(elementPredicate: KFunction1<T, Boolean>) = anyElement(Matcher(elementPredicate)) /** * Matches an [Iterable] if all elements are matched by [elementMatcher]. */ fun <T> allElements(elementMatcher: Matcher<T>) = object : Matcher.Primitive<Iterable<T>>() { override fun invoke(actual: Iterable<T>): MatchResult = match(actual.all(elementMatcher.asPredicate())) { "was ${describe(actual)}" } override val description: String get() = "in which all elements ${describe(elementMatcher)}" override val negatedDescription: String get() = "in which not all elements ${describe(elementMatcher)}" } /** * Matches an [Iterable] if all elements are matched by [elementPredicate]. */ fun <T> allElements(elementPredicate: KFunction1<T, Boolean>) = allElements(Matcher(elementPredicate)) /** * Matches an empty collection. */ val isEmpty = Matcher(Collection<Any>::isEmpty) /** * Matches a collection with a size that matches [sizeMatcher]. */ fun hasSize(sizeMatcher: Matcher<Int>) = has(Collection<Any>::size, sizeMatcher) /** * Matches a collection that contains [element] * * See [Collection::contains] */ fun <T> hasElement(element: T): Matcher<Collection<T>> = object : Matcher.Primitive<Collection<T>>() { override fun invoke(actual: Collection<T>): MatchResult = match(element in actual) { "was ${describe(actual)}" } override val description: String get() = "contains ${describe(element)}" override val negatedDescription: String get() = "does not contain ${describe(element)}" } fun <T> isIn(i: Iterable<T>) : Matcher<T> = object : Matcher.Primitive<T>() { override fun invoke(actual: T) = match(actual in i) {"was not in ${describe(i)}"} override val description: String get() = "is in ${describe(i)}" override val negatedDescription: String get() = "is not in ${describe(i)}" } fun <T> isIn(vararg elements: T) = isIn(elements.toList())
apache-2.0
385d6f4eaf0e0d2cc80fe80ca19a902e
39.030769
107
0.700615
4.059282
false
false
false
false
VerachadW/kraph
core/src/test/kotlin/me/lazmaid/kraph/test/RelayPrintSpek.kt
1
8757
package me.lazmaid.kraph.test import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import me.lazmaid.kraph.lang.Argument import me.lazmaid.kraph.lang.Field import me.lazmaid.kraph.lang.SelectionSet import me.lazmaid.kraph.lang.PrintFormat import me.lazmaid.kraph.lang.relay.CursorConnection import me.lazmaid.kraph.lang.relay.Edges import me.lazmaid.kraph.lang.relay.InputArgument import me.lazmaid.kraph.lang.relay.PageInfo import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it /** * Created by VerachadW on 10/3/2016 AD. */ class RelayPrintSpek : Spek({ data class Expectation(val normal: String, val pretty: String, val json: String) describe("Relay InputArgument") { val tests = listOf( Triple( mapOf("id" to 1), "one number argument", Expectation("(input: { id: 1 })", "(input: { id: 1 })", "(input: { id: 1 })") ), Triple( mapOf("name" to "John Doe"), "name string argument", Expectation( "(input: { name: \"John Doe\" })", "(input: { name: \"John Doe\" })", "(input: { name: \\\"John Doe\\\" })" ) ) ) for((args, title, expectation) in tests) { val arguments = InputArgument(args) given(title) { it("should print correctly in NORMAL mode") { assertThat(arguments.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal)) } it("should print correctly in PRETTY mode") { assertThat(arguments.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty)) } it("should print correctly in JSON mode") { assertThat(arguments.print(PrintFormat.JSON, 0), equalTo(expectation.json)) } } } } describe("Relay Edges") { val tests = listOf( Triple( Edges(SelectionSet(listOf(Field("title"))), additionalField = listOf(Field("id"))), "edges with addtional field id", Expectation( "edges { node { title } id }", "edges {\n node {\n title\n }\n id\n}", "edges { node { title } id }" ) ), Triple( Edges(SelectionSet(listOf(Field("id"), Field("title")))), "edges with id and title inside node object", Expectation( "edges { node { id title } }", "edges {\n node {\n id\n title\n }\n}", "edges { node { id title } }" ) ) ) for((edge, title, expectation) in tests) { given(title) { it("should print correctly in NORMAL mode") { assertThat(edge.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal)) } it("should print correctly in PRETTY mode") { assertThat(edge.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty)) } it("should print correctly in JSON mode") { assertThat(edge.print(PrintFormat.JSON, 0), equalTo(expectation.json)) } } } } describe("Relay PageInfo") { given("default pageInfo with hasNextPage and hasPreviousPage") { val node = PageInfo(SelectionSet(listOf(Field("hasNextPage"),Field("hasPreviousPage")))) it("should print correctly in NORMAL mode") { assertThat(node.print(PrintFormat.NORMAL, 0), equalTo("pageInfo { hasNextPage hasPreviousPage }")) } it("should print correctly in PRETTY mode") { assertThat(node.print(PrintFormat.PRETTY, 0), equalTo("pageInfo {\n hasNextPage\n hasPreviousPage\n}")) } it("should print correctly in JSON mode") { assertThat(node.print(PrintFormat.JSON, 0), equalTo("pageInfo { hasNextPage hasPreviousPage }")) } } } describe("Relay Cursor Connection") { val tests = listOf( Triple( CursorConnection( "notes", Argument(mapOf("first" to 10)), SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title")))))) ), "name notes, title in node object, and only 10 items", Expectation( "notes (first: 10) { edges { node { title } } }", "notes (first: 10) {\n edges {\n node {\n title\n }\n }\n}", "notes (first: 10) { edges { node { title } } }" ) ), Triple( CursorConnection( "notes", Argument(mapOf("first" to 10, "after" to "abcd1234")), SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title")))))) ), "name notes, title in node object, and only next 10 items after 'abcd1234'", Expectation( "notes (first: 10, after: \"abcd1234\") { edges { node { title } } }", "notes (first: 10, after: \"abcd1234\") {\n edges {\n node {\n title\n }\n }\n}", "notes (first: 10, after: \\\"abcd1234\\\") { edges { node { title } } }" ) ), Triple( CursorConnection( "notes", Argument(mapOf("last" to 10)), SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title")))))) ), "name notes, title in node object, and only last 10 items", Expectation( "notes (last: 10) { edges { node { title } } }", "notes (last: 10) {\n edges {\n node {\n title\n }\n }\n}", "notes (last: 10) { edges { node { title } } }" ) ), Triple( CursorConnection( "notes", Argument(mapOf("last" to 10, "before" to "abcd1234")), SelectionSet(listOf(Edges(SelectionSet(listOf(Field("title")))))) ), "name notes with title in node object and only last 10 items before 'abcd1234'", Expectation( "notes (last: 10, before: \"abcd1234\") { edges { node { title } } }", "notes (last: 10, before: \"abcd1234\") {\n edges {\n node {\n title\n }\n }\n}", "notes (last: 10, before: \\\"abcd1234\\\") { edges { node { title } } }" ) ), Triple( CursorConnection( "notes", Argument(mapOf("first" to 10)), SelectionSet( listOf( Edges(SelectionSet(listOf(Field("title")))), PageInfo(SelectionSet(listOf( Field("hasNextPage"), Field("hasPreviousPage") ))) ) ) ), "name notes and a PageInfo object", Expectation( "notes (first: 10) { edges { node { title } } pageInfo { hasNextPage hasPreviousPage } }", "notes (first: 10) {\n edges {\n node {\n title\n }\n }\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n}", "notes (first: 10) { edges { node { title } } pageInfo { hasNextPage hasPreviousPage } }" ) ) ) for((cursor, title, expectation) in tests) { given(title) { it("should print correctly in NORMAL mode") { assertThat(cursor.print(PrintFormat.NORMAL, 0), equalTo(expectation.normal)) } it("should print correctly in PRETTY mode") { assertThat(cursor.print(PrintFormat.PRETTY, 0), equalTo(expectation.pretty)) } it("should print correctly in JSON mode") { assertThat(cursor.print(PrintFormat.JSON, 0), equalTo(expectation.json)) } } } } })
mit
3335879f469785b8c7276221449ae9bf
44.139175
150
0.477675
4.900392
false
false
false
false
sksamuel/akka-patterns
rxhive-parquet/src/main/kotlin/com/sksamuel/rxhive/parquet/FromParquetSchema.kt
1
4059
package com.sksamuel.rxhive.parquet import com.sksamuel.rxhive.ArrayType import com.sksamuel.rxhive.BinaryType import com.sksamuel.rxhive.BooleanType import com.sksamuel.rxhive.DateType import com.sksamuel.rxhive.DecimalType import com.sksamuel.rxhive.EnumType import com.sksamuel.rxhive.Float32Type import com.sksamuel.rxhive.Float64Type import com.sksamuel.rxhive.Int16Type import com.sksamuel.rxhive.Int32Type import com.sksamuel.rxhive.Int64Type import com.sksamuel.rxhive.Int8Type import com.sksamuel.rxhive.Precision import com.sksamuel.rxhive.Scale import com.sksamuel.rxhive.StringType import com.sksamuel.rxhive.StructField import com.sksamuel.rxhive.StructType import com.sksamuel.rxhive.TimeMillisType import com.sksamuel.rxhive.TimestampMillisType import com.sksamuel.rxhive.Type import org.apache.parquet.schema.GroupType import org.apache.parquet.schema.MessageType import org.apache.parquet.schema.OriginalType import org.apache.parquet.schema.PrimitiveType /** * Conversion functions from parquet types to rxhive types. * * Parquet types are defined at the parquet repo: * https://github.com/apache/parquet-format/blob/c6d306daad4910d21927b8b4447dc6e9fae6c714/LogicalTypes.md */ object FromParquetSchema { fun fromParquet(type: org.apache.parquet.schema.Type): Type { return when (type) { is PrimitiveType -> fromPrimitiveType(type) is MessageType -> fromGroupType(type) is GroupType -> fromGroupType(type) else -> throw UnsupportedOperationException() } } fun fromGroupType(groupType: GroupType): StructType { val fields = groupType.fields.map { val fieldType = fromParquet(it) StructField( it.name, fieldType, it.repetition.isNullable() ) } return StructType(fields) } fun fromPrimitiveType(type: PrimitiveType): Type { fun int32(original: OriginalType?): Type = when (original) { OriginalType.UINT_32 -> Int32Type OriginalType.INT_32 -> Int32Type OriginalType.UINT_16 -> Int16Type OriginalType.INT_16 -> Int16Type OriginalType.UINT_8 -> Int8Type OriginalType.INT_8 -> Int8Type OriginalType.DATE -> DateType OriginalType.TIME_MILLIS -> TimeMillisType else -> Int32Type } fun int64(original: OriginalType?): Type = when (original) { OriginalType.UINT_64 -> Int64Type OriginalType.INT_64 -> Int64Type OriginalType.TIMESTAMP_MILLIS -> TimestampMillisType else -> Int64Type } fun binary(type: PrimitiveType, original: OriginalType?, length: Int): Type = when (original) { OriginalType.ENUM -> EnumType(emptyList()) OriginalType.UTF8 -> StringType OriginalType.DECIMAL -> { val meta = type.decimalMetadata DecimalType(Precision(meta.precision), Scale(meta.scale)) } else -> BinaryType } val elementType = when (type.primitiveTypeName) { PrimitiveType.PrimitiveTypeName.BINARY -> binary(type, type.originalType, type.typeLength) PrimitiveType.PrimitiveTypeName.BOOLEAN -> BooleanType PrimitiveType.PrimitiveTypeName.DOUBLE -> Float64Type PrimitiveType.PrimitiveTypeName.FLOAT -> Float32Type PrimitiveType.PrimitiveTypeName.INT32 -> int32(type.originalType) PrimitiveType.PrimitiveTypeName.INT64 -> int64(type.originalType) // INT96 is deprecated, but it's commonly used (wrongly) for timestamp millis // Spark does this, so we must do too // https://issues.apache.org/jira/browse/PARQUET-323 PrimitiveType.PrimitiveTypeName.INT96 -> TimestampMillisType PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY -> binary(type, type.originalType, type.typeLength) } return if (type.isRepeated()) ArrayType(elementType) else elementType } } private fun org.apache.parquet.schema.Type.Repetition.isNullable(): Boolean = this == org.apache.parquet.schema.Type.Repetition.OPTIONAL private fun PrimitiveType.isRepeated(): Boolean { return repetition == org.apache.parquet.schema.Type.Repetition.REPEATED }
apache-2.0
35a9b36addc04c8cf71c1dba80292cc4
35.576577
110
0.742055
4.259182
false
false
false
false
GoogleChromeLabs/android-web-payment
SamplePay/app/src/main/java/com/example/android/samplepay/PaymentActivity.kt
1
12141
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.samplepay import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.util.Log import android.widget.RadioButton import androidx.activity.viewModels import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatRadioButton import androidx.core.view.ViewCompat import androidx.core.view.isVisible import com.example.android.samplepay.databinding.PaymentActivityBinding import com.example.android.samplepay.model.PaymentDetailsUpdate import com.example.android.samplepay.model.PaymentParams import org.chromium.components.payments.IPaymentDetailsUpdateService import org.chromium.components.payments.IPaymentDetailsUpdateServiceCallback import org.json.JSONObject import java.util.* import kotlin.math.roundToInt private const val TAG = "PaymentActivity" /** * This activity handles the PAY action from Chrome. * * It [returns][setResult] [#RESULT_OK] when the user clicks on the "Pay" button. The "Pay" button * is disabled unless the calling app is Chrome. */ class PaymentActivity : AppCompatActivity(R.layout.payment_activity) { private val viewModel: PaymentViewModel by viewModels() private val binding by viewBindings(PaymentActivityBinding::bind) private var paymentDetailsUpdateService: IPaymentDetailsUpdateService? = null private var shippingOptionsListenerEnabled = false private var shippingAddressListenerEnabled = false private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder?) { Log.d(TAG, "IPaymentDetailsUpdateService connected") paymentDetailsUpdateService = IPaymentDetailsUpdateService.Stub.asInterface(service) } override fun onServiceDisconnected(className: ComponentName?) { Log.d(TAG, "IPaymentDetailsUpdateService disconnected") paymentDetailsUpdateService = null } } private val callback = object : IPaymentDetailsUpdateServiceCallback.Stub() { override fun paymentDetailsNotUpdated() { Log.d("TAG", "Payment details did not change.") } override fun updateWith(newPaymentDetails: Bundle) { val update = PaymentDetailsUpdate.from(newPaymentDetails) runOnUiThread { update.shippingOptions?.let { viewModel.updateShippingOptions(it) } update.total?.let { viewModel.updateTotal(it) } viewModel.updateError(update.error ?: "") update.addressErrors?.let { viewModel.updateAddressErrors(it) } viewModel.updatePromotionError(update.stringifiedPaymentMethodErrors ?: "") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.payment.layoutParams.width = (resources.displayMetrics.widthPixels * 0.90).roundToInt() setSupportActionBar(findViewById(R.id.toolbar)) // Bind values from ViewModel to views. viewModel.merchantName.observe(this) { merchantName -> binding.merchantName.isVisible = merchantName != null binding.merchantName.text = merchantName } viewModel.origin.observe(this) { origin -> binding.origin.isVisible = origin != null binding.origin.text = origin } viewModel.error.observe(this) { error -> if (error.isEmpty()) { // No error binding.error.isVisible = false binding.error.text = null binding.pay.isEnabled = true } else { binding.error.isVisible = true binding.error.text = error binding.pay.isEnabled = false } } viewModel.promotionError.observe(this) { promotionError -> if (promotionError.isEmpty()) { // No promotion error binding.promotionError.isVisible = false binding.promotionError.text = null } else { binding.promotionError.isVisible = true binding.promotionError.text = promotionError } } viewModel.total.observe(this) { total -> binding.total.isVisible = total != null binding.total.text = if (total != null) { getString(R.string.total_format, total.currency, total.value) } else { null } } viewModel.paymentOptions.observe(this) { paymentOptions -> binding.payerName.isVisible = paymentOptions.requestPayerName binding.payerPhone.isVisible = paymentOptions.requestPayerPhone binding.payerEmail.isVisible = paymentOptions.requestPayerEmail binding.contactTitle.isVisible = paymentOptions.requireContact binding.shippingOptions.isVisible = paymentOptions.requestShipping binding.shippingAddresses.isVisible = paymentOptions.requestShipping binding.optionTitle.text = formatTitle( R.string.option_title_format, paymentOptions.shippingType ) binding.addressTitle.text = formatTitle( R.string.address_title_format, paymentOptions.shippingType ) } viewModel.shippingOptions.observe(this) { shippingOptions -> shippingOptionsListenerEnabled = false binding.shippingOptions.removeAllViews() var selectedId = 0 for (option in shippingOptions) { binding.shippingOptions.addView( AppCompatRadioButton(this).apply { text = getString( R.string.option_format, option.label, option.amountCurrency, option.amountValue ) tag = option.id id = ViewCompat.generateViewId() if (option.selected) { selectedId = id } } ) } if (selectedId != 0) { binding.shippingOptions.check(selectedId) } shippingOptionsListenerEnabled = true } viewModel.paymentAddresses.observe(this) { addresses -> shippingAddressListenerEnabled = false binding.canadaAddress.text = addresses[R.id.canada_address].toString() binding.usAddress.text = addresses[R.id.us_address].toString() binding.ukAddress.text = addresses[R.id.uk_address].toString() shippingAddressListenerEnabled = true } // Handle UI events. binding.promotionButton.setOnClickListener { val promotionCode = binding.promotionCode.text.toString() paymentDetailsUpdateService?.changePaymentMethod( Bundle().apply { putString("methodName", BuildConfig.SAMPLE_PAY_METHOD_NAME) putString("details", JSONObject().apply { put("promotionCode", promotionCode) }.toString()) }, callback ) } binding.shippingOptions.setOnCheckedChangeListener { group, checkedId -> if (shippingOptionsListenerEnabled) { group.findViewById<RadioButton>(checkedId)?.let { button -> val shippingOptionId = button.tag as String paymentDetailsUpdateService?.changeShippingOption(shippingOptionId, callback) } } } binding.shippingAddresses.setOnCheckedChangeListener { _, checkedId -> if (shippingAddressListenerEnabled) { viewModel.paymentAddresses.value?.get(checkedId)?.let { address -> paymentDetailsUpdateService?.changeShippingAddress(address.asBundle(), callback) } } } binding.pay.setOnClickListener { pay() } if (savedInstanceState == null) { val result = handleIntent() if (!result) cancel() } } private fun handleIntent(): Boolean { val intent = intent ?: return false if (intent.action != "org.chromium.intent.action.PAY") { return false } val extras = intent.extras ?: return false viewModel.initialize(PaymentParams.from(extras), callingPackage) return true } override fun onStart() { super.onStart() bindPaymentDetailsUpdateService() } override fun onStop() { super.onStop() unbindService(serviceConnection) } private fun bindPaymentDetailsUpdateService() { val callingBrowserPackage = callingPackage ?: return val intent = Intent("org.chromium.intent.action.UPDATE_PAYMENT_DETAILS") .setPackage(callingBrowserPackage) if (packageManager.resolveServiceByFilter(intent) == null) { // Fallback to Chrome-only approach. intent.setClassName( callingBrowserPackage, "org.chromium.components.payments.PaymentDetailsUpdateService" ) intent.action = IPaymentDetailsUpdateService::class.java.name } bindService(intent, serviceConnection, BIND_AUTO_CREATE) } private fun cancel() { setResult(RESULT_CANCELED) finish() } private fun pay() { setResult(RESULT_OK, Intent().apply { putExtra("methodName", BuildConfig.SAMPLE_PAY_METHOD_NAME) putExtra("details", "{\"token\": \"put-some-data-here\"}") val paymentOptions = viewModel.paymentOptions.value if (paymentOptions == null) { cancel() return } if (paymentOptions.requestPayerName) { putExtra("payerName", binding.payerName.text.toString()) } if (paymentOptions.requestPayerPhone) { putExtra("payerPhone", binding.payerPhone.text.toString()) } if (paymentOptions.requestPayerEmail) { putExtra("payerEmail", binding.payerEmail.text.toString()) } if (paymentOptions.requestShipping) { val addresses = viewModel.paymentAddresses.value!! putExtra( "shippingAddress", addresses[binding.shippingAddresses.checkedRadioButtonId]?.asBundle() ) val optionId = binding.shippingOptions.findViewById<RadioButton>( binding.shippingOptions.checkedRadioButtonId ).tag as String putExtra("shippingOptionId", optionId) } if (BuildConfig.DEBUG) { Log.d(getString(R.string.payment_response), "${this.extras}") } }) finish() } private fun formatTitle(@StringRes id: Int, label: String): String { return getString( id, label.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } ) } }
apache-2.0
1057a564d6c7592b1bc4e47af553dca0
39.335548
100
0.615929
5.528689
false
false
false
false
Jasper-Hilven/dynamic-extensions-for-alfresco
annotations-runtime/src/main/kotlin/com/github/dynamicextensionsalfresco/web/ResourceWebscript.kt
1
2901
package com.github.dynamicextensionsalfresco.web import com.github.dynamicextensionsalfresco.webscripts.DummyStore import com.github.dynamicextensionsalfresco.webscripts.support.AbstractBundleResourceHandler import org.osgi.framework.BundleContext import org.springframework.extensions.webscripts.* import java.util.ResourceBundle import javax.servlet.http.HttpServletResponse /** * Webscript to serve static web resources found in an extension * When requests are prefixed with symbolic-name/web, no cache headers are set, * with the /web-cached/$version prefix, cache is set to expire now + 1 year * * @author Laurent Van der Linden */ public class ResourceWebscript(private val bundleContext: BundleContext) : WebScript, AbstractBundleResourceHandler() { private val module = "alfresco-dynamic-extensions-repo-control-panel"; init { initContentTypes() } private val descriptionImpl = run { val uris = arrayOf("/$module/web/{path}", "/$module/web-cached/{version}/{path}") val id = "${module}-web" val descriptionImpl = DescriptionImpl( id, "staticWebResource$module", "static web resources for extension $module", uris.first() ) descriptionImpl.method = "GET" descriptionImpl.formatStyle = Description.FormatStyle.argument descriptionImpl.defaultFormat = "html" descriptionImpl.setUris(uris) descriptionImpl.familys = setOf("static-web") descriptionImpl.store = DummyStore() descriptionImpl.requiredAuthentication = Description.RequiredAuthentication.none descriptionImpl.requiredTransactionParameters = with(TransactionParameters()) { required = Description.RequiredTransaction.none this } descriptionImpl } override fun getBundleContext(): BundleContext? { return bundleContext } override fun setURLModelFactory(urlModelFactory: URLModelFactory?) {} override fun init(container: Container?, description: Description?) {} override fun execute(req: WebScriptRequest, res: WebScriptResponse) { val path = req.serviceMatch.templateVars.get("path") if (path != null) { if (req.serviceMatch.path.startsWith("/$module/web-cached/") && !shouldNotCache(path)) { setInfinateCache(res) } handleResource(path, req, res) } else { res.setStatus(HttpServletResponse.SC_BAD_REQUEST) } } private fun shouldNotCache(path: String) = path.endsWith(".map") override fun getBundleEntryPath(path: String?): String? { return "/META-INF/alfresco/web/$path" } override fun getDescription(): Description? { return descriptionImpl } override fun getResources(): ResourceBundle? { return null } }
apache-2.0
3cc5d81fe31fb1385290c69345b6c543
33.963855
119
0.681834
4.950512
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/params/BatchPublishToSocialMedia.kt
1
811
package com.vimeo.networking2.params import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Encapsulates publishing data for each of the supported social media platforms. * * @param facebook Optional publishing data for Facebook. * @param youTube Optional publishing data for YouTube. * @param twitter Optional publishing data for Twitter. * @param linkedIn Optional publishing data for LinkedIn. */ @JsonClass(generateAdapter = true) data class BatchPublishToSocialMedia( @Json(name = "facebook") val facebook: PublishToFacebookPost? = null, @Json(name = "youtube") val youTube: PublishToYouTubePost? = null, @Json(name = "twitter") val twitter: PublishToTwitterPost? = null, @Json(name = "linkedin") val linkedIn: PublishToLinkedInPost? = null )
mit
b198c44c1b35019327497b90a328371d
27.964286
81
0.739827
4.180412
false
false
false
false
vimeo/vimeo-networking-java
model-generator/plugin/src/main/java/com/vimeo/modelgenerator/extensions/KotlinPoetExtensions.kt
1
4015
package com.vimeo.modelgenerator.extensions import com.squareup.kotlinpoet.* import org.jetbrains.kotlin.psi.ValueArgument /** * Adds a list of Types to the given [FileSpec], good for when building a single * file that contains multiple classes or objects. * * @param types a list of [TypeSpec]. */ internal fun FileSpec.Builder.addTypes(types: List<TypeSpec>): FileSpec.Builder = apply { types.forEach { addType(it) } } /** * Adds a list of functions to the given [FileSpec], good for when building a single * file that contains multiple classes or objects. * * @param functions a list of [FunSpec]. */ internal fun FileSpec.Builder.addFunctions(functions: List<FunSpec>): FileSpec.Builder = apply { functions.forEach { addFunction(it) } } /** * Adds a list of properties to the given [FileSpec], good for when building a single * file that contains multiple classes or objects. * * @param properties a list of [FunSpec]. */ internal fun FileSpec.Builder.addProperties(properties: List<PropertySpec>): FileSpec.Builder = apply { properties.forEach { addProperty(it) } } /** * Add a list of imports to the given [FileSpec]. * * @param imports a list of Imports. */ internal fun FileSpec.Builder.addImports(imports: List<Pair<String, String>>): FileSpec.Builder = apply { imports.forEach { addImport(it.second, it.first) } } /** * Adds a list of [AnnotationSpec] to the given [FileSpec]. * * @param annotations a list of [AnnotationSpec]. */ internal fun FileSpec.Builder.addAnnotations(annotations: List<AnnotationSpec>): FileSpec.Builder = apply { annotations.forEach { addAnnotation(it) } } /** * Conditionally add a block of code to a [Taggable.Builder]. * * This can be applied to [FileSpec.Builder], [PropertySpec.Builder], [ParameterSpec.Builder] or any class that has * [Taggable.Builder] as a super. * * @param condition a condition if met will add the [addition] to the given [Taggable.Builder]. * @param addition a block of code that can be applied to the [Taggable.Builder] if the [condition] is met. */ internal fun <T : Taggable.Builder<T>> T.addIfConditionMet( condition: Boolean, addition: T.() -> Unit ): T = apply { if (condition) addition() } /** * Parses [valArgs] to create parameters for AnnotationSpec.Builders [AnnotationSpec.Builder]. * * @param valArgs a list of [ValueArgument]. */ internal fun AnnotationSpec.Builder.addMembers(valArgs: List<ValueArgument>): AnnotationSpec.Builder = apply { valArgs.toParams.forEach { addMember(it) } } /** * Adds a list of enums to a given [TypeSpec]. * * @param enums takes a list of [Pairs][Pair] with the first type being the enum name, and the second being the class body. */ internal fun TypeSpec.Builder.addEnumConstants(enums: List<Pair<String, TypeSpec>>): TypeSpec.Builder = apply { enums.forEach { addEnumConstant(it.first, it.second) } } /** * Adds all the given params to a superclass constructor. * * @param params a list of pairs representing params for a superclass constructor. */ internal fun TypeSpec.Builder.addSuperclassConstructorParameters(params: List<Pair<String, Any>>): TypeSpec.Builder = apply { params.forEach { addSuperclassConstructorParameter(it.first, it.second) } } /** * Adds a list of KDocs to the [TypeSpec.Builder]. * * @param docs a list of KDocs */ internal fun TypeSpec.Builder.addKdocs(docs: List<String>): TypeSpec.Builder = apply { docs.forEach { addKdoc(it) } } /** * Adds a list of KDocs to the [FunSpec.Builder]. * * @param docs a list of KDocs */ internal fun FunSpec.Builder.addKdocs(docs: List<String>): FunSpec.Builder = apply { docs.forEach { addKdoc(it) } } /** * Adds a list of KDocs to the [PropertySpec.Builder]. * * @param docs a list of KDocs */ internal fun PropertySpec.Builder.addKdocs(docs: List<String>): PropertySpec.Builder = apply { docs.forEach { addKdoc(it) } }
mit
a1bc4c0ab10fe1a7f3c3dd2593de73c5
30.614173
123
0.700623
3.940137
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/core/providers/urltilebuilder/UrlTileBuilderIgnSpain.kt
1
399
package com.peterlaurence.trekme.core.providers.urltilebuilder class UrlTileBuilderIgnSpain : UrlTileBuilder { override fun build(level: Int, row: Int, col: Int): String { return "http://www.ign.es/wmts/mapa-raster?Layer=MTN&Style=normal&Tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix=$level&TileCol=$col&TileRow=$row" } }
gpl-3.0
64c117c29d1656b9bf319d5871141d09
56.142857
214
0.77193
3.297521
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsTupleFieldDecl.kt
2
1210
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.search.SearchScope import com.intellij.psi.stubs.IStubElementType import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsEnumVariant import org.rust.lang.core.psi.RsPsiImplUtil import org.rust.lang.core.psi.RsTupleFieldDecl import org.rust.lang.core.stubs.RsPlaceholderStub import javax.swing.Icon val RsTupleFieldDecl.position: Int? get() = owner?.positionalFields?.withIndex()?.firstOrNull { it.value === this }?.index abstract class RsTupleFieldDeclImplMixin : RsStubbedElementImpl<RsPlaceholderStub<*>>, RsTupleFieldDecl { constructor(node: ASTNode) : super(node) constructor(stub: RsPlaceholderStub<*>, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int): Icon = if (owner is RsEnumVariant) RsIcons.FIELD else iconWithVisibility(flags, RsIcons.FIELD) override fun getName(): String? = position?.toString() override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope() }
mit
d42047b82e200f1601c732deb930910d
36.8125
111
0.767769
4.115646
false
false
false
false
mvarnagiris/expensius
app-core/src/main/kotlin/com/mvcoding/expensius/feature/currency/SystemCurrencyFormatsProvider.kt
1
3733
/* * Copyright (C) 2016 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.expensius.feature.currency import com.mvcoding.expensius.extensions.toSystemCurrency import com.mvcoding.expensius.model.Currency import com.mvcoding.expensius.model.CurrencyFormat import java.text.DecimalFormat import java.text.NumberFormat import java.util.* class SystemCurrencyFormatsProvider : CurrencyFormatsProvider { override fun getCurrencyFormat(currency: Currency): CurrencyFormat = currency.toSystemCurrency()?.toCurrencyFormat() ?: currency.getDefaultCurrencyFormat() private fun Currency.getDefaultCurrencyFormat(): CurrencyFormat { return NumberFormat.getCurrencyInstance(Locale.getDefault()) .let { CurrencyFormat( code, it.symbolPosition(), symbolDistance(), it.decimalSeparator(), it.groupSeparator(), it.minFractionDigits(), it.maxFractionDigits()) } } private fun java.util.Currency.toCurrencyFormat(): CurrencyFormat { return NumberFormat.getCurrencyInstance(Locale.getDefault()) .apply { currency = this@toCurrencyFormat } .let { CurrencyFormat( symbol, it.symbolPosition(), symbolDistance(), it.decimalSeparator(), it.groupSeparator(), it.minFractionDigits(), it.maxFractionDigits()) } } private fun NumberFormat.symbolPosition(): CurrencyFormat.SymbolPosition = if (this is DecimalFormat) { toLocalizedPattern().indexOf('\u00A4').let { if (it == 0) CurrencyFormat.SymbolPosition.START else CurrencyFormat.SymbolPosition.END } } else { CurrencyFormat.SymbolPosition.START } private fun NumberFormat.decimalSeparator(): CurrencyFormat.DecimalSeparator = if (this is DecimalFormat) { decimalFormatSymbols.decimalSeparator.let { when (it) { ',' -> CurrencyFormat.DecimalSeparator.COMMA ' ' -> CurrencyFormat.DecimalSeparator.SPACE else -> CurrencyFormat.DecimalSeparator.DOT } } } else { CurrencyFormat.DecimalSeparator.DOT } private fun NumberFormat.groupSeparator(): CurrencyFormat.GroupSeparator = if (this is DecimalFormat) { decimalFormatSymbols.groupingSeparator.let { when (it) { '.' -> CurrencyFormat.GroupSeparator.DOT ',' -> CurrencyFormat.GroupSeparator.COMMA ' ' -> CurrencyFormat.GroupSeparator.SPACE else -> CurrencyFormat.GroupSeparator.NONE } } } else { CurrencyFormat.GroupSeparator.NONE } private fun symbolDistance() = CurrencyFormat.SymbolDistance.FAR private fun NumberFormat.minFractionDigits() = minimumFractionDigits private fun NumberFormat.maxFractionDigits() = maximumFractionDigits }
gpl-3.0
28a692e9fe3b0f679ad99787b7431865
40.488889
159
0.622823
5.869497
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/intentions/ChopParameterListIntentionTest.kt
3
2557
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions class ChopParameterListIntentionTest : RsIntentionTestBase(ChopParameterListIntention::class) { fun `test one parameter`() = doUnavailableTest(""" fn foo(/*caret*/p1: i32) {} """) fun `test two parameter`() = doAvailableTest(""" fn foo(/*caret*/p1: i32, p2: i32) {} """, """ fn foo( p1: i32, p2: i32 ) {} """) fun `test has all line breaks`() = doUnavailableTest(""" fn foo( /*caret*/p1: i32, p2: i32, p3: i32 ) {} """) fun `test has some line breaks`() = doAvailableTest(""" fn foo(p1: i32, /*caret*/p2: i32, p3: i32 ) {} """, """ fn foo( p1: i32, p2: i32, p3: i32 ) {} """) fun `test has some line breaks 2`() = doAvailableTest(""" fn foo( p1: i32, p2: i32, p3: i32/*caret*/ ) {} """, """ fn foo( p1: i32, p2: i32, p3: i32 ) {} """) fun `test has comment`() = doUnavailableTest(""" fn foo( /*caret*/p1: i32, /* comment */ p2: i32, p3: i32 ) {} """) fun `test has comment 2`() = doAvailableTest(""" fn foo( /*caret*/p1: i32, /* comment */p2: i32, p3: i32 ) {} """, """ fn foo( p1: i32, /* comment */ p2: i32, p3: i32 ) {} """) fun `test has single line comment`() = doAvailableTest(""" fn foo(/*caret*/p1: i32, // comment p1 p2: i32, p3: i32 // comment p3 ) {} """, """ fn foo( p1: i32, // comment p1 p2: i32, p3: i32 // comment p3 ) {} """) fun `test trailing comma`() = doAvailableTest(""" fn foo(/*caret*/p1: i32, p2: i32, p3: i32,) {} """, """ fn foo( p1: i32, p2: i32, p3: i32, ) {} """) fun `test trailing comma with comments`() = doAvailableTest(""" fn foo(/*caret*/p1: i32 /* comment 1 */, p2: i32, p3: i32 /* comment 2 */,) {} """, """ fn foo( p1: i32 /* comment 1 */, p2: i32, p3: i32 /* comment 2 */, ) {} """) }
mit
7691812da7d221eb0e214bb7b09f91c0
22.245455
95
0.40086
3.705797
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/FAQOverviewFragment.kt
1
4437
package com.habitrpg.android.habitica.ui.fragments.support import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.os.bundleOf import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.FAQRepository import com.habitrpg.android.habitica.databinding.FragmentFaqOverviewBinding import com.habitrpg.android.habitica.databinding.SupportFaqItemBinding import com.habitrpg.android.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.setMarkdown import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import io.reactivex.rxjava3.functions.Consumer import javax.inject.Inject class FAQOverviewFragment : BaseMainFragment<FragmentFaqOverviewBinding>() { override var binding: FragmentFaqOverviewBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentFaqOverviewBinding { return FragmentFaqOverviewBinding.inflate(inflater, container, false) } @Inject lateinit var faqRepository: FAQRepository override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { hidesToolbar = true showsBackButton = true return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.healthSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfHeartLarge()) binding?.experienceSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfExperienceReward()) binding?.manaSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfMagicLarge()) binding?.goldSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfGoldReward()) binding?.gemsSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfGem()) binding?.hourglassesSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfHourglassLarge()) binding?.statsSection?.findViewById<ImageView>(R.id.icon_view)?.setImageBitmap(HabiticaIconsHelper.imageOfStats()) binding?.moreHelpTextView?.setMarkdown(context?.getString(R.string.need_help_header_description, "[Habitica Help Guild](https://habitica.com/groups/guild/5481ccf3-5d2d-48a9-a871-70a7380cee5a)")) binding?.moreHelpTextView?.setOnClickListener { MainNavigationController.navigate(R.id.guildFragment, bundleOf("groupID" to "5481ccf3-5d2d-48a9-a871-70a7380cee5a")) } binding?.moreHelpTextView?.movementMethod = LinkMovementMethod.getInstance() this.loadArticles() } override fun onDestroy() { faqRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun loadArticles() { compositeSubscription.add( faqRepository.getArticles().subscribe( Consumer { val context = context ?: return@Consumer for (article in it) { val binding = SupportFaqItemBinding.inflate(context.layoutInflater, binding?.faqLinearLayout, true) binding.textView.text = article.question binding.root.setOnClickListener { val direction = FAQOverviewFragmentDirections.openFAQDetail(null, null) direction.position = article.position ?: 0 MainNavigationController.navigate(direction) } } }, RxErrorHandler.handleEmptyError() ) ) } }
gpl-3.0
a6c99411280026328dceb8e2f639e035
46.758242
202
0.713545
5.024915
false
false
false
false
rwinch/spring-security
config/src/test/kotlin/org/springframework/security/config/annotation/web/AuthorizeHttpRequestsDslTests.kt
1
25384
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.annotation.web import org.assertj.core.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.UnsatisfiedDependencyException import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpMethod import org.springframework.security.authorization.AuthorizationDecision import org.springframework.security.authorization.AuthorizationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.core.Authentication import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.provisioning.InMemoryUserDetailsManager import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.access.intercept.RequestAuthorizationContext import org.springframework.security.web.util.matcher.RegexRequestMatcher import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post import org.springframework.test.web.servlet.put import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.PathMatchConfigurer import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import org.springframework.web.util.WebUtils import java.util.function.Supplier import jakarta.servlet.DispatcherType /** * Tests for [AuthorizeHttpRequestsDsl] * * @author Yuriy Savchenko */ @ExtendWith(SpringTestContextExtension::class) class AuthorizeHttpRequestsDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `request when secured by regex matcher then responds with forbidden`() { this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire() this.mockMvc.get("/private") .andExpect { status { isForbidden() } } } @Test fun `request when allowed by regex matcher then responds with ok`() { this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire() this.mockMvc.get("/path") .andExpect { status { isOk() } } } @Test fun `request when allowed by regex matcher with http method then responds based on method`() { this.spring.register(AuthorizeHttpRequestsByRegexConfig::class.java).autowire() this.mockMvc.post("/onlyPostPermitted") { with(csrf()) } .andExpect { status { isOk() } } this.mockMvc.get("/onlyPostPermitted") .andExpect { status { isForbidden() } } } @EnableWebSecurity open class AuthorizeHttpRequestsByRegexConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(RegexRequestMatcher("/path", null), permitAll) authorize(RegexRequestMatcher("/onlyPostPermitted", "POST"), permitAll) authorize(RegexRequestMatcher("/onlyPostPermitted", "GET"), denyAll) authorize(RegexRequestMatcher(".*", null), authenticated) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } @RequestMapping("/onlyPostPermitted") fun onlyPostPermitted() { } } } @Test fun `request when secured by mvc then responds with forbidden`() { this.spring.register(AuthorizeHttpRequestsByMvcConfig::class.java).autowire() this.mockMvc.get("/private") .andExpect { status { isForbidden() } } } @Test fun `request when allowed by mvc then responds with OK`() { this.spring.register(AuthorizeHttpRequestsByMvcConfig::class.java, LegacyMvcMatchingConfig::class.java).autowire() this.mockMvc.get("/path") .andExpect { status { isOk() } } this.mockMvc.get("/path.html") .andExpect { status { isOk() } } this.mockMvc.get("/path/") .andExpect { status { isOk() } } } @EnableWebSecurity @EnableWebMvc open class AuthorizeHttpRequestsByMvcConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/path", permitAll) authorize("/**", authenticated) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Configuration open class LegacyMvcMatchingConfig : WebMvcConfigurer { override fun configurePathMatch(configurer: PathMatchConfigurer) { configurer.setUseSuffixPatternMatch(true) } } @Test fun `request when secured by mvc path variables then responds based on path variable value`() { this.spring.register(MvcMatcherPathVariablesConfig::class.java).autowire() this.mockMvc.get("/user/user") .andExpect { status { isOk() } } this.mockMvc.get("/user/deny") .andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class MvcMatcherPathVariablesConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { val access = AuthorizationManager { _: Supplier<Authentication>, context: RequestAuthorizationContext -> AuthorizationDecision(context.variables["userName"] == "user") } http { authorizeHttpRequests { authorize("/user/{userName}", access) } } return http.build() } @RestController internal class PathController { @RequestMapping("/user/{user}") fun path(@PathVariable user: String) { } } } @Test fun `request when user has allowed role then responds with OK`() { this.spring.register(HasRoleConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("admin", "password")) }.andExpect { status { isOk() } } } @Test fun `request when user does not have allowed role then responds with forbidden`() { this.spring.register(HasRoleConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("user", "password")) }.andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class HasRoleConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/**", hasRole("ADMIN")) } httpBasic { } } return http.build() } @RestController internal class PathController { @GetMapping("/") fun index() { } } @Bean open fun userDetailsService(): UserDetailsService { val userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() val adminDetails = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN") .build() return InMemoryUserDetailsManager(userDetails, adminDetails) } } @Test fun `request when user has some allowed roles then responds with OK`() { this.spring.register(HasAnyRoleConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("user", "password")) }.andExpect { status { isOk() } } this.mockMvc.get("/") { with(httpBasic("admin", "password")) }.andExpect { status { isOk() } } } @Test fun `request when user does not have any allowed roles then responds with forbidden`() { this.spring.register(HasAnyRoleConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("other", "password")) }.andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class HasAnyRoleConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/**", hasAnyRole("ADMIN", "USER")) } httpBasic { } } return http.build() } @RestController internal class PathController { @GetMapping("/") fun index() { } } @Bean open fun userDetailsService(): UserDetailsService { val userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() val admin1Details = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN") .build() val admin2Details = User.withDefaultPasswordEncoder() .username("other") .password("password") .roles("OTHER") .build() return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details) } } @Test fun `request when user has allowed authority then responds with OK`() { this.spring.register(HasAuthorityConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("admin", "password")) }.andExpect { status { isOk() } } } @Test fun `request when user does not have allowed authority then responds with forbidden`() { this.spring.register(HasAuthorityConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("user", "password")) }.andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class HasAuthorityConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/**", hasAuthority("ROLE_ADMIN")) } httpBasic { } } return http.build() } @RestController internal class PathController { @GetMapping("/") fun index() { } } @Bean open fun userDetailsService(): UserDetailsService { val userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() val adminDetails = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN") .build() return InMemoryUserDetailsManager(userDetails, adminDetails) } } @Test fun `request when user has some allowed authorities then responds with OK`() { this.spring.register(HasAnyAuthorityConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("user", "password")) }.andExpect { status { isOk() } } this.mockMvc.get("/") { with(httpBasic("admin", "password")) }.andExpect { status { isOk() } } } @Test fun `request when user does not have any allowed authorities then responds with forbidden`() { this.spring.register(HasAnyAuthorityConfig::class.java).autowire() this.mockMvc.get("/") { with(httpBasic("other", "password")) }.andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class HasAnyAuthorityConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/**", hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")) } httpBasic { } } return http.build() } @RestController internal class PathController { @GetMapping("/") fun index() { } } @Bean open fun userDetailsService(): UserDetailsService { val userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .authorities("ROLE_USER") .build() val admin1Details = User.withDefaultPasswordEncoder() .username("admin") .password("password") .authorities("ROLE_ADMIN") .build() val admin2Details = User.withDefaultPasswordEncoder() .username("other") .password("password") .authorities("ROLE_OTHER") .build() return InMemoryUserDetailsManager(userDetails, admin1Details, admin2Details) } } @Test fun `request when secured by mvc with servlet path then responds based on servlet path`() { this.spring.register(MvcMatcherServletPathConfig::class.java).autowire() this.mockMvc.perform(get("/spring/path") .with { request -> request.servletPath = "/spring" request }) .andExpect(status().isForbidden) this.mockMvc.perform(get("/other/path") .with { request -> request.servletPath = "/other" request }) .andExpect(status().isOk) } @EnableWebSecurity @EnableWebMvc open class MvcMatcherServletPathConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize("/path", "/spring", denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when secured by mvc with http method then responds based on http method`() { this.spring.register(AuthorizeRequestsByMvcConfigWithHttpMethod::class.java).autowire() this.mockMvc.get("/path") .andExpect { status { isOk() } } this.mockMvc.put("/path") { with(csrf()) } .andExpect { status { isForbidden() } } } @EnableWebSecurity @EnableWebMvc open class AuthorizeRequestsByMvcConfigWithHttpMethod { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(HttpMethod.GET, "/path", permitAll) authorize(HttpMethod.PUT, "/path", denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when secured by mvc with servlet path and http method then responds based on path and method`() { this.spring.register(MvcMatcherServletPathHttpMethodConfig::class.java).autowire() this.mockMvc.perform(get("/spring/path") .with { request -> request.apply { servletPath = "/spring" } }) .andExpect(status().isForbidden) this.mockMvc.perform(put("/spring/path") .with { request -> request.apply { servletPath = "/spring" csrf() } }) .andExpect(status().isForbidden) this.mockMvc.perform(get("/other/path") .with { request -> request.apply { servletPath = "/other" } }) .andExpect(status().isOk) } @EnableWebSecurity @EnableWebMvc open class MvcMatcherServletPathHttpMethodConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(HttpMethod.GET, "/path", "/spring", denyAll) authorize(HttpMethod.PUT, "/path", "/spring", denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when both authorizeRequests and authorizeHttpRequests configured then exception`() { assertThatThrownBy { this.spring.register(BothAuthorizeRequestsConfig::class.java).autowire() } .isInstanceOf(UnsatisfiedDependencyException::class.java) .hasRootCauseInstanceOf(IllegalStateException::class.java) .hasMessageContaining( "authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one." ) } @EnableWebSecurity @EnableWebMvc open class BothAuthorizeRequestsConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeRequests { authorize(anyRequest, permitAll) } authorizeHttpRequests { authorize(anyRequest, denyAll) } } return http.build() } } @Test fun `request when shouldFilterAllDispatcherTypes and denyAll and ERROR then responds with forbidden`() { this.spring.register(ShouldFilterAllDispatcherTypesTrueDenyAllConfig::class.java).autowire() this.mockMvc.perform(get("/path") .with { request -> request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error") request.apply { dispatcherType = DispatcherType.ERROR } }) .andExpect(status().isForbidden) } @EnableWebSecurity @EnableWebMvc open class ShouldFilterAllDispatcherTypesTrueDenyAllConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { shouldFilterAllDispatcherTypes = true authorize(anyRequest, denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when shouldFilterAllDispatcherTypes and permitAll and ERROR then responds with ok`() { this.spring.register(ShouldFilterAllDispatcherTypesTruePermitAllConfig::class.java).autowire() this.mockMvc.perform(get("/path") .with { request -> request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error") request.apply { dispatcherType = DispatcherType.ERROR } }) .andExpect(status().isOk) } @EnableWebSecurity @EnableWebMvc open class ShouldFilterAllDispatcherTypesTruePermitAllConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { shouldFilterAllDispatcherTypes = true authorize(anyRequest, permitAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when shouldFilterAllDispatcherTypes false and ERROR dispatcher then responds with ok`() { this.spring.register(ShouldFilterAllDispatcherTypesFalseAndDenyAllConfig::class.java).autowire() this.mockMvc.perform(get("/path") .with { request -> request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error") request.apply { dispatcherType = DispatcherType.ERROR } }) .andExpect(status().isOk) } @EnableWebSecurity @EnableWebMvc open class ShouldFilterAllDispatcherTypesFalseAndDenyAllConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { shouldFilterAllDispatcherTypes = false authorize(anyRequest, denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } @Test fun `request when shouldFilterAllDispatcherTypes omitted and ERROR dispatcher then responds with forbidden`() { this.spring.register(ShouldFilterAllDispatcherTypesOmittedAndDenyAllConfig::class.java).autowire() this.mockMvc.perform(get("/path") .with { request -> request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error") request.apply { dispatcherType = DispatcherType.ERROR } }) .andExpect(status().isForbidden) } @EnableWebSecurity @EnableWebMvc open class ShouldFilterAllDispatcherTypesOmittedAndDenyAllConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(anyRequest, denyAll) } } return http.build() } @RestController internal class PathController { @RequestMapping("/path") fun path() { } } } }
apache-2.0
d46ce5e52d0bc80943b4dfe50fa4fd11
30.849435
122
0.578475
5.657232
false
true
false
false
robfletcher/keiko
keiko-spring/src/main/kotlin/com/netflix/spinnaker/config/QueueConfiguration.kt
1
3642
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.config import com.netflix.spinnaker.q.Activator import com.netflix.spinnaker.q.DeadMessageCallback import com.netflix.spinnaker.q.EnabledActivator import com.netflix.spinnaker.q.MessageHandler import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.q.QueueExecutor import com.netflix.spinnaker.q.QueueProcessor import com.netflix.spinnaker.q.metrics.EventPublisher import com.netflix.spinnaker.q.metrics.QueueEvent import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.ApplicationEventPublisher import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor import java.time.Clock import java.time.Duration @Configuration @EnableConfigurationProperties(QueueProperties::class, ObjectMapperSubtypeProperties::class) @ComponentScan(basePackages = ["com.netflix.spinnaker.q"]) @EnableScheduling class QueueConfiguration { @Bean @ConditionalOnMissingBean(Clock::class) fun systemClock(): Clock = Clock.systemDefaultZone() @Bean fun messageHandlerPool(queueProperties: QueueProperties) = ThreadPoolTaskExecutor().apply { threadNamePrefix = queueProperties.handlerThreadNamePrefix corePoolSize = queueProperties.handlerCorePoolSize maxPoolSize = queueProperties.handlerMaxPoolSize setQueueCapacity(0) } @Bean @ConditionalOnMissingBean(QueueExecutor::class) fun queueExecutor(messageHandlerPool: ThreadPoolTaskExecutor) = object : QueueExecutor<ThreadPoolTaskExecutor>(messageHandlerPool) { override fun hasCapacity() = executor.threadPoolExecutor.run { activeCount < maximumPoolSize } override fun availableCapacity() = executor.threadPoolExecutor.run { maximumPoolSize - activeCount } } @Bean fun queueProcessor( queue: Queue, executor: QueueExecutor<*>, handlers: Collection<MessageHandler<*>>, activators: List<Activator>, publisher: EventPublisher, queueProperties: QueueProperties, deadMessageHandler: DeadMessageCallback ) = QueueProcessor( queue, executor, handlers, activators, publisher, deadMessageHandler, queueProperties.fillExecutorEachCycle, Duration.ofSeconds(queueProperties.requeueDelaySeconds), Duration.ofSeconds(queueProperties.requeueMaxJitterSeconds) ) @Bean fun enabledActivator(queueProperties: QueueProperties) = EnabledActivator(queueProperties.enabled) @Bean fun queueEventPublisher( applicationEventPublisher: ApplicationEventPublisher ) = object : EventPublisher { override fun publishEvent(event: QueueEvent) { applicationEventPublisher.publishEvent(event) } } }
apache-2.0
fea61026e1319c463d9f05c15509e5aa
33.685714
100
0.784734
4.91498
false
true
false
false
androidx/androidx
compose/ui/ui/src/test/kotlin/androidx/compose/ui/node/LayoutNodeTest.kt
3
91750
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.node import androidx.compose.testutils.TestViewConfiguration import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.autofill.Autofill import androidx.compose.ui.autofill.AutofillTree import androidx.compose.ui.draw.DrawModifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.geometry.MutableRect import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.RenderEffect import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.input.InputModeManager import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerIconService import androidx.compose.ui.input.pointer.PointerInputFilter import androidx.compose.ui.input.pointer.PointerInputModifier import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.LayoutModifier import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.layout.RootMeasurePolicy.measure import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.modifier.ModifierLocalManager import androidx.compose.ui.platform.AccessibilityManager import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.TextToolbar import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.platform.WindowInfo import androidx.compose.ui.platform.invertTo import androidx.compose.ui.semantics.SemanticsConfiguration import androidx.compose.ui.semantics.SemanticsModifier import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.TextInputService import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toOffset import androidx.compose.ui.zIndex import com.google.common.truth.Truth.assertThat import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @OptIn(ExperimentalComposeUiApi::class) class LayoutNodeTest { // Ensure that attach and detach work properly @Test fun layoutNodeAttachDetach() { val node = LayoutNode() assertNull(node.owner) val owner = MockOwner() node.attach(owner) assertEquals(owner, node.owner) assertTrue(node.isAttached) assertEquals(1, owner.onAttachParams.count { it === node }) node.detach() assertNull(node.owner) assertFalse(node.isAttached) assertEquals(1, owner.onDetachParams.count { it === node }) } // Ensure that LayoutNode's children are ordered properly through add, remove, move @Test fun layoutNodeChildrenOrder() { val (node, child1, child2) = createSimpleLayout() assertEquals(2, node.children.size) assertEquals(child1, node.children[0]) assertEquals(child2, node.children[1]) assertEquals(0, child1.children.size) assertEquals(0, child2.children.size) node.removeAt(index = 0, count = 1) assertEquals(1, node.children.size) assertEquals(child2, node.children[0]) node.insertAt(index = 0, instance = child1) assertEquals(2, node.children.size) assertEquals(child1, node.children[0]) assertEquals(child2, node.children[1]) node.removeAt(index = 0, count = 2) assertEquals(0, node.children.size) val child3 = LayoutNode() val child4 = LayoutNode() node.insertAt(0, child1) node.insertAt(1, child2) node.insertAt(2, child3) node.insertAt(3, child4) assertEquals(4, node.children.size) assertEquals(child1, node.children[0]) assertEquals(child2, node.children[1]) assertEquals(child3, node.children[2]) assertEquals(child4, node.children[3]) node.move(from = 3, count = 1, to = 0) assertEquals(4, node.children.size) assertEquals(child4, node.children[0]) assertEquals(child1, node.children[1]) assertEquals(child2, node.children[2]) assertEquals(child3, node.children[3]) node.move(from = 0, count = 2, to = 3) assertEquals(4, node.children.size) assertEquals(child2, node.children[0]) assertEquals(child3, node.children[1]) assertEquals(child4, node.children[2]) assertEquals(child1, node.children[3]) } // Ensure that attach of a LayoutNode connects all children @Test fun layoutNodeAttach() { val (node, child1, child2) = createSimpleLayout() val owner = MockOwner() node.attach(owner) assertEquals(owner, node.owner) assertEquals(owner, child1.owner) assertEquals(owner, child2.owner) assertEquals(1, owner.onAttachParams.count { it === node }) assertEquals(1, owner.onAttachParams.count { it === child1 }) assertEquals(1, owner.onAttachParams.count { it === child2 }) } // Ensure that detach of a LayoutNode detaches all children @Test fun layoutNodeDetach() { val (node, child1, child2) = createSimpleLayout() val owner = MockOwner() node.attach(owner) owner.onAttachParams.clear() node.detach() assertEquals(node, child1.parent) assertEquals(node, child2.parent) assertNull(node.owner) assertNull(child1.owner) assertNull(child2.owner) assertEquals(1, owner.onDetachParams.count { it === node }) assertEquals(1, owner.onDetachParams.count { it === child1 }) assertEquals(1, owner.onDetachParams.count { it === child2 }) } // Ensure that dropping a child also detaches it @Test fun layoutNodeDropDetaches() { val (node, child1, child2) = createSimpleLayout() val owner = MockOwner() node.attach(owner) node.removeAt(0, 1) assertEquals(owner, node.owner) assertNull(child1.owner) assertEquals(owner, child2.owner) assertEquals(0, owner.onDetachParams.count { it === node }) assertEquals(1, owner.onDetachParams.count { it === child1 }) assertEquals(0, owner.onDetachParams.count { it === child2 }) } // Ensure that adopting a child also attaches it @Test fun layoutNodeAdoptAttaches() { val (node, child1, child2) = createSimpleLayout() val owner = MockOwner() node.attach(owner) node.removeAt(0, 1) node.insertAt(1, child1) assertEquals(owner, node.owner) assertEquals(owner, child1.owner) assertEquals(owner, child2.owner) assertEquals(1, owner.onAttachParams.count { it === node }) assertEquals(2, owner.onAttachParams.count { it === child1 }) assertEquals(1, owner.onAttachParams.count { it === child2 }) } @Test fun childAdd() { val node = LayoutNode() val owner = MockOwner() node.attach(owner) assertEquals(1, owner.onAttachParams.count { it === node }) val child = LayoutNode() node.insertAt(0, child) assertEquals(1, owner.onAttachParams.count { it === child }) assertEquals(1, node.children.size) assertEquals(node, child.parent) assertEquals(owner, child.owner) } @Test fun childCount() { val node = LayoutNode() assertEquals(0, node.children.size) node.insertAt(0, LayoutNode()) assertEquals(1, node.children.size) } @Test fun childGet() { val node = LayoutNode() val child = LayoutNode() node.insertAt(0, child) assertEquals(child, node.children[0]) } @Test fun noMove() { val (layout, child1, child2) = createSimpleLayout() layout.move(0, 0, 1) assertEquals(child1, layout.children[0]) assertEquals(child2, layout.children[1]) } @Test fun childRemove() { val node = LayoutNode() val owner = MockOwner() node.attach(owner) val child = LayoutNode() node.insertAt(0, child) node.removeAt(index = 0, count = 1) assertEquals(1, owner.onDetachParams.count { it === child }) assertEquals(0, node.children.size) assertEquals(null, child.parent) assertNull(child.owner) } // Ensure that depth is as expected @Test fun depth() { val root = LayoutNode() val (child, grand1, grand2) = createSimpleLayout() root.insertAt(0, child) val owner = MockOwner() root.attach(owner) assertEquals(0, root.depth) assertEquals(1, child.depth) assertEquals(2, grand1.depth) assertEquals(2, grand2.depth) } // layoutNode hierarchy should be set properly when a LayoutNode is a child of a LayoutNode @Test fun directLayoutNodeHierarchy() { val layoutNode = LayoutNode() val childLayoutNode = LayoutNode() layoutNode.insertAt(0, childLayoutNode) assertNull(layoutNode.parent) assertEquals(layoutNode, childLayoutNode.parent) val layoutNodeChildren = layoutNode.children assertEquals(1, layoutNodeChildren.size) assertEquals(childLayoutNode, layoutNodeChildren[0]) layoutNode.removeAt(index = 0, count = 1) assertNull(childLayoutNode.parent) } @Test fun testLayoutNodeAdd() { val (layout, child1, child2) = createSimpleLayout() val inserted = LayoutNode() layout.insertAt(0, inserted) val children = layout.children assertEquals(3, children.size) assertEquals(inserted, children[0]) assertEquals(child1, children[1]) assertEquals(child2, children[2]) } @Test fun testLayoutNodeRemove() { val (layout, child1, _) = createSimpleLayout() val child3 = LayoutNode() val child4 = LayoutNode() layout.insertAt(2, child3) layout.insertAt(3, child4) layout.removeAt(index = 1, count = 2) val children = layout.children assertEquals(2, children.size) assertEquals(child1, children[0]) assertEquals(child4, children[1]) } @Test fun testMoveChildren() { val (layout, child1, child2) = createSimpleLayout() val child3 = LayoutNode() val child4 = LayoutNode() layout.insertAt(2, child3) layout.insertAt(3, child4) layout.move(from = 2, to = 1, count = 2) val children = layout.children assertEquals(4, children.size) assertEquals(child1, children[0]) assertEquals(child3, children[1]) assertEquals(child4, children[2]) assertEquals(child2, children[3]) layout.move(from = 1, to = 3, count = 2) assertEquals(4, children.size) assertEquals(child1, children[0]) assertEquals(child2, children[1]) assertEquals(child3, children[2]) assertEquals(child4, children[3]) } @Test fun testPxGlobalToLocal() { val node0 = ZeroSizedLayoutNode() node0.attach(MockOwner()) val node1 = ZeroSizedLayoutNode() node0.insertAt(0, node1) val x0 = 100 val y0 = 10 val x1 = 50 val y1 = 80 node0.place(x0, y0) node1.place(x1, y1) val globalPosition = Offset(250f, 300f) val expectedX = globalPosition.x - x0.toFloat() - x1.toFloat() val expectedY = globalPosition.y - y0.toFloat() - y1.toFloat() val expectedPosition = Offset(expectedX, expectedY) val result = node1.coordinates.windowToLocal(globalPosition) assertEquals(expectedPosition, result) } @Test fun testIntPxGlobalToLocal() { val node0 = ZeroSizedLayoutNode() node0.attach(MockOwner()) val node1 = ZeroSizedLayoutNode() node0.insertAt(0, node1) val x0 = 100 val y0 = 10 val x1 = 50 val y1 = 80 node0.place(x0, y0) node1.place(x1, y1) val globalPosition = Offset(250f, 300f) val expectedX = globalPosition.x - x0.toFloat() - x1.toFloat() val expectedY = globalPosition.y - y0.toFloat() - y1.toFloat() val expectedPosition = Offset(expectedX, expectedY) val result = node1.coordinates.windowToLocal(globalPosition) assertEquals(expectedPosition, result) } @Test fun testPxLocalToGlobal() { val node0 = ZeroSizedLayoutNode() node0.attach(MockOwner()) val node1 = ZeroSizedLayoutNode() node0.insertAt(0, node1) val x0 = 100 val y0 = 10 val x1 = 50 val y1 = 80 node0.place(x0, y0) node1.place(x1, y1) val localPosition = Offset(5f, 15f) val expectedX = localPosition.x + x0.toFloat() + x1.toFloat() val expectedY = localPosition.y + y0.toFloat() + y1.toFloat() val expectedPosition = Offset(expectedX, expectedY) val result = node1.coordinates.localToWindow(localPosition) assertEquals(expectedPosition, result) } @Test fun testIntPxLocalToGlobal() { val node0 = ZeroSizedLayoutNode() node0.attach(MockOwner()) val node1 = ZeroSizedLayoutNode() node0.insertAt(0, node1) val x0 = 100 val y0 = 10 val x1 = 50 val y1 = 80 node0.place(x0, y0) node1.place(x1, y1) val localPosition = Offset(5f, 15f) val expectedX = localPosition.x + x0.toFloat() + x1.toFloat() val expectedY = localPosition.y + y0.toFloat() + y1.toFloat() val expectedPosition = Offset(expectedX, expectedY) val result = node1.coordinates.localToWindow(localPosition) assertEquals(expectedPosition, result) } @Test fun testPxLocalToGlobalUsesOwnerPosition() { val node = ZeroSizedLayoutNode() node.attach(MockOwner(IntOffset(20, 20))) node.place(100, 10) val result = node.coordinates.localToWindow(Offset.Zero) assertEquals(Offset(120f, 30f), result) } @Test fun testIntPxLocalToGlobalUsesOwnerPosition() { val node = ZeroSizedLayoutNode() node.attach(MockOwner(IntOffset(20, 20))) node.place(100, 10) val result = node.coordinates.localToWindow(Offset.Zero) assertEquals(Offset(120f, 30f), result) } @Test fun testChildToLocal() { val node0 = ZeroSizedLayoutNode() node0.attach(MockOwner()) val node1 = ZeroSizedLayoutNode() node0.insertAt(0, node1) val x1 = 50 val y1 = 80 node0.place(100, 10) node1.place(x1, y1) val localPosition = Offset(5f, 15f) val expectedX = localPosition.x + x1.toFloat() val expectedY = localPosition.y + y1.toFloat() val expectedPosition = Offset(expectedX, expectedY) val result = node0.coordinates.localPositionOf(node1.coordinates, localPosition) assertEquals(expectedPosition, result) } @Test fun testLocalPositionOfWithSiblings() { val node0 = LayoutNode() node0.attach(MockOwner()) val node1 = LayoutNode() val node2 = LayoutNode() node0.insertAt(0, node1) node0.insertAt(1, node2) node1.place(10, 20) node2.place(100, 200) val offset = node2.coordinates.localPositionOf(node1.coordinates, Offset(5f, 15f)) assertEquals(Offset(-85f, -165f), offset) } @Test fun testChildToLocalFailedWhenNotAncestorNoParent() { val owner = MockOwner() val node0 = LayoutNode() node0.attach(owner) val node1 = LayoutNode() node1.attach(owner) Assert.assertThrows(IllegalArgumentException::class.java) { node1.coordinates.localPositionOf(node0.coordinates, Offset(5f, 15f)) } } @Test fun testChildToLocalTheSameNode() { val node = LayoutNode() node.attach(MockOwner()) val position = Offset(5f, 15f) val result = node.coordinates.localPositionOf(node.coordinates, position) assertEquals(position, result) } @Test fun testPositionRelativeToRoot() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) parent.place(-100, 10) child.place(50, 80) val actual = child.coordinates.positionInRoot() assertEquals(Offset(-50f, 90f), actual) } @Test fun testPositionRelativeToRootIsNotAffectedByOwnerPosition() { val parent = LayoutNode() parent.attach(MockOwner(IntOffset(20, 20))) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) child.place(50, 80) val actual = child.coordinates.positionInRoot() assertEquals(Offset(50f, 80f), actual) } @Test fun testPositionRelativeToAncestorWithParent() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) parent.place(-100, 10) child.place(50, 80) val actual = parent.coordinates.localPositionOf(child.coordinates, Offset.Zero) assertEquals(Offset(50f, 80f), actual) } @Test fun testPositionRelativeToAncestorWithGrandParent() { val grandParent = ZeroSizedLayoutNode() grandParent.attach(MockOwner()) val parent = ZeroSizedLayoutNode() val child = ZeroSizedLayoutNode() grandParent.insertAt(0, parent) parent.insertAt(0, child) grandParent.place(-7, 17) parent.place(23, -13) child.place(-3, 11) val actual = grandParent.coordinates.localPositionOf(child.coordinates, Offset.Zero) assertEquals(Offset(20f, -2f), actual) } // LayoutNode shouldn't allow adding beyond the count @Test fun testAddBeyondCurrent() { val node = LayoutNode() Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.insertAt(1, LayoutNode()) } } // LayoutNode shouldn't allow adding below 0 @Test fun testAddBelowZero() { val node = LayoutNode() Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.insertAt(-1, LayoutNode()) } } // LayoutNode should error when removing at index < 0 @Test fun testRemoveNegativeIndex() { val node = LayoutNode() node.insertAt(0, LayoutNode()) Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.removeAt(-1, 1) } } // LayoutNode should error when removing at index > count @Test fun testRemoveBeyondIndex() { val node = LayoutNode() node.insertAt(0, LayoutNode()) Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.removeAt(1, 1) } } // LayoutNode should error when removing at count < 0 @Test fun testRemoveNegativeCount() { val node = LayoutNode() node.insertAt(0, LayoutNode()) Assert.assertThrows(IllegalArgumentException::class.java) { node.removeAt(0, -1) } } // LayoutNode should error when removing at count > entry count @Test fun testRemoveWithIndexBeyondSize() { val node = LayoutNode() node.insertAt(0, LayoutNode()) Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.removeAt(0, 2) } } // LayoutNode should error when there aren't enough items @Test fun testRemoveWithIndexEqualToSize() { val node = LayoutNode() Assert.assertThrows(IndexOutOfBoundsException::class.java) { node.removeAt(0, 1) } } // LayoutNode should allow removing two items @Test fun testRemoveTwoItems() { val node = LayoutNode() node.insertAt(0, LayoutNode()) node.insertAt(0, LayoutNode()) node.removeAt(0, 2) assertEquals(0, node.children.size) } // The layout coordinates of a LayoutNode should be attached when // the layout node is attached. @Test fun coordinatesAttachedWhenLayoutNodeAttached() { val layoutNode = LayoutNode() val layoutModifier = Modifier.graphicsLayer { } layoutNode.modifier = layoutModifier assertFalse(layoutNode.coordinates.isAttached) assertFalse(layoutNode.coordinates.isAttached) layoutNode.attach(MockOwner()) assertTrue(layoutNode.coordinates.isAttached) assertTrue(layoutNode.coordinates.isAttached) layoutNode.detach() assertFalse(layoutNode.coordinates.isAttached) assertFalse(layoutNode.coordinates.isAttached) } // The NodeCoordinator should be reused when it has been replaced with the same type @Test fun nodeCoordinatorSameWithReplacementModifier() { val layoutNode = LayoutNode() val layoutModifier = Modifier.graphicsLayer { } layoutNode.modifier = layoutModifier val oldNodeCoordinator = layoutNode.outerCoordinator assertFalse(oldNodeCoordinator.isAttached) layoutNode.attach(MockOwner()) assertTrue(oldNodeCoordinator.isAttached) layoutNode.modifier = Modifier.graphicsLayer { } val newNodeCoordinator = layoutNode.outerCoordinator assertSame(newNodeCoordinator, oldNodeCoordinator) } // The NodeCoordinator should be reused when it has been replaced with the same type, // even with multiple NodeCoordinators for one modifier. @Test fun nodeCoordinatorSameWithReplacementMultiModifier() { class TestModifier : DrawModifier, LayoutModifier { override fun ContentDrawScope.draw() { drawContent() } override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ) = layout(0, 0) {} } val layoutNode = LayoutNode() layoutNode.modifier = TestModifier() val oldNodeCoordinator = layoutNode.outerCoordinator val oldNodeCoordinator2 = oldNodeCoordinator.wrapped layoutNode.modifier = TestModifier() val newNodeCoordinator = layoutNode.outerCoordinator val newNodeCoordinator2 = newNodeCoordinator.wrapped assertSame(newNodeCoordinator, oldNodeCoordinator) assertSame(newNodeCoordinator2, oldNodeCoordinator2) } // The NodeCoordinator should be detached when it has been replaced. @Test fun nodeCoordinatorAttachedWhenLayoutNodeAttached() { val layoutNode = LayoutNode() // 2 modifiers at the start val layoutModifier = Modifier.graphicsLayer { }.graphicsLayer { } layoutNode.modifier = layoutModifier val oldNodeCoordinator = layoutNode.outerCoordinator val oldInnerNodeCoordinator = oldNodeCoordinator.wrapped assertFalse(oldNodeCoordinator.isAttached) assertNotNull(oldInnerNodeCoordinator) assertFalse(oldInnerNodeCoordinator!!.isAttached) layoutNode.attach(MockOwner()) assertTrue(oldNodeCoordinator.isAttached) // only 1 modifier now, so one should be detached and the other can be reused layoutNode.modifier = Modifier.graphicsLayer() val newNodeCoordinator = layoutNode.outerCoordinator // one can be reused, but we don't care which one val notReused = if (newNodeCoordinator == oldNodeCoordinator) { oldInnerNodeCoordinator } else { oldNodeCoordinator } assertTrue(newNodeCoordinator.isAttached) assertFalse(notReused.isAttached) } @Test fun nodeCoordinatorParentLayoutCoordinates() { val layoutNode = LayoutNode() val layoutNode2 = LayoutNode() val layoutModifier = Modifier.graphicsLayer { } layoutNode.modifier = layoutModifier layoutNode2.insertAt(0, layoutNode) layoutNode2.attach(MockOwner()) assertEquals( layoutNode2.innerCoordinator, layoutNode.innerCoordinator.parentLayoutCoordinates ) assertEquals( layoutNode2.innerCoordinator, layoutNode.outerCoordinator.parentLayoutCoordinates ) } @Test fun nodeCoordinatorParentCoordinates() { val layoutNode = LayoutNode() val layoutNode2 = LayoutNode() val layoutModifier = object : LayoutModifier { override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { TODO("Not yet implemented") } } val drawModifier = Modifier.drawBehind { } layoutNode.modifier = layoutModifier.then(drawModifier) layoutNode2.insertAt(0, layoutNode) layoutNode2.attach(MockOwner()) val layoutModifierWrapper = layoutNode.outerCoordinator assertEquals( layoutModifierWrapper, layoutNode.innerCoordinator.parentCoordinates ) assertEquals( layoutNode2.innerCoordinator, layoutModifierWrapper.parentCoordinates ) } @Test fun nodeCoordinator_transformFrom_offsets() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) parent.place(-100, 10) child.place(50, 80) val matrix = Matrix() child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix) assertEquals(Offset(-50f, -80f), matrix.map(Offset.Zero)) parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix) assertEquals(Offset(50f, 80f), matrix.map(Offset.Zero)) } @Test fun nodeCoordinator_transformFrom_translation() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) child.modifier = Modifier.graphicsLayer { translationX = 5f translationY = 2f } parent.outerCoordinator .measure(listOf(parent.outerCoordinator), Constraints()) child.outerCoordinator .measure(listOf(child.outerCoordinator), Constraints()) parent.place(0, 0) child.place(0, 0) val matrix = Matrix() child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix) assertEquals(-5f, matrix.map(Offset.Zero).x, 0.001f) assertEquals(-2f, matrix.map(Offset.Zero).y, 0.001f) parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix) assertEquals(5f, matrix.map(Offset.Zero).x, 0.001f) assertEquals(2f, matrix.map(Offset.Zero).y, 0.001f) } @Test fun nodeCoordinator_transformFrom_rotation() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) child.modifier = Modifier.graphicsLayer { rotationZ = 90f } parent.outerCoordinator .measure(listOf(parent.outerCoordinator), Constraints()) child.outerCoordinator .measure(listOf(child.outerCoordinator), Constraints()) parent.place(0, 0) child.place(0, 0) val matrix = Matrix() child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix) assertEquals(0f, matrix.map(Offset(1f, 0f)).x, 0.001f) assertEquals(-1f, matrix.map(Offset(1f, 0f)).y, 0.001f) parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix) assertEquals(0f, matrix.map(Offset(1f, 0f)).x, 0.001f) assertEquals(1f, matrix.map(Offset(1f, 0f)).y, 0.001f) } @Test fun nodeCoordinator_transformFrom_scale() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child = ZeroSizedLayoutNode() parent.insertAt(0, child) child.modifier = Modifier.graphicsLayer { scaleX = 0f } parent.outerCoordinator .measure(listOf(parent.outerCoordinator), Constraints()) child.outerCoordinator .measure(listOf(child.outerCoordinator), Constraints()) parent.place(0, 0) child.place(0, 0) val matrix = Matrix() child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix) // The X coordinate is somewhat nonsensical since it is scaled to 0 // We've chosen to make it not transform when there's a nonsensical inverse. assertEquals(1f, matrix.map(Offset(1f, 1f)).x, 0.001f) assertEquals(1f, matrix.map(Offset(1f, 1f)).y, 0.001f) parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix) // This direction works, so we can expect the normal scaling assertEquals(0f, matrix.map(Offset(1f, 1f)).x, 0.001f) assertEquals(1f, matrix.map(Offset(1f, 1f)).y, 0.001f) child.innerCoordinator.onLayerBlockUpdated { scaleX = 0.5f scaleY = 0.25f } child.innerCoordinator.transformFrom(parent.innerCoordinator, matrix) assertEquals(2f, matrix.map(Offset(1f, 1f)).x, 0.001f) assertEquals(4f, matrix.map(Offset(1f, 1f)).y, 0.001f) parent.innerCoordinator.transformFrom(child.innerCoordinator, matrix) assertEquals(0.5f, matrix.map(Offset(1f, 1f)).x, 0.001f) assertEquals(0.25f, matrix.map(Offset(1f, 1f)).y, 0.001f) } @Test fun nodeCoordinator_transformFrom_siblings() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child1 = ZeroSizedLayoutNode() parent.insertAt(0, child1) child1.modifier = Modifier.graphicsLayer { scaleX = 0.5f scaleY = 0.25f transformOrigin = TransformOrigin(0f, 0f) } val child2 = ZeroSizedLayoutNode() parent.insertAt(0, child2) child2.modifier = Modifier.graphicsLayer { scaleX = 5f scaleY = 2f transformOrigin = TransformOrigin(0f, 0f) } parent.outerCoordinator .measure(listOf(parent.outerCoordinator), Constraints()) child1.outerCoordinator .measure(listOf(child1.outerCoordinator), Constraints()) child2.outerCoordinator .measure(listOf(child2.outerCoordinator), Constraints()) parent.place(0, 0) child1.place(100, 200) child2.place(5, 11) val matrix = Matrix() child2.innerCoordinator.transformFrom(child1.innerCoordinator, matrix) // (20, 36) should be (10, 9) in real coordinates due to scaling // Translate to (110, 209) in the parent // Translate to (105, 198) in child2's coordinates, discounting scale // Scaled to (21, 99) val offset = matrix.map(Offset(20f, 36f)) assertEquals(21f, offset.x, 0.001f) assertEquals(99f, offset.y, 0.001f) child1.innerCoordinator.transformFrom(child2.innerCoordinator, matrix) val offset2 = matrix.map(Offset(21f, 99f)) assertEquals(20f, offset2.x, 0.001f) assertEquals(36f, offset2.y, 0.001f) } @Test fun nodeCoordinator_transformFrom_cousins() { val parent = ZeroSizedLayoutNode() parent.attach(MockOwner()) val child1 = ZeroSizedLayoutNode() parent.insertAt(0, child1) val child2 = ZeroSizedLayoutNode() parent.insertAt(1, child2) val grandChild1 = ZeroSizedLayoutNode() child1.insertAt(0, grandChild1) val grandChild2 = ZeroSizedLayoutNode() child2.insertAt(0, grandChild2) parent.place(-100, 10) child1.place(10, 11) child2.place(22, 33) grandChild1.place(45, 27) grandChild2.place(17, 59) val matrix = Matrix() grandChild1.innerCoordinator.transformFrom(grandChild2.innerCoordinator, matrix) // (17, 59) + (22, 33) - (10, 11) - (45, 27) = (-16, 54) assertEquals(Offset(-16f, 54f), matrix.map(Offset.Zero)) grandChild2.innerCoordinator.transformFrom(grandChild1.innerCoordinator, matrix) assertEquals(Offset(16f, -54f), matrix.map(Offset.Zero)) } @Test fun hitTest_pointerInBounds_pointerInputFilterHit() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1, 1, PointerInputModifierImpl(pointerInputFilter) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(0f, 0f), hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1, 1, PointerInputModifierImpl(pointerInputFilter), DpSize(48.dp, 48.dp) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(-3f, 3f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_horizontal() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1000, 1, PointerInputModifierImpl(pointerInputFilter), DpSize(48.dp, 48.dp) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(0f, 3f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_vertical() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1, 1000, PointerInputModifierImpl(pointerInputFilter), DpSize(48.dp, 48.dp) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(3f, 0f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInMinimumTouchTarget_pointerInputFilterHit_nestedNodes() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val outerNode = LayoutNode(0, 0, 1, 1).apply { attach(MockOwner()) } val layoutNode = LayoutNode( 0, 0, 1, 1, PointerInputModifierImpl(pointerInputFilter), DpSize(48.dp, 48.dp) ) outerNode.add(layoutNode) layoutNode.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() outerNode.hitTest(Offset(-3f, 3f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInputFilterHit_outsideParent() { val outerPointerInputFilter: PointerInputFilter = mockPointerInputFilter() val outerNode = LayoutNode( 0, 0, 10, 10, PointerInputModifierImpl(outerPointerInputFilter) ).apply { attach(MockOwner()) } val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 20, 20, 30, 30, PointerInputModifierImpl(pointerInputFilter) ) outerNode.add(layoutNode) layoutNode.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() outerNode.hitTest(Offset(25f, 25f), hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerInputFilterHit_outsideParent_interceptOutOfBoundsChildEvents() { val outerPointerInputFilter: PointerInputFilter = mockPointerInputFilter( interceptChildEvents = true ) val outerNode = LayoutNode( 0, 0, 10, 10, PointerInputModifierImpl(outerPointerInputFilter) ).apply { attach(MockOwner()) } val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 20, 20, 30, 30, PointerInputModifierImpl(pointerInputFilter) ) outerNode.add(layoutNode) layoutNode.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() outerNode.hitTest(Offset(25f, 25f), hit) assertThat(hit.toFilters()).isEqualTo(listOf(outerPointerInputFilter, pointerInputFilter)) } @Test fun hitTest_pointerInMinimumTouchTarget_closestHit() { val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 0, 0, 5, 5, PointerInputModifierImpl(pointerInputFilter1), DpSize(48.dp, 48.dp) ) val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val layoutNode2 = LayoutNode( 6, 6, 11, 11, PointerInputModifierImpl(pointerInputFilter2), DpSize(48.dp, 48.dp) ) val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) } outerNode.add(layoutNode1) outerNode.add(layoutNode2) layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() // Hit closer to layoutNode1 outerNode.hitTest(Offset(5.1f, 5.5f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) hit.clear() // Hit closer to layoutNode2 outerNode.hitTest(Offset(5.9f, 5.5f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) hit.clear() // Hit closer to layoutNode1 outerNode.hitTest(Offset(5.5f, 5.1f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) hit.clear() // Hit closer to layoutNode2 outerNode.hitTest(Offset(5.5f, 5.9f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) hit.clear() // Hit inside layoutNode1 outerNode.hitTest(Offset(4.9f, 4.9f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) hit.clear() // Hit inside layoutNode2 outerNode.hitTest(Offset(6.1f, 6.1f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) } /** * When a child is in the minimum touch target area, but the parent is big enough to not * worry about minimum touch target, the child should still be able to be hit outside the * parent's bounds. */ @Test fun hitTest_pointerInMinimumTouchTarget_inChild_closestHit() { test_pointerInMinimumTouchTarget_inChild_closestHit { outerNode, nodeWithChild, soloNode -> outerNode.add(nodeWithChild) outerNode.add(soloNode) } } /** * When a child is in the minimum touch target area, but the parent is big enough to not * worry about minimum touch target, the child should still be able to be hit outside the * parent's bounds. This is different from * [hitTest_pointerInMinimumTouchTarget_inChild_closestHit] because the node with the nested * child is after the other node. */ @Test fun hitTest_pointerInMinimumTouchTarget_inChildOver_closestHit() { test_pointerInMinimumTouchTarget_inChild_closestHit { outerNode, nodeWithChild, soloNode -> outerNode.add(soloNode) outerNode.add(nodeWithChild) } } private fun test_pointerInMinimumTouchTarget_inChild_closestHit( block: (outerNode: LayoutNode, nodeWithChild: LayoutNode, soloNode: LayoutNode) -> Unit ) { val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 5, 5, 10, 10, PointerInputModifierImpl(pointerInputFilter1), DpSize(48.dp, 48.dp) ) val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter(interceptChildEvents = true) val layoutNode2 = LayoutNode( 0, 0, 10, 10, PointerInputModifierImpl(pointerInputFilter2), DpSize(48.dp, 48.dp) ) layoutNode2.add(layoutNode1) val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter() val layoutNode3 = LayoutNode( 12, 12, 17, 17, PointerInputModifierImpl(pointerInputFilter3), DpSize(48.dp, 48.dp) ) val outerNode = LayoutNode(0, 0, 20, 20).apply { attach(MockOwner()) } block(outerNode, layoutNode2, layoutNode3) layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() layoutNode3.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() // Hit outside of layoutNode2, but near layoutNode1 outerNode.hitTest(Offset(10.1f, 10.1f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2, pointerInputFilter1)) hit.clear() // Hit closer to layoutNode3 outerNode.hitTest(Offset(11.9f, 11.9f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter3)) } @Test fun hitTest_pointerInMinimumTouchTarget_closestHitWithOverlap() { val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 0, 0, 5, 5, PointerInputModifierImpl(pointerInputFilter1), DpSize(48.dp, 48.dp) ) val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val layoutNode2 = LayoutNode( 4, 4, 9, 9, PointerInputModifierImpl(pointerInputFilter2), DpSize(48.dp, 48.dp) ) val outerNode = LayoutNode(0, 0, 9, 9).apply { attach(MockOwner()) } outerNode.add(layoutNode1) outerNode.add(layoutNode2) layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() val hit = mutableListOf<PointerInputModifierNode>() // Hit layoutNode1 outerNode.hitTest(Offset(3.95f, 3.95f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) hit.clear() // Hit layoutNode2 outerNode.hitTest(Offset(4.05f, 4.05f), hit, true) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) } @Test fun hitTestSemantics_pointerInMinimumTouchTarget_pointerInputFilterHit() { val semanticsConfiguration = SemanticsConfiguration() val semanticsModifier = object : SemanticsModifier { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val layoutNode = LayoutNode( 0, 0, 1, 1, semanticsModifier, DpSize(48.dp, 48.dp) ).apply { attach(MockOwner()) } val hit = HitTestResult<SemanticsModifierNode>() layoutNode.hitTestSemantics(Offset(-3f, 3f), hit) assertThat(hit).hasSize(1) // assertThat(hit[0].modifier).isEqualTo(semanticsModifier) } @Test fun hitTestSemantics_pointerInMinimumTouchTarget_pointerInputFilterHit_nestedNodes() { val semanticsConfiguration = SemanticsConfiguration() val semanticsModifier = object : SemanticsModifier { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val outerNode = LayoutNode(0, 0, 1, 1).apply { attach(MockOwner()) } val layoutNode = LayoutNode(0, 0, 1, 1, semanticsModifier, DpSize(48.dp, 48.dp)) outerNode.add(layoutNode) layoutNode.onNodePlaced() val hit = HitTestResult<SemanticsModifierNode>() layoutNode.hitTestSemantics(Offset(-3f, 3f), hit) assertThat(hit).hasSize(1) assertThat(hit[0].toModifier()).isEqualTo(semanticsModifier) } @Test fun hitTestSemantics_pointerInMinimumTouchTarget_closestHit() { val semanticsConfiguration = SemanticsConfiguration() val semanticsModifier1 = object : SemanticsModifierNode, Modifier.Node() { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val semanticsModifier2 = object : SemanticsModifierNode, Modifier.Node() { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val semanticsModifierElement1 = modifierElementOf(null, { semanticsModifier1 }, { }, { }) val semanticsModifierElement2 = modifierElementOf(null, { semanticsModifier2 }, { }, { }) val layoutNode1 = LayoutNode(0, 0, 5, 5, semanticsModifierElement1, DpSize(48.dp, 48.dp)) val layoutNode2 = LayoutNode(6, 6, 11, 11, semanticsModifierElement2, DpSize(48.dp, 48.dp)) val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) } outerNode.add(layoutNode1) outerNode.add(layoutNode2) layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() // Hit closer to layoutNode1 val hit1 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(5.1f, 5.5f), hit1, true) assertThat(hit1).hasSize(1) assertThat(hit1[0]).isEqualTo(semanticsModifier1) // Hit closer to layoutNode2 val hit2 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(5.9f, 5.5f), hit2, true) assertThat(hit2).hasSize(1) assertThat(hit2[0]).isEqualTo(semanticsModifier2) // Hit closer to layoutNode1 val hit3 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(5.5f, 5.1f), hit3, true) assertThat(hit3).hasSize(1) assertThat(hit3[0]).isEqualTo(semanticsModifier1) // Hit closer to layoutNode2 val hit4 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(5.5f, 5.9f), hit4, true) assertThat(hit4).hasSize(1) assertThat(hit4[0]).isEqualTo(semanticsModifier2) // Hit inside layoutNode1 val hit5 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(4.9f, 4.9f), hit5, true) assertThat(hit5).hasSize(1) assertThat(hit5[0]).isEqualTo(semanticsModifier1) // Hit inside layoutNode2 val hit6 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(6.1f, 6.1f), hit6, true) assertThat(hit6).hasSize(1) assertThat(hit6[0]).isEqualTo(semanticsModifier2) } @Test fun hitTestSemantics_pointerInMinimumTouchTarget_closestHitWithOverlap() { val semanticsConfiguration = SemanticsConfiguration() val semanticsModifier1 = object : SemanticsModifier { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val semanticsModifier2 = object : SemanticsModifier { override val semanticsConfiguration: SemanticsConfiguration = semanticsConfiguration } val layoutNode1 = LayoutNode(0, 0, 5, 5, semanticsModifier1, DpSize(48.dp, 48.dp)) val layoutNode2 = LayoutNode(4, 4, 9, 9, semanticsModifier2, DpSize(48.dp, 48.dp)) val outerNode = LayoutNode(0, 0, 11, 11).apply { attach(MockOwner()) } outerNode.add(layoutNode1) outerNode.add(layoutNode2) layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() // Hit layoutNode1 val hit1 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(3.95f, 3.95f), hit1, true) assertThat(hit1).hasSize(1) assertThat(hit1[0].toModifier()).isEqualTo(semanticsModifier1) // Hit layoutNode2 val hit2 = HitTestResult<SemanticsModifierNode>() outerNode.hitTestSemantics(Offset(4.05f, 4.05f), hit2, true) assertThat(hit2).hasSize(1) assertThat(hit2[0].toModifier()).isEqualTo(semanticsModifier2) } @Test fun hitTest_pointerOutOfBounds_nothingHit() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1, 1, PointerInputModifierImpl(pointerInputFilter) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(-1f, -1f), hit) layoutNode.hitTest(Offset(0f, -1f), hit) layoutNode.hitTest(Offset(1f, -1f), hit) layoutNode.hitTest(Offset(-1f, 0f), hit) // 0, 0 would hit layoutNode.hitTest(Offset(1f, 0f), hit) layoutNode.hitTest(Offset(-1f, 1f), hit) layoutNode.hitTest(Offset(0f, 1f), hit) layoutNode.hitTest(Offset(1f, 1f), hit) assertThat(hit).isEmpty() } @Test fun hitTest_pointerOutOfBounds_nothingHit_extendedBounds() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 1, 1, PointerInputModifierImpl(pointerInputFilter), minimumTouchTargetSize = DpSize(4.dp, 8.dp) ).apply { attach(MockOwner()) } val hit = mutableListOf<PointerInputModifierNode>() layoutNode.hitTest(Offset(-3f, -5f), hit) layoutNode.hitTest(Offset(0f, -5f), hit) layoutNode.hitTest(Offset(3f, -5f), hit) layoutNode.hitTest(Offset(-3f, 0f), hit) // 0, 0 would hit layoutNode.hitTest(Offset(3f, 0f), hit) layoutNode.hitTest(Offset(-3f, 5f), hit) layoutNode.hitTest(Offset(0f, 5f), hit) layoutNode.hitTest(Offset(-3f, 5f), hit) assertThat(hit).isEmpty() } @Test fun hitTest_nestedOffsetNodesHits3_allHitInCorrectOrder() { hitTest_nestedOffsetNodes_allHitInCorrectOrder(3) } @Test fun hitTest_nestedOffsetNodesHits2_allHitInCorrectOrder() { hitTest_nestedOffsetNodes_allHitInCorrectOrder(2) } @Test fun hitTest_nestedOffsetNodesHits1_allHitInCorrectOrder() { hitTest_nestedOffsetNodes_allHitInCorrectOrder(1) } private fun hitTest_nestedOffsetNodes_allHitInCorrectOrder(numberOfChildrenHit: Int) { // Arrange val childPointerInputFilter: PointerInputFilter = mockPointerInputFilter() val middlePointerInputFilter: PointerInputFilter = mockPointerInputFilter() val parentPointerInputFilter: PointerInputFilter = mockPointerInputFilter() val childLayoutNode = LayoutNode( 100, 100, 200, 200, PointerInputModifierImpl( childPointerInputFilter ) ) val middleLayoutNode: LayoutNode = LayoutNode( 100, 100, 400, 400, PointerInputModifierImpl( middlePointerInputFilter ) ).apply { insertAt(0, childLayoutNode) } val parentLayoutNode: LayoutNode = LayoutNode( 0, 0, 500, 500, PointerInputModifierImpl( parentPointerInputFilter ) ).apply { insertAt(0, middleLayoutNode) attach(MockOwner()) } middleLayoutNode.onNodePlaced() childLayoutNode.onNodePlaced() val offset = when (numberOfChildrenHit) { 3 -> Offset(250f, 250f) 2 -> Offset(150f, 150f) 1 -> Offset(50f, 50f) else -> throw IllegalStateException() } val hit = mutableListOf<PointerInputModifierNode>() // Act. parentLayoutNode.hitTest(offset, hit) // Assert. when (numberOfChildrenHit) { 3 -> assertThat(hit.toFilters()) .isEqualTo( listOf( parentPointerInputFilter, middlePointerInputFilter, childPointerInputFilter ) ) 2 -> assertThat(hit.toFilters()) .isEqualTo( listOf( parentPointerInputFilter, middlePointerInputFilter ) ) 1 -> assertThat(hit.toFilters()) .isEqualTo( listOf( parentPointerInputFilter ) ) else -> throw IllegalStateException() } } /** * This test creates a layout of this shape: * * ------------- * | | | * | t | | * | | | * |-----| | * | | * | |-----| * | | | * | | t | * | | | * ------------- * * Where there is one child in the top right and one in the bottom left, and 2 pointers where * one in the top left and one in the bottom right. */ @Test fun hitTest_2PointersOver2DifferentPointerInputModifiers_resultIsCorrect() { // Arrange val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val childLayoutNode1 = LayoutNode( 0, 0, 50, 50, PointerInputModifierImpl( childPointerInputFilter1 ) ) val childLayoutNode2 = LayoutNode( 50, 50, 100, 100, PointerInputModifierImpl( childPointerInputFilter2 ) ) val parentLayoutNode = LayoutNode(0, 0, 100, 100).apply { insertAt(0, childLayoutNode1) insertAt(1, childLayoutNode2) attach(MockOwner()) } childLayoutNode1.onNodePlaced() childLayoutNode2.onNodePlaced() val offset1 = Offset(25f, 25f) val offset2 = Offset(75f, 75f) val hit1 = mutableListOf<PointerInputModifierNode>() val hit2 = mutableListOf<PointerInputModifierNode>() // Act parentLayoutNode.hitTest(offset1, hit1) parentLayoutNode.hitTest(offset2, hit2) // Assert assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2)) } /** * This test creates a layout of this shape: * * --------------- * | t | | * | | | * | |-------| | * | | t | | * | | | | * | | | | * |--| |-------| * | | | t | * | | | | * | | | | * | |--| | * | | | * --------------- * * There are 3 staggered children and 3 pointers, the first is on child 1, the second is on * child 2 in a space that overlaps child 1, and the third is in a space in child 3 that * overlaps child 2. */ @Test fun hitTest_3DownOnOverlappingPointerInputModifiers_resultIsCorrect() { val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val childPointerInputFilter3: PointerInputFilter = mockPointerInputFilter() val childLayoutNode1 = LayoutNode( 0, 0, 100, 100, PointerInputModifierImpl( childPointerInputFilter1 ) ) val childLayoutNode2 = LayoutNode( 50, 50, 150, 150, PointerInputModifierImpl( childPointerInputFilter2 ) ) val childLayoutNode3 = LayoutNode( 100, 100, 200, 200, PointerInputModifierImpl( childPointerInputFilter3 ) ) val parentLayoutNode = LayoutNode(0, 0, 200, 200).apply { insertAt(0, childLayoutNode1) insertAt(1, childLayoutNode2) insertAt(2, childLayoutNode3) attach(MockOwner()) } childLayoutNode1.onNodePlaced() childLayoutNode2.onNodePlaced() childLayoutNode3.onNodePlaced() val offset1 = Offset(25f, 25f) val offset2 = Offset(75f, 75f) val offset3 = Offset(125f, 125f) val hit1 = mutableListOf<PointerInputModifierNode>() val hit2 = mutableListOf<PointerInputModifierNode>() val hit3 = mutableListOf<PointerInputModifierNode>() parentLayoutNode.hitTest(offset1, hit1) parentLayoutNode.hitTest(offset2, hit2) parentLayoutNode.hitTest(offset3, hit3) assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2)) assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter3)) } /** * This test creates a layout of this shape: * * --------------- * | | * | t | * | | * | |-------| | * | | | | * | | t | | * | | | | * | |-------| | * | | * | t | * | | * --------------- * * There are 2 children with one over the other and 3 pointers: the first is on background * child, the second is on the foreground child, and the third is again on the background child. */ @Test fun hitTest_3DownOnFloatingPointerInputModifierV_resultIsCorrect() { val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val childLayoutNode1 = LayoutNode( 0, 0, 100, 150, PointerInputModifierImpl( childPointerInputFilter1 ) ) val childLayoutNode2 = LayoutNode( 25, 50, 75, 100, PointerInputModifierImpl( childPointerInputFilter2 ) ) val parentLayoutNode = LayoutNode(0, 0, 150, 150).apply { insertAt(0, childLayoutNode1) insertAt(1, childLayoutNode2) attach(MockOwner()) } childLayoutNode1.onNodePlaced() childLayoutNode2.onNodePlaced() val offset1 = Offset(50f, 25f) val offset2 = Offset(50f, 75f) val offset3 = Offset(50f, 125f) val hit1 = mutableListOf<PointerInputModifierNode>() val hit2 = mutableListOf<PointerInputModifierNode>() val hit3 = mutableListOf<PointerInputModifierNode>() // Act parentLayoutNode.hitTest(offset1, hit1) parentLayoutNode.hitTest(offset2, hit2) parentLayoutNode.hitTest(offset3, hit3) // Assert assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2)) assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) } /** * This test creates a layout of this shape: * * ----------------- * | | * | |-------| | * | | | | * | t | t | t | * | | | | * | |-------| | * | | * ----------------- * * There are 2 children with one over the other and 3 pointers: the first is on background * child, the second is on the foreground child, and the third is again on the background child. */ @Test fun hitTest_3DownOnFloatingPointerInputModifierH_resultIsCorrect() { val childPointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val childPointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val childLayoutNode1 = LayoutNode( 0, 0, 150, 100, PointerInputModifierImpl( childPointerInputFilter1 ) ) val childLayoutNode2 = LayoutNode( 50, 25, 100, 75, PointerInputModifierImpl( childPointerInputFilter2 ) ) val parentLayoutNode = LayoutNode(0, 0, 150, 150).apply { insertAt(0, childLayoutNode1) insertAt(1, childLayoutNode2) attach(MockOwner()) } childLayoutNode2.onNodePlaced() childLayoutNode1.onNodePlaced() val offset1 = Offset(25f, 50f) val offset2 = Offset(75f, 50f) val offset3 = Offset(125f, 50f) val hit1 = mutableListOf<PointerInputModifierNode>() val hit2 = mutableListOf<PointerInputModifierNode>() val hit3 = mutableListOf<PointerInputModifierNode>() // Act parentLayoutNode.hitTest(offset1, hit1) parentLayoutNode.hitTest(offset2, hit2) parentLayoutNode.hitTest(offset3, hit3) // Assert assertThat(hit1.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) assertThat(hit2.toFilters()).isEqualTo(listOf(childPointerInputFilter2)) assertThat(hit3.toFilters()).isEqualTo(listOf(childPointerInputFilter1)) } /** * This test creates a layout of this shape: * 0 1 2 3 4 * ......... ......... * 0 . t . . t . * . |---|---|---| . * 1 . t | t | | t | t . * ....|---| |---|.... * 2 | | * ....|---| |---|.... * 3 . t | t | | t | t . * . |---|---|---| . * 4 . t . . t . * ......... ......... * * 4 LayoutNodes with PointerInputModifiers that are clipped by their parent LayoutNode. 4 * touches touch just inside the parent LayoutNode and inside the child LayoutNodes. 8 * touches touch just outside the parent LayoutNode but inside the child LayoutNodes. * * Because layout node bounds are not used to clip pointer input hit testing, all pointers * should hit. */ @Test fun hitTest_4DownInClippedAreaOfLnsWithPims_resultIsCorrect() { // Arrange val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter4: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( -1, -1, 1, 1, PointerInputModifierImpl( pointerInputFilter1 ) ) val layoutNode2 = LayoutNode( 2, -1, 4, 1, PointerInputModifierImpl( pointerInputFilter2 ) ) val layoutNode3 = LayoutNode( -1, 2, 1, 4, PointerInputModifierImpl( pointerInputFilter3 ) ) val layoutNode4 = LayoutNode( 2, 2, 4, 4, PointerInputModifierImpl( pointerInputFilter4 ) ) val parentLayoutNode = LayoutNode(1, 1, 4, 4).apply { insertAt(0, layoutNode1) insertAt(1, layoutNode2) insertAt(2, layoutNode3) insertAt(3, layoutNode4) attach(MockOwner()) } layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() layoutNode3.onNodePlaced() layoutNode4.onNodePlaced() val offsetsThatHit1 = listOf( Offset(0f, 1f), Offset(1f, 0f), Offset(1f, 1f) ) val offsetsThatHit2 = listOf( Offset(3f, 0f), Offset(3f, 1f), Offset(4f, 1f) ) val offsetsThatHit3 = listOf( Offset(0f, 3f), Offset(1f, 3f), Offset(1f, 4f) ) val offsetsThatHit4 = listOf( Offset(3f, 3f), Offset(3f, 4f), Offset(4f, 3f) ) val hit = mutableListOf<PointerInputModifierNode>() // Act and Assert offsetsThatHit1.forEach { hit.clear() parentLayoutNode.hitTest(it, hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) } offsetsThatHit2.forEach { hit.clear() parentLayoutNode.hitTest(it, hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) } offsetsThatHit3.forEach { hit.clear() parentLayoutNode.hitTest(it, hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter3)) } offsetsThatHit4.forEach { hit.clear() parentLayoutNode.hitTest(it, hit) assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter4)) } } @Test fun hitTest_pointerOn3NestedPointerInputModifiers_allPimsHitInCorrectOrder() { // Arrange. val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter() val modifier = PointerInputModifierImpl( pointerInputFilter1 ) then PointerInputModifierImpl( pointerInputFilter2 ) then PointerInputModifierImpl( pointerInputFilter3 ) val layoutNode = LayoutNode( 25, 50, 75, 100, modifier ).apply { attach(MockOwner()) } val offset1 = Offset(50f, 75f) val hit = mutableListOf<PointerInputModifierNode>() // Act. layoutNode.hitTest(offset1, hit) // Assert. assertThat(hit.toFilters()).isEqualTo( listOf( pointerInputFilter1, pointerInputFilter2, pointerInputFilter3 ) ) } @Test fun hitTest_pointerOnDeeplyNestedPointerInputModifier_pimIsHit() { // Arrange. val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 1, 5, 500, 500, PointerInputModifierImpl( pointerInputFilter ) ) val layoutNode2: LayoutNode = LayoutNode(2, 6, 500, 500).apply { insertAt(0, layoutNode1) } val layoutNode3: LayoutNode = LayoutNode(3, 7, 500, 500).apply { insertAt(0, layoutNode2) } val layoutNode4: LayoutNode = LayoutNode(4, 8, 500, 500).apply { insertAt(0, layoutNode3) }.apply { attach(MockOwner()) } layoutNode3.onNodePlaced() layoutNode2.onNodePlaced() layoutNode1.onNodePlaced() val offset1 = Offset(499f, 499f) val hit = mutableListOf<PointerInputModifierNode>() // Act. layoutNode4.hitTest(offset1, hit) // Assert. assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter)) } @Test fun hitTest_pointerOnComplexPointerAndLayoutNodePath_pimsHitInCorrectOrder() { // Arrange. val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter3: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter4: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 1, 6, 500, 500, PointerInputModifierImpl( pointerInputFilter1 ) then PointerInputModifierImpl( pointerInputFilter2 ) ) val layoutNode2: LayoutNode = LayoutNode(2, 7, 500, 500).apply { insertAt(0, layoutNode1) } val layoutNode3 = LayoutNode( 3, 8, 500, 500, PointerInputModifierImpl( pointerInputFilter3 ) then PointerInputModifierImpl( pointerInputFilter4 ) ).apply { insertAt(0, layoutNode2) } val layoutNode4: LayoutNode = LayoutNode(4, 9, 500, 500).apply { insertAt(0, layoutNode3) } val layoutNode5: LayoutNode = LayoutNode(5, 10, 500, 500).apply { insertAt(0, layoutNode4) }.apply { attach(MockOwner()) } layoutNode4.onNodePlaced() layoutNode3.onNodePlaced() layoutNode2.onNodePlaced() layoutNode1.onNodePlaced() val offset1 = Offset(499f, 499f) val hit = mutableListOf<PointerInputModifierNode>() // Act. layoutNode5.hitTest(offset1, hit) // Assert. assertThat(hit.toFilters()).isEqualTo( listOf( pointerInputFilter3, pointerInputFilter4, pointerInputFilter1, pointerInputFilter2 ) ) } @Test fun hitTest_pointerOnFullyOverlappingPointerInputModifiers_onlyTopPimIsHit() { val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val layoutNode1 = LayoutNode( 0, 0, 100, 100, PointerInputModifierImpl( pointerInputFilter1 ) ) val layoutNode2 = LayoutNode( 0, 0, 100, 100, PointerInputModifierImpl( pointerInputFilter2 ) ) val parentLayoutNode = LayoutNode(0, 0, 100, 100).apply { insertAt(0, layoutNode1) insertAt(1, layoutNode2) attach(MockOwner()) } layoutNode1.onNodePlaced() layoutNode2.onNodePlaced() val offset = Offset(50f, 50f) val hit = mutableListOf<PointerInputModifierNode>() // Act. parentLayoutNode.hitTest(offset, hit) // Assert. assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter2)) } @Test fun hitTest_pointerOnPointerInputModifierInLayoutNodeWithNoSize_nothingHit() { val pointerInputFilter: PointerInputFilter = mockPointerInputFilter() val layoutNode = LayoutNode( 0, 0, 0, 0, PointerInputModifierImpl( pointerInputFilter ) ).apply { attach(MockOwner()) } val offset = Offset.Zero val hit = mutableListOf<PointerInputModifierNode>() // Act. layoutNode.hitTest(offset, hit) // Assert. assertThat(hit.toFilters()).isEmpty() } @Test fun hitTest_zIndexIsAccounted() { val pointerInputFilter1: PointerInputFilter = mockPointerInputFilter() val pointerInputFilter2: PointerInputFilter = mockPointerInputFilter() val parent = LayoutNode( 0, 0, 2, 2 ).apply { attach( MockOwner().apply { measureIteration = 1L } ) } parent.insertAt( 0, LayoutNode( 0, 0, 2, 2, PointerInputModifierImpl( pointerInputFilter1 ).zIndex(1f) ) ) parent.insertAt( 1, LayoutNode( 0, 0, 2, 2, PointerInputModifierImpl( pointerInputFilter2 ) ) ) parent.remeasure() parent.replace() val hit = mutableListOf<PointerInputModifierNode>() // Act. parent.hitTest(Offset(1f, 1f), hit) // Assert. assertThat(hit.toFilters()).isEqualTo(listOf(pointerInputFilter1)) } @Test fun onRequestMeasureIsNotCalledOnDetachedNodes() { val root = LayoutNode() val node1 = LayoutNode() root.add(node1) val node2 = LayoutNode() node1.add(node2) val owner = MockOwner() root.attach(owner) owner.onAttachParams.clear() owner.onRequestMeasureParams.clear() // Dispose root.removeAt(0, 1) assertFalse(node1.isAttached) assertFalse(node2.isAttached) assertEquals(0, owner.onRequestMeasureParams.count { it === node1 }) assertEquals(0, owner.onRequestMeasureParams.count { it === node2 }) } @Test fun modifierMatchesWrapperWithIdentity() { val modifier1 = Modifier.layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } val modifier2 = Modifier.layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.place(1, 1) } } val root = LayoutNode() root.modifier = modifier1.then(modifier2) val wrapper1 = root.outerCoordinator val wrapper2 = root.outerCoordinator.wrapped assertEquals( modifier1, (wrapper1 as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier() ) assertEquals( modifier2, (wrapper2 as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier() ) root.modifier = modifier2.then(modifier1) assertEquals( modifier1, (root.outerCoordinator.wrapped as LayoutModifierNodeCoordinator) .layoutModifierNode .toModifier() ) assertEquals( modifier2, (root.outerCoordinator as LayoutModifierNodeCoordinator).layoutModifierNode.toModifier() ) } @Test fun measureResultAndPositionChangesCallOnLayoutChange() { val node = LayoutNode(20, 20, 100, 100) val owner = MockOwner() node.attach(owner) node.innerCoordinator.measureResult = object : MeasureResult { override val width = 50 override val height = 50 override val alignmentLines: Map<AlignmentLine, Int> get() = mapOf() override fun placeChildren() {} } assertEquals(1, owner.layoutChangeCount) node.place(0, 0) assertEquals(2, owner.layoutChangeCount) } @Test fun layerParamChangeCallsOnLayoutChange() { val node = LayoutNode(20, 20, 100, 100, Modifier.graphicsLayer()) val owner = MockOwner() node.attach(owner) assertEquals(0, owner.layoutChangeCount) node.innerCoordinator.onLayerBlockUpdated { scaleX = 0.5f } assertEquals(1, owner.layoutChangeCount) repeat(2) { node.innerCoordinator.onLayerBlockUpdated { scaleX = 1f } } assertEquals(2, owner.layoutChangeCount) node.innerCoordinator.onLayerBlockUpdated(null) assertEquals(3, owner.layoutChangeCount) } @Test fun reuseModifiersThatImplementMultipleModifierInterfaces() { val drawAndLayoutModifier: Modifier = object : DrawModifier, LayoutModifier { override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { val placeable = measurable.measure(constraints) return layout(placeable.width, placeable.height) { placeable.placeRelative(IntOffset.Zero) } } override fun ContentDrawScope.draw() { drawContent() } } val a = Modifier.then(EmptyLayoutModifier()).then(drawAndLayoutModifier) val b = Modifier.then(EmptyLayoutModifier()).then(drawAndLayoutModifier) val node = LayoutNode(20, 20, 100, 100) val owner = MockOwner() node.attach(owner) node.modifier = a assertEquals(2, node.getModifierInfo().size) node.modifier = b assertEquals(2, node.getModifierInfo().size) } @Test fun nodeCoordinator_alpha() { val root = LayoutNode().apply { this.modifier = Modifier.drawBehind {} } val layoutNode1 = LayoutNode().apply { this.modifier = Modifier.graphicsLayer { }.graphicsLayer { }.drawBehind {} } val layoutNode2 = LayoutNode().apply { this.modifier = Modifier.drawBehind {} } val owner = MockOwner() root.insertAt(0, layoutNode1) layoutNode1.insertAt(0, layoutNode2) root.attach(owner) // provide alpha to the graphics layer layoutNode1.outerCoordinator.wrapped!!.onLayerBlockUpdated { alpha = 0f } layoutNode1.outerCoordinator.wrapped!!.wrapped!!.onLayerBlockUpdated { alpha = 0.5f } assertFalse(layoutNode1.outerCoordinator.isTransparent()) assertTrue(layoutNode1.innerCoordinator.isTransparent()) assertTrue(layoutNode2.outerCoordinator.isTransparent()) assertTrue(layoutNode2.innerCoordinator.isTransparent()) } private fun createSimpleLayout(): Triple<LayoutNode, LayoutNode, LayoutNode> { val layoutNode = ZeroSizedLayoutNode() val child1 = ZeroSizedLayoutNode() val child2 = ZeroSizedLayoutNode() layoutNode.insertAt(0, child1) layoutNode.insertAt(1, child2) return Triple(layoutNode, child1, child2) } private fun ZeroSizedLayoutNode() = LayoutNode(0, 0, 0, 0) private class PointerInputModifierImpl(override val pointerInputFilter: PointerInputFilter) : PointerInputModifier } private class EmptyLayoutModifier : LayoutModifier { override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { val placeable = measurable.measure(constraints) return layout(placeable.width, placeable.height) { placeable.placeRelative(IntOffset.Zero) } } } @OptIn(InternalCoreApi::class) internal class MockOwner( val position: IntOffset = IntOffset.Zero, override val root: LayoutNode = LayoutNode() ) : Owner { val onRequestMeasureParams = mutableListOf<LayoutNode>() val onAttachParams = mutableListOf<LayoutNode>() val onDetachParams = mutableListOf<LayoutNode>() var layoutChangeCount = 0 override val rootForTest: RootForTest get() = TODO("Not yet implemented") override val hapticFeedBack: HapticFeedback get() = TODO("Not yet implemented") override val inputModeManager: InputModeManager get() = TODO("Not yet implemented") override val clipboardManager: ClipboardManager get() = TODO("Not yet implemented") override val accessibilityManager: AccessibilityManager get() = TODO("Not yet implemented") override val textToolbar: TextToolbar get() = TODO("Not yet implemented") @OptIn(ExperimentalComposeUiApi::class) override val autofillTree: AutofillTree get() = TODO("Not yet implemented") @OptIn(ExperimentalComposeUiApi::class) override val autofill: Autofill? get() = TODO("Not yet implemented") override val density: Density get() = Density(1f) override val textInputService: TextInputService get() = TODO("Not yet implemented") override val pointerIconService: PointerIconService get() = TODO("Not yet implemented") override val focusManager: FocusManager get() = TODO("Not yet implemented") override val windowInfo: WindowInfo get() = TODO("Not yet implemented") @Deprecated( "fontLoader is deprecated, use fontFamilyResolver", replaceWith = ReplaceWith("fontFamilyResolver") ) @Suppress("DEPRECATION") override val fontLoader: Font.ResourceLoader get() = TODO("Not yet implemented") override val fontFamilyResolver: FontFamily.Resolver get() = TODO("Not yet implemented") override val layoutDirection: LayoutDirection get() = LayoutDirection.Ltr override var showLayoutBounds: Boolean = false override val snapshotObserver = OwnerSnapshotObserver { it.invoke() } override val modifierLocalManager: ModifierLocalManager = ModifierLocalManager(this) override fun onRequestMeasure( layoutNode: LayoutNode, affectsLookahead: Boolean, forceRequest: Boolean ) { onRequestMeasureParams += layoutNode if (affectsLookahead) { layoutNode.markLookaheadMeasurePending() } layoutNode.markMeasurePending() } override fun onRequestRelayout( layoutNode: LayoutNode, affectsLookahead: Boolean, forceRequest: Boolean ) { if (affectsLookahead) { layoutNode.markLookaheadLayoutPending() } layoutNode.markLayoutPending() } override fun requestOnPositionedCallback(layoutNode: LayoutNode) { } override fun onAttach(node: LayoutNode) { onAttachParams += node } override fun onDetach(node: LayoutNode) { onDetachParams += node } override fun calculatePositionInWindow(localPosition: Offset): Offset = localPosition + position.toOffset() override fun calculateLocalPosition(positionInWindow: Offset): Offset = positionInWindow - position.toOffset() override fun requestFocus(): Boolean = false override fun measureAndLayout(sendPointerUpdate: Boolean) { } override fun measureAndLayout(layoutNode: LayoutNode, constraints: Constraints) { } override fun forceMeasureTheSubtree(layoutNode: LayoutNode) { } override fun registerOnEndApplyChangesListener(listener: () -> Unit) { listener() } override fun onEndApplyChanges() { } override fun registerOnLayoutCompletedListener(listener: Owner.OnLayoutCompletedListener) { TODO("Not yet implemented") } override fun createLayer( drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit ): OwnedLayer { val transform = Matrix() val inverseTransform = Matrix() return object : OwnedLayer { override fun updateLayerProperties( scaleX: Float, scaleY: Float, alpha: Float, translationX: Float, translationY: Float, shadowElevation: Float, rotationX: Float, rotationY: Float, rotationZ: Float, cameraDistance: Float, transformOrigin: TransformOrigin, shape: Shape, clip: Boolean, renderEffect: RenderEffect?, ambientShadowColor: Color, spotShadowColor: Color, compositingStrategy: CompositingStrategy, layoutDirection: LayoutDirection, density: Density ) { transform.reset() // This is not expected to be 100% accurate transform.scale(scaleX, scaleY) transform.rotateZ(rotationZ) transform.translate(translationX, translationY) transform.invertTo(inverseTransform) } override fun isInLayer(position: Offset) = true override fun move(position: IntOffset) { } override fun resize(size: IntSize) { } override fun drawLayer(canvas: Canvas) { drawBlock(canvas) } override fun updateDisplayList() { } override fun invalidate() { } override fun destroy() { } override fun mapBounds(rect: MutableRect, inverse: Boolean) { } override fun reuseLayer( drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit ) { } override fun transform(matrix: Matrix) { matrix.timesAssign(transform) } override fun inverseTransform(matrix: Matrix) { matrix.timesAssign(inverseTransform) } override fun mapOffset(point: Offset, inverse: Boolean) = point } } override fun onSemanticsChange() { } override fun onLayoutChange(layoutNode: LayoutNode) { layoutChangeCount++ } override fun getFocusDirection(keyEvent: KeyEvent): FocusDirection? { TODO("Not yet implemented") } override var measureIteration: Long = 0 override val viewConfiguration: ViewConfiguration get() = TODO("Not yet implemented") override val sharedDrawScope = LayoutNodeDrawScope() } @OptIn(ExperimentalComposeUiApi::class) private fun LayoutNode.hitTest( pointerPosition: Offset, hitPointerInputFilters: MutableList<PointerInputModifierNode>, isTouchEvent: Boolean = false ) { val hitTestResult = HitTestResult<PointerInputModifierNode>() hitTest(pointerPosition, hitTestResult, isTouchEvent) hitPointerInputFilters.addAll(hitTestResult) } internal fun LayoutNode( x: Int, y: Int, x2: Int, y2: Int, modifier: Modifier = Modifier, minimumTouchTargetSize: DpSize = DpSize.Zero ) = LayoutNode().apply { this.viewConfiguration = TestViewConfiguration(minimumTouchTargetSize = minimumTouchTargetSize) this.modifier = modifier measurePolicy = object : LayoutNode.NoIntrinsicsMeasurePolicy("not supported") { override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult = layout(x2 - x, y2 - y) { measurables.forEach { it.measure(constraints).place(0, 0) } } } attach(MockOwner()) markMeasurePending() remeasure(Constraints()) var wrapper: NodeCoordinator? = outerCoordinator while (wrapper != null) { wrapper.measureResult = innerCoordinator.measureResult wrapper = (wrapper as? NodeCoordinator)?.wrapped } place(x, y) detach() } private fun mockPointerInputFilter( interceptChildEvents: Boolean = false ): PointerInputFilter = object : PointerInputFilter() { override fun onPointerEvent( pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize ) { } override fun onCancel() { } override val interceptOutOfBoundsChildEvents: Boolean get() = interceptChildEvents } // This returns the corresponding modifier that produced the PointerInputNode. This is only // possible for PointerInputNodes that are BackwardsCompatNodes and once we refactor the // pointerInput modifier to use Modifier.Nodes directly, the tests that use this should be rewritten @OptIn(ExperimentalComposeUiApi::class) fun PointerInputModifierNode.toFilter(): PointerInputFilter { val node = this as? BackwardsCompatNode ?: error("Incorrectly assumed PointerInputNode was a BackwardsCompatNode") val modifier = node.element as? PointerInputModifier ?: error("Incorrectly assumed Modifier.Element was a PointerInputModifier") return modifier.pointerInputFilter } @OptIn(ExperimentalComposeUiApi::class) fun List<PointerInputModifierNode>.toFilters(): List<PointerInputFilter> = map { it.toFilter() } // This returns the corresponding modifier that produced the Node. This is only possible for // Nodes that are BackwardsCompatNodes and once we refactor semantics / pointer input to use // Modifier.Nodes directly, the tests that use this should be rewritten @OptIn(ExperimentalComposeUiApi::class) fun DelegatableNode.toModifier(): Modifier.Element { val node = node as? BackwardsCompatNode ?: error("Incorrectly assumed Modifier.Node was a BackwardsCompatNode") return node.element }
apache-2.0
d6c943bc4727c689a9a735eaee781a59
32.171005
100
0.62121
4.96241
false
true
false
false
qikh/kong-lang
src/main/kotlin/antlr/Function.kt
1
1008
package antlr import antlr.KongParser.ExpressionContext import org.antlr.v4.runtime.tree.ParseTree import org.antlr.v4.runtime.tree.TerminalNode class Function(val id: String, val params: List<TerminalNode>, val block: ParseTree) { fun invoke(params: List<ExpressionContext>, functions: Map<String, Function>, outerScope: Scope?): NodeValue { if (params.size != this.params.size) { throw RuntimeException("Illegal Function call") } var functionScope = Scope(outerScope) // create function functionScope val evalVisitor = EvalVisitor(functionScope, functions) for (i in this.params.indices) { val value = evalVisitor.visit(params[i]) functionScope.assignParam(this.params[i].text, value) } var ret: NodeValue? try { ret = evalVisitor.visit(this.block) } catch (returnValue: ReturnValue) { ret = returnValue.value } return ret ?: NodeValue.VOID } }
apache-2.0
2d1bde00050e5d88080b64de074216bc
33.758621
114
0.654762
4.2
false
false
false
false
hewking/TanTanPaneView
app/src/main/java/com/hewking/widget/TanTanRippleView.kt
1
7158
package com.hewking.widget import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.support.v4.content.ContextCompat.getColor import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import com.hewking.dp2px import com.hewking.getColor import hewking.github.customviewdemo.BuildConfig import hewking.github.customviewdemo.R import java.util.concurrent.CopyOnWriteArrayList /** * 项目名称:FlowChat * 类的描述:xfermode 的使用采用canvas.drawBitmap 的方式实现 * 创建人员:hewking * 创建时间:2018/12/11 0011 * 修改人员:hewking * 修改时间:2018/12/11 0011 * 修改备注: * Version: 1.0.0 */ class TanTanRippleView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { private var radiuls: Int = 0 private val rippleCircles = CopyOnWriteArrayList<RippleCircle>() init { } private val ripplePaint by lazy { Paint().apply { style = Paint.Style.STROKE strokeWidth = dp2px(0.5f).toFloat() color = getColor(R.color.color_FF434343) isAntiAlias = true } } private val backPaint by lazy { Paint().apply { style = Paint.Style.FILL isAntiAlias = true strokeWidth = dp2px(0.5f).toFloat() } } private var sweepProgress = 0 set(value) { if (value >= 360) { field = 0 } else { field = value } } private var fps: Int = 0 private var fpsPaint = Paint().apply { isAntiAlias = true style = Paint.Style.STROKE color = Color.GREEN textSize = dp2px(20f).toFloat() strokeWidth = dp2px(1f).toFloat() } private val renderAnimator by lazy { ValueAnimator.ofInt(0, 60) .apply { interpolator = LinearInterpolator() duration = 1000 repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE addUpdateListener { postInvalidateOnAnimation() fps++ sweepProgress++ } addListener(object : AnimatorListenerAdapter() { override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) fps = 0 } }) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val wMode = MeasureSpec.getMode(widthMeasureSpec) val wSize = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) val hSize = MeasureSpec.getSize(heightMeasureSpec) val size = Math.min(wSize, hSize) if (wMode == MeasureSpec.AT_MOST || hMode == MeasureSpec.AT_MOST) { radiuls = size.div(2) } } var backCanvas: Canvas? = null var backBitmap: Bitmap? = null override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) backBitmap?.recycle() if (w != 0 && h != 0) { backBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) backCanvas = Canvas(backBitmap) } } override fun onDraw(canvas: Canvas?) { canvas ?: return val maxRadius = Math.min(width, height).div(2).toFloat() val radius = maxRadius canvas.save() canvas.rotate(sweepProgress.toFloat(), width.div(2f), height.div(2f)) val colors = intArrayOf(getColor(R.color.pink_fa758a), getColor(R.color.pink_f5b8c2), getColor(R.color.top_background_color), getColor(R.color.white)) backPaint.setShader(SweepGradient(width.div(2).toFloat(), height.div(2).toFloat(), colors, floatArrayOf(0f, 0.001f, 0.9f, 1f))) val rectF = RectF(width.div(2f) - radius , height.div(2f) - radius , width.div(2f) + radius , height.div(2f) + radius) val sc = canvas.saveLayer(rectF, backPaint, Canvas.ALL_SAVE_FLAG) // canvas.drawBitmap(makeDst(), null,rectF, backPaint) canvas.drawCircle(width.div(2).toFloat(), height.div(2).toFloat(), radius, backPaint) backPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OUT)) // canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint) /* rectF.apply { left = width.div(2f) - radius * 1f.div(3) top = height.div(2f) - radius * 1f.div(3) right = width.div(2f) + radius * 1f.div(3) bottom = height.div(2f) + radius * 1f.div(3) } canvas.drawBitmap(makeSrc(),null,rectF,backPaint)*/ canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint) backPaint.setXfermode(null) backPaint.setShader(null) canvas.restoreToCount(sc) canvas.restore() for (i in 0 until rippleCircles.size) { rippleCircles[i].draw(canvas) } if (BuildConfig.DEBUG) { canvas.drawText(fps.toString(), paddingStart.toFloat() , height - dp2px(10f).toFloat() - paddingBottom, fpsPaint) } } override fun onAttachedToWindow() { super.onAttachedToWindow() // start anim // startRipple() renderAnimator.start() } open fun startRipple() { val runnable = Runnable { rippleCircles.add(RippleCircle().apply { cx = width.div(2).toFloat() cy = height.div(2).toFloat() val maxRadius = Math.min(width, height).div(2).toFloat() startRadius = maxRadius.div(3) endRadius = maxRadius }) // startRipple() } postOnAnimation(runnable) // postOnAnimationDelayed(runnable, 2000) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // end anim renderAnimator.end() backBitmap?.recycle() } inner class RippleCircle { // 4s * 60 frms = 240 private val slice = 150 var startRadius = 0f var endRadius = 0f var cx = 0f var cy = 0f private var progress = 0 fun draw(canvas: Canvas) { if (progress >= slice) { // remove post { rippleCircles.remove(this) } return } progress++ ripplePaint.alpha = (1 - progress.div(slice * 1.0f)).times(255).toInt() val radis = startRadius + (endRadius - startRadius).div(slice).times(progress) canvas.drawCircle(cx, cy, radis, ripplePaint) } } }
mit
55105df42e48fd16006a7ea41687e987
31.726852
158
0.575127
4.360271
false
false
false
false