repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/blacklist/BlacklistActivity.kt
1
3887
package com.sedsoftware.yaptalker.presentation.feature.blacklist import android.content.Context import android.content.Intent import android.os.Bundle import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import androidx.core.view.isVisible import com.afollestad.materialdialogs.MaterialDialog import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import com.sedsoftware.yaptalker.R import com.sedsoftware.yaptalker.common.annotation.LayoutResource import com.sedsoftware.yaptalker.presentation.base.BaseActivity import com.sedsoftware.yaptalker.presentation.delegate.MessagesDelegate import com.sedsoftware.yaptalker.presentation.extensions.string import com.sedsoftware.yaptalker.presentation.feature.blacklist.adapter.BlacklistAdapter import com.sedsoftware.yaptalker.presentation.model.base.BlacklistedTopicModel import kotlinx.android.synthetic.main.activity_blacklist.blacklisted_topics import kotlinx.android.synthetic.main.activity_blacklist.empty_label import kotlinx.android.synthetic.main.include_main_appbar.toolbar import javax.inject.Inject @LayoutResource(R.layout.activity_blacklist) class BlacklistActivity : BaseActivity(), BlacklistView { companion object { fun getIntent(ctx: Context): Intent = Intent(ctx, BlacklistActivity::class.java) } @Inject lateinit var blacklistAdapter: BlacklistAdapter @Inject lateinit var messagesDelegate: MessagesDelegate @Inject @InjectPresenter lateinit var presenter: BlacklistPresenter @ProvidePresenter fun providePresenter() = presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) with(blacklisted_topics) { val linearLayout = LinearLayoutManager(context) layoutManager = linearLayout adapter = blacklistAdapter addItemDecoration( DividerItemDecoration( context, DividerItemDecoration.VERTICAL ) ) setHasFixedSize(true) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_blacklist, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_delete_all -> { presenter.clearBlacklist() true } R.id.action_delete_month -> { presenter.clearBlacklistMonthOld() true } else -> super.onOptionsItemSelected(item) } override fun showBlacklistedTopics(topics: List<BlacklistedTopicModel>) { if (topics.isNotEmpty()) { blacklisted_topics.isVisible = true empty_label.isVisible = false blacklistAdapter.setTopics(topics) } else { blacklisted_topics.isVisible = false empty_label.isVisible = true } } override fun showDeleteConfirmationDialog(topicId: Int) { MaterialDialog.Builder(this) .content(R.string.msg_blacklist_request_deletion) .positiveText(R.string.msg_blacklist_confirm_delete) .negativeText(R.string.msg_blacklist_confirm_no) .onPositive { _, _ -> presenter.deleteTopicFromBlacklist(topicId) } .show() } override fun showErrorMessage(message: String) { messagesDelegate.showMessageError(message) } override fun updateCurrentUiState() { supportActionBar?.title = string(R.string.title_blacklist) } }
apache-2.0
60b48374a61f23e212a6b3fb5e8b6cf7
33.705357
88
0.701312
5.148344
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/persistence/collections/LazyQueryCollection.kt
1
8301
package com.onyx.persistence.collections import com.onyx.buffer.BufferStream import com.onyx.buffer.BufferStreamable import com.onyx.descriptor.EntityDescriptor import com.onyx.exception.BufferingException import com.onyx.exception.OnyxException import com.onyx.extension.common.ClassMetadata.classForName import com.onyx.extension.identifier import com.onyx.interactors.record.data.Reference import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.Contexts import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import java.util.* import java.util.function.Consumer /** * LazyQueryCollection is used to return query results that are lazily instantiated. * * If by calling executeLazyQuery it will return a list with record references. The references are then used to hydrate the results when referenced through the List interface methods. * * Also, this is not available using the Web API. It is a limitation due to the JSON serialization. * * @author Tim Osborn * @since 1.0.0 * * PersistenceManager manager = factory.getPersistenceManager(); * * Query query = new Query(); * query.setEntityType(MyEntity.class); * List myResults = manager.executeLazyQuery(query); // Returns an instance of LazyQueryCollection * */ class LazyQueryCollection<E : IManagedEntity> () : AbstractList<E>(), List<E>, BufferStreamable { @Transient private var values: MutableMap<Any, E?> = WeakHashMap() @Transient private lateinit var contextId: String @Transient private var persistenceManager: PersistenceManager? = null @Transient lateinit var entityDescriptor: EntityDescriptor lateinit var identifiers: MutableList<Reference> private var hasSelections = false constructor(entityDescriptor: EntityDescriptor, references: List<Reference>, context: SchemaContext):this() { this.entityDescriptor = entityDescriptor this.contextId = context.contextId this.persistenceManager = context.serializedPersistenceManager this.identifiers = synchronized(references) { ArrayList(references) } } /** * Quantity or record references within the List * * @since 1.0.0 * * @return Size of the List */ override val size: Int get() = identifiers.size /** * Boolean key indicating whether the list is empty * * @since 1.0.0 * * @return (size equals 0) */ override fun isEmpty(): Boolean = identifiers.isEmpty() /** * Contains an value and is initialized * * @since 1.0.0 * * @param element Object to check * @return Boolean */ override operator fun contains(element: E): Boolean = identifiers.contains((element as IManagedEntity).identifier(descriptor = entityDescriptor)) /** * Add an element to the lazy collection * * This must add a managed entity * * @since 1.0.0 * * @param element Record that implements ManagedEntity * @return Added or not */ override fun add(element: E?): Boolean = throw RuntimeException("Method unsupported") /** * Remove all objects * * @since 1.0.0 */ override fun clear() { values.clear() identifiers.clear() } /** * Get value at index and initialize it if it does not exist * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity */ override fun get(index: Int): E { var entity: E? = values[index] if (entity == null) { entity = try { val reference = identifiers[index] persistenceManager!!.getWithReference(entityDescriptor.entityClass, reference) } catch (e: OnyxException) { null } values[index] = entity } return entity!! } /** * Get value at index and initialize it if it does not exist * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity */ @Suppress("UNCHECKED_CAST") fun getDict(index: Int): Map<String, Any?>? = try { persistenceManager!!.getMapWithReferenceId(entityDescriptor.entityClass, identifiers[index]) } catch (e: OnyxException) { null } /** * Set value at index * * @since 1.0.0 * * @param index Record Index * @param element ManagedEntity * @return Record set */ override fun set(index: Int, element: E?): E = throw RuntimeException("Method unsupported") /** * Add value at index * * @since 1.0.0 * * @param index Record Index * @param element ManagedEntity */ override fun add(index: Int, element: E?) { this[index] = element } /** * Remove value at index * * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity removed */ override fun removeAt(index: Int): E { val existingObject = identifiers[index] identifiers.remove(existingObject) return values.remove(existingObject) as E } override fun remove(element: E): Boolean { val identifier: Any? = (element as IManagedEntity?)!!.identifier(descriptor = entityDescriptor) values.remove(identifier) return identifiers.remove(identifier) } @Throws(BufferingException::class) @Suppress("UNCHECKED_CAST") override fun read(buffer: BufferStream) { this.values = WeakHashMap() this.identifiers = buffer.collection as MutableList<Reference> val className = buffer.string this.contextId = buffer.string this.hasSelections = buffer.boolean val context = Contexts.get(contextId) ?: Contexts.firstRemote() this.entityDescriptor = context.getBaseDescriptorForEntity(classForName(className, context))!! this.persistenceManager = context.systemPersistenceManager } @Throws(BufferingException::class) override fun write(buffer: BufferStream) { buffer.putCollection(this.identifiers) buffer.putString(this.entityDescriptor.entityClass.name) buffer.putString(contextId) buffer.putBoolean(hasSelections) } /** * Returns an iterator over the elements in this list in proper sequence. * * The returned iterator is [*fail-fast*](#fail-fast). * * @return an iterator over the elements in this list in proper sequence */ override fun iterator(): MutableIterator<E> = object : MutableIterator<E> { var i = 0 override fun hasNext(): Boolean = i < size override fun next(): E = try { get(i) } finally { i++ } override fun remove() = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.remove") } /** * For Each This is overridden to utilize the iterator * * @param action consumer to apply each iteration */ override fun forEach(action: Consumer<in E>) { val iterator = iterator() while (iterator.hasNext()) { action.accept(iterator.next()) } } /** * {@inheritDoc} */ override fun listIterator(): MutableListIterator<E> = object : MutableListIterator<E> { var i = -1 override fun hasNext(): Boolean = i + 1 < size override fun next(): E = try { get(i) } finally { i++ } override fun hasPrevious(): Boolean = i > 0 override fun previous(): E = try { get(i) } finally { i-- } override fun nextIndex(): Int = i + 1 override fun previousIndex(): Int = i - 1 override fun remove() = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.remove") override fun set(element: E) = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.set") override fun add(element: E) = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.add") } }
agpl-3.0
22526a2443e4d43a2059e63dd4dcdb85
28.967509
184
0.64426
4.632254
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/ShowDiffForSavedPatchesAction.kt
4
3135
// 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.openapi.vcs.changes.savedPatches import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionExtensionProvider import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData abstract class AbstractShowDiffForSavedPatchesAction : AnActionExtensionProvider { override fun isActive(e: AnActionEvent): Boolean { return e.getData(SavedPatchesUi.SAVED_PATCHES_UI) != null } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { val project = e.project val changesBrowser = e.getData(SavedPatchesUi.SAVED_PATCHES_UI)?.changesBrowser if (project == null || changesBrowser == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true val selection = if (e.getData(ChangesBrowserBase.DATA_KEY) == null) { VcsTreeModelData.all(changesBrowser.viewer) } else { VcsTreeModelData.selected(changesBrowser.viewer) } e.presentation.isEnabled = selection.iterateUserObjects().any { getDiffRequestProducer(changesBrowser, it) != null } } override fun actionPerformed(e: AnActionEvent) { val changesBrowser = e.getRequiredData(SavedPatchesUi.SAVED_PATCHES_UI).changesBrowser val selection = if (e.getData(ChangesBrowserBase.DATA_KEY) == null) { ListSelection.createAt(VcsTreeModelData.all(changesBrowser.viewer).userObjects(), 0) } else { VcsTreeModelData.getListSelectionOrAll(changesBrowser.viewer) } ChangesBrowserBase.showStandaloneDiff(e.project!!, changesBrowser, selection) { change -> getDiffRequestProducer(changesBrowser, change) } } abstract fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? } class ShowDiffForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffRequestProducer(userObject) } } class CompareWithLocalForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffWithLocalRequestProducer(userObject, false) } } class CompareBeforeWithLocalForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffWithLocalRequestProducer(userObject, true) } }
apache-2.0
9e062592db0c5f784b31b9d286f4eaf7
41.945205
134
0.793301
4.815668
false
false
false
false
vovagrechka/fucking-everything
pieces/pieces-100/src/main/java/alraune/alraune-package-3.kt
1
6579
package alraune import alraune.entity.* import pieces100.* import vgrechka.* import wasing.OoWasingLandingPage import java.sql.Timestamp import java.util.* import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 fun redirect(path: String): Nothing { rctx0.commands.clear() btfSetLocationHref(path) spitFreakingPage {} throw ShitServed() } fun spitWindowOpenPage(href: String) { btfEval("window.open(${jsStringLiteral(href)})") spitUsualPage {div()} } fun redirectToLandingIfSiteIsNot(site: AlSite) { if (rctx0.al.site() != site) redirect(landingPagePath()) } fun landingPagePath() = when (rctx0.al.site()) { AlSite.BoloneCustomer -> OoCustomerLandingPage.path AlSite.BoloneWriter -> OoWriterLandingPage.path AlSite.BoloneAdmin -> OoAdminLandingPage.path AlSite.Wasing -> OoWasingLandingPage.path } fun bailOutToLittleErrorPage(content: String): Nothing { bailOutToLittleErrorPage(span(content)) } fun bailOutToLittleErrorPage_boldArg(template: String, arg: Any?): Nothing { val html = escapeHtml(template).replace("%s", when { arg == null || arg is String && arg.isBlank() -> "<i style='color: ${Color.Gray700};'>${t("blank", "пусто")}</i>" else -> "<b>" + escapeHtml(arg.toString()) + "</b>" }) bailOutToLittleErrorPage(rawHtml(html)) } fun bailOutToLittleErrorPage(content: Renderable): Nothing { cancelAllCommandsAndSpitLittleErrorPage(content) throw ShitServed() } fun cancelAllCommandsAndSpitLittleErrorPage(content: Renderable) { check(!rctx0.isPost) rctx0.commands.clear() spitFreakingPage { oo(content) } } fun largeUUID() = UUID.randomUUID().toString() // TODO:vgrechka Make it larger? fun <T> relateStack(stackCapture: StackCaptureException, f: () -> T): T { if (!alConfig.debug.enabled.relateStack) return f() AlGlobal_MergeMeToKotlinVersion.relatedStacks.get().addLast(stackCapture) try { return f() } finally { AlGlobal_MergeMeToKotlinVersion.relatedStacks.get().removeLast() } } annotation class LeJson(val withTypeInfo: Boolean = false) annotation class LeXStream interface WithUUID { val uuid: String } fun isLeJsonProperty(prop: KProperty1<Any, Any?>) = findLeJsonAnnotation(prop) != null fun findLeJsonAnnotation(prop: KProperty1<*, *>) = prop.annotations.find {it is LeJson} as LeJson? fun findLeXStreamAnnotation(prop: KProperty1<*, *>) = prop.annotations.find {it is LeXStream} as LeXStream? data class FAIconWithStyle( val icon: FA.Icon, val style: String = "", val nonFirstItemClass: AlCSS.Pack = AlCSS.fartus1.p1BlueGray, val amendTitleBar: (AlTag) -> Unit = {}) fun checkAtMostOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.size > 1) wtf("[${::checkAtMostOneNotNull.name}] notNulls = [${notNulls.joinToString(", ") {it.name}}]") } fun checkExactlyOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.size != 1) wtf("[${::checkExactlyOneNotNull.name}] notNulls = [${notNulls.joinToString(", ") {it.name}}]") } fun checkAtLeastOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.isEmpty()) wtf(::checkAtLeastOneNotNull.name) } fun <T> fqnamed(make: (List<String>) -> T) = object : ReadOnlyProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (value == null) { val clazz = thisRef!!::class val packageName = clazz.java.`package`.name var className = clazz.qualifiedName!! className = className.substring(packageName.length + 1) val pieces = className.split(".") value = make(pieces + listOf(property.name)) } return bang(value) } } fun myFqname_under() = fqnamed {it.joinToString("_")} fun <T : Any> getParamOrBailOut(param: AlBunchOfGetParams.Param<T>): T = param.get() ?: bailOutToLittleErrorPage(rawHtml(t("TOTE", "Я хочу в URL параметр <b>${param.name}</b>"))) interface GenericOperationInfoProps { val operationId: Long val actorDescr: String val title: String val time: Timestamp val timeString: String val userIcon: FA.Icon fun hasStateBefore(): Boolean } //sealed class OperationInfo : GenericOperationInfoProps { // class Order_V1( // override val operationId: Long, // val data: AlOperation_Order_V1, // override val actorDescr: String, // override val title: String, // override val time: Timestamp, // override val timeString: String, // override val userIcon: FA.Icon) : OperationInfo() { // // fun idAndTime() = AlText.numString(operationId) + ", " + timeString // override fun hasStateBefore() = data.orderBeforeOperation != null // } //} //fun drooOrderParamsComparison(entity1: AlUAOrder?, entity2: AlUAOrder) { // oo(div().with { // // Children are counted in CSS (nth-child stuff) relative to this div // fun drooPropComparisons(obj1: Any?, obj2: Any, exclude: List<KProperty1<*, *>> = listOf()) { // val props = (obj2::class.memberProperties - exclude) // for (prop in props) { // ooPropComparison(PropComparisonParams(prop), obj1, obj2) // } // } // // drooPropComparisons(entity1, entity2, exclude = listOf( // AlUAOrder::_id, AlUAOrder::createdAt, // AlUAOrder::updatedAt, AlUAOrder::deleted, AlUAOrder::dataPile)) // drooPropComparisons(entity1?.dataPile, entity2.dataPile) // }) //} fun isNullOrBlankString(x: Any?) = x == null || x is String && x.isBlank() //fun <T> T.fluent(block: () -> Unit): T { // block() // return this //} enum class Rightness { Left, Right; fun cssString(): String = name.toLowerCase() } interface Titled { val title: String } interface WithId { val id: Long } interface WithOptimisticVersion { var optimisticVersion: String } interface WithMutableId: WithId { override var id: Long } fun isWriterAssigned(order: Order) = false interface EncryptedDownloadableResource { var name: String var size: Int var downloadUrl: String var secretKeyBase64: String }
apache-2.0
b61f364fd90c11a60df4d7fb6a8d7409
25.451613
103
0.664329
3.710407
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InterfaceWithFieldConversion.kt
2
1407
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.declarationList import org.jetbrains.kotlin.nj2k.getOrCreateCompanionObject import org.jetbrains.kotlin.nj2k.tree.* class InterfaceWithFieldConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind != JKClass.ClassKind.INTERFACE && element.classKind != JKClass.ClassKind.ANNOTATION ) return recurse(element) val fieldsToMoveToCompanion = element.declarationList .filterIsInstance<JKField>() .filter { field -> field.modality == Modality.FINAL || element.classKind == JKClass.ClassKind.ANNOTATION } if (fieldsToMoveToCompanion.isNotEmpty()) { element.classBody.declarations -= fieldsToMoveToCompanion val companion = element.getOrCreateCompanionObject() companion.classBody.declarations += fieldsToMoveToCompanion } return recurse(element) } }
apache-2.0
8ca2094cd0dfd4f1abda810e26d56cef
44.419355
120
0.732054
5.007117
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/PsiFileNavigationTarget.kt
1
1907
// 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.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.fileLocation import com.intellij.codeInsight.navigation.fileStatusAttributes import com.intellij.model.Pointer import com.intellij.navigation.NavigationRequest import com.intellij.navigation.NavigationTarget import com.intellij.navigation.TargetPresentation import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.createSmartPointer internal class PsiFileNavigationTarget( private val psiFile: PsiFile ) : NavigationTarget { override fun createPointer(): Pointer<out NavigationTarget> = Pointer.delegatingPointer( psiFile.createSmartPointer(), PsiFileNavigationTarget::class.java, ::PsiFileNavigationTarget ) override fun getTargetPresentation(): TargetPresentation { val project = psiFile.project var builder = TargetPresentation .builder(psiFile.name) .icon(psiFile.getIcon(0)) .containerText(psiFile.parent?.virtualFile?.presentableUrl) val file = psiFile.virtualFile ?: return builder.presentation() builder = builder .backgroundColor(VfsPresentationUtil.getFileBackgroundColor(project, file)) .presentableTextAttributes(fileStatusAttributes(project, file)) // apply file error and file status highlighting to file name val locationAndIcon = fileLocation(project, file) ?: return builder.presentation() @Suppress("HardCodedStringLiteral") builder = builder.locationText(locationAndIcon.text, locationAndIcon.icon) return builder.presentation() } override fun navigationRequest(): NavigationRequest? { return psiFile.navigationRequest() } }
apache-2.0
c79fc98f50e26f28af9f431a2987151e
38.729167
158
0.77871
5.071809
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt
1
4596
// 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.compiler.configuration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.JDOMUtil import com.intellij.util.ReflectionUtil import com.intellij.util.messages.Topic import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilterBase import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.idea.syncPublisherWithDisposeCheck import kotlin.reflect.KClass abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) : PersistentStateComponent<Element>, Cloneable { // Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters private object DefaultValuesFilter : SerializationFilterBase() { private val defaultBeans = HashMap<Class<*>, Any>() private fun createDefaultBean(beanClass: Class<Any>): Any { return ReflectionUtil.newInstance<Any>(beanClass).apply { if (this is K2JSCompilerArguments) { sourceMapPrefix = "" } } } private fun getDefaultValue(accessor: Accessor, bean: Any): Any? { if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) { return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null } val beanClass = bean.javaClass val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) } return accessor.read(defaultBean) } override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean { val defValue = getDefaultValue(accessor, bean) return if (defValue is Element && beanValue is Element) { !JDOMUtil.areElementsEqual(beanValue, defValue) } else { !Comparing.equal(beanValue, defValue) } } } @Suppress("LeakingThis") private var _settings: T = createSettings().frozen() private set(value) { field = value.frozen() } var settings: T get() = _settings set(value) { validateNewSettings(value) _settings = value ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(value) } } fun update(changer: T.() -> Unit) { settings = settings.unfrozen().apply { changer() } } protected fun validateInheritedFieldsUnchanged(settings: T) { @Suppress("UNCHECKED_CAST") val inheritedProperties = collectProperties<T>(settings::class as KClass<T>, true) val defaultInstance = createSettings() val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) } if (invalidFields.isNotEmpty()) { throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}") } } protected open fun validateNewSettings(settings: T) { } protected abstract fun createSettings(): T override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter) override fun loadState(state: Element) { _settings = ReflectionUtil.newInstance(_settings.javaClass).apply { if (this is CommonCompilerArguments) { freeArgs = mutableListOf() internalArguments = mutableListOf() } XmlSerializer.deserializeInto(this, state) } ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(settings) } } public override fun clone(): Any = super.clone() } interface KotlinCompilerSettingsListener { fun <T> settingsChanged(newSettings: T) companion object { val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java) } }
apache-2.0
9509c5d24a452ad22690fcdff74170b7
38.62931
164
0.685596
5.106667
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
1
62044
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.codeInsight.template.* import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.UnfairTextRange import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.DialogWithEditor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* import kotlin.math.max /** * Represents a single choice for a type (e.g. parameter type or return type). */ class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) { val typeParameters: Array<TypeParameterDescriptor> var renderedTypes: List<String> = emptyList() private set var renderedTypeParameters: List<RenderedTypeParameter>? = null private set fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) { renderedTypes = theType.renderShort(typeParameterNameMap) renderedTypeParameters = typeParameters.map { RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap.getValue(it)) } } init { val typeParametersInType = theType.getTypeParameters() if (scope == null) { typeParameters = typeParametersInType.toTypedArray() renderedTypes = theType.renderShort(Collections.emptyMap()) } else { typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray() } } override fun toString() = theType.toString() } data class RenderedTypeParameter( val typeParameter: TypeParameterDescriptor, val fake: Boolean, val text: String ) fun List<TypeCandidate>.getTypeByRenderedType(renderedTypes: List<String>): KotlinType? = firstOrNull { it.renderedTypes == renderedTypes }?.theType class CallableBuilderConfiguration( val callableInfos: List<CallableInfo>, val originalElement: KtElement, val currentFile: KtFile = originalElement.containingKtFile, val currentEditor: Editor? = null, val isExtension: Boolean = false, val enableSubstitutions: Boolean = true ) sealed class CallablePlacement { class WithReceiver(val receiverTypeCandidate: TypeCandidate) : CallablePlacement() class NoReceiver(val containingElement: PsiElement) : CallablePlacement() } class CallableBuilder(val config: CallableBuilderConfiguration) { private var finished: Boolean = false val currentFileContext = config.currentFile.analyzeWithContent() private lateinit var _currentFileModule: ModuleDescriptor val currentFileModule: ModuleDescriptor get() { if (!_currentFileModule.isValid) { updateCurrentModule() } return _currentFileModule } init { updateCurrentModule() } val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) } private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>() var placement: CallablePlacement? = null private val elementsToShorten = ArrayList<KtElement>() private fun updateCurrentModule() { _currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor } fun computeTypeCandidates(typeInfo: TypeInfo): List<TypeCandidate> = typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } } private fun computeTypeCandidates( typeInfo: TypeInfo, substitutions: List<KotlinTypeSubstitution>, scope: HierarchicalScope ): List<TypeCandidate> { if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo) return typeCandidates.getOrPut(typeInfo) { val types = typeInfo.getPossibleTypes(this).asReversed() // We have to use semantic equality here data class EqWrapper(val _type: KotlinType) { override fun equals(other: Any?) = this === other || other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type) override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() } val newTypes = LinkedHashSet(types.map(::EqWrapper)) for (substitution in substitutions) { // each substitution can be applied or not, so we offer all options val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) } // substitution.byType are type arguments, but they cannot already occur in the type before substitution val toRemove = newTypes.filter { substitution.byType in it._type } newTypes.addAll(toAdd.map(::EqWrapper)) newTypes.removeAll(toRemove) } if (newTypes.isEmpty()) { newTypes.add(EqWrapper(currentFileModule.builtIns.anyType)) } newTypes.map { TypeCandidate(it._type, scope) }.asReversed() } } private fun buildNext(iterator: Iterator<CallableInfo>) { if (iterator.hasNext()) { val context = Context(iterator.next()) runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } } ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } } else { runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) } } } fun build(onFinish: () -> Unit = {}) { try { assert(config.currentEditor != null) { "Can't run build() without editor" } check(!finished) { "Current builder has already finished" } buildNext(config.callableInfos.iterator()) } finally { finished = true onFinish() } } private inner class Context(val callableInfo: CallableInfo) { val skipReturnType: Boolean val ktFileToEdit: KtFile val containingFileEditor: Editor val containingElement: PsiElement val dialogWithEditor: DialogWithEditor? val receiverClassDescriptor: ClassifierDescriptor? val typeParameterNameMap: Map<TypeParameterDescriptor, String> val receiverTypeCandidate: TypeCandidate? val mandatoryTypeParametersAsCandidates: List<TypeCandidate> val substitutions: List<KotlinTypeSubstitution> var finished: Boolean = false init { // gather relevant information val placement = placement var nullableReceiver = false when (placement) { is CallablePlacement.NoReceiver -> { containingElement = placement.containingElement receiverClassDescriptor = with(placement.containingElement) { when (this) { is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this] is PsiClass -> getJavaClassDescriptor() else -> null } } } is CallablePlacement.WithReceiver -> { val theType = placement.receiverTypeCandidate.theType nullableReceiver = theType.isMarkedNullable receiverClassDescriptor = theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } else -> throw IllegalArgumentException("Placement wan't initialized") } val receiverType = receiverClassDescriptor?.defaultType?.let { if (nullableReceiver) it.makeNullable() else it } val project = config.currentFile.project if (containingElement.containingFile != config.currentFile) { NavigationUtil.activateFileWithPsiElement(containingElement) } dialogWithEditor = if (containingElement is KtElement) { ktFileToEdit = containingElement.containingKtFile containingFileEditor = if (ktFileToEdit != config.currentFile) { FileEditorManager.getInstance(project).selectedTextEditor!! } else { config.currentEditor!! } null } else { val dialog = object : DialogWithEditor(project, KotlinBundle.message("fix.create.from.usage.dialog.title"), "") { override fun doOKAction() { project.executeWriteCommand(KotlinBundle.message("premature.end.of.template")) { TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false) } super.doOKAction() } } containingFileEditor = dialog.editor with(containingFileEditor.settings) { additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project) additionalLinesCount = 5 } ktFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile ktFileToEdit.analysisContext = config.currentFile dialog } val scope = getDeclarationScope() receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) } val fakeFunction: FunctionDescriptor? // figure out type substitutions for type parameters val substitutionMap = LinkedHashMap<KotlinType, KotlinType>() if (config.enableSubstitutions) { collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap) val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos .map { val typeCandidates = computeTypeCandidates(it) assert(typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" } typeCandidates.first().theType } .subtract(substitutionMap.keys) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } } else { fakeFunction = null mandatoryTypeParametersAsCandidates = Collections.emptyList() } substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) } callableInfo.parameterInfos.forEach { computeTypeCandidates(it.typeInfo, substitutions, scope) } val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull() skipReturnType = when (callableInfo.kind) { CallableKind.FUNCTION -> returnTypeCandidate?.theType?.isUnit() ?: false CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false CallableKind.CONSTRUCTOR -> true CallableKind.PROPERTY -> containingElement is KtBlockExpression } // figure out type parameter renames to avoid conflicts typeParameterNameMap = getTypeParameterRenames(scope) callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) } if (!skipReturnType) { renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction) } receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction) mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun getDeclarationScope(): HierarchicalScope { if (config.isExtension || receiverClassDescriptor == null) { return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope() } if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) { return receiverClassDescriptor.scopeForMemberDeclarationResolution } assert(receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" } val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters) .map { TypeProjectionImpl(it.defaultType) } val memberScope = receiverClassDescriptor.getMemberScope(projections) return LexicalScopeImpl( memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, LexicalScopeKind.SYNTHETIC ) { receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) } } } private fun collectSubstitutionsForReceiverTypeParameters( receiverType: KotlinType?, result: MutableMap<KotlinType, KotlinType> ) { if (placement is CallablePlacement.NoReceiver) return val classTypeParameters = receiverType?.arguments ?: Collections.emptyList() val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments ?: Collections.emptyList() assert(ownerTypeArguments.size == classTypeParameters.size) ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type } } private fun collectSubstitutionsForCallableTypeParameters( fakeFunction: FunctionDescriptor, typeArguments: Set<KotlinType>, result: MutableMap<KotlinType, KotlinType> ) { for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) { result[typeArgument] = typeParameter.defaultType } } @OptIn(FrontendInternals::class) private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor { val fakeFunction = SimpleFunctionDescriptorImpl.create( MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")), Annotations.EMPTY, Name.identifier("fake"), CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE ) val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val parameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) val typeParameters = (0 until typeParameterCount).map { TypeParameterDescriptorImpl.createWithDefaultBound( fakeFunction, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier(parameterNames[it]), it, ktFileToEdit.getResolutionFacade().frontendService() ) } return fakeFunction.initialize( null, null, typeParameters, Collections.emptyList(), null, null, DescriptorVisibilities.INTERNAL ) } private fun renderTypeCandidates( typeInfo: TypeInfo, typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor? ) { typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun isInsideInnerOrLocalClass(): Boolean { val classOrObject = containingElement.getNonStrictParentOfType<KtClassOrObject>() return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal) } private fun createDeclarationSkeleton(): KtNamedDeclaration { with(config) { val assignmentToReplace = if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable == true) { originalElement as KtBinaryExpression } else null val pointerOfAssignmentToReplace = assignmentToReplace?.createSmartPointer() val ownerTypeString = if (isExtension) { val renderedType = receiverTypeCandidate!!.renderedTypes.first() val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor if (isFunctionType) "($renderedType)." else "$renderedType." } else "" val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind fun renderParamList(): String { val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else "" val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" } return if (callableInfo.parameterInfos.isNotEmpty() || callableInfo.kind == CallableKind.FUNCTION || callableInfo.kind == CallableKind.CONSTRUCTOR ) "($list)" else list } val paramList = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR -> renderParamList() CallableKind.PROPERTY -> "" } val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any" val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString" val psiFactory = KtPsiFactory(currentFile) val modifiers = buildString { val modifierList = callableInfo.modifierList?.copied() ?: psiFactory.createEmptyModifierList() val visibilityKeyword = modifierList.visibilityModifierType() if (visibilityKeyword == null) { val defaultVisibility = if (callableInfo.isAbstract) "" else if (containingElement is KtClassOrObject && !(containingElement is KtClass && containingElement.isInterface()) && containingElement.isAncestor(config.originalElement) && callableInfo.kind != CallableKind.CONSTRUCTOR ) "private " else if (isExtension) "private " else "" append(defaultVisibility) } // TODO: Get rid of isAbstract if (callableInfo.isAbstract && containingElement is KtClass && !containingElement.isInterface() && !modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD) ) { modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD) } val text = modifierList.normalize().text if (text.isNotEmpty()) { append("$text ") } } val isExpectClassMember by lazy { containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false } val declaration: KtNamedDeclaration = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> { val body = when { callableInfo is ConstructorInfo -> if (callableInfo.withBody) "{\n\n}" else "" callableInfo.isAbstract -> "" containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.isCompanion() && containingElement.parent.parent is KtClass && (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" isExpectClassMember -> "" else -> "{\n\n}" } @Suppress("USELESS_CAST") // KT-10755 when { callableInfo is FunctionInfo -> psiFactory.createFunction("${modifiers}fun<> $header $body") as KtNamedDeclaration (callableInfo as ConstructorInfo).isPrimary -> { val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration } else -> psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration } } CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> { val classWithPrimaryConstructorInfo = callableInfo as ClassWithPrimaryConstructorInfo with(classWithPrimaryConstructorInfo.classInfo) { val classBody = when (kind) { ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> "" else -> "{\n\n}" } val safeName = name.quoteIfNeeded() when (kind) { ClassKind.ENUM_ENTRY -> { val targetParent = applicableParents.singleOrNull() if (!(targetParent is KtClass && targetParent.isEnum())) { throw KotlinExceptionWithAttachments("Enum class expected: ${targetParent?.let { it::class.java }}") .withPsiAttachment("targetParent", targetParent) } val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty() psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}") } else -> { val openMod = if (open && kind != ClassKind.INTERFACE) "open " else "" val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else "" val typeParamList = when (kind) { ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>" else -> "" } val ctor = classWithPrimaryConstructorInfo.primaryConstructorVisibility?.name?.let { " $it constructor" } ?: "" psiFactory.createDeclaration<KtClassOrObject>( "$openMod$innerMod${kind.keyword} $safeName$typeParamList$ctor$paramList$returnTypeString $classBody" ) } } } } CallableKind.PROPERTY -> { val isVar = (callableInfo as PropertyInfo).writable val const = if (callableInfo.isConst) "const " else "" val valVar = if (isVar) "var" else "val" val accessors = if (isExtension && !isExpectClassMember) { buildString { append("\nget() {}") if (isVar) { append("\nset() {}") } } } else "" psiFactory.createProperty("$modifiers$const$valVar<> $header$accessors") } } if (callableInfo is PropertyInfo) { callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) } } val newInitializer = pointerOfAssignmentToReplace?.element if (newInitializer != null) { (declaration as KtProperty).initializer = newInitializer.right return newInitializer.replace(declaration) as KtCallableDeclaration } val container = if (containingElement is KtClass && callableInfo.isForCompanion) { containingElement.getOrCreateCompanionObject() } else containingElement val declarationInPlace = placeDeclarationInContainer(declaration, container, config.originalElement, ktFileToEdit) if (declarationInPlace is KtSecondaryConstructor) { val containingClass = declarationInPlace.containingClassOrObject!! val primaryConstructorParameters = containingClass.primaryConstructorParameters if (primaryConstructorParameters.isNotEmpty()) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors .all { it.valueParameters.isNotEmpty() } ) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) } if (declarationInPlace.valueParameters.size > primaryConstructorParameters.size) { val hasCompatibleTypes = primaryConstructorParameters.zip(callableInfo.parameterInfos).all { (primary, secondary) -> val primaryType = currentFileContext[BindingContext.TYPE, primary.typeReference] ?: return@all false val secondaryType = computeTypeCandidates(secondary.typeInfo).firstOrNull()?.theType ?: return@all false secondaryType.isSubtypeOf(primaryType) } if (hasCompatibleTypes) { val delegationCallArgumentList = declarationInPlace.getDelegationCall().valueArgumentList primaryConstructorParameters.forEach { val name = it.name if (name != null) delegationCallArgumentList?.addArgument(psiFactory.createArgument(name)) } } } } return declarationInPlace } } private fun getTypeParameterRenames(scope: HierarchicalScope): Map<TypeParameterDescriptor, String> { val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>() mandatoryTypeParametersAsCandidates.asSequence() .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() }) .flatMap { it.typeParameters.asSequence() } .toCollection(allTypeParametersNotInScope) if (!skipReturnType) { computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) { it.typeParameters.asSequence() } } val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val typeParameterNames = allTypeParametersNotInScope.map { KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) } return allTypeParametersNotInScope.zip(typeParameterNames).toMap() } private fun setupTypeReferencesForShortening( declaration: KtNamedDeclaration, parameterTypeExpressions: List<TypeExpression> ) { if (config.isExtension) { val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first() val replacingTypeRef = KtPsiFactory(declaration).createType(receiverTypeText) (declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!! } val returnTypeRefs = declaration.getReturnTypeReferences() if (returnTypeRefs.isNotEmpty()) { val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType( returnTypeRefs.map { it.text } ) if (returnType != null) { // user selected a given type replaceWithLongerName(returnTypeRefs, returnType) } } val valueParameters = declaration.getValueParameters() val parameterIndicesToShorten = ArrayList<Int>() assert(valueParameters.size == parameterTypeExpressions.size) for ((i, parameter) in valueParameters.asSequence().withIndex()) { val parameterTypeRef = parameter.typeReference if (parameterTypeRef != null) { val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( listOf(parameterTypeRef.text) ) if (parameterType != null) { replaceWithLongerName(listOf(parameterTypeRef), parameterType) parameterIndicesToShorten.add(i) } } } } private fun postprocessDeclaration(declaration: KtNamedDeclaration) { if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) { if (declaration.containingClassOrObject == null) return val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val returnType = propertyDescriptor.returnType ?: return if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return declaration.addModifier(KtTokens.LATEINIT_KEYWORD) } if (callableInfo.isAbstract) { val containingClass = declaration.containingClassOrObject if (containingClass is KtClass && containingClass.isInterface()) { declaration.removeModifier(KtTokens.ABSTRACT_KEYWORD) } } } private fun setupDeclarationBody(func: KtDeclarationWithBody) { if (func !is KtNamedFunction && func !is KtPropertyAccessor) return if (skipReturnType && callableInfo is FunctionInfo && callableInfo.preferEmptyBody) return val oldBody = func.bodyExpression ?: return val bodyText = getFunctionBodyTextFromTemplate( func.project, TemplateKind.FUNCTION, if (callableInfo.name.isNotEmpty()) callableInfo.name else null, if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "", receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) } ) oldBody.replace(KtPsiFactory(func).createBlock(bodyText)) } private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) { val oldTypeArgumentList = callElement.typeArgumentList ?: return val renderedTypeArgs = typeParameters.map { typeParameter -> val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType IdeDescriptorRenderers.SOURCE_CODE.renderType(type) } if (renderedTypeArgs.isEmpty()) { oldTypeArgumentList.delete() } else { oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">"))) elementsToShorten.add(callElement.typeArgumentList!!) } } private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? { val candidates = typeCandidates[callableInfo.returnTypeInfo]!! if (candidates.isEmpty()) return null val elementToReplace: KtElement? val expression: TypeExpression = when (declaration) { is KtCallableDeclaration -> { elementToReplace = declaration.typeReference TypeExpression.ForTypeReference(candidates) } is KtClassOrObject -> { elementToReplace = declaration.superTypeListEntries.firstOrNull() TypeExpression.ForDelegationSpecifier(candidates) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } if (elementToReplace == null) return null if (candidates.size == 1) { builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text) return null } builder.replaceElement(elementToReplace, expression) return expression } private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) { if (!(callableInfo as PropertyInfo).writable) { builder.replaceElement(property.valOrVarKeyword, ValVarExpression) } } private fun setupTypeParameterListTemplate( builder: TemplateBuilderImpl, declaration: KtNamedDeclaration ): TypeParameterListExpression? { when (declaration) { is KtObjectDeclaration -> return null !is KtTypeParameterListOwner -> { throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } } val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>() val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>() //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() } callableInfo.parameterInfos.asSequence() .flatMap { typeCandidates[it.typeInfo]!!.asSequence() } .forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } if (declaration.getReturnTypeReference() != null) { typeCandidates[callableInfo.returnTypeInfo]!!.forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } } val expression = TypeParameterListExpression( mandatoryTypeParameters, typeParameterMap, callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR ) val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace val rangeStart = leftSpace?.startOffset ?: typeParameterList.startOffset val offset = typeParameterList.startOffset val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset) builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false) return expression } private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> { assert(parameterList.size == callableInfo.parameterInfos.size) val typeParameters = ArrayList<TypeExpression>() for ((parameter, ktParameter) in callableInfo.parameterInfos.zip(parameterList)) { val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!) val parameterTypeRef = ktParameter.typeReference!! builder.replaceElement(parameterTypeRef, parameterTypeExpression) // add parameter name to the template val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext) val possibleNames = arrayOf(*parameter.nameSuggestions.toTypedArray(), *possibleNamesFromExpression) // figure out suggested names for each type option val parameterTypeToNamesMap = HashMap<String, Array<String>>() typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate -> val suggestedNames = KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true }) parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray() } // add expression to builder val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap) val parameterNameIdentifier = ktParameter.nameIdentifier!! builder.replaceElement(parameterNameIdentifier, parameterNameExpression) typeParameters.add(parameterTypeExpression) } return typeParameters } private fun replaceWithLongerName(typeRefs: List<KtTypeReference>, theType: KotlinType) { val psiFactory = KtPsiFactory(ktFileToEdit.project) val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) } (typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) } } private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean { fun convertToJava(targetClass: PsiClass): PsiMember? { val psiFactory = KtPsiFactory(declaration) psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let { declaration.containingFile.addBefore(it, null) } val adjustedDeclaration = when (declaration) { is KtNamedFunction, is KtProperty -> { val klass = psiFactory.createClass("class Foo {}") klass.body!!.add(declaration) (declaration.replace(klass) as KtClass).body!!.declarations.first() } else -> declaration } return when (adjustedDeclaration) { is KtNamedFunction, is KtSecondaryConstructor -> { createJavaMethod(adjustedDeclaration as KtFunction, targetClass) } is KtProperty -> { createJavaField(adjustedDeclaration, targetClass) } is KtClass -> { createJavaClass(adjustedDeclaration, targetClass) } else -> null } } if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass if (targetClass == null || !targetClass.canRefactor()) return false val project = declaration.project val newJavaMember = convertToJava(targetClass) ?: return false val modifierList = newJavaMember.modifierList!! if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { modifierList.setModifierProperty(PsiModifier.FINAL, false) } val needStatic = when (callableInfo) { is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) { !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS } else -> callableInfo.receiverTypeInfo.staticContextRequired } modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember) val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! targetEditor.selectionModel.removeSelection() when (newJavaMember) { is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor) is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1) is PsiClass -> { val constructor = newJavaMember.constructors.firstOrNull() val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement val superCall = superStatement?.expression as? PsiMethodCallExpression if (superCall != null) { val lParen = superCall.argumentList.firstChild targetEditor.caretModel.moveToOffset(lParen.endOffset) } else { targetEditor.caretModel.moveToOffset(newJavaMember.nameIdentifier?.startOffset ?: newJavaMember.startOffset) } } } targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) return true } private fun setupEditor(declaration: KtNamedDeclaration) { if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) { val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType val defaultValue = defaultValueType?.let { CodeInsightUtils.defaultInitializer(it) } ?: "null" val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!! val range = initializer.textRange containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset) containingFileEditor.caretModel.moveToOffset(range.endOffset) return } if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) { containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1) return } setupEditorSelection(containingFileEditor, declaration) } // build templates fun buildAndRunTemplate(onFinish: () -> Unit) { val declarationSkeleton = createDeclarationSkeleton() val project = declarationSkeleton.project val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton) // build templates val documentManager = PsiDocumentManager.getInstance(project) val document = containingFileEditor.document documentManager.commitDocument(document) documentManager.doPostponedOperationsAndUnblockDocument(document) val caretModel = containingFileEditor.caretModel caretModel.moveToOffset(ktFileToEdit.node.startOffset) val declaration = declarationPointer.element ?: return val declarationMarker = document.createRangeMarker(declaration.textRange) val builder = TemplateBuilderImpl(ktFileToEdit) if (declaration is KtProperty) { setupValVarTemplate(builder, declaration) } if (!skipReturnType) { setupReturnTypeTemplate(builder, declaration) } val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters()) // add a segment for the parameter list // Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we // need to create the segment first and then hack the Expression into the template later. We use this template to update the type // parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to // it. val expression = setupTypeParameterListTemplate(builder, declaration) documentManager.doPostponedOperationsAndUnblockDocument(document) // the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it val templateImpl = builder.buildInlineTemplate() as TemplateImpl val variables = templateImpl.variables!! if (variables.isNotEmpty()) { val typeParametersVar = if (expression != null) variables.removeAt(0) else null for (i in callableInfo.parameterInfos.indices) { Collections.swap(variables, i * 2, i * 2 + 1) } typeParametersVar?.let { variables.add(it) } } // TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening templateImpl.isToShortenLongNames = false // run the template TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() { private fun finishTemplate(brokenOff: Boolean) { try { documentManager.commitDocument(document) dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE) if (brokenOff && !isUnitTestMode()) return // file templates val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset( ktFileToEdit, declarationMarker.startOffset, declaration::class.java, false ) ?: return runWriteAction { postprocessDeclaration(newDeclaration) // file templates if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) { setupDeclarationBody(newDeclaration as KtFunction) } if (newDeclaration is KtProperty) { newDeclaration.getter?.let { setupDeclarationBody(it) } if (callableInfo is PropertyInfo && callableInfo.initializer != null) { newDeclaration.initializer = callableInfo.initializer } } val callElement = config.originalElement as? KtCallElement if (callElement != null) { setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList()) } CodeStyleManager.getInstance(project).reformat(newDeclaration) // change short type names to fully qualified ones (to be shortened below) if (newDeclaration.getValueParameters().size == parameterTypeExpressions.size) { setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions) } if (!transformToJavaMemberIfApplicable(newDeclaration)) { elementsToShorten.add(newDeclaration) setupEditor(newDeclaration) } } } finally { declarationMarker.dispose() finished = true onFinish() } } override fun templateCancelled(template: Template?) { finishTemplate(true) } override fun templateFinished(template: Template, brokenOff: Boolean) { finishTemplate(brokenOff) } }) } fun showDialogIfNeeded() { if (!isUnitTestMode() && dialogWithEditor != null && !finished) { dialogWithEditor.show() } } } } // TODO: Simplify and use formatter as much as possible @Suppress("UNCHECKED_CAST") internal fun <D : KtNamedDeclaration> placeDeclarationInContainer( declaration: D, container: PsiElement, anchor: PsiElement, fileToEdit: KtFile = container.containingFile as KtFile ): D { val psiFactory = KtPsiFactory(container) val newLine = psiFactory.createNewLine() fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int { var lineBreaksPresent = 0 var neighbor: PsiElement? = null siblingsLoop@ for (sibling in decl.siblings(forward = after, withItself = false)) { when (sibling) { is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' } else -> { neighbor = sibling break@siblingsLoop } } } val neighborType = neighbor?.node?.elementType val lineBreaksNeeded = when { neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1 neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2 else -> 1 } return max(lineBreaksNeeded - lineBreaksPresent, 0) } val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container fun addDeclarationToClassOrObject( classOrObject: KtClassOrObject, declaration: KtNamedDeclaration ): KtNamedDeclaration { val classBody = classOrObject.getOrCreateBody() return if (declaration is KtNamedFunction) { val neighbor = PsiTreeUtil.skipSiblingsBackward( classBody.rBrace ?: classBody.lastChild!!, PsiWhiteSpace::class.java ) classBody.addAfter(declaration, neighbor) as KtNamedDeclaration } else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration } fun addNextToOriginalElementContainer(addBefore: Boolean): D { val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer } return if (addBefore || PsiTreeUtil.hasErrorElements(sibling)) { actualContainer.addBefore(declaration, sibling) } else { actualContainer.addAfter(declaration, sibling) } as D } val declarationInPlace = when { declaration is KtPrimaryConstructor -> { (container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration) } declaration is KtProperty && container !is KtBlockExpression -> { val sibling = actualContainer.getChildOfType<KtProperty>() ?: when (actualContainer) { is KtClassBody -> actualContainer.declarations.firstOrNull() ?: actualContainer.rBrace is KtFile -> actualContainer.declarations.first() else -> null } sibling?.let { actualContainer.addBefore(declaration, it) as D } ?: fileToEdit.add(declaration) as D } actualContainer.isAncestor(anchor, true) -> { val insertToBlock = container is KtBlockExpression if (insertToBlock) { val parent = container.parent if (parent is KtFunctionLiteral) { if (!parent.isMultiLine()) { parent.addBefore(newLine, container) parent.addAfter(newLine, container) } } } addNextToOriginalElementContainer(insertToBlock || declaration is KtTypeAlias) } container is KtFile -> container.add(declaration) as D container is PsiClass -> { if (declaration is KtSecondaryConstructor) { val wrappingClass = psiFactory.createClass("class ${container.name} {\n}") addDeclarationToClassOrObject(wrappingClass, declaration) (fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D } else { fileToEdit.add(declaration) as D } } container is KtClassOrObject -> { var sibling: PsiElement? = container.declarations.lastOrNull { it::class == declaration::class } if (sibling == null && declaration is KtProperty) { sibling = container.body?.lBrace } insertMember(null, container, declaration, sibling) } else -> throw KotlinExceptionWithAttachments("Invalid containing element: ${container::class.java}") .withPsiAttachment("container", container) } when (declaration) { is KtEnumEntry -> { val prevEnumEntry = declarationInPlace.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtEnumEntry>() if (prevEnumEntry != null) { if ((prevEnumEntry.prevSibling as? PsiWhiteSpace)?.text?.contains('\n') == true) { declarationInPlace.parent.addBefore(psiFactory.createNewLine(), declarationInPlace) } val comma = psiFactory.createComma() if (prevEnumEntry.allChildren.any { it.node.elementType == KtTokens.COMMA }) { declarationInPlace.add(comma) } else { prevEnumEntry.add(comma) } val semicolon = prevEnumEntry.allChildren.firstOrNull { it.node?.elementType == KtTokens.SEMICOLON } if (semicolon != null) { (semicolon.prevSibling as? PsiWhiteSpace)?.text?.let { declarationInPlace.add(psiFactory.createWhiteSpace(it)) } declarationInPlace.add(psiFactory.createSemicolon()) semicolon.delete() } } } !is KtPrimaryConstructor -> { val parent = declarationInPlace.parent calcNecessaryEmptyLines(declarationInPlace, false).let { if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace) } calcNecessaryEmptyLines(declarationInPlace, true).let { if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace) } } } return declarationInPlace } fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull() internal fun KtNamedDeclaration.getReturnTypeReferences(): List<KtTypeReference> { return when (this) { is KtCallableDeclaration -> listOfNotNull(typeReference) is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference } else -> throw AssertionError("Unexpected declaration kind: $text") } } fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this)
apache-2.0
d5b1c1ce3acc0cad625843fb5d71cd7c
49.606852
158
0.617594
6.524766
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCustomCodeStyleSettings.kt
1
1416
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.settings import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CustomCodeStyleSettings import org.intellij.plugins.markdown.lang.MarkdownLanguage @Suppress("PropertyName") class MarkdownCustomCodeStyleSettings(settings: CodeStyleSettings) : CustomCodeStyleSettings(MarkdownLanguage.INSTANCE.id, settings) { //BLANK LINES @JvmField var MAX_LINES_AROUND_HEADER: Int = 1 @JvmField var MIN_LINES_AROUND_HEADER: Int = 1 @JvmField var MAX_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MIN_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MAX_LINES_BETWEEN_PARAGRAPHS: Int = 1 @JvmField var MIN_LINES_BETWEEN_PARAGRAPHS: Int = 1 //SPACES @JvmField var FORCE_ONE_SPACE_BETWEEN_WORDS: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_LIST_BULLET: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL: Boolean = true @JvmField var WRAP_TEXT_IF_LONG = true @JvmField var KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS = true @JvmField var WRAP_TEXT_INSIDE_BLOCKQUOTES = true @JvmField var INSERT_QUOTE_ARROWS_ON_WRAP = true }
apache-2.0
a8fde66f13eaac288974390404d250d4
24.745455
158
0.757062
3.837398
false
false
false
false
LouisCAD/Splitties
modules/resources/src/androidMain/kotlin/splitties/resources/PrimitiveResources.kt
1
4138
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") @file:OptIn(InternalSplittiesApi::class) package splitties.resources import android.content.Context import android.util.TypedValue import android.view.View import androidx.annotation.ArrayRes import androidx.annotation.AttrRes import androidx.annotation.BoolRes import androidx.annotation.IntegerRes import androidx.fragment.app.Fragment import splitties.experimental.InternalSplittiesApi import splitties.init.appCtx inline fun Context.bool(@BoolRes boolResId: Int): Boolean = resources.getBoolean(boolResId) inline fun Fragment.bool(@BoolRes boolResId: Int) = context!!.bool(boolResId) inline fun View.bool(@BoolRes boolResId: Int) = context.bool(boolResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appBool(@BoolRes boolResId: Int) = appCtx.bool(boolResId) inline fun Context.int(@IntegerRes intResId: Int): Int = resources.getInteger(intResId) inline fun Fragment.int(@IntegerRes intResId: Int) = context!!.int(intResId) inline fun View.int(@IntegerRes intResId: Int) = context.int(intResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appInt(@IntegerRes intResId: Int) = appCtx.int(intResId) inline fun Context.intArray( @ArrayRes intArrayResId: Int ): IntArray = resources.getIntArray(intArrayResId) inline fun Fragment.intArray(@ArrayRes intArrayResId: Int) = context!!.intArray(intArrayResId) inline fun View.intArray(@ArrayRes intArrayResId: Int) = context.intArray(intArrayResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appIntArray(@ArrayRes intArrayResId: Int) = appCtx.intArray(intArrayResId) // Styled resources below fun Context.styledBool(@AttrRes attr: Int): Boolean = withResolvedThemeAttribute(attr) { require(type == TypedValue.TYPE_INT_BOOLEAN) { unexpectedThemeAttributeTypeErrorMessage(expectedKind = "bool") } when (val value = data) { 0 -> false 1 -> true else -> error("Expected 0 or 1 but got $value") } } inline fun Fragment.styledBool(@AttrRes attr: Int) = context!!.styledBool(attr) inline fun View.styledBool(@AttrRes attr: Int) = context.styledBool(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledBool(@AttrRes attr: Int) = appCtx.styledBool(attr) fun Context.styledInt(@AttrRes attr: Int): Int = withResolvedThemeAttribute(attr) { require(type == TypedValue.TYPE_INT_DEC || type == TypedValue.TYPE_INT_HEX) { unexpectedThemeAttributeTypeErrorMessage(expectedKind = "int") } data } inline fun Fragment.styledInt(@AttrRes attr: Int) = context!!.styledInt(attr) inline fun View.styledInt(@AttrRes attr: Int) = context.styledInt(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledInt(@AttrRes attr: Int) = appCtx.styledInt(attr)
apache-2.0
998a91df326e5c9601cf1406ca8579a3
38.788462
109
0.758337
4.117413
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/TimedIconCache.kt
9
3683
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl import com.intellij.execution.ProgramRunnerUtil import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.registry.Registry import com.intellij.ui.IconDeferrer import com.intellij.util.containers.ObjectLongHashMap import gnu.trove.THashMap import java.util.concurrent.locks.ReentrantReadWriteLock import javax.swing.Icon import kotlin.concurrent.read import kotlin.concurrent.write class TimedIconCache { private val idToIcon = THashMap<String, Icon>() private val iconCheckTimes = ObjectLongHashMap<String>() private val iconCalcTime = ObjectLongHashMap<String>() private val lock = ReentrantReadWriteLock() fun remove(id: String) { lock.write { idToIcon.remove(id) iconCheckTimes.remove(id) iconCalcTime.remove(id) } } fun get(id: String, settings: RunnerAndConfigurationSettings, project: Project): Icon { return lock.read { idToIcon.get(id) } ?: lock.write { idToIcon.get(id)?.let { return it } val icon = IconDeferrer.getInstance().deferAutoUpdatable(settings.configuration.icon, project.hashCode() xor settings.hashCode()) { if (project.isDisposed) { return@deferAutoUpdatable null } lock.write { iconCalcTime.remove(id) } val startTime = System.currentTimeMillis() val icon = calcIcon(settings, project) lock.write { iconCalcTime.put(id, System.currentTimeMillis() - startTime) } icon } set(id, icon) icon } } private fun calcIcon(settings: RunnerAndConfigurationSettings, project: Project): Icon { try { settings.checkSettings() return ProgramRunnerUtil.getConfigurationIcon(settings, false) } catch (e: IndexNotReadyException) { return ProgramRunnerUtil.getConfigurationIcon(settings, false) } catch (ignored: RuntimeConfigurationException) { return ProgramRunnerUtil.getConfigurationIcon(settings, !DumbService.isDumb(project)) } } private fun set(id: String, icon: Icon) { idToIcon.put(id, icon) iconCheckTimes.put(id, System.currentTimeMillis()) } fun clear() { lock.write { idToIcon.clear() iconCheckTimes.clear() iconCalcTime.clear() } } fun checkValidity(id: String) { lock.read { val lastCheckTime = iconCheckTimes.get(id) var expired = lastCheckTime == -1L if (!expired) { var calcTime = iconCalcTime.get(id) if (calcTime == -1L || calcTime < 150) { calcTime = 150L } expired = (System.currentTimeMillis() - lastCheckTime) > (calcTime * 10) } if (expired) { lock.write { idToIcon.remove(id) } } } } }
apache-2.0
74b700a09cbd1bb6ef4316a2647c6459
28.472
137
0.6959
4.442702
false
true
false
false
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/stories/websocket/WebsocketNotificationsDefs.kt
2
8212
package com.github.kerubistan.kerub.stories.websocket import com.github.kerubistan.kerub.createClient import com.github.kerubistan.kerub.login import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.Pool import com.github.kerubistan.kerub.model.messages.EntityAddMessage import com.github.kerubistan.kerub.model.messages.EntityRemoveMessage import com.github.kerubistan.kerub.model.messages.EntityUpdateMessage import com.github.kerubistan.kerub.model.messages.Message import com.github.kerubistan.kerub.model.messages.SubscribeMessage import com.github.kerubistan.kerub.runRestAction import com.github.kerubistan.kerub.services.HostService import com.github.kerubistan.kerub.services.PoolService import com.github.kerubistan.kerub.services.RestCrud import com.github.kerubistan.kerub.services.VirtualMachineService import com.github.kerubistan.kerub.services.VirtualNetworkService import com.github.kerubistan.kerub.services.VirtualStorageDeviceService import com.github.kerubistan.kerub.services.getServiceBaseUrl import com.github.kerubistan.kerub.stories.entities.EntityDefs import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testVirtualNetwork import com.github.kerubistan.kerub.testVm import com.github.kerubistan.kerub.testWsUrl import com.github.kerubistan.kerub.utils.createObjectMapper import com.github.kerubistan.kerub.utils.getLogger import cucumber.api.java.en.Given import cucumber.api.java.en.Then import cucumber.api.java.en.When import io.github.kerubistan.kroki.time.now import org.eclipse.jetty.websocket.api.Session import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage import org.eclipse.jetty.websocket.api.annotations.WebSocket import org.eclipse.jetty.websocket.client.WebSocketClient import org.junit.After import java.net.CookieManager import java.net.HttpCookie import java.net.URI import java.util.UUID import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.BlockingQueue import java.util.concurrent.TimeUnit import kotlin.reflect.KClass import kotlin.test.fail class WebsocketNotificationsDefs { private var socketClient: WebSocketClient? = null private var session: Session? = null private val events: BlockingQueue<Any> = ArrayBlockingQueue<Any>(1024) private var entities = listOf<Any>() private var listener: Listener? = null data class ConnectEvent(val time: Long = now()) data class DisconnectEvent(val time: Long = now()) data class MessageEvent(val time: Long = now(), val message: Message) @WebSocket class Listener(private val messages: BlockingQueue<Any>) { companion object { private val mapper = createObjectMapper() } @OnWebSocketConnect fun connect(session: Session) { logger.info("connected: ${session.isOpen}") messages.put(ConnectEvent()) } @OnWebSocketClose fun close(code: Int, msg: String?) { logger.info("connection closed {} {}", code, msg) messages.put(DisconnectEvent()) } @OnWebSocketMessage fun message(session: Session, input: String) { logger.info("message: {}", input) val msg = mapper.readValue(input, Message::class.java) messages.add(MessageEvent(message = msg)) logger.info("message: {}", msg) } @OnWebSocketError fun error(error: Throwable) { logger.info("socket error", error) } } companion object { private val logger = getLogger() private val mapper = createObjectMapper(prettyPrint = true) } @Given("(\\S+) is connected to websocket") fun connectToWebsocket(listenerUser: String) { val client = createClient() val response = client.login(username = listenerUser, password = "password") socketClient = WebSocketClient() socketClient!!.cookieStore = CookieManager().cookieStore response.cookies.forEach { socketClient!!.cookieStore.add(URI(getServiceBaseUrl()), HttpCookie(it.value.name, it.value.value)) } socketClient!!.start() listener = Listener(events) session = socketClient!!.connect(listener, URI(testWsUrl)).get() } @Given("user subscribed to message feed (\\S+)") fun subscribeToMessageFeed(messageFeed: String) { session!!.remote.sendString(mapper.writeValueAsString(SubscribeMessage(channel = messageFeed))) } private val actions = mapOf<String, (RestCrud<Entity<UUID>>, Entity<UUID>) -> Any>( "creates" to { x, obj -> entities += x.add(obj) obj }, "updates" to { x, obj -> x.update(obj.id, obj) }, "deletes" to { x, obj -> x.delete(obj.id) EntityDefs.instance.entityDropped(obj) } ) private val entityTypes = mapOf<String, KClass<*>>( "vm" to VirtualMachineService::class, "virtual network" to VirtualNetworkService::class, "virtual disk" to VirtualStorageDeviceService::class, "pool" to PoolService::class, "host" to HostService::class ) @When("the user (\\S+) creates (vm|virtual network|virtual disk|pool)") fun runUserAdd(userName: String, entityType: String) { val client = createClient() client.login(userName, "password") when(entityType) { "vm" -> client.runRestAction(VirtualMachineService::class) { entities += it.add(testVm.copy(id= UUID.randomUUID())) } "virtual network" -> client.runRestAction(VirtualNetworkService::class) { entities += it.add(testVirtualNetwork.copy(id = UUID.randomUUID())) } "virtual disk" -> client.runRestAction(VirtualStorageDeviceService::class) { entities += it.add(testDisk.copy(id = UUID.randomUUID())) } "pool" -> client.runRestAction(PoolService::class) { entities += it.add(Pool(name = "test pool", templateId = UUID.randomUUID())) } } } @When("the user (\\S+) (updates|deletes) (vm|virtual network|virtual disk|pool) (\\S+)") fun runUserAction(userName: String, action: String, entityType: String, entityName: String) { val client = createClient() client.login(userName, "password") client.runRestAction(requireNotNull(entityTypes[entityType]) { "Unknown type: $entityType" }) { val actionFn = requireNotNull(actions[action]) { "Unhandled action: $action" } actionFn(it as RestCrud<Entity<UUID>>, EntityDefs.instance.getEntity(entityName)) } } @Then("listener user must not receive socket notification( with type.*)?") fun checkNoNotification(type: String?) { logger.info("expecting NO message....") val expectedType = type?.substringAfter(" with type ")?.trim() var event = events.poll(100, TimeUnit.MILLISECONDS) while (event != null) { logger.info("event: {}", event) if (event is MessageEvent && matchesType(expectedType, event)) { fail("expected no ${expectedType ?: ""} message, got $event") } event = events.poll(100, TimeUnit.MILLISECONDS) } } @Then("listener user must receive socket notification( with type .*)?") fun checkNotification(type: String?) { val eventsReceived = mutableListOf<Any>() val expectedType = type?.substringAfter(" with type ")?.trim() logger.info("expecting message....") var event = events.poll(1000, TimeUnit.MILLISECONDS) while (event != null) { eventsReceived.add(event) logger.info("event: {}", event) if (event is MessageEvent && matchesType(expectedType, event)) { logger.info("pass...") return } event = events.poll(1000, TimeUnit.MILLISECONDS) } fail("expected ${expectedType ?: ""} message not received\n got instead: $eventsReceived") } private val eventTypes = mapOf( "update" to EntityUpdateMessage::class, "delete" to EntityRemoveMessage::class, "create" to EntityAddMessage::class ) private fun matchesType(expectedType: String?, event: MessageEvent): Boolean = expectedType == null || event.message.javaClass.kotlin == eventTypes[expectedType] @After fun cleanup() { socketClient?.stop() val client = createClient() client.login("admin", "password") entities.forEach { entity -> when (entity) { is Entity<*> -> client.runRestAction(VirtualMachineService::class) { it.delete(entity.id as UUID) } else -> fail("can not clean up $entity") } } } }
apache-2.0
63a4214d46c9cde1fd357f7e03bda6d0
33.654008
102
0.74379
3.705776
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/NotificationChannels.kt
1
3609
package com.orgzly.android import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.graphics.Color import android.os.Build import androidx.annotation.RequiresApi import com.orgzly.R import com.orgzly.android.reminders.RemindersNotifications import com.orgzly.android.ui.util.getNotificationManager /** * Creates all channels for notifications. */ object NotificationChannels { const val ONGOING = "ongoing" const val REMINDERS = "reminders" const val SYNC_PROGRESS = "sync-progress" const val SYNC_FAILED = "sync-failed" @JvmStatic fun createAll(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createForOngoing(context) createForReminders(context) createForSyncProgress(context) createForSyncFailed(context) } } @RequiresApi(Build.VERSION_CODES.O) private fun createForReminders(context: Context) { val id = REMINDERS val name = context.getString(R.string.reminders_channel_name) val description = context.getString(R.string.reminders_channel_description) val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(id, name, importance) channel.description = description channel.enableLights(true) channel.lightColor = Color.BLUE channel.vibrationPattern = RemindersNotifications.VIBRATION_PATTERN channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForOngoing(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = ONGOING val name = context.getString(R.string.ongoing_channel_name) val description = context.getString(R.string.ongoing_channel_description) val importance = NotificationManager.IMPORTANCE_MIN val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForSyncProgress(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = SYNC_PROGRESS val name = context.getString(R.string.sync_progress_channel_name) val description = context.getString(R.string.sync_progress_channel_description) val importance = NotificationManager.IMPORTANCE_LOW val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForSyncFailed(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = SYNC_FAILED val name = context.getString(R.string.sync_failed_channel_name) val description = context.getString(R.string.sync_failed_channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(true) context.getNotificationManager().createNotificationChannel(channel) } }
gpl-3.0
6cddea50b42b1193689a215442ec7de6
30.666667
87
0.700748
4.717647
false
false
false
false
seventhroot/elysium
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/purchase/RPKPurchaseProviderImpl.kt
1
3617
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.store.bukkit.purchase import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.database.table.RPKConsumablePurchaseTable import com.rpkit.store.bukkit.database.table.RPKPermanentPurchaseTable import com.rpkit.store.bukkit.database.table.RPKPurchaseTable import com.rpkit.store.bukkit.database.table.RPKTimedPurchaseTable import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseCreateEvent import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseDeleteEvent import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseUpdateEvent class RPKPurchaseProviderImpl(private val plugin: RPKStoresBukkit): RPKPurchaseProvider { override fun getPurchases(profile: RPKProfile): List<RPKPurchase> { return plugin.core.database.getTable(RPKPurchaseTable::class).get(profile) } override fun getPurchase(id: Int): RPKPurchase? { return plugin.core.database.getTable(RPKPurchaseTable::class)[id] } override fun addPurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseCreateEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).insert(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).insert(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).insert(eventPurchase) } } override fun updatePurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseUpdateEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).update(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).update(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).update(eventPurchase) } } override fun removePurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseDeleteEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).delete(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).delete(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).delete(eventPurchase) } } }
apache-2.0
68911d66688501b856782abb23def91d
46.605263
126
0.75394
4.572693
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/osm/OsmJotiMap.kt
1
5973
package nl.rsdt.japp.jotial.maps.wrapper.osm import android.graphics.Bitmap import android.location.Location import android.util.Pair import android.view.PixelCopy import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.* import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter import nl.rsdt.japp.jotial.maps.wrapper.* import org.osmdroid.events.MapEventsReceiver import org.osmdroid.events.MapListener import org.osmdroid.events.ScrollEvent import org.osmdroid.events.ZoomEvent import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.MapEventsOverlay import java.util.* /** * Created by mattijn on 07/08/17. */ class OsmJotiMap private constructor(val osmMap: MapView //todo fix type ) : IJotiMap { private var eventsOverlay: MapEventsOverlay? = null override val uiSettings: IUiSettings get() = OsmUiSettings(osmMap) override val previousCameraPosition: ICameraPosition get() = OsmCameraPosition(osmMap) init { eventsOverlay = MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { return false } override fun longPressHelper(p: GeoPoint): Boolean { return false } }) osmMap.overlays.add(0, eventsOverlay) } override fun setPreviousCameraPosition(latitude: Double, longitude: Double) { val previousCameraPosition = GeoPoint(latitude, longitude) } override fun setPreviousZoom(previousZoom: Int) { //TODO } override fun setPreviousRotation(rotation: Float) { //TODO } override fun delete() { if (osm_instances.containsValue(this)) { osm_instances.remove(this.osmMap) } } override fun setInfoWindowAdapter(infoWindowAdapter: CustomInfoWindowAdapter) { //// TODO: 30/08/17 } override fun setGMapType(mapType: Int) { //// TODO: 30/08/17 } override fun setMapStyle(mapStyleOptions: MapStyleOptions): Boolean { return false //// TODO: 30/08/17 } override fun animateCamera(latLng: LatLng, zoom: Int) { osmMap.controller.animateTo(GeoPoint(latLng.latitude, latLng.longitude)) osmMap.controller.zoomTo(zoom)//// TODO: 07/08/17 controleren of de zoomlevels van googlemaps en osm enigzins overeenkomen. } override fun addMarker(markerOptions: Pair<MarkerOptions, Bitmap?>): IMarker { return OsmMarker(markerOptions, osmMap) } override fun addPolyline(polylineOptions: PolylineOptions): IPolyline { return OsmPolyline(polylineOptions, osmMap) } override fun addPolygon(polygonOptions: PolygonOptions): IPolygon { return OsmPolygon(polygonOptions, osmMap) } override fun addCircle(circleOptions: CircleOptions): ICircle { return OsmCircle(circleOptions, osmMap) } override fun setOnMapClickListener(onMapClickListener: IJotiMap.OnMapClickListener?) { osmMap.overlays.remove(eventsOverlay) eventsOverlay = MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { return onMapClickListener?.onMapClick(LatLng(p.latitude, p.longitude)) ?: false } override fun longPressHelper(p: GeoPoint): Boolean { return false } }) osmMap.overlays.add(0, eventsOverlay) } override fun snapshot(snapshotReadyCallback: IJotiMap.SnapshotReadyCallback?) { this.osmMap.isDrawingCacheEnabled = false this.osmMap.isDrawingCacheEnabled = true this.osmMap.buildDrawingCache() val bm = this.osmMap.drawingCache snapshotReadyCallback?.onSnapshotReady(bm) } override fun animateCamera(latLng: LatLng, zoom: Int, cancelableCallback: IJotiMap.CancelableCallback?) { osmMap.controller.setCenter(GeoPoint(latLng.latitude, latLng.longitude)) osmMap.controller.setZoom(zoom) cancelableCallback?.onFinish() } override fun setOnCameraMoveStartedListener(onCameraMoveStartedListener: GoogleMap.OnCameraMoveStartedListener?) { if (onCameraMoveStartedListener != null) { osmMap.setMapListener(object : MapListener { override fun onScroll(event: ScrollEvent): Boolean { onCameraMoveStartedListener.onCameraMoveStarted(GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) return false } override fun onZoom(event: ZoomEvent): Boolean { onCameraMoveStartedListener.onCameraMoveStarted(GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) return false } }) } else { osmMap.setMapListener(null) } } override fun cameraToLocation(b: Boolean, location: Location, zoom: Float, aoa: Float, bearing: Float) { osmMap.controller.animateTo(GeoPoint(location.latitude, location.longitude)) } override fun clear() { osmMap.overlays.clear() } override fun setOnInfoWindowLongClickListener(onInfoWindowLongClickListener: GoogleMap.OnInfoWindowLongClickListener?) { //// TODO: 30/08/17 } override fun setMarkerOnClickListener(listener: IJotiMap.OnMarkerClickListener?) { OsmMarker.setAllOnClickLister(listener) } override fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) { callback.onMapReady(this) } companion object { private val osm_instances = HashMap<MapView, OsmJotiMap>() fun getJotiMapInstance(map: MapView): OsmJotiMap? { if (!osm_instances.containsKey(map)) { val jm = OsmJotiMap(map) osm_instances[map] = jm } return osm_instances[map] } } }
apache-2.0
03ecf932866fc9a99754a167a102d01a
32
131
0.677884
4.766959
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/mentions/ui/MentionsFragment.kt
2
4234
package chat.rocket.android.mentions.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.chatroom.adapter.ChatRoomAdapter import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.chatroom.uimodel.BaseUiModel import chat.rocket.android.helper.EndlessRecyclerViewScrollListener import chat.rocket.android.mentions.presentention.MentionsPresenter import chat.rocket.android.mentions.presentention.MentionsView import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_mentions.* import javax.inject.Inject fun newInstance(chatRoomId: String): Fragment = MentionsFragment().apply { arguments = Bundle(1).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) } } internal const val TAG_MENTIONS_FRAGMENT = "MentionsFragment" private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id" class MentionsFragment : Fragment(), MentionsView { @Inject lateinit var presenter: MentionsPresenter @Inject lateinit var analyticsManager: AnalyticsManager private lateinit var chatRoomId: String private val adapter = ChatRoomAdapter(enableActions = false) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_mentions) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() presenter.loadMentions(chatRoomId) analyticsManager.logScreenView(ScreenViewEvent.Mentions) } override fun showMentions(mentions: List<BaseUiModel<*>>) { ui { if (recycler_view.adapter == null) { recycler_view.adapter = adapter val linearLayoutManager = LinearLayoutManager(context) recycler_view.layoutManager = linearLayoutManager recycler_view.itemAnimator = DefaultItemAnimator() if (mentions.size >= 30) { recycler_view.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore( page: Int, totalItemsCount: Int, recyclerView: RecyclerView ) { presenter.loadMentions(chatRoomId) } }) } group_no_mention.isVisible = mentions.isEmpty() } adapter.appendData(mentions) } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) override fun showLoading() { ui { view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false } } private fun setupToolbar() { (activity as ChatRoomActivity).setupToolbarTitle((getString(R.string.msg_mentions))) } }
mit
81cb88035d54819317e014b920c0272c
34
101
0.681389
5.11971
false
false
false
false
EdenYoon/LifeLogging
src/com/humanebyte/lifelogging/MyActivity.kt
1
2980
package com.humanebyte.lifelogging import android.app.Activity import android.content.Intent import android.os.Bundle import android.provider.Settings import android.view.View import android.widget.Button import android.widget.TextView class MyActivity : Activity(), View.OnClickListener { internal lateinit var service_status: TextView internal lateinit var setting: Button internal lateinit var button_force_speaker: Button internal lateinit var button_cancel_force_use: Button internal lateinit var button_bypass_keyevent: Button internal lateinit var button_eat_keyevent: Button public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) service_status = findViewById(R.id.accessibility_service_status) as TextView setting = findViewById(R.id.setting) as Button setting.setOnClickListener(this) button_force_speaker = findViewById(R.id.force_speaker) as Button button_force_speaker.setOnClickListener(this) button_cancel_force_use = findViewById(R.id.cancel_force_use) as Button button_cancel_force_use.setOnClickListener(this) button_bypass_keyevent = findViewById(R.id.bypass_keyevent) as Button button_bypass_keyevent.setOnClickListener(this) button_eat_keyevent = findViewById(R.id.eat_keyevent) as Button button_eat_keyevent.setOnClickListener(this) } override fun onResume() { val isSet = AccessibilityServiceUtil.isAccessibilityServiceOn( applicationContext, "com.humanebyte.lifelogging", "com.humanebyte.lifelogging.MyAccessibilityService") if (isSet) { service_status.setText(R.string.accessibility_service_on) } else { service_status.setText(R.string.accessibility_service_off) } super.onResume() } override fun onClick(v: View) { when (v.id) { R.id.setting -> { val accessibilityServiceIntent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) startActivity(accessibilityServiceIntent) } R.id.force_speaker -> { val i = Intent("com.humanebyte.lifelogging.force_speaker").putExtra("force_speaker", true) this.sendBroadcast(i) } R.id.cancel_force_use -> { val i = Intent("com.humanebyte.lifelogging.force_speaker").putExtra("force_speaker", false) this.sendBroadcast(i) } R.id.bypass_keyevent -> { val i = Intent("com.humanebyte.lifelogging.eat_keyevent").putExtra("eat", false) this.sendBroadcast(i) } R.id.eat_keyevent -> { val i = Intent("com.humanebyte.lifelogging.eat_keyevent").putExtra("eat", true) this.sendBroadcast(i) } } } }
mit
6b3389e01942dd05a5fc7b9d8367edf3
38.746667
107
0.651342
4.306358
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/group-layers/src/main/java/com/esri/arcgisruntime/sample/grouplayers/MainActivity.kt
1
8114
/* * Copyright 2020 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.arcgisruntime.sample.grouplayers import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.data.ServiceFeatureTable import com.esri.arcgisruntime.layers.* import com.esri.arcgisruntime.mapping.ArcGISScene import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.LayerList import com.esri.arcgisruntime.mapping.view.Camera import com.esri.arcgisruntime.mapping.view.SceneView import com.esri.arcgisruntime.sample.grouplayers.databinding.ActivityMainBinding import com.google.android.material.bottomsheet.BottomSheetBehavior class MainActivity : AppCompatActivity() { private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val sceneView: SceneView by lazy { activityMainBinding.sceneView } private val bottomSheet: LinearLayout by lazy { activityMainBinding.bottomSheet.bottomSheetLayout } private val header: ConstraintLayout by lazy { activityMainBinding.bottomSheet.header } private val arrowImageView: ImageView by lazy { activityMainBinding.bottomSheet.arrowImageView } private val recyclerView: RecyclerView by lazy { activityMainBinding.bottomSheet.recyclerView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create different types of layers val trees = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_Trees/SceneServer/layers/0").apply { name = "Trees" } val pathways = FeatureLayer(ServiceFeatureTable("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_Pathways/FeatureServer/1")).apply { name = "Pathways" } val projectArea = FeatureLayer(ServiceFeatureTable("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/DevelopmentProjectArea/FeatureServer/0")).apply { name = "Project area" // set the scene's viewpoint based on this layer's extent addDoneLoadingListener { sceneView.setViewpointCamera( Camera( fullExtent.center, 700.0, 0.0, 60.0, 0.0 ) ) } } val buildingsA = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_BuildingShells/SceneServer/layers/0").apply { name = "Dev A" } val buildingsB = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevB_BuildingShells/SceneServer/layers/0").apply { name = "Dev B" } // create a group layer from scratch by adding the trees, pathways, and project area as children val projectAreaGroupLayer = GroupLayer().apply { name = "Project area group" layers.addAll(arrayOf(trees, pathways, projectArea)) } // create a group layer for the buildings and set its visibility mode to exclusive val buildingsGroupLayer = GroupLayer().apply { name = "Buildings group" layers.addAll(arrayOf(buildingsA, buildingsB)) visibilityMode = GroupVisibilityMode.EXCLUSIVE } // create a scene with an imagery basemap val scene = ArcGISScene(BasemapStyle.ARCGIS_IMAGERY).apply { // add the group layer and other layers to the scene as operational layers operationalLayers.addAll(arrayOf(projectAreaGroupLayer, buildingsGroupLayer)) addDoneLoadingListener { setupBottomSheet(operationalLayers) } } // set the scene to be displayed in the scene view sceneView.scene = scene } private fun onLayerCheckedChanged(layer: Layer, isChecked: Boolean) { layer.isVisible = isChecked } /** Creates a bottom sheet to display a list of group layers. * * @param layers a list of layers and group layers to be displayed on the scene */ private fun setupBottomSheet(layers: LayerList) { // create a bottom sheet behavior from the bottom sheet view in the main layout val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet).apply { // expand the bottom sheet, and ensure it is displayed on the screen when collapsed state = BottomSheetBehavior.STATE_EXPANDED peekHeight = header.height // animate the arrow when the bottom sheet slides addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(bottomSheet: View, slideOffset: Float) { arrowImageView.rotation = slideOffset * 180f } override fun onStateChanged(bottomSheet: View, newState: Int) { arrowImageView.rotation = when (newState) { BottomSheetBehavior.STATE_EXPANDED -> 180f else -> arrowImageView.rotation } } }) } bottomSheet.apply { visibility = View.VISIBLE // expand or collapse the bottom sheet when the header is clicked header.setOnClickListener { bottomSheetBehavior.state = when (bottomSheetBehavior.state) { BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_EXPANDED else -> BottomSheetBehavior.STATE_COLLAPSED } } // initialize the recycler view with the group layers and set the callback for the checkboxes recyclerView.adapter = LayerListAdapter(layers) { layer: Layer, isChecked: Boolean -> onLayerCheckedChanged( layer, isChecked ) } recyclerView.layoutManager = LinearLayoutManager(applicationContext) // rotate the arrow so it starts off in the correct rotation arrowImageView.rotation = 180f } // shrink the scene view so it is not hidden under the bottom sheet header when collapsed (sceneView.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin = header.height } override fun onResume() { super.onResume() sceneView.resume() } override fun onPause() { sceneView.pause() super.onPause() } override fun onDestroy() { sceneView.dispose() super.onDestroy() } }
apache-2.0
7309c4cd0f6f784d5491400e5a84f9e7
38.970443
161
0.650974
5.168153
false
false
false
false
googlecodelabs/android-compose-codelabs
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/data/Cities.kt
1
2651
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.samples.crane.data val MADRID = City( name = "Madrid", country = "Spain", latitude = "40.416775", longitude = "-3.703790" ) val NAPLES = City( name = "Naples", country = "Italy", latitude = "40.853294", longitude = "14.305573" ) val DALLAS = City( name = "Dallas", country = "US", latitude = "32.779167", longitude = "-96.808891" ) val CORDOBA = City( name = "Cordoba", country = "Argentina", latitude = "-31.416668", longitude = "-64.183334" ) val MALDIVAS = City( name = "Maldivas", country = "South Asia", latitude = "1.924992", longitude = "73.399658" ) val ASPEN = City( name = "Aspen", country = "Colorado", latitude = "39.191097", longitude = "-106.817535" ) val BALI = City( name = "Bali", country = "Indonesia", latitude = "-8.3405", longitude = "115.0920" ) val BIGSUR = City( name = "Big Sur", country = "California", latitude = "36.2704", longitude = "-121.8081" ) val KHUMBUVALLEY = City( name = "Khumbu Valley", country = "Nepal", latitude = "27.9320", longitude = "86.8050" ) val ROME = City( name = "Rome", country = "Italy", latitude = "41.902782", longitude = "12.496366" ) val GRANADA = City( name = "Granada", country = "Spain", latitude = "37.18817", longitude = "-3.60667" ) val WASHINGTONDC = City( name = "Washington DC", country = "USA", latitude = "38.9072", longitude = "-77.0369" ) val BARCELONA = City( name = "Barcelona", country = "Spain", latitude = "41.390205", longitude = "2.154007" ) val CRETE = City( name = "Crete", country = "Greece", latitude = "35.2401", longitude = "24.8093" ) val LONDON = City( name = "London", country = "United Kingdom", latitude = "51.509865", longitude = "-0.118092" ) val PARIS = City( name = "Paris", country = "France", latitude = "48.864716", longitude = "2.349014" )
apache-2.0
8555ed48fec102e719fbbd68ea46236c
19.550388
75
0.605809
3.050633
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/module/common/view/LoadStateView.kt
1
2924
/* * Copyright (C) 2017 YangBin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package tech.summerly.quiet.module.common.view import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import kotlinx.android.synthetic.main.common_view_load_state.view.* import tech.summerly.quiet.R /** * author : yangbin10 * date : 2017/11/17 * 放在需要加载数据的view上,提供一个加载的动画和加载失败的重试按钮 */ class LoadStateView : FrameLayout { private val root: View constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { @SuppressLint("InflateParams") root = LayoutInflater.from(context).inflate(R.layout.common_view_load_state, null, false) root.setOnTouchListener { _, _ -> //拦截触摸事件.. true } addView(root, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } var loadingText: String = "载入中..." var failedText: String = "载入失败,点击重试." private var onRetryClickListener: View.OnClickListener? = null fun setLoading() { visibility = View.VISIBLE progressBar.visibility = View.VISIBLE imageStateIndicator.visibility = View.GONE textHint.text = loadingText } fun setLoadFailed() { visibility = View.VISIBLE progressBar.visibility = View.GONE imageStateIndicator.visibility = View.VISIBLE imageStateIndicator.setImageResource(R.drawable.ic_error_outline_black_24dp) textHint.text = failedText textHint.setOnClickListener { textHint.setOnClickListener(null) textHint.isClickable = false onRetryClickListener?.onClick(it) } } fun hide() { visibility = View.GONE } fun setRetryClickListener(listener: View.OnClickListener) { onRetryClickListener = listener } }
gpl-2.0
78b10b366c55aab87eb300fe15eff47c
31.94186
114
0.704096
4.26506
false
false
false
false
cketti/k-9
app/core/src/test/java/com/fsck/k9/mailstore/MessageListRepositoryTest.kt
1
14809
package com.fsck.k9.mailstore import com.fsck.k9.mail.Address import com.fsck.k9.mail.Flag import com.fsck.k9.message.extractors.PreviewResult import com.google.common.truth.Truth.assertThat import java.util.UUID import org.junit.After import org.junit.Before import org.junit.Test import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.stub private const val MESSAGE_ID = 1L private const val MESSAGE_ID_2 = 2L private const val MESSAGE_ID_3 = 3L private const val FOLDER_ID = 20L private const val FOLDER_ID_2 = 21L private const val THREAD_ROOT = 30L private const val THREAD_ROOT_2 = 31L private const val SELECTION = "irrelevant" private val SELECTION_ARGS = arrayOf("irrelevant") private const val SORT_ORDER = "irrelevant" class MessageListRepositoryTest { private val accountUuid = UUID.randomUUID().toString() private val messageStore = mock<ListenableMessageStore>() private val messageStoreManager = mock<MessageStoreManager> { on { getMessageStore(accountUuid) } doReturn messageStore } private val messageListRepository = MessageListRepository(messageStoreManager) @Before fun setUp() { startKoin { modules( module { single { messageListRepository } } ) } } @After fun tearDown() { stopKoin() } @Test fun `adding and removing listener`() { var messageListChanged = 0 val listener = MessageListChangedListener { messageListChanged++ } messageListRepository.addListener(accountUuid, listener) messageListRepository.notifyMessageListChanged(accountUuid) assertThat(messageListChanged).isEqualTo(1) messageListRepository.removeListener(listener) messageListRepository.notifyMessageListChanged(accountUuid) assertThat(messageListChanged).isEqualTo(1) } @Test fun `only notify listener when account UUID matches`() { var messageListChanged = 0 val listener = MessageListChangedListener { messageListChanged++ } messageListRepository.addListener(accountUuid, listener) messageListRepository.notifyMessageListChanged("otherAccountUuid") assertThat(messageListChanged).isEqualTo(0) } @Test fun `notifyMessageListChanged() without any listeners should not throw`() { messageListRepository.notifyMessageListChanged(accountUuid) } @Test fun `getMessages() should use flag values from the cache`() { addMessages( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ) ) } @Test fun `getMessages() should skip messages marked as hidden in the cache`() { addMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2) } @Test fun `getMessages() should not skip message when marked as hidden in a different folder`() { addMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2) } @Test fun `getThreadedMessages() should use flag values from the cache`() { addThreadedMessages( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ) ) } @Test fun `getThreadedMessages() should skip messages marked as hidden in the cache`() { addThreadedMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT_2) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2) } @Test fun `getThreadedMessages() should not skip message when marked as hidden in a different folder`() { addThreadedMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT_2) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2) } @Test fun `getThread() should use flag values from the cache`() { addMessagesToThread( THREAD_ROOT, MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ), MessageData( messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = true, isForwarded = false ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getThread( accountUuid, THREAD_ROOT, SORT_ORDER ) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ), MessageData( messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = false, isAnswered = true, isForwarded = false ) ) } @Test fun `getThread() should skip messages marked as hidden in the cache`() { addMessagesToThread( THREAD_ROOT, MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_3, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getThread(accountUuid, THREAD_ROOT, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2, MESSAGE_ID_3) } @Test fun `getThread() should not skip message when marked as hidden in a different folder`() { addMessagesToThread( THREAD_ROOT, MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_3, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getThread(accountUuid, THREAD_ROOT, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2, MESSAGE_ID_3) } private fun addMessages(vararg messages: MessageData) { messageStore.stub { on { getMessages<Any>(eq(SELECTION), eq(SELECTION_ARGS), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(3) runMessageMapper(messages, mapper) } } } private fun addThreadedMessages(vararg messages: MessageData) { messageStore.stub { on { getThreadedMessages<Any>(eq(SELECTION), eq(SELECTION_ARGS), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(3) runMessageMapper(messages, mapper) } } } @Suppress("SameParameterValue") private fun addMessagesToThread(threadRoot: Long, vararg messages: MessageData) { messageStore.stub { on { getThread<Any>(eq(threadRoot), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(2) runMessageMapper(messages, mapper) } } } private fun runMessageMapper(messages: Array<out MessageData>, mapper: MessageMapper<Any?>): List<Any> { return messages.mapNotNull { message -> mapper.map(object : MessageDetailsAccessor { override val id = message.messageId override val messageServerId = "irrelevant" override val folderId = message.folderId override val fromAddresses = emptyList<Address>() override val toAddresses = emptyList<Address>() override val ccAddresses = emptyList<Address>() override val messageDate = 0L override val internalDate = 0L override val subject = "irrelevant" override val preview = PreviewResult.error() override val isRead = message.isRead override val isStarred = message.isStarred override val isAnswered = message.isAnswered override val isForwarded = message.isForwarded override val hasAttachments = false override val threadRoot = message.threadRoot override val threadCount = 0 }) } } @Suppress("SameParameterValue") private fun hideMessage(messageId: Long, folderId: Long) { val cache = MessageListCache.getCache(accountUuid) val localFolder = mock<LocalFolder> { on { databaseId } doReturn folderId } val localMessage = mock<LocalMessage> { on { databaseId } doReturn messageId on { folder } doReturn localFolder } cache.hideMessages(listOf(localMessage)) } } private data class MessageData( val messageId: Long, val folderId: Long, val threadRoot: Long, val isRead: Boolean = false, val isStarred: Boolean = false, val isAnswered: Boolean = false, val isForwarded: Boolean = false, )
apache-2.0
0cabd85c0ccde57d945a7eb152470b7f
33.200924
119
0.588831
4.971131
false
false
false
false
LorittaBot/Loritta
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/views/home/ThankYou.kt
1
2174
package net.perfectdreams.loritta.cinnamon.showtime.backend.views.home import com.mrpowergamerbr.loritta.utils.locale.BaseLocale import kotlinx.html.DIV import kotlinx.html.a import kotlinx.html.div import kotlinx.html.h1 import kotlinx.html.h2 import kotlinx.html.img import kotlinx.html.p import kotlinx.html.style fun DIV.thankYou(locale: BaseLocale, sectionClassName: String) { div(classes = "$sectionClassName wobbly-bg") { style = "text-align: center;" h1 { + locale["website.home.thankYou.title"] } div(classes = "media") { div(classes = "media-figure") { img(src = "https://www.yourkit.com/images/yklogo.png") {} } div(classes = "media-body") { div { style = "text-align: left;" div { style = "text-align: center;" h2 { + "YourKit" } } p { + "YourKit supports open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of "; a(href = "https://www.yourkit.com/java/profiler/") { + "YourKit Java Profiler" }; + " and "; a(href = "https://www.yourkit.com/.net/profiler/") { + "YourKit .NET Profiler" }; + " innovative and intelligent tools for profiling Java and .NET applications." } } } } /* div(classes = "cards") { div { img(src = "https://cdn.worldvectorlogo.com/logos/kotlin-2.svg") {} } div { img(src = "https://camo.githubusercontent.com/f2e0860a3b1a34658f23a8bcea96f9725b1f8a73/68747470733a2f2f692e696d6775722e636f6d2f4f4737546e65382e706e67") {} } div { img(src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/IntelliJ_IDEA_Logo.svg/1024px-IntelliJ_IDEA_Logo.svg.png") {} } div { img(src = "https://ktor.io/assets/images/ktor_logo_white.svg") {} } } */ } }
agpl-3.0
d78d16a7d5ed4349395fd0b93d801f13
36.5
391
0.538638
3.774306
false
false
false
false
j2ghz/tachiyomi-extensions
src/all/nhentai/src/eu/kanade/tachiyomi/extension/all/nhentai/NHentaiMetadata.kt
1
954
package eu.kanade.tachiyomi.extension.all.nhentai /** * NHentai metadata */ class NHentaiMetadata { var id: Long? = null var url: String? get() = id?.let { "/g/$it" } set(a) { id = a?.substringAfterLast('/')?.toLong() } var uploadDate: Long? = null var favoritesCount: Long? = null var mediaId: String? = null var japaneseTitle: String? = null var englishTitle: String? = null var shortTitle: String? = null var coverImageType: String? = null var pageImageTypes: MutableList<String> = mutableListOf() var thumbnailImageType: String? = null var scanlator: String? = null val tags: MutableMap<String, MutableList<Tag>> = mutableMapOf() companion object { fun typeToExtension(t: String?) = when (t) { "p" -> "png" "j" -> "jpg" else -> null } } }
apache-2.0
0e19eaccc0389ac2c31a8e2fa1e27f7f
20.681818
67
0.54717
4.184211
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/DemonCommand.kt
1
1406
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.gifs.DemonGIF import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.MiscUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.morenitta.LorittaBot class DemonCommand(loritta: LorittaBot) : AbstractCommand(loritta, "demon", listOf("demônio", "demonio", "demónio"), category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.demon.description") override fun getExamplesKey() = Command.TWO_IMAGES_EXAMPLES_KEY // TODO: Fix Usage override fun needsToUploadFiles() = true override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } val file = DemonGIF.getGIF(contextImage, context.config.localeId) loritta.gifsicle.optimizeGIF(file) context.sendFile(file, "demon.gif", context.getAsMention(true)) file.delete() } }
agpl-3.0
2fda6dc993354c114565f2e895786c6f
47.448276
195
0.819088
4.057803
false
false
false
false
Nagarajj/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/memory/InMemoryQueue.kt
1
3436
/* * 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.orca.q.memory import com.netflix.spinnaker.orca.q.Message import com.netflix.spinnaker.orca.q.Queue import com.netflix.spinnaker.orca.q.ScheduledAction import org.slf4j.Logger import org.slf4j.LoggerFactory.getLogger import org.threeten.extra.Temporals.chronoUnit import java.io.Closeable import java.time.Clock import java.time.Duration import java.time.Instant import java.time.temporal.TemporalAmount import java.util.* import java.util.UUID.randomUUID import java.util.concurrent.DelayQueue import java.util.concurrent.Delayed import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import javax.annotation.PreDestroy class InMemoryQueue( private val clock: Clock, override val ackTimeout: TemporalAmount = Duration.ofMinutes(1), override val deadMessageHandler: (Queue, Message) -> Unit ) : Queue, Closeable { private val log: Logger = getLogger(javaClass) private val queue = DelayQueue<Envelope>() private val unacked = DelayQueue<Envelope>() private val redeliveryWatcher = ScheduledAction(this::redeliver) override fun poll(callback: (Message, () -> Unit) -> Unit) { queue.poll()?.let { envelope -> unacked.put(envelope.copy(scheduledTime = clock.instant().plus(ackTimeout))) callback.invoke(envelope.payload) { ack(envelope.id) } } } override fun push(message: Message, delay: TemporalAmount) = queue.put(Envelope(message, clock.instant().plus(delay), clock)) private fun ack(messageId: UUID) { unacked.removeIf { it.id == messageId } } @PreDestroy override fun close() { log.info("stopping redelivery watcher for $this") redeliveryWatcher.close() } internal fun redeliver() { unacked.pollAll { if (it.count >= Queue.maxRedeliveries) { deadMessageHandler.invoke(this, it.payload) } else { log.warn("redelivering unacked message ${it.payload}") queue.put(it.copy(scheduledTime = clock.instant(), count = it.count + 1)) } } } private fun <T : Delayed> DelayQueue<T>.pollAll(block: (T) -> Unit) { var done = false while (!done) { val value = poll() if (value == null) { done = true } else { block.invoke(value) } } } } internal data class Envelope( val id: UUID, val payload: Message, val scheduledTime: Instant, val clock: Clock, val count: Int = 1 ) : Delayed { constructor(payload: Message, scheduledTime: Instant, clock: Clock) : this(randomUUID(), payload, scheduledTime, clock) override fun compareTo(other: Delayed) = getDelay(MILLISECONDS).compareTo(other.getDelay(MILLISECONDS)) override fun getDelay(unit: TimeUnit) = clock.instant().until(scheduledTime, unit.toChronoUnit()) } private fun TimeUnit.toChronoUnit() = chronoUnit(this)
apache-2.0
8432549ee89223fda78ec1d2d9015c30
29.678571
82
0.714494
3.878104
false
false
false
false
christophpickl/kpotpourri
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/random/random.kt
1
3108
package com.github.christophpickl.kpotpourri.common.random import com.github.christophpickl.kpotpourri.common.KPotpourriException import java.lang.IllegalArgumentException /** * Random generator as an interface in order to be testable. */ interface RandX { /** * Generate a random number based on the given range (inclusive), optionally specifying an item to be excluded. */ fun randomBetween(from: Int, to: Int, except: Int? = null): Int /** * Retrieve a single element from the given list, optionally specifying an item to be excluded. */ fun <T> randomOf(items: List<T>, exceptItem: T? = null): T // fun <T> randomElementsExcept(items: List<T>, randomElementsCount: Int, except: T): List<T> } private val MAX_ITERATIONS = 9000 /** * Default implementation of RandX. */ class RandXImpl(private val generator: RandGenerator = RealRandGenerator) : RandX { override fun randomBetween(from: Int, to: Int, except: Int?): Int { if (from < 0 || to < 0) throw IllegalArgumentException("No negative values are allowed: from=$from, to=$to") if (from >= to) throw IllegalArgumentException("From must be bigger then from: from=$from, to=$to") val diff = to - from if (except == null) { return generator.rand(diff) + from } if (except < from || except > to) throw IllegalArgumentException("Except value of '$except' must be within from=$from, to=$to") var randPos: Int? var count = 0 do { randPos = generator.rand(diff) + from if (count++ >= MAX_ITERATIONS) { throw KPotpourriException("Maximum random iterations was reached! Generator: $generator") } } while (randPos == except) return randPos!! } // override fun <T> randomOf(items: List<T>) = items[randomBetween(0, items.size - 1)] override fun <T> randomOf(items: List<T>, exceptItem: T?): T { if (items.isEmpty()) throw IllegalArgumentException("list must not be empty") if (items.size == 1) return items[0] var randItem: T? var count = 0 do { randItem = items[randomBetween(0, items.size - 1)] if (count++ >= MAX_ITERATIONS) { throw KPotpourriException("Maximum random iterations was reached! Generator: $generator") } } while (randItem == exceptItem) return randItem!! } // override fun <T> randomElementsExcept(items: List<T>, randomElementsCount: Int, except: T): List<T> { // if (items.size < randomElementsCount) { // throw IllegalArgumentException("items.size [${items.size}] < randomElementsCount [$randomElementsCount]") // } // val result = mutableListOf<T>() // var honeypot = items.toMutableList().minus(except) // while (result.size != randomElementsCount) { // val randomElement = randomOf(honeypot) // result += randomElement // honeypot = honeypot.minus(randomElement) // } // return result // } // // // // }
apache-2.0
599129cbc8e35911cce8dbe70eeff600
36
135
0.622587
4.068063
false
false
false
false
SerenityEnterprises/SerenityCE
src/main/java/host/serenity/serenity/api/value/Value.kt
1
1375
package host.serenity.serenity.api.value import java.util.* interface ValueChangeListener { fun onChanged(oldValue: Any?) } abstract class Value<T>(val name: String, value: T) { val defaultValue: T = value open var value: T = value set(_value) { val oldValue = value field = _value changed(oldValue) } val changeListeners: List<ValueChangeListener> = ArrayList() private fun changed(oldValue: T) { changeListeners.forEach { it.onChanged(oldValue) } } abstract fun setValueFromString(string: String) } abstract class BoundedValue<T : Number>(name: String, value: T, var min: T, var max: T) : Value<T>(name, value) { override var value: T get() = super.value set(value) { if (isWithinBounds(value)) { super.value = value } else { if (value.toDouble() < min.toDouble()) { super.value = min } if (value.toDouble() > max.toDouble()) { super.value = max } } } fun isWithinBounds(value: T): Boolean { return value.toDouble() >= min.toDouble() && value.toDouble() <= max.toDouble() } } @Target(AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) annotation class ModuleValue
gpl-3.0
46da30a2cb94930c322d9a98ea8d5603
27.061224
113
0.573818
4.351266
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/jvmMain/kotlin/io/kotest/assertions/AssertionCounter.kt
1
520
package io.kotest.assertions actual object AssertionCounter { private val context = object : ThreadLocal<Int>() { override fun initialValue(): Int = 0 } /** * Returns the number of assertions executed in the current context. */ actual fun get(): Int = context.get() /** * Resets the count for the current context */ actual fun reset() = context.set(0) /** * Increments the counter for the current context. */ actual fun inc() = context.set(context.get() + 1) }
apache-2.0
8b30711c7a4e43c9a1fca27d7cd434d6
21.608696
71
0.632692
4.227642
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/ThatIsThenPaused/AndThePlayerIdles/WhenThePlayerWillNotPlayWhenReady.kt
1
2369
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.ThatIsThenPaused.AndThePlayerIdles import com.annimon.stream.Stream import com.google.android.exoplayer2.Player import com.lasthopesoftware.any import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import org.junit.BeforeClass import org.junit.Test import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.Mockito import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException class WhenThePlayerWillNotPlayWhenReady { companion object { private val eventListeners: MutableCollection<Player.EventListener> = ArrayList() private val mockExoPlayer = Mockito.mock(PromisingExoPlayer::class.java) @JvmStatic @BeforeClass @Throws(InterruptedException::class, ExecutionException::class) fun before() { Mockito.`when`(mockExoPlayer.setPlayWhenReady(anyBoolean())).thenReturn(mockExoPlayer.toPromise()) Mockito.`when`(mockExoPlayer.getPlayWhenReady()).thenReturn(true.toPromise()) Mockito.`when`(mockExoPlayer.getCurrentPosition()).thenReturn(50L.toPromise()) Mockito.`when`(mockExoPlayer.getDuration()).thenReturn(100L.toPromise()) Mockito.doAnswer { invocation -> eventListeners.add(invocation.getArgument(0)) mockExoPlayer.toPromise() }.`when`(mockExoPlayer).addListener(any()) val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer) val playbackPromise = exoPlayerPlaybackHandler.promisePlayback() playbackPromise .eventually { p -> val playableFilePromise = p.promisePause() Stream.of(eventListeners) .forEach { e -> e.onPlayerStateChanged(false, Player.STATE_IDLE) } playableFilePromise } val playedPromise = playbackPromise .eventually { obj -> obj.promisePlayedFile() } try { FuturePromise(playedPromise)[1, TimeUnit.SECONDS] } catch (ignored: TimeoutException) { } } } @Test fun thenPlaybackIsNotRestarted() { Mockito.verify(mockExoPlayer, Mockito.times(1)).setPlayWhenReady(true) } }
lgpl-3.0
38630d59eacba8492ad084ced2dffa26
39.844828
122
0.798227
4.307273
false
false
false
false
raniejade/kspec
kspec-engine/src/test/kotlin/io/polymorphicpanda/kspec/engine/FilterTest.kt
1
10527
package io.polymorphicpanda.kspec.engine import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.polymorphicpanda.kspec.KSpec import io.polymorphicpanda.kspec.config.KSpecConfig import io.polymorphicpanda.kspec.context import io.polymorphicpanda.kspec.context.Context import io.polymorphicpanda.kspec.describe import io.polymorphicpanda.kspec.engine.discovery.DiscoveryRequest import io.polymorphicpanda.kspec.engine.execution.ExecutionListenerAdapter import io.polymorphicpanda.kspec.engine.execution.ExecutionNotifier import io.polymorphicpanda.kspec.it import io.polymorphicpanda.kspec.tag.SimpleTag import org.junit.Test /** * @author Ranie Jade Ramiso */ class FilterTest { object Tag1: SimpleTag() object Tag2: SimpleTag() object Tag3: SimpleTag() @Test fun testIncludeExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class IncludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.include(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(IncludeSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testIncludeExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class IncludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.include(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(IncludeSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testExcludeExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class ExcludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.exclude(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(ExcludeSpec::class), KSpecConfig(), null)) val expected = """ it: example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testExcludeExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class ExcludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.exclude(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(ExcludeSpec::class), KSpecConfig(), null)) val expected = """ it: example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testMatchExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testMatchExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testNoMatch() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context") { it("another example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig())) val expected = """ it: example it: another example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testFilterPrecedence() { /** * The order filters are applied is: * 1. Match * 2. Include * 3. Exclude */ val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class FilterSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) config.filter.include(Tag2::class) config.filter.exclude(Tag3::class) } override fun spec() { describe("group") { it("first included example", Tag1) { /** * not executed, has match filter but not include filter tag */ } it("unmatched example", Tag2) { } context("matched context", Tag1) { it("excluded example", Tag3) { } it ("included example", Tag2) { /** * Executed as parent has match filter and example has include tag */ } describe("included group", Tag2) { it ("some example") { /** * Executed as parent has include filter tag */ } } } } } } val result = engine.discover(DiscoveryRequest(listOf(FilterSpec::class), KSpecConfig())) val expected = """ it: included example it: some example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } }
mit
b6192841a1c40e055ee78fbdc7bb68cb
27.22252
103
0.525791
5.423493
false
true
false
false
alessio-b-zak/myRivers
android/app/src/main/java/com/epimorphics/android/myrivers/fragments/WIMSDetailsFragment.kt
1
8766
package com.epimorphics.android.myrivers.fragments import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.widget.Toolbar import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageButton import android.widget.TableLayout import android.widget.TextView import com.epimorphics.android.myrivers.R import com.epimorphics.android.myrivers.activities.DataViewActivity import com.epimorphics.android.myrivers.data.Measurement import com.epimorphics.android.myrivers.data.WIMSPoint import com.epimorphics.android.myrivers.helpers.FragmentHelper /** * A fragment occupying full screen showcasing all the data stored inside a WIMSPoint. * It is initiated by clicking a "More Info" button in WIMSDataFragment * * @see <a href="https://github.com/alessio-b-zak/myRivers/blob/master/graphic%20assets/screenshots/wims_details_view.png">Screenshot</a> * @see WIMSDataFragment */ open class WIMSDetailsFragment : FragmentHelper() { private lateinit var mDataViewActivity: DataViewActivity private lateinit var mWIMSDetailsFragment: WIMSDetailsFragment private lateinit var mWIMSDetailsView: View private lateinit var mToolbar: Toolbar private lateinit var mBackButton: ImageButton private lateinit var mFullReportButton: Button private lateinit var mGeneralTable: TableLayout private lateinit var mDissolvedOxygenTable: TableLayout private lateinit var mOxygenDemandTable: TableLayout private lateinit var mNitratesTable: TableLayout private lateinit var mPhosphatesTable: TableLayout private lateinit var mMetalsTable: TableLayout private lateinit var mSolidsTable: TableLayout private val TAG = "WIMS_DETAILS_FRAGMENT" private val URL_PREFIX = "http://environment.data.gov.uk/water-quality/view/sampling-point/" /** * Called when a fragment is created. Initiates mDataViewActivity * * @param savedInstanceState Saved state of the fragment */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true mDataViewActivity = activity as DataViewActivity } /** * Called when a fragment view is created. Initiates and manipulates all required layout elements. * * @param inflater LayoutInflater * @param container ViewGroup * @param savedInstanceState Saved state of the fragment * * @return inflated and fully populated View */ override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_wims_details_view, container, false) mWIMSDetailsView = view mWIMSDetailsFragment = this mGeneralTable = view.bind(R.id.wims_details_general_table) mDissolvedOxygenTable = view.bind(R.id.wims_details_diss_oxygen_table) mOxygenDemandTable = view.bind(R.id.wims_details_oxygen_demand_table) mNitratesTable = view.bind(R.id.wims_details_nitrates_table) mPhosphatesTable = view.bind(R.id.wims_details_phosphates_table) mMetalsTable = view.bind(R.id.wims_details_metals_table) mSolidsTable = view.bind(R.id.wims_details_solids_table) val wimsPoint = mDataViewActivity.selectedWIMSPoint val wimsPointLabel: TextView = view.bind(R.id.wims_details_title) // If wimsPoint.label is not null show wimsPoint.label as name, otherwise show wimsPoint.id wimsPointLabel.text = if(wimsPoint.label != null) "Samples from ${wimsPoint.label}" else "Samples from ${wimsPoint.id}" mToolbar = view.bind(R.id.wims_details_toolbar) // Links to the WIMS web view mFullReportButton = view.bind(R.id.wims_full_report_button) mFullReportButton.setOnClickListener { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.addCategory(Intent.CATEGORY_BROWSABLE) intent.data = Uri.parse(URL_PREFIX + wimsPoint.id) startActivity(intent) } mBackButton = view.bind(R.id.back_button_wims_details_view) mBackButton.setOnClickListener { activity.onBackPressed() } populateData(wimsPoint) return view } /** * Populates data into the data tables * * @param wimsPoint WIMSPoint containing data to be populated */ fun populateData(wimsPoint: WIMSPoint) { val groupList = arrayListOf<String>("general", "diss_oxygen", "oxygen_demand", "nitrates", "phosphates", "metals", "solids") var emptyGroupCount = 0 // Loops through all the measurement groups and populates the data for (group in groupList) { var groupDeterminandList: ArrayList<String> var groupTable: TableLayout val groupTitle: TextView = mWIMSDetailsView.bind(resources.getIdentifier( "wims_details_" + group + "_title", "id", mDataViewActivity.packageName)) when (group) { "general" -> { groupDeterminandList = WIMSPoint.generalGroup groupTable = mGeneralTable } "diss_oxygen" -> { groupDeterminandList = WIMSPoint.dissolvedOxygenGroup groupTable = mDissolvedOxygenTable } "oxygen_demand" -> { groupDeterminandList = WIMSPoint.oxygenDemandGroup groupTable = mOxygenDemandTable } "nitrates" -> { groupDeterminandList = WIMSPoint.nitrateGroup groupTable = mNitratesTable } "phosphates" -> { groupDeterminandList = WIMSPoint.phosphateGroup groupTable = mPhosphatesTable } "solids" -> { groupDeterminandList = WIMSPoint.solidGroup groupTable = mSolidsTable } else -> { // metals val filterMap = wimsPoint.measurementMap.filterKeys { key: String -> !WIMSPoint.nonMetalGroup.contains(key) } groupDeterminandList = ArrayList(filterMap.keys) groupTable = mMetalsTable } } val groupHasRecords = wimsPoint.measurementMap.any { entry: Map.Entry<String, ArrayList<Measurement>> -> groupDeterminandList.contains(entry.key) } if (groupHasRecords) { var rowIndex = 0 // Set Header Row var tableHeaderRow = newTableRow(rowIndex++) addTextView(tableHeaderRow, "Determinand", 0.3, R.style.text_view_table_parent, Gravity.START) addTextView(tableHeaderRow, "Unit", 0.2, R.style.text_view_table_parent) addTextView(tableHeaderRow, "Result", 0.2, R.style.text_view_table_parent) addTextView(tableHeaderRow, "Date", 0.3, R.style.text_view_table_parent) groupTable.addView(tableHeaderRow) for (entry: String in groupDeterminandList) { if (wimsPoint.measurementMap.containsKey(entry)) { tableHeaderRow = newTableRow(rowIndex++) addTextView(tableHeaderRow, entry, 0.3, R.style.text_view_table_child, Gravity.START, 0, wimsPoint.measurementMap[entry]!![0].descriptor) addTextView(tableHeaderRow, wimsPoint.measurementMap[entry]!![0].unit, 0.2, R.style.text_view_table_child) addTextView(tableHeaderRow, wimsPoint.measurementMap[entry]!![0].result.toString(), 0.2, R.style.text_view_table_child) addTextView(tableHeaderRow, simplifyDate(wimsPoint.measurementMap[entry]!![0].date), 0.3, R.style.text_view_table_child) groupTable.addView(tableHeaderRow) } } } else { groupTitle.visibility = View.GONE groupTable.visibility = View.GONE emptyGroupCount++ } } // If there is not data show an info message pointing out the "Detailed Report" button available if (groupList.size == emptyGroupCount) { val noDataExplanation: TextView = mWIMSDetailsView.bind(R.id.wims_details_no_data) noDataExplanation.visibility = View.VISIBLE } } }
mit
dd38cd8dfd331c172d5b5187487194dc
42.40099
161
0.64271
4.685195
false
false
false
false
chat-sdk/chat-sdk-android
chat-sdk-vendor/src/main/java/smartadapter/viewevent/swipe/BasicSwipeEventBinder.kt
1
3413
package smartadapter.viewevent.swipe /* * Created by Manne Öhlund on 2019-08-15. * Copyright (c) All rights reserved. */ import android.graphics.Canvas import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import smartadapter.SmartRecyclerAdapter import smartadapter.SmartViewHolderType import smartadapter.viewevent.model.ViewEvent import smartadapter.viewevent.viewholder.OnItemSwipedListener import smartadapter.viewholder.SmartViewHolder import kotlin.math.abs /** * The basic implementation of [SwipeEventBinder]. * * @see SwipeEventBinder */ open class BasicSwipeEventBinder( override val identifier: Any = BasicSwipeEventBinder::class, override var longPressDragEnabled: Boolean = false, override var swipeFlags: SwipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT, override var viewHolderTypes: List<SmartViewHolderType> = listOf(SmartViewHolder::class), override var eventListener: (ViewEvent.OnItemSwiped) -> Unit ) : SwipeEventBinder() { override lateinit var smartRecyclerAdapter: SmartRecyclerAdapter override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { var swipeFlags = 0 for (viewHolderType in viewHolderTypes) { if (viewHolderType.java.isAssignableFrom(viewHolder.javaClass)) { swipeFlags = this.swipeFlags break } } return makeMovementFlags(0, swipeFlags) } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { if (viewHolder is OnItemSwipedListener) { viewHolder.onItemSwiped( ViewEvent.OnItemSwiped( smartRecyclerAdapter, viewHolder as SmartViewHolder<*>, viewHolder.adapterPosition, viewHolder.itemView, direction ) ) } eventListener.invoke( ViewEvent.OnItemSwiped( smartRecyclerAdapter, viewHolder as SmartViewHolder<*>, viewHolder.adapterPosition, viewHolder.itemView, direction ) ) } override fun isLongPressDragEnabled(): Boolean = longPressDragEnabled override fun onChildDraw( canvas: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val alpha = 1 - abs(dX) / recyclerView.width viewHolder.itemView.alpha = alpha } super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } override fun bind( smartRecyclerAdapter: SmartRecyclerAdapter, recyclerView: RecyclerView ): BasicSwipeEventBinder { this.smartRecyclerAdapter = smartRecyclerAdapter val touchHelper = ItemTouchHelper(this) touchHelper.attachToRecyclerView(recyclerView) return this } }
apache-2.0
589fb53d1d445f7bee2af4e3a3ce2560
31.495238
99
0.661196
5.529984
false
false
false
false
consp1racy/android-commons
commons-dimen/src/main/java/net/xpece/android/content/res/Dimen.kt
1
1718
package net.xpece.android.content.res import android.content.Context /** * Created by pechanecjr on 4. 1. 2015. */ data class Dimen internal constructor(val value: Float) : Comparable<Dimen> { override fun compareTo(other: Dimen): Int = this.value.compareTo(other.value) operator fun plus(that: Dimen): Dimen = Dimen( this.value + that.value) operator fun minus(that: Dimen): Dimen = Dimen( this.value - that.value) operator fun plus(that: Number): Dimen = Dimen( this.value + that.toFloat()) operator fun minus(that: Number): Dimen = Dimen( this.value - that.toFloat()) operator fun unaryMinus() = Dimen(-this.value) operator fun unaryPlus() = Dimen(this.value) operator fun times(q: Number) = Dimen(this.value * q.toFloat()) operator fun div(d: Number) = Dimen(this.value / d.toFloat()) operator fun div(d: Dimen) = this.value / d.value val pixelSize: Int get() { val res = (value + 0.5F).toInt() if (res != 0) return res if (value == 0F) return 0 if (value > 0) return 1 return -1 } val pixelOffset: Int get() = value.toInt() override fun toString(): String = "Dimen(${value}px)" /** * Along px prints also dp and sp values according to provided context. */ fun toString(context: Context): String { val density = context.resources.displayMetrics.density val dp = Math.round(value / density) val scaledDensity = context.resources.displayMetrics.scaledDensity val sp = Math.round(value / scaledDensity) return "Dimen(${value}px ~ ${dp}dp ~ ${sp}sp)" } }
apache-2.0
c25cc4da20452c5c6d063b50690bc64e
29.140351
81
0.611176
3.976852
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/entities/factories/EntityFactory.kt
1
44718
package ru.icarumbas.bagel.engine.entities.factories import com.badlogic.ashley.core.Entity import com.badlogic.ashley.utils.ImmutableArray import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.maps.MapObject import com.badlogic.gdx.maps.objects.PolylineMapObject import com.badlogic.gdx.maps.objects.RectangleMapObject import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.BodyDef import com.badlogic.gdx.utils.Array import ru.icarumbas.bagel.engine.components.other.* import ru.icarumbas.bagel.engine.components.physics.BodyComponent import ru.icarumbas.bagel.engine.components.physics.InactiveMarkerComponent import ru.icarumbas.bagel.engine.components.physics.StaticComponent import ru.icarumbas.bagel.engine.components.physics.WeaponComponent import ru.icarumbas.bagel.engine.components.velocity.FlyComponent import ru.icarumbas.bagel.engine.components.velocity.JumpComponent import ru.icarumbas.bagel.engine.components.velocity.RunComponent import ru.icarumbas.bagel.engine.components.velocity.TeleportComponent import ru.icarumbas.bagel.engine.entities.EntityState import ru.icarumbas.bagel.engine.resources.ResourceManager import ru.icarumbas.bagel.engine.systems.physics.WeaponSystem import ru.icarumbas.bagel.engine.world.PIX_PER_M import ru.icarumbas.bagel.utils.* import ru.icarumbas.bagel.view.renderer.components.* import kotlin.experimental.or class EntityFactory( private val bodyFactory: BodyFactory, private val animationFactory: AnimationFactory, private val assets: ResourceManager ) { fun swingWeaponEntity(width: Int, height: Int, mainBody: Body, anchorA: Vector2, anchorB: Vector2, speed: Float, maxSpeed: Float): Entity { return Entity().apply { add(BodyComponent(bodyFactory.swordWeapon( categoryBit = WEAPON_BIT, maskBit = AI_BIT or BREAKABLE_BIT or PLAYER_BIT, size = Vector2(width / PIX_PER_M, height / PIX_PER_M)) .createRevoluteJoint(mainBody, anchorA, anchorB, maxSpeed, speed))) add(InactiveMarkerComponent()) }.also { body[it].body.userData = it } } fun playerEntity(): Entity { val playerBody = bodyFactory.playerBody() val weaponAtlas = assets.getTextureAtlas("Packs/weapons.pack") val playerAtlas = assets.getTextureAtlas("Packs/GuyKnight.pack") return Entity() .add(TextureComponent()) .add(PlayerComponent(0)) .add(RunComponent(acceleration = .4f, maxSpeed = 6f)) .add(SizeComponent(Vector2(50 / PIX_PER_M, 105 / PIX_PER_M), .425f)) .add(JumpComponent(jumpVelocity = 1.5f, maxJumps = 5)) .add(HealthComponent( HP = 100, canBeDamagedTime = 1f)) .add(BodyComponent(playerBody)) .add(EquipmentComponent()) .add(WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( width = 30, height = 100, mainBody = playerBody, anchorA = Vector2(0f, -.2f), anchorB = Vector2(0f, -1f), speed = 5f, maxSpeed = 3f) .add(AlwaysRenderingMarkerComponent()) .add(TextureComponent(weaponAtlas.findRegion("eyes_sword"))) .add((TranslateComponent())) .add(SizeComponent(Vector2(30 / PIX_PER_M, 150 / PIX_PER_M), .1f)), entityRight = swingWeaponEntity( width = 30, height = 100, mainBody = playerBody, anchorA = Vector2(0f, -.2f), anchorB = Vector2(0f, -.8f), speed = -5f, maxSpeed = 3f) .add(AlwaysRenderingMarkerComponent()) .add((TranslateComponent())) .add(TextureComponent(weaponAtlas.findRegion("eyes_sword"))) .add(SizeComponent(Vector2(30 / PIX_PER_M, 150 / PIX_PER_M), .1f)))) .add(StateComponent(ImmutableArray(Array.with( EntityState.RUNNING, EntityState.JUMPING, EntityState.STANDING, EntityState.ATTACKING, EntityState.DEAD, EntityState.WALKING, EntityState.JUMP_ATTACKING )))) .add(AnimationComponent(hashMapOf( EntityState.RUNNING to animationFactory.create("Run", 10, .075f, playerAtlas), EntityState.JUMPING to animationFactory.create("Jump", 10, .15f, playerAtlas), EntityState.STANDING to animationFactory.create("Idle", 10, .1f, playerAtlas), EntityState.DEAD to animationFactory.create("Dead", 10, .1f, playerAtlas, Animation.PlayMode.NORMAL), EntityState.ATTACKING to animationFactory.create("Attack", 7, .075f, playerAtlas), EntityState.WALKING to animationFactory.create("Walk", 10, .075f, playerAtlas), EntityState.JUMP_ATTACKING to animationFactory.create("JumpAttack", 10, .075f, playerAtlas) ))) .add(AlwaysRenderingMarkerComponent()) .add(AttackComponent(strength = 15, knockback = Vector2(1.5f, 1f))) .add((TranslateComponent())) .also { body[it].body.userData = it } } fun groundEntity(obj: MapObject, bit: Short): Entity{ return Entity() .add(when (obj) { is RectangleMapObject -> { BodyComponent(bodyFactory.rectangleMapObjectBody( obj.rectangle, BodyDef.BodyType.StaticBody, obj.rectangle.width / PIX_PER_M, obj.rectangle.height / PIX_PER_M, bit)) } is PolylineMapObject -> { BodyComponent(bodyFactory.polylineMapObjectBody( obj, BodyDef.BodyType.StaticBody, bit)) } else -> throw IllegalArgumentException("Cant create ${obj.name} object") }) } fun lootEntity(r: Int, point: Pair<Float,Float>, roomId: Int, playerEntity: Entity): Entity{ val atlas = assets.getTextureAtlas("weapons.pack") val loot = Entity() .add(SizeComponent(Vector2(30 / PIX_PER_M, 100 / PIX_PER_M), 1.5f)) .add(TextureComponent(atlas.findRegion("sword1"))) .add((TranslateComponent(point.first - 15 / PIX_PER_M, point.second))) .add(LootComponent(arrayListOf( WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( width = 30, height = 100, mainBody = body[playerEntity].body, anchorA = Vector2(0f, -.2f), anchorB = Vector2(0f, -1f), speed = 5f, maxSpeed = 3f) .add(AlwaysRenderingMarkerComponent()) .add((TranslateComponent())) .add(SizeComponent(Vector2(5 / PIX_PER_M, 100 / PIX_PER_M), 2f)) .add(TextureComponent(atlas.findRegion("sword1"))), entityRight = swingWeaponEntity( width = 30, height = 100, mainBody = body[playerEntity].body, anchorA = Vector2(0f, -.2f), anchorB = Vector2(0f, -.8f), speed = -5f, maxSpeed = 3f) .add(AlwaysRenderingMarkerComponent()) .add((TranslateComponent())) .add(TextureComponent(atlas.findRegion("sword1"))) .add(SizeComponent(Vector2(5 / PIX_PER_M, 100 / PIX_PER_M), 2f)) ), AttackComponent(strength = 30, knockback = Vector2(2f, 2f)) ))) loot.add(RoomIdComponent(roomId)) // loot.add(ShaderComponent(ShaderProgram(FileHandle("Shaders/bleak.vert"), FileHandle("Shaders/bleak.frag")))) return loot } fun idMapObjectEntity(roomId: Int, rect: Rectangle, objectPath: String, r: Int, playerEntity: Entity): Entity? { val atlas = assets.getTextureAtlas("Packs/items.pack") return when(objectPath){ "vase" -> { val size = when (r) { 1 -> Pair(132, 171) 2 -> Pair(65, 106) 3 -> Pair(120, 162) 4 -> Pair(98, 72) else -> return null } Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, size.first / PIX_PER_M, size.second / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(SizeComponent(Vector2(size.first / PIX_PER_M, size.second / PIX_PER_M))) .add(TextureComponent(atlas.findRegion("Vase ($r)"))) } "window" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 86 / PIX_PER_M, 169 / PIX_PER_M, STATIC_BIT, WEAPON_BIT))) .add(SizeComponent(Vector2(86 / PIX_PER_M, 169 / PIX_PER_M))) .add(TextureComponent(atlas.findRegion("Window Small ($r)"))) } "chair1" -> { if (r == 2) return null Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 70 / PIX_PER_M, 128 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(SizeComponent(Vector2(70 / PIX_PER_M, 128 / PIX_PER_M))) .add(TextureComponent(atlas.findRegion("Chair (1)"))) } "chair2" -> { if (r == 2) return null Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 70 / PIX_PER_M, 128 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(SizeComponent(Vector2(70 / PIX_PER_M, 128 / PIX_PER_M))) .add(TextureComponent(atlas.findRegion("Chair (2)"))) } "table" -> { if (r == 2) return null Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 137 / PIX_PER_M, 69 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(SizeComponent(Vector2(137 / PIX_PER_M, 69 / PIX_PER_M))) .add(TextureComponent(atlas.findRegion("Table"))) } "chandelier" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 243 / PIX_PER_M, 120 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(AnimationComponent(hashMapOf(EntityState.STANDING to animationFactory.create("Chandelier", 4, .125f, atlas)))) .add(StateComponent( ImmutableArray(Array.with(EntityState.STANDING)), MathUtils.random() )) .add(SizeComponent(Vector2(243 / PIX_PER_M, 120 / PIX_PER_M))) .add(TextureComponent()) } "candle" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 178 / PIX_PER_M, 208 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(AnimationComponent(hashMapOf(EntityState.STANDING to animationFactory.create("Candle", 4, .125f, atlas)))) .add(StateComponent( ImmutableArray(Array.with(EntityState.STANDING)), MathUtils.random() )) .add(SizeComponent(Vector2(178 / PIX_PER_M, 208 / PIX_PER_M))) .add(TextureComponent()) } "smallBanner" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 126 / PIX_PER_M, 180 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(SizeComponent(Vector2(126 / PIX_PER_M, 180 / PIX_PER_M))) .add(HealthComponent(5)) .add(TextureComponent(atlas.findRegion("Banner ($r)"))) } "chest" -> { if (r == 2) return null Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 96 / PIX_PER_M, 96 / PIX_PER_M, KEY_OPEN_BIT, PLAYER_BIT))) .add(SizeComponent(Vector2(96 / PIX_PER_M, 96 / PIX_PER_M))) .add(AnimationComponent(hashMapOf( EntityState.STANDING to animationFactory.create("Chest", 1, .125f, atlas), EntityState.OPENING to animationFactory.create("Chest", 4, .125f, atlas)))) .add(StateComponent( ImmutableArray(Array.with(EntityState.STANDING, EntityState.OPENING)), 0f )) .add(TextureComponent(atlas.findRegion("Chest (1)"))) .add(OpenComponent()) } "door" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, 170 / PIX_PER_M, 244 / PIX_PER_M, KEY_OPEN_BIT, PLAYER_BIT))) .add(SizeComponent(Vector2(170 / PIX_PER_M, 244 / PIX_PER_M))) .add(AnimationComponent( if (r == 1) { hashMapOf( EntityState.STANDING to animationFactory.create("IronDoor", 1, .125f, atlas), EntityState.OPENING to animationFactory.create("IronDoor", 4, .125f, atlas) ) } else { hashMapOf( EntityState.STANDING to animationFactory.create("Wood Door", 1, .125f, atlas), EntityState.OPENING to animationFactory.create("Wood Door", 4, .125f, atlas) ) } )) .add(StateComponent( ImmutableArray(Array.with(EntityState.STANDING, EntityState.OPENING)), 0f )) .add(TextureComponent()) .add(OpenComponent()) .add(DoorComponent()) } "crateBarrel" -> { if (r == 3) return null Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.StaticBody, if (r == 1) 106 / PIX_PER_M else 119 / PIX_PER_M, if (r == 1) 106 / PIX_PER_M else 133 / PIX_PER_M, BREAKABLE_BIT, WEAPON_BIT))) .add(HealthComponent(5)) .add(SizeComponent(Vector2( if (r == 1) 106 / PIX_PER_M else 119 / PIX_PER_M, if (r == 1) 106 / PIX_PER_M else 133 / PIX_PER_M))) .add(TextureComponent(atlas.findRegion(if (r == 1) "Crate" else "Barrel"))) } "flyingEnemy" -> { when (r) { 1 -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.DynamicBody, 64 / PIX_PER_M, 64 / PIX_PER_M, AI_BIT, PLAYER_BIT or WEAPON_BIT, true, 0f))) .add(HealthComponent(roomId + 20)) .add(AnimationComponent(hashMapOf( EntityState.STANDING to Animation( .1f, assets.getTextureAtlas("Packs/Enemies/MiniDragon.pack") .findRegions("miniDragon"), Animation.PlayMode.LOOP) ))) .add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING)))) .add(AIComponent(refreshSpeed = MathUtils.random(.2f, .3f), attackDistance = 1f, entityTarget = playerEntity)) .add(SizeComponent(Vector2(64 / PIX_PER_M, 64 / PIX_PER_M), .15f)) .add(AttackComponent(strength = roomId + 15, knockback = Vector2(2f, 2f))) .add(TextureComponent()) .add(FlyComponent(.005f)) } else -> return null } } "groundEnemy" -> { when (r) { 1 -> { val skeletonAtlas = assets.getTextureAtlas("Packs/Enemies/Skeleton.pack") val body = bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.DynamicBody, 85 / PIX_PER_M, 192 / PIX_PER_M, AI_BIT, WEAPON_BIT or GROUND_BIT or PLATFORM_BIT) Entity() .add(BodyComponent(body)) .add(HealthComponent(roomId + 40)) .add(AnimationComponent(hashMapOf( EntityState.STANDING to Animation( .125f, skeletonAtlas.findRegions("idle"), Animation.PlayMode.LOOP), EntityState.ATTACKING to Animation( .125f, skeletonAtlas.findRegions("hit"), Animation.PlayMode.LOOP), EntityState.DEAD to Animation( .125f, skeletonAtlas.findRegions("die"), Animation.PlayMode.NORMAL), EntityState.APPEARING to Animation( .1f, skeletonAtlas.findRegions("appear"), Animation.PlayMode.LOOP), EntityState.WALKING to Animation( .125f, skeletonAtlas.findRegions("go"), Animation.PlayMode.LOOP)) )) .add(StateComponent( ImmutableArray(Array.with( EntityState.STANDING, EntityState.ATTACKING, EntityState.DEAD, EntityState.APPEARING, EntityState.WALKING)) )) .add(RunComponent(.25f, 1f)) .add(AIComponent(refreshSpeed = MathUtils.random(.2f, .3f), attackDistance = 1f, entityTarget = playerEntity)) .add(SizeComponent(Vector2(180 / PIX_PER_M, 230 / PIX_PER_M), 1f)) .add(WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( 35, 135, body, Vector2(0f, -.3f), Vector2(0f, -.5f), speed = 4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)), entityRight = swingWeaponEntity( 35, 135, body, Vector2(0f, -.3f), Vector2(0f, -.5f), speed = -4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)))) .add(AttackComponent(strength = roomId + 15, knockback = Vector2(2.5f, 2.5f))) .add(TextureComponent()) } 2 -> { val golemAtlas = assets.getTextureAtlas("Packs/Enemies/Golem.pack") val body = bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.DynamicBody, 230 / PIX_PER_M, 230 / PIX_PER_M, AI_BIT, WEAPON_BIT or GROUND_BIT or PLATFORM_BIT) Entity() .add(BodyComponent(body)) .add(HealthComponent(roomId + 80)) .add(AnimationComponent(hashMapOf( EntityState.STANDING to Animation( .125f, golemAtlas.findRegions("idle"), Animation.PlayMode.LOOP), EntityState.ATTACKING to Animation( .125f, golemAtlas.findRegions("hit"), Animation.PlayMode.LOOP), EntityState.DEAD to Animation( .15f, golemAtlas.findRegions("die"), Animation.PlayMode.NORMAL), EntityState.APPEARING to Animation( .1f, golemAtlas.findRegions("appear"), Animation.PlayMode.LOOP), EntityState.WALKING to Animation( .1f, golemAtlas.findRegions("idle"), Animation.PlayMode.LOOP)) )) .add(StateComponent( ImmutableArray(Array.with( EntityState.STANDING, EntityState.ATTACKING, EntityState.DEAD, EntityState.APPEARING, EntityState.WALKING)) )) .add(RunComponent(.5f, .5f)) .add(AIComponent(refreshSpeed = MathUtils.random(.45f, .55f), attackDistance = 2f, entityTarget = playerEntity)) .add(SizeComponent(Vector2(230 / PIX_PER_M, 230 / PIX_PER_M), 1f)) .add(WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( 50, 215, body, Vector2(0f, -.3f), Vector2(0f, -1f), speed = 4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)), entityRight = swingWeaponEntity( 50, 215, body, Vector2(0f, -.3f), Vector2(0f, -1f), speed = -4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)))) .add(AttackComponent(strength = roomId + 25, knockback = Vector2(3.5f, 3.5f))) .add(TextureComponent()) } 3 -> { val zombieAtlas = assets.getTextureAtlas("Packs/Enemies/Zombie.pack") val body = bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.DynamicBody, 85 / PIX_PER_M, 192 / PIX_PER_M, AI_BIT, WEAPON_BIT or GROUND_BIT or PLATFORM_BIT or SHARP_BIT) Entity() .add(BodyComponent(body)) .add(HealthComponent(roomId + 30)) .add(AnimationComponent(hashMapOf( EntityState.STANDING to Animation( .125f, zombieAtlas.findRegions("idle"), Animation.PlayMode.LOOP), EntityState.ATTACKING to Animation( .125f, zombieAtlas.findRegions("hit"), Animation.PlayMode.LOOP), EntityState.DEAD to Animation( .125f, zombieAtlas.findRegions("die"), Animation.PlayMode.NORMAL), EntityState.APPEARING to Animation( .1f, zombieAtlas.findRegions("appear"), Animation.PlayMode.LOOP), EntityState.WALKING to Animation( .075f, zombieAtlas.findRegions("go"), Animation.PlayMode.LOOP)) )) .add(StateComponent( ImmutableArray(Array.with( EntityState.STANDING, EntityState.ATTACKING, EntityState.DEAD, EntityState.APPEARING, EntityState.WALKING)) )) .add(RunComponent(.25f, 2f)) .add(AIComponent(refreshSpeed = MathUtils.random(.1f, .2f), attackDistance = 1f, entityTarget = playerEntity)) .add(SizeComponent(Vector2(125 / PIX_PER_M, 202 / PIX_PER_M), 1f)) .add(WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( 35, 110, body, Vector2(0f, -.3f), Vector2(0f, -.5f), speed = 4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)), entityRight = swingWeaponEntity( 35, 110, body, Vector2(0f, -.3f), Vector2(0f, -.5f), speed = -4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)))) .add(AttackComponent(strength = roomId + 10, knockback = Vector2(2.5f, 2.5f))) .add(TextureComponent()) } 4 -> { val vampAtlas = assets.getTextureAtlas("Packs/Enemies/Vamp.pack") val body = bodyFactory.rectangleMapObjectBody( rect, BodyDef.BodyType.DynamicBody, 85 / PIX_PER_M, 192 / PIX_PER_M, AI_BIT, WEAPON_BIT or GROUND_BIT or PLATFORM_BIT or SHARP_BIT) Entity() .add(BodyComponent(body)) .add(HealthComponent(roomId + 20)) .add(AnimationComponent(hashMapOf( EntityState.STANDING to Animation( .125f, vampAtlas.findRegions("go"), Animation.PlayMode.LOOP), EntityState.ATTACKING to Animation( .125f, vampAtlas.findRegions("hit"), Animation.PlayMode.LOOP), EntityState.DEAD to Animation( .125f, vampAtlas.findRegions("appear"), Animation.PlayMode.NORMAL), EntityState.APPEARING to Animation( .1f, vampAtlas.findRegions("appear").apply { reverse() }, Animation.PlayMode.LOOP), EntityState.WALKING to Animation( .1f, vampAtlas.findRegions("go"), Animation.PlayMode.LOOP), EntityState.DISAPPEARING to Animation( .1f, vampAtlas.findRegions("appear"), Animation.PlayMode.LOOP)) )) .add(StateComponent( ImmutableArray(Array.with( EntityState.STANDING, EntityState.ATTACKING, EntityState.DEAD, EntityState.APPEARING, EntityState.WALKING, EntityState.DISAPPEARING)) )) .add(RunComponent(.225f, .75f)) .add(AIComponent(refreshSpeed = MathUtils.random(.7f, 1f), attackDistance = 2f, entityTarget = playerEntity)) .add(SizeComponent(Vector2(85 / PIX_PER_M, 202 / PIX_PER_M), 1f)) .add(WeaponComponent( type = WeaponSystem.WeaponType.SWING, entityLeft = swingWeaponEntity( 35, 220, body, Vector2(0f, -.3f), Vector2(0f, -1f), speed = 4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)), entityRight = swingWeaponEntity( 35, 220, body, Vector2(0f, -.3f), Vector2(0f, -1f), speed = -4f, maxSpeed = 2f) .add(RoomIdComponent(roomId)))) .add(TeleportComponent()) .add(AttackComponent(strength = roomId + 15, knockback = Vector2(1.5f, 1.5f))) .add(TextureComponent()) } else -> return null } } else -> throw IllegalArgumentException("Cant create object with objectPath = $objectPath") }.apply { add(TranslateComponent()) add(RoomIdComponent(roomId)) }.also { body[it].body.userData = it } } fun staticMapObjectEntity(roomPath: String, objectPath: String, atlas: TextureAtlas, obj: MapObject): Entity{ return when(objectPath){ "spikes" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( (obj as RectangleMapObject).rectangle, BodyDef.BodyType.StaticBody, 64 / PIX_PER_M, 64 / PIX_PER_M, SHARP_BIT, PLAYER_BIT or AI_BIT))) .add(SizeComponent(Vector2(64 / PIX_PER_M, 64 / PIX_PER_M), .5f)) .add(AttackComponent(15, Vector2(0f, .05f))) .add(TextureComponent(atlas.findRegion("Spike"))) .add((TranslateComponent())) } "lighting" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( (obj as RectangleMapObject).rectangle, BodyDef.BodyType.StaticBody, 98 / PIX_PER_M, 154 / PIX_PER_M, STATIC_BIT, -1))) .add(AnimationComponent(hashMapOf(EntityState.STANDING to animationFactory.create("Lighting", 4, .125f, atlas)))) .add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING)), MathUtils.random())) .add(SizeComponent(Vector2(98 / PIX_PER_M, 154 / PIX_PER_M))) .add(TextureComponent()) .add((TranslateComponent())) } "torch" -> { Entity() .add(BodyComponent(bodyFactory.rectangleMapObjectBody( (obj as RectangleMapObject).rectangle, BodyDef.BodyType.StaticBody, 178 / PIX_PER_M, 116 / PIX_PER_M, STATIC_BIT, -1))) .add(AnimationComponent(hashMapOf(EntityState.STANDING to animationFactory.create("Torch", 4, .125f, atlas)))) .add(StateComponent(ImmutableArray(Array.with(EntityState.STANDING)), MathUtils.random())) .add(SizeComponent(Vector2(178 / PIX_PER_M, 116 / PIX_PER_M))) .add(TextureComponent()) .add((TranslateComponent())) } "ground" -> groundEntity(obj, GROUND_BIT) "platform" -> { groundEntity(obj, PLATFORM_BIT) .add(SizeComponent(Vector2( (obj as RectangleMapObject).rectangle.width / PIX_PER_M, obj.rectangle.height / PIX_PER_M))) .add((TranslateComponent())) } else -> throw IllegalArgumentException("Cant create object with objectPath = $objectPath") } .add(StaticComponent(roomPath)) .also { body[it].body.userData = it } } }
apache-2.0
449cebf871e17ce79379f25f9dde14ac
50.997674
144
0.365759
6.190199
false
false
false
false
rowysock/codecov2discord
src/main/kotlin/com/wabadaba/codecov2discord/MainController.kt
1
3792
package com.wabadaba.codecov2discord import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.client.HttpComponentsClientHttpRequestFactory import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.client.RestTemplate import java.math.BigDecimal import java.math.RoundingMode @Suppress("unused") @RestController class MainController { @Autowired lateinit var mapper: ObjectMapper val logger = LoggerFactory.getLogger(this::class.java) private val iconUrl = "https://chocolatey.org/content/packageimages/codecov.1.0.1.png" @RequestMapping("/discord-webhook/{id}/{token}") fun test( @PathVariable id: String, @PathVariable token: String, @RequestBody bodyString: String ) { logger.info(bodyString) val body = mapper.readValue(bodyString, CodecovWebhook::class.java) val template = RestTemplate(HttpComponentsClientHttpRequestFactory()) val author = DiscordWebhook.Embed.Author(body.head.author.username) val commitIdShort = body.head.commitid.substring(0, 6) val description = "[`$commitIdShort`](${body.head.service_url}) ${body.head.message}" val embed = DiscordWebhook.Embed( "[${body.repo.name}:${body.head.branch}]", description, body.repo.url, author, color = 0xF70557) val webhook = DiscordWebhook(""" Coverage: **${body.head.totals.c.setScale(2, RoundingMode.HALF_UP)}%** [Change: **${body.compare.coverage.setScale(2, RoundingMode.HALF_UP)}%**](${body.compare.url}) """.trimIndent(), "Codecov", iconUrl, listOf(embed)) template.postForEntity("https://discordapp.com/api/webhooks/$id/$token", webhook, String::class.java) } } data class DiscordWebhook( val content: String, val username: String, val avatar_url: String, val embeds: List<Embed>) { data class Embed( val title: String, val description: String, val url: String, val author: Author, val fields: List<Field>? = null, val provider: Provider? = null, val thumbnail: Thumbnail? = null, val color: Int) { data class Author( val name: String ) data class Field( val name: String, val value: String ) data class Provider( val name: String ) data class Thumbnail( val url: String, val height: Int, val width: Int ) } } data class CodecovWebhook( val repo: Repo, val head: Head, val compare: Compare) { data class Head( val url: String, val message: String, val author: Author, val totals: Totals, val branch: String, val commitid: String, val service_url: String) { data class Totals( val c: BigDecimal ) data class Author( val username: String, val name: String ) } data class Repo( val name: String, val url: String ) data class Compare( val coverage: BigDecimal, val url: String ) }
mit
b4e61c273794149beb011bacd9e81b66
28.395349
110
0.590454
4.647059
false
false
false
false
polson/MetroTripper
app/src/main/java/com/philsoft/metrotripper/utils/ui/Ui.kt
1
1288
package com.philsoft.metrotripper.utils.ui import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.Point import android.graphics.drawable.BitmapDrawable import android.view.WindowManager import com.philsoft.metrotripper.utils.createBitmap object Ui { fun createBitmapFromDrawableResource(context: Context, widthOffset: Int, heightOffset: Int, drawableResource: Int): Bitmap { val d = context.resources.getDrawable(drawableResource) val bd = d.current as BitmapDrawable val b = bd.bitmap return Bitmap.createScaledBitmap(b, b.width + widthOffset, b.height + heightOffset, false) } fun createBitmapFromLayoutResource(activity: Activity, layoutResource: Int): Bitmap { val view = activity.layoutInflater.inflate(layoutResource, null, false) return view.createBitmap() } fun getCurrentScreenHeight(context: Context): Int { val size = getDisplaySize(context) return size.y } private fun getDisplaySize(context: Context): Point { val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val display = wm.defaultDisplay val size = Point() display.getSize(size) return size } }
apache-2.0
35afa909e51d275a2d182fd050b6603b
33.810811
128
0.727484
4.683636
false
false
false
false
uber/RIBs
android/libraries/rib-coroutines/src/main/kotlin/com/uber/rib/core/RibCoroutineScopes.kt
1
2811
/* * Copyright (C) 2022. Uber Technologies * * 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.uber.rib.core import android.app.Application import com.uber.autodispose.ScopeProvider import com.uber.autodispose.coroutinesinterop.asCoroutineScope import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import java.util.WeakHashMap import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.reflect.KProperty /** * [CoroutineScope] tied to this [ScopeProvider]. * This scope will be canceled when ScopeProvider is completed * * This scope is bound to * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] */ public val ScopeProvider.coroutineScope: CoroutineScope by LazyCoroutineScope<ScopeProvider> { val context: CoroutineContext = SupervisorJob() + RibDispatchers.Main.immediate + CoroutineName("${this::class.simpleName}:coroutineScope") + (RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext) asCoroutineScope(context) } /** * [CoroutineScope] tied to this [Application]. * This scope will not be cancelled, it lives for the full application process. * * This scope is bound to * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] */ public val Application.coroutineScope: CoroutineScope by LazyCoroutineScope<Application> { val context: CoroutineContext = SupervisorJob() + RibDispatchers.Main.immediate + CoroutineName("${this::class.simpleName}:coroutineScope") + (RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext) CoroutineScope(context) } internal class LazyCoroutineScope<This : Any>(val initializer: This.() -> CoroutineScope) { companion object { private val values = WeakHashMap<Any, CoroutineScope>() // Used to get and set Test overrides from rib-coroutines-test utils operator fun get(provider: Any) = values[provider] operator fun set(provider: Any, scope: CoroutineScope?) { values[provider] = scope } } operator fun getValue(thisRef: This, property: KProperty<*>): CoroutineScope = synchronized(LazyCoroutineScope) { return values.getOrPut(thisRef) { thisRef.initializer() } } }
apache-2.0
b60bd0bd5534f56665f835092b5f49df
36.986486
115
0.7709
4.677205
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/test/java/com/garpr/android/data/models/SimpleDateTest.kt
1
2001
package com.garpr.android.data.models import com.garpr.android.test.BaseTest import org.junit.Assert.assertEquals import org.junit.Test import java.util.Calendar import java.util.Collections import java.util.Date class SimpleDateTest : BaseTest() { @Test fun testChronologicalOrder() { val list = listOf(SimpleDate(Date(2)), SimpleDate(Date(0)), SimpleDate(Date(1)), SimpleDate(Date(5)), SimpleDate(Date(20))) Collections.sort(list, SimpleDate.CHRONOLOGICAL_ORDER) assertEquals(0, list[0].date.time) assertEquals(1, list[1].date.time) assertEquals(2, list[2].date.time) assertEquals(5, list[3].date.time) assertEquals(20, list[4].date.time) } @Test fun testHashCodeWithChristmas() { val date = with(Calendar.getInstance()) { clear() set(Calendar.YEAR, 2017) set(Calendar.MONTH, Calendar.DECEMBER) set(Calendar.DAY_OF_MONTH, 25) time } val simpleDate = SimpleDate(date) assertEquals(date.hashCode(), simpleDate.hashCode()) } @Test fun testHashCodeWithGenesis7() { val date = with(Calendar.getInstance()) { clear() set(Calendar.YEAR, 2020) set(Calendar.MONTH, Calendar.JANUARY) set(Calendar.DAY_OF_MONTH, 24) time } val simpleDate = SimpleDate(date) assertEquals(date.hashCode(), simpleDate.hashCode()) } @Test fun testReverseChronologicalOrder() { val list = listOf(SimpleDate(Date(2)), SimpleDate(Date(0)), SimpleDate(Date(1)), SimpleDate(Date(5)), SimpleDate(Date(20))) Collections.sort(list, SimpleDate.REVERSE_CHRONOLOGICAL_ORDER) assertEquals(20, list[0].date.time) assertEquals(5, list[1].date.time) assertEquals(2, list[2].date.time) assertEquals(1, list[3].date.time) assertEquals(0, list[4].date.time) } }
unlicense
d4537d0a24f5072bf2a91b5bf63d8ed0
29.318182
79
0.61919
3.962376
false
true
false
false
jtransc/jtransc
jtransc-utils/src/com/jtransc/text/token.kt
2
3279
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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.jtransc.text import com.jtransc.error.InvalidOperationException import java.io.Reader class TokenReader<T>(val list: List<T>) { var position = 0 val size = list.size val hasMore: Boolean get() = position < size fun peek(): T = list[position] fun read(): T { val result = peek() skip() return result } fun tryRead(vararg expected: T): Boolean { val value = peek() if (value in expected) { skip(1) return true } else { return false } } fun expect(expected: T): T { val value = read() if (value != expected) { throw InvalidOperationException("Expected $expected but found $value") } return value } fun expect(expected: Set<T>): T { val value = read() if (value !in expected) throw InvalidOperationException("Expected $expected but found $value") return value } fun unread() { position-- } fun skip(count: Int = 1): TokenReader<T> { position += count return this } } fun Char.isLetterOrUnderscore(): Boolean = this.isLetter() || this == '_' || this == '$' fun Char.isLetterDigitOrUnderscore(): Boolean = this.isLetterOrDigit() || this == '_' || this == '$' fun Char.isLetterOrDigitOrDollar(): Boolean = this.isLetterOrDigit() || this == '$' // @TODO: Make a proper table // 0x20, 0x7e //return this.isLetterDigitOrUnderscore() || this == '.' || this == '/' || this == '\'' || this == '"' || this == '(' || this == ')' || this == '[' || this == ']' || this == '+' || this == '-' || this == '*' || this == '/' fun Char.isPrintable(): Boolean = when (this) { in '\u0020'..'\u007e', in '\u00a1'..'\u00ff' -> true else -> false } fun GenericTokenize(sr: Reader): List<String> { val symbols = setOf("...") val tokens = arrayListOf<String>() while (sr.hasMore) { val char = sr.peekch() if (char.isLetterOrUnderscore()) { var token = "" while (sr.hasMore) { val c = sr.peekch() if (!c.isLetterDigitOrUnderscore()) break token += c sr.skip(1) } tokens.add(token) } else if (char.isWhitespace()) { sr.skip(1) } else if (char.isDigit()) { var token = "" while (sr.hasMore) { val c = sr.peekch() if (!c.isLetterOrDigit() && c != '.') break token += c sr.skip(1) } tokens.add(token) } else if (char == '"') { var token = "\"" sr.skip(1) while (sr.hasMore) { val c = sr.peekch() token += c sr.skip(1) if (c == '"') break } tokens.add(token) } else { //val peek = sr.peek(3) if (sr.peek(3) in symbols) { tokens.add(sr.read(3)) } else if (sr.peek(2) in symbols) { tokens.add(sr.read(2)) } else { tokens.add("$char") sr.skip(1) } } } return tokens.toList() }
apache-2.0
0c2d924c22d0b5abc9ed846bd110f730
24.038168
222
0.614517
3.177326
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/home/viewmodel/MessageDetailViewModel.kt
1
3650
package me.sweetll.tucao.business.home.viewmodel import androidx.databinding.ObservableField import android.view.View import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import me.sweetll.tucao.base.BaseViewModel import me.sweetll.tucao.business.home.MessageDetailActivity import me.sweetll.tucao.business.home.model.MessageDetail import me.sweetll.tucao.di.service.ApiConfig import me.sweetll.tucao.extension.NonNullObservableField import me.sweetll.tucao.extension.toast import org.jsoup.Jsoup import org.jsoup.nodes.Document import java.text.SimpleDateFormat import java.util.* class MessageDetailViewModel(val activity: MessageDetailActivity, val id: String, val _username: String, val _avatar: String): BaseViewModel() { val message = NonNullObservableField<String>("") fun loadData() { rawApiService.readMessageDetail(id) .bindToLifecycle(activity) .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .map { parseMessageDetail(Jsoup.parse(it.string())) } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ activity.onLoadData(it) }, { error -> error.printStackTrace() }) } fun parseMessageDetail(doc: Document): MutableList<MessageDetail> { val table_right = doc.selectFirst("td.tableright") val divs = table_right.child(3).children() val res = mutableListOf<MessageDetail>() for (index in 0 until divs.size / 3) { val div1 = divs[3 * index] val div2 = divs[3 * index + 1] val class_name = div1.className() val type = if ("userpicr" in class_name) MessageDetail.TYPE_RIGHT else MessageDetail.TYPE_LEFT val message = div2.ownText().trim() val time = div2.selectFirst("div.time").text() val avatar = if (type == MessageDetail.TYPE_LEFT) _avatar else user.avatar res.add(MessageDetail(avatar, message, time, type)) } return res } fun onClickSendMessage(view: View) { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") activity.addMessage(MessageDetail(user.avatar, message.get(), sdf.format(Date()), MessageDetail.TYPE_RIGHT)) rawApiService.replyMessage(message.get(), id, user.name) .bindToLifecycle(activity) .doOnNext { message.set("") } .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .map { parseSendResult(Jsoup.parse(it.string())) } .flatMap { (code, msg) -> if (code == 0) { Observable.just(Object()) } else { Observable.error(Error(msg)) } } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ // }, { error -> error.printStackTrace() error.localizedMessage.toast() }) } fun parseSendResult(doc: Document): Pair<Int, String> { val content = doc.body().text() return if ("成功" in content) { Pair(0, "") } else { Pair(1, content) } } }
mit
28d8f7d38a0f91fa555859939935108a
35.47
144
0.575425
4.716688
false
false
false
false
strooooke/quickfit
app/src/main/java/com/lambdasoup/quickfit/alarm/AlarmService.kt
1
8576
/* * Copyright 2016-2019 Juliane Lehmann <[email protected]> * * 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.lambdasoup.quickfit.alarm import android.app.* import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import android.os.PowerManager import androidx.core.app.NotificationCompat import com.lambdasoup.quickfit.Constants import com.lambdasoup.quickfit.Constants.PENDING_INTENT_WORKOUT_LIST import com.lambdasoup.quickfit.R import com.lambdasoup.quickfit.persist.QuickFitContentProvider import com.lambdasoup.quickfit.ui.WorkoutListActivity import com.lambdasoup.quickfit.util.WakefulIntents import timber.log.Timber import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit /** * ForegroundService, handling alarm-related background I/O work. Could also have been solved as a [androidx.core.app.JobIntentService], * or as a collection of jobs for [androidx.work.WorkManager], but (a) reading the documentation says that JobScheduler is for _deferrable_ * I/O work, which this is not - and also no promises are given as to the timeliness of the execution of JobScheduler jobs that are free * of restrictions. Although it seems to be fine in practice (on non-background crippling devices). Also (b) - just for trying it out. * Currently, this project serves as an exhibition of different ways of performing background work. */ class AlarmService : Service() { private val alarms by lazy { Alarms(this.applicationContext) } private val runWakeLock by lazy { (getSystemService(Context.POWER_SERVICE) as PowerManager) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AlarmService::class.java.canonicalName) } private lateinit var executor: ExecutorService override fun onCreate() { super.onCreate() executor = Executors.newFixedThreadPool(2) } override fun onDestroy() { executor.shutdownNow() super.onDestroy() } override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @Suppress("ReplaceGuardClauseWithFunctionCall") // IDE fails then, demands wrong type. New type inference at fault? if (intent == null) throw IllegalArgumentException("Should never receive null intents because of START_REDELIVER_INTENT") startForeground(Constants.NOTIFICATION_ALARM_BG_IO_WORK, buildForegroundNotification()) runWakeLock.acquire(TimeUnit.SECONDS.toMillis(30)) WakefulIntents.completeWakefulIntent(intent) Timber.d("Done with wakelock handover and foreground start, about to enqueue intent processing. intent=$intent") executor.submit { try { fun getScheduleId() = QuickFitContentProvider.getScheduleIdFromUriOrThrow(intent.data!!) when (intent.action) { ACTION_SNOOZE -> alarms.onSnoozed(getScheduleId()) ACTION_DIDIT -> { val workoutId = QuickFitContentProvider.getWorkoutIdFromUriOrThrow(intent.data!!) alarms.onDidIt(getScheduleId(), workoutId) } ACTION_ON_NOTIFICATION_SHOWN -> alarms.onNotificationShown(getScheduleId()) ACTION_ON_NOTIFICATION_DISMISSED -> alarms.onNotificationDismissed(getScheduleId()) ACTION_ON_SCHEDULE_CHANGED -> alarms.onScheduleChanged(getScheduleId()) ACTION_ON_SCHEDULE_DELETED -> alarms.onScheduleDeleted(getScheduleId()) ACTION_TIME_DISCONTINUITY -> alarms.resetAlarms() else -> throw IllegalArgumentException("Unknown action: ${intent.action}") } } catch (e: Throwable) { Timber.e(e, "Failed to execute $intent") } finally { runWakeLock.release() stopSelf(startId) } } return START_REDELIVER_INTENT } private fun buildForegroundNotification(): Notification = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID_BG_IO) .setContentTitle(getString(R.string.notification_alarm_bg_io_title)) .setContentText(getString(R.string.notification_alarm_bg_io_content)) .setContentIntent( PendingIntent.getActivity( this, PENDING_INTENT_WORKOUT_LIST, Intent(this, WorkoutListActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT) ) .build() companion object { private const val ACTION_SNOOZE = "com.lambdasoup.quickfit.alarm.ACTION_SNOOZE" private const val ACTION_DIDIT = "com.lambdasoup.quickfit.alarm.ACTION_DIDIT" private const val ACTION_ON_NOTIFICATION_SHOWN = "com.lambdasoup.quickfit.alarm.ACTION_ON_NOTIFICATION_SHOWN" private const val ACTION_ON_NOTIFICATION_DISMISSED = "com.lambdasoup.quickfit.alarm.ACTION_ON_NOTIFICATION_DISMISSED" private const val ACTION_ON_SCHEDULE_CHANGED = "com.lambdasoup.quickfit.alarm.ACTION_ON_SCHEDULE_CHANGED" private const val ACTION_ON_SCHEDULE_DELETED = "com.lambdasoup.quickfit.alarm.ACTION_ON_SCHEDULE_DELETED" private const val ACTION_TIME_DISCONTINUITY = "com.lambdasoup.quickfit.alarm.ACTION_TIME_DISCONTINUITY" fun getSnoozeIntent(context: Context, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriSchedulesId(scheduleId)) .setAction(ACTION_SNOOZE) fun getDidItIntent(context: Context, workoutId: Long, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId)) .setAction(ACTION_DIDIT) fun getOnNotificationShownIntent(context: Context, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriSchedulesId(scheduleId)) .setAction(ACTION_ON_NOTIFICATION_SHOWN) fun getOnNotificationDismissedIntent(context: Context, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriSchedulesId(scheduleId)) .setAction(ACTION_ON_NOTIFICATION_DISMISSED) fun getOnScheduleChangedIntent(context: Context, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriSchedulesId(scheduleId)) .setAction(ACTION_ON_SCHEDULE_CHANGED) fun getOnScheduleDeletedIntent(context: Context, scheduleId: Long) = Intent(context, AlarmService::class.java) .setData(QuickFitContentProvider.getUriSchedulesId(scheduleId)) .setAction(ACTION_ON_SCHEDULE_DELETED) fun getOnBootCompletedIntent(context: Context) = Intent(context, AlarmService::class.java) .setAction(ACTION_TIME_DISCONTINUITY) fun initNotificationChannels(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val bgIoChannel = NotificationChannel( Constants.NOTIFICATION_CHANNEL_ID_BG_IO, context.getString(R.string.notification_channel_bg_io_name), NotificationManager.IMPORTANCE_LOW ) context.getSystemService(NotificationManager::class.java)!!.createNotificationChannel(bgIoChannel) } } } }
apache-2.0
d794426d93a2364c207c27efd352a584
48.572254
139
0.663946
4.911798
false
false
false
false
yuyashuai/SurfaceViewFrameAnimation
frameanimation/src/main/java/com/yuyashuai/frameanimation/FrameAnimationSurfaceView.kt
1
2028
package com.yuyashuai.frameanimation import android.content.Context import android.util.AttributeSet import android.view.SurfaceView import android.view.View /** * the frame animation view to handle the animation life circle * @see SurfaceView * @author yuyashuai 2019-05-16. */ class FrameAnimationSurfaceView private constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int, val animation: FrameAnimation) : SurfaceView(context, attributeSet, defStyle), AnimationController by animation { constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : this(context, attributeSet, defStyle, FrameAnimation(context)) constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0) constructor(context: Context) : this(context, null) private var lastStopIndex = 0 private var lastStopPaths: MutableList<FrameAnimation.PathData>? = null /** * whether to resume playback */ var restoreEnable = true init { animation.bindView(this) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() saveAndStop() } /** * stop the animation, save the index when the animation stops playing */ private fun saveAndStop() { lastStopPaths = animation.mPaths lastStopIndex = stopAnimation() } /** * resume animation */ private fun restoreAndStart() { if (lastStopPaths != null && restoreEnable) { playAnimation(lastStopPaths!!, lastStopIndex) } } override fun onAttachedToWindow() { super.onAttachedToWindow() restoreAndStart() } override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) if (visibility == View.GONE || visibility == View.INVISIBLE) { saveAndStop() } else if (visibility == View.VISIBLE) { restoreAndStart() } } }
apache-2.0
29de83f21c6ae9eb6f4be127ab927c0f
29.283582
144
0.675049
4.794326
false
false
false
false
rock3r/detekt
detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/rules/TooManyFunctions.kt
1
1275
package io.gitlab.arturbosch.detekt.sample.extensions.rules import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction /** * This is a sample rule reporting too many functions inside a file. */ class TooManyFunctions : Rule() { override val issue = Issue( javaClass.simpleName, Severity.CodeSmell, "This rule reports a file with an excessive function count.", Debt.TWENTY_MINS ) private var amount: Int = 0 override fun visitKtFile(file: KtFile) { super.visitKtFile(file) if (amount > THRESHOLD) { report(CodeSmell(issue, Entity.from(file), message = "The file ${file.name} has $amount function declarations. " + "Threshold is specified with $THRESHOLD.")) } amount = 0 } override fun visitNamedFunction(function: KtNamedFunction) { super.visitNamedFunction(function) amount++ } } const val THRESHOLD = 10
apache-2.0
e2ead79234b79989b74a02e58d371148
29.357143
87
0.690196
4.322034
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/update_tags/StringMapEntryChange.kt
1
1806
package de.westnordost.streetcomplete.data.osm.edits.update_tags import kotlinx.serialization.Serializable @Serializable sealed class StringMapEntryChange { abstract override fun toString(): String abstract override fun equals(other: Any?): Boolean abstract override fun hashCode(): Int abstract fun conflictsWith(map: Map<String, String>): Boolean abstract fun applyTo(map: MutableMap<String, String>) abstract fun reversed(): StringMapEntryChange } @Serializable data class StringMapEntryAdd(val key: String, val value: String) : StringMapEntryChange() { override fun toString() = "ADD \"$key\"=\"$value\"" override fun conflictsWith(map: Map<String, String>) = map.containsKey(key) && map[key] != value override fun applyTo(map: MutableMap<String, String>) { map[key] = value } override fun reversed() = StringMapEntryDelete(key, value) } @Serializable data class StringMapEntryModify(val key: String, val valueBefore: String, val value: String) : StringMapEntryChange() { override fun toString() = "MODIFY \"$key\"=\"$valueBefore\" -> \"$key\"=\"$value\"" override fun conflictsWith(map: Map<String, String>) = map[key] != valueBefore && map[key] != value override fun applyTo(map: MutableMap<String, String>) { map[key] = value } override fun reversed() = StringMapEntryModify(key, value, valueBefore) } @Serializable data class StringMapEntryDelete(val key: String, val valueBefore: String) : StringMapEntryChange() { override fun toString() = "DELETE \"$key\"=\"$valueBefore\"" override fun conflictsWith(map: Map<String, String>) = map.containsKey(key) && map[key] != valueBefore override fun applyTo(map: MutableMap<String, String>) { map.remove(key) } override fun reversed() = StringMapEntryAdd(key, valueBefore) }
gpl-3.0
547c2d3c764791acfbcda053753ddee6
44.15
119
0.722591
4.341346
false
false
false
false
wzhxyz/ACManager
src/main/java/com/zzkun/util/prob/PbDiffCalcer.kt
1
1208
package com.zzkun.util.prob import com.zzkun.dao.ExtOjPbInfoRepo import com.zzkun.dao.UserACPbRepo import com.zzkun.model.OJType import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.util.* /** * Created by Administrator on 2017/2/26 0026. */ @Component open class PbDiffCalcer( @Autowired private val extOjPbInfoRepo: ExtOjPbInfoRepo, @Autowired private val userACPbRepo: UserACPbRepo) { fun calcPbDiff(ojName: OJType, pbId: String, pbNum: String): Double { // val info = extOjPbInfoRepo.findByOjNameAndPid(ojName, pbId) // val weAC = userACPbRepo.countByOjNameAndOjPbId(ojName, pbNum) // val res = (DEFAULT_MAX - log(1.0 + info.dacu)) / log(1.7 + weAC) // println("${ojName},${pbId},${pbNum},${info.dacu},${info.ac},${weAC}") // return res return 1.0; } fun allPbDiff(): HashMap<String, Double> { val res = HashMap<String, Double>() val list = extOjPbInfoRepo.findAll() list.forEach { res["${it.num}@${it.ojName}"] = calcPbDiff(it.ojName, it.pid, it.num) } return res } }
gpl-3.0
1d036cbfcaf8e42c643b0a057febd9ff
32.571429
81
0.642384
3.247312
false
false
false
false
devmil/PaperLaunch
app/src/main/java/de/devmil/paperlaunch/view/LauncherView.kt
1
17351
/* * Copyright 2015 Devmil Solutions * * 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 de.devmil.paperlaunch.view import android.animation.Animator import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.graphics.Rect import android.support.v4.content.ContextCompat import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import java.io.InvalidClassException import java.util.ArrayList import de.devmil.paperlaunch.R import de.devmil.paperlaunch.model.IEntry import de.devmil.paperlaunch.model.IFolder import de.devmil.paperlaunch.config.LaunchConfig import de.devmil.paperlaunch.model.Launch import de.devmil.paperlaunch.utils.PositionAndSizeEvaluator import de.devmil.paperlaunch.view.utils.ViewUtils import de.devmil.paperlaunch.view.utils.ColorUtils import de.devmil.paperlaunch.view.widgets.VerticalTextView class LauncherView : RelativeLayout { private var viewModel: LauncherViewModel? = null private val laneViews = ArrayList<LaunchLaneView>() private var background: RelativeLayout? = null private var neutralZone: LinearLayout? = null private var neutralZoneBackground: LinearLayout? = null private var neutralZoneBackgroundImage: ImageView? = null private var neutralZoneBackgroundAppNameText: VerticalTextView? = null private var listener: ILauncherViewListener? = null private var autoStartMotionEvent: MotionEvent? = null private var currentlySelectedItem: IEntry? = null interface ILauncherViewListener { fun onFinished() } constructor(context: Context) : super(context) { construct() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { construct() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { construct() } fun doInitialize(config: LaunchConfig) { buildViewModel(config) } private fun start() { buildViews() transitToState(LauncherViewModel.State.Init) transitToState(LauncherViewModel.State.Initializing) } fun setListener(listener: ILauncherViewListener) { this.listener = listener } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) autoStartMotionEvent?.let { start() onTouchEvent(it) autoStartMotionEvent = null } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { return super.onTouchEvent(event) || handleTouchEvent(event.action, event.x, event.y) } fun handleTouchEvent(action: Int, x: Float, y: Float): Boolean { return laneViews.fold(false) { currentResult, laneView -> sendIfMatches(laneView, action, x, y) || currentResult } } fun doAutoStart(firstMotionEvent: MotionEvent) { autoStartMotionEvent = firstMotionEvent } private fun construct() { ViewUtils.disableClipping(this) } private fun buildViewModel(config: LaunchConfig) { viewModel = LauncherViewModel(config) } private val laneIds: IntArray get() = intArrayOf( R.id.id_launchview_lane1, R.id.id_launchview_lane2, R.id.id_launchview_lane3, R.id.id_launchview_lane4, R.id.id_launchview_lane5, R.id.id_launchview_lane6, R.id.id_launchview_lane7, R.id.id_launchview_lane8, R.id.id_launchview_lane9, R.id.id_launchview_lane10, R.id.id_launchview_lane11, R.id.id_launchview_lane12, R.id.id_launchview_lane13) private fun buildViews() { removeAllViews() laneViews.clear() addBackground() addNeutralZone() val laneIds = laneIds val localNeutralZone = neutralZone!! val localNeutralZoneBackground = neutralZoneBackground!! val localViewModel = viewModel!! laneIds.indices.fold(localNeutralZone.id) { current, i -> addLaneView(i, current).id } setEntriesToLane(laneViews[0], localViewModel.entries) laneViews.indices.reversed().forEach { i -> laneViews[i].bringToFront() } localNeutralZone.bringToFront() localNeutralZoneBackground.bringToFront() } private fun addLaneView(laneIndex: Int, anchorId: Int): LaunchLaneView { val laneIds = laneIds val id = laneIds[laneIndex] val llv = LaunchLaneView(context) llv.id = id val localViewModel = viewModel!! val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) params.addRule(RelativeLayout.ALIGN_PARENT_TOP) params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) if (localViewModel.isOnRightSide) params.addRule(RelativeLayout.LEFT_OF, anchorId) else params.addRule(RelativeLayout.RIGHT_OF, anchorId) addView(llv, params) laneViews.add(llv) llv.setLaneListener(object : LaunchLaneView.ILaneListener { override fun onItemSelected(selectedItem: IEntry?) { currentlySelectedItem = selectedItem if (selectedItem == null) { return } if (selectedItem.isFolder) { val f = selectedItem as IFolder if (laneViews.size <= laneIndex + 1) { return } val nextLaneView = laneViews[laneIndex + 1] setEntriesToLane(nextLaneView, f.subEntries.orEmpty()) nextLaneView.start() } } override fun onItemSelecting(selectedItem: IEntry?) { currentlySelectedItem = selectedItem } override fun onStateChanged(oldState: LaunchLaneViewModel.State, newState: LaunchLaneViewModel.State) { if (newState === LaunchLaneViewModel.State.Focusing) { for (idx in laneIndex + 1 until laneViews.size) { laneViews[idx].stop() } } } }) return llv } private fun setEntriesToLane(laneView: LaunchLaneView, entries: List<IEntry>) { val localViewModel = viewModel!! val entryModels = entries.map { LaunchEntryViewModel.createFrom(context, it, viewModel!!.entryConfig) } val vm = LaunchLaneViewModel(entryModels, localViewModel.laneConfig) laneView.doInitializeData(vm) } private fun addBackground() { val localViewModel = viewModel!! val localBackground = RelativeLayout(context) localBackground.setBackgroundColor(localViewModel.backgroundColor) localBackground.alpha = 0f background = localBackground val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) params.addRule(RelativeLayout.ALIGN_PARENT_TOP) params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) params.addRule(RelativeLayout.ALIGN_PARENT_LEFT) params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) addView(localBackground, params) } private fun addNeutralZone() { val localViewModel = viewModel!! val localNeutralZone = LinearLayout(context) localNeutralZone.id = R.id.id_launchview_neutralzone localNeutralZone.minimumWidth = ViewUtils.getPxFromDip(context, localViewModel.neutralZoneWidthDip).toInt() localNeutralZone.isClickable = false val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) params.addRule(RelativeLayout.ALIGN_PARENT_TOP) params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) if (localViewModel.isOnRightSide) { params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) } else { params.addRule(RelativeLayout.ALIGN_PARENT_LEFT) } addView(localNeutralZone, params) val localNeutralZoneBackground = LinearLayout(context) localNeutralZoneBackground.setBackgroundColor(localViewModel.designConfig.frameDefaultColor) localNeutralZoneBackground.elevation = ViewUtils.getPxFromDip(context, localViewModel.highElevationDip) localNeutralZoneBackground.isClickable = false localNeutralZoneBackground.orientation = LinearLayout.VERTICAL localNeutralZoneBackground.gravity = Gravity.CENTER_HORIZONTAL val backParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ) localNeutralZone.addView(localNeutralZoneBackground, backParams) if(localViewModel.laneConfig.showLogo) { val localNeutralZoneBackgroundImage = ImageView(context) localNeutralZoneBackgroundImage.setImageResource(R.mipmap.ic_launcher) localNeutralZoneBackgroundImage.isClickable = false localNeutralZoneBackgroundImage.visibility = View.GONE val backImageParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) backImageParams.setMargins(0, ViewUtils.getPxFromDip(context, localViewModel.laneConfig.laneIconTopMarginDip).toInt(), 0, 0) localNeutralZoneBackground.addView(localNeutralZoneBackgroundImage, backImageParams) val localNeutralZoneBackgroundAppNameText = VerticalTextView(context) localNeutralZoneBackgroundAppNameText.visibility = View.GONE localNeutralZoneBackgroundAppNameText.setTextSize(TypedValue.COMPLEX_UNIT_SP, localViewModel.itemNameTextSizeSP) //this is needed because the parts in the system run with another theme than the application parts localNeutralZoneBackgroundAppNameText.setTextColor(ContextCompat.getColor(context, R.color.name_label)) localNeutralZoneBackgroundAppNameText.setText(R.string.app_name) localNeutralZoneBackgroundAppNameText.visibility = View.GONE val backTextParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) backTextParams.setMargins(0, ViewUtils.getPxFromDip(context, localViewModel.laneConfig.laneTextTopMarginDip).toInt(), 0, 0) localNeutralZoneBackground.addView(localNeutralZoneBackgroundAppNameText, backTextParams) localNeutralZoneBackground.setBackgroundColor( ColorUtils.getBackgroundColorFromImage( resources.getDrawable( R.mipmap.ic_launcher, context.theme ), localViewModel.frameDefaultColor)) neutralZoneBackgroundImage = localNeutralZoneBackgroundImage neutralZoneBackgroundAppNameText = localNeutralZoneBackgroundAppNameText } else { neutralZoneBackgroundImage = null neutralZoneBackgroundAppNameText = null } neutralZone = localNeutralZone neutralZoneBackground = localNeutralZoneBackground } private fun sendIfMatches(laneView: LaunchLaneView, action: Int, x: Float, y: Float): Boolean { val laneX = (x - laneView.x).toInt() val laneY = (y - laneView.y).toInt() laneView.doHandleTouch(action, laneX, laneY) if (action == MotionEvent.ACTION_UP) { launchAppIfSelected() listener?.onFinished() } return true } private fun launchAppIfSelected() { if (currentlySelectedItem?.isFolder != false) { return } val l = currentlySelectedItem as Launch? val intent = l?.launchIntent intent?.let { it.flags = it.flags or Intent.FLAG_ACTIVITY_NEW_TASK } try { context.startActivity(intent) } catch (e: Exception) { Log.e(TAG, "Error while launching app", e) } } private fun transitToState(newState: LauncherViewModel.State) { when (newState) { LauncherViewModel.State.Init -> { hideBackground() hideNeutralZone() } LauncherViewModel.State.Initializing -> { animateBackground() animateNeutralZone() } LauncherViewModel.State.Ready -> startLane() } viewModel!!.state = newState } private fun startLane() { laneViews[0].start() } private fun hideBackground() { background?.alpha = 0f } private fun hideNeutralZone() { neutralZoneBackground?.visibility = View.INVISIBLE } private fun animateBackground() { if (viewModel?.showBackground == true) { val localBackground = background!! val localViewModel = viewModel!! localBackground.visibility = View.VISIBLE localBackground .animate() .alpha(localViewModel.backgroundAlpha) .setDuration(localViewModel.backgroundAnimationDurationMS.toLong()) .start() } else { background?.visibility = View.GONE } } private fun animateNeutralZone() { val localViewModel = viewModel!! val size = localViewModel.neutralZoneWidthDip val fromLeft = if (localViewModel.isOnRightSide) width - size.toInt() else 0 var fromTop = (height - size.toInt()) / 2 if (autoStartMotionEvent != null) { fromTop = Math.min( height - size.toInt(), autoStartMotionEvent!!.y.toInt() ) } val fromRight = fromLeft + size.toInt() val fromBottom = fromTop + size.toInt() val fromRect = Rect( fromLeft, fromTop, fromRight, fromBottom ) val toRect = Rect( fromLeft, 0, fromRight, height ) val anim: ObjectAnimator? try { anim = ObjectAnimator.ofObject( neutralZoneBackground, "margins", PositionAndSizeEvaluator(neutralZoneBackground!!), fromRect, toRect) anim.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator) { neutralZoneBackground?.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator) { Thread(Runnable { try { Thread.sleep(100) } catch (e: InterruptedException) { } neutralZoneBackground?.post { transitToState(LauncherViewModel.State.Ready) } }).start() } override fun onAnimationCancel(animation: Animator) {} override fun onAnimationRepeat(animation: Animator) {} }) anim.duration = localViewModel.launcherInitAnimationDurationMS.toLong() anim.start() Thread(Runnable { try { Thread.sleep((localViewModel.launcherInitAnimationDurationMS / 2).toLong()) neutralZoneBackgroundImage?.post { neutralZoneBackgroundImage!!.visibility = View.VISIBLE neutralZoneBackgroundAppNameText!!.visibility = View.VISIBLE } } catch (e: InterruptedException) { } }).start() } catch (e: InvalidClassException) { e.printStackTrace() } } companion object { private val TAG = LauncherView::class.java.simpleName } }
apache-2.0
5eb1685a56ce2e8f094630101e38f00b
35.528421
136
0.63224
5.020544
false
false
false
false
i7c/cfm
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/common/security/CfmAuthProvider.kt
1
2134
package org.rliz.cfm.recorder.common.security import org.rliz.cfm.recorder.user.boundary.UserBoundary import org.rliz.cfm.recorder.user.data.User import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional @Component class CfmAuthProvider : AuthenticationProvider { @Autowired private lateinit var userBoundary: UserBoundary private val encoder = BCryptPasswordEncoder() @Transactional override fun authenticate(authentication: Authentication?): Authentication { if (authentication == null) throw BadCredentialsException("Internal error") val name = authentication.name val password = authentication.credentials.toString() if (name.isEmpty()) throw BadCredentialsException("Provide a username") if (password.isEmpty()) throw BadCredentialsException("Provide a password") return regularUserLogin(name, password) } private fun regularUserLogin(name: String, password: String): Authentication { userBoundary.findUserByName(name)?.let { if (encoder.matches(password, it.password)) { return UsernamePasswordAuthenticationToken(it, "removed", determineRoles(it)) } } throw BadCredentialsException("Bad credentials") } override fun supports(authentication: Class<*>?): Boolean = authentication!!.isAssignableFrom(UsernamePasswordAuthenticationToken::class.java) } fun determineRoles(u: User) = (if (u.systemUser) listOf(SimpleGrantedAuthority("ROLE_ADMIN")) else emptyList()) .plus(SimpleGrantedAuthority("ROLE_USER"))
gpl-3.0
cbde61f0d99b0f22cd7fe4eb9b83fd3d
42.55102
111
0.776007
5.295285
false
false
false
false
die-tageszeitung/tazapp-android
tazapp/src/main/java/de/thecode/android/tazreader/audio/AudioPlayerService.kt
1
11066
package de.thecode.android.tazreader.audio import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.media.AudioManager import android.media.MediaPlayer import android.os.IBinder import android.os.Parcelable import android.os.PowerManager import android.widget.Toast import androidx.appcompat.content.res.AppCompatResources import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.core.graphics.drawable.toBitmap import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.github.ajalt.timberkt.Timber.d import com.github.ajalt.timberkt.Timber.e import com.github.ajalt.timberkt.Timber.i import de.thecode.android.tazreader.R import de.thecode.android.tazreader.notifications.NotificationUtils import de.thecode.android.tazreader.start.StartActivity import kotlinx.android.parcel.Parcelize import java.io.IOException import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import kotlin.math.max class AudioPlayerService : Service(), MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, AudioManager.OnAudioFocusChangeListener { enum class State { LOADING, PLAYING, PAUSED } companion object { const val EXTRA_AUDIO_ITEM = "audioExtra" const val ACTION_STATE_CHANGED = "serviceAudioStateChanged" const val ACTION_POSITION_UPDATE = "serviceAudioPositionChanged" var instance: AudioPlayerService? = null } private var mediaPlayer: MediaPlayer? = null private var audioManager: AudioManager? = null private var executor:ScheduledExecutorService? = null var audioItem: AudioItem? = null var state: State = State.LOADING set(value) { d {"setState $value"} field = value val serviceIntent = Intent() serviceIntent.action = ACTION_STATE_CHANGED LocalBroadcastManager.getInstance(this) .sendBroadcast(serviceIntent) when(value) { State.PLAYING -> { if (executor == null) { executor = Executors.newSingleThreadScheduledExecutor() executor?.scheduleAtFixedRate({ updatePlayerPosition() }, 0, 500, TimeUnit.MILLISECONDS) } } else -> { executor?.shutdown() executor = null } } } override fun onBind(intent: Intent?): IBinder? { TODO("not implemented") } override fun onCreate() { super.onCreate() instance = this d { "XXX SERVICE CREATED" } } override fun onDestroy() { instance = null removeAudioFocus() state = State.LOADING super.onDestroy() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { d { "onStartCommand $intent" } intent?.let { onStartIntent -> val audioItemExtra = onStartIntent.getParcelableExtra<AudioItem>(EXTRA_AUDIO_ITEM) audioItemExtra?.let { audioItem = it if (isPlaying()) { mediaPlayer?.stop() mediaPlayer?.release() mediaPlayer = null } initForeground() //Request audio focus if (requestAudioFocus()) { initMediaPlayer() } else { Toast.makeText(this, R.string.audio_service_error_gain_focus, Toast.LENGTH_LONG) .show() //Could not gain focus stopSelf() } } } return super.onStartCommand(intent, flags, startId) } private fun initForeground() { val builder = NotificationCompat.Builder(this, NotificationUtils.AUDIO_CHANNEL_ID) val title = StringBuilder() title.append(audioItem!!.title) builder.setContentTitle(title.toString()) .setContentText(audioItem!!.source) builder.setWhen(System.currentTimeMillis()) builder.setSmallIcon(R.drawable.ic_audio_notification) val drawableRes = if (isPlaying()) R.drawable.ic_record_voice_over_black_32dp else R.drawable.ic_pause_black_24dp val drawable = AppCompatResources.getDrawable(this, drawableRes) drawable?.let { var wrappedDrawable = DrawableCompat.wrap(it) wrappedDrawable = wrappedDrawable.mutate() DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(this, R.color.color_accent)) builder.setLargeIcon(wrappedDrawable.toBitmap()) } builder.priority = NotificationCompat.PRIORITY_DEFAULT val intent = Intent(this, StartActivity::class.java) intent.putExtra(NotificationUtils.NOTIFICATION_EXTRA_BOOKID, audioItem!!.sourceId) intent.putExtra(NotificationUtils.NOTIFICATION_EXTRA_TYPE_ID, NotificationUtils.AUDIOSERVICE_NOTIFICATION_ID) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) val uniqueInt = (System.currentTimeMillis() and 0xfffffff).toInt() val contentIntent = PendingIntent.getActivity(this, uniqueInt, intent, PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(contentIntent) val notification = builder.build() // Start foreground service. startForeground(1, notification) } fun isPlaying(): Boolean { return try { mediaPlayer?.isPlaying ?: throw IllegalStateException() //mediaPlayer.isPlaying also throws IllegalstateException } catch (ex: IllegalStateException) { false } } private fun initMediaPlayer() { val mp = MediaPlayer() mp.setOnBufferingUpdateListener(this) mp.setOnCompletionListener(this) mp.setOnErrorListener(this) mp.setOnPreparedListener(this) mp.setOnInfoListener(this) mp.reset() mp.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK) mp.setAudioStreamType(AudioManager.STREAM_MUSIC) try { mp.setDataSource(audioItem!!.uri) } catch (ex: IOException) { e(ex) stopSelf() } state = State.LOADING mp.prepareAsync() mediaPlayer = mp } fun stopPlaying() { mediaPlayer?.let { if (it.isPlaying) { it.stop() } it.release() } stopSelf() } fun pauseOrResumePlaying() { d { "pauseOrResumePlaying" } mediaPlayer?.let { mp -> if (mp.isPlaying) { mp.pause() state = State.PAUSED audioItem?.let { it.resumePosition = mp.currentPosition } } else { audioItem?.let { mp.seekTo(it.resumePosition) } mp.start() state= State.PLAYING } initForeground() } } fun seekToPosition(position:Int) { mediaPlayer?.seekTo(position) updatePlayerPosition() } fun rewind30Seconds() { mediaPlayer?.let { val newPos = it.currentPosition - TimeUnit.SECONDS.toMillis(30).toInt() it.seekTo(max(newPos,0)) updatePlayerPosition() } } private fun updatePlayerPosition() { mediaPlayer?.let { audioItem?.resumePosition = it.currentPosition val timeIntent = Intent() timeIntent.action = ACTION_POSITION_UPDATE LocalBroadcastManager.getInstance(this) .sendBroadcast(timeIntent) } } private fun requestAudioFocus(): Boolean { val audioManagerService = getSystemService(Context.AUDIO_SERVICE) as AudioManager audioManager = audioManagerService val result = audioManagerService.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) d { "requestAudioFocus $result" } return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED } private fun removeAudioFocus(): Boolean { d { "removeAudioFocus" } audioManager?.let { return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == it.abandonAudioFocus(this) } ?: return false } override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) { d { "onBufferingUpdate $percent" } } override fun onPrepared(mp: MediaPlayer?) { d { "onPrepared duration ${mp?.duration}" } mp?.let { audioItem?.duration = mp.duration } pauseOrResumePlaying() } override fun onCompletion(mp: MediaPlayer?) { d { "onCompletion" } stopPlaying() } override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean { e { "onError what: $what extra: $extra" } return false } override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean { i { "onInfo what: $what extra: $extra" } return false } override fun onAudioFocusChange(focusChange: Int) { d { "onAudioFocusChange $focusChange" } when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { if (mediaPlayer == null) { initMediaPlayer() } else if (!isPlaying()) { pauseOrResumePlaying() } mediaPlayer?.setVolume(1F, 1F) // resume or start playback } AudioManager.AUDIOFOCUS_LOSS -> { // Lost focus for an unbounded amount of time: stop playback and release media player stopPlaying() } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { // Lost focus for a short time, but we have to stop // playback. We don't release the media player because playback // is likely to resume if (isPlaying()) pauseOrResumePlaying() } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { // Lost focus for a short time, but it's ok to keep playing if (isPlaying()) mediaPlayer?.setVolume(0.1F, 0.1F) } } } } @Parcelize data class AudioItem(val uri: String, val title: String, val source: String, val sourceId: String, var resumePosition: Int = 0, var duration: Int = 0) : Parcelable
agpl-3.0
cdf66891e571146f205d3e30322ccaa9
32.947853
241
0.60356
5.069171
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/dialog/ProgressDialogFragment.kt
1
2496
package com.quickblox.sample.chat.kotlin.ui.dialog import android.app.Dialog import android.app.ProgressDialog import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.KeyEvent import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import com.quickblox.sample.chat.kotlin.R private const val ARG_MESSAGE_ID = "message_id" class ProgressDialogFragment : DialogFragment() { companion object { private val TAG = ProgressDialogFragment::class.java.simpleName fun show(fragmentManager: FragmentManager) { // We're not using dialogFragment.show() method because we may call this DialogFragment // in onActivityResult() method and there will be a state loss exception if (fragmentManager.findFragmentByTag(TAG) == null) { Log.d(TAG, "fragmentManager.findFragmentByTag(TAG) == null") val args = Bundle() args.putInt(ARG_MESSAGE_ID, R.string.dlg_loading) val dialog = ProgressDialogFragment() dialog.arguments = args Log.d(TAG, "newInstance = $dialog") fragmentManager.beginTransaction().add(dialog, TAG).commitAllowingStateLoss() } Log.d(TAG, "backstack = " + fragmentManager.fragments) } fun hide(fragmentManager: FragmentManager) { val fragment = fragmentManager.findFragmentByTag(TAG) fragment?.let { fragmentManager.beginTransaction().remove(it).commitAllowingStateLoss() Log.d(TAG, "fragmentManager.beginTransaction().remove(fragment)$fragment") } Log.d(TAG, "backstack = " + fragmentManager.fragments) } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = ProgressDialog(activity) dialog.setMessage(getString(arguments?.getInt(ARG_MESSAGE_ID) ?: R.string.dlg_loading)) dialog.isIndeterminate = true dialog.setCancelable(false) dialog.setCanceledOnTouchOutside(false) // Disable the back button val keyListener = DialogInterface.OnKeyListener { dialog, keyCode, event -> keyCode == KeyEvent.KEYCODE_BACK } dialog.setOnKeyListener(keyListener) return dialog } }
bsd-3-clause
4f3dad7d6b8b7c6c8048f3b094eec312
39.934426
99
0.635417
5.288136
false
false
false
false
GeoffreyMetais/vlc-android
application/live-plot-graph/src/main/java/org/videolan/liveplotgraph/PlotView.kt
1
9662
/* * ************************************************************************ * PlotView.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.liveplotgraph import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.util.Log import android.widget.FrameLayout import org.videolan.tools.dp import kotlin.math.log10 import kotlin.math.pow import kotlin.math.round class PlotView : FrameLayout { private val textPaint: Paint by lazy { val p = Paint() p.color = color p.textSize = 10.dp.toFloat() p } val data = ArrayList<LineGraph>() private val maxsY = ArrayList<Float>() private val maxsX = ArrayList<Long>() private val minsX = ArrayList<Long>() private var color: Int = 0xFFFFFF private var listeners = ArrayList<PlotViewDataChangeListener>() constructor(context: Context) : super(context) { setWillNotDraw(false) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initAttributes(attrs, 0) setWillNotDraw(false) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { initAttributes(attrs, defStyle) setWillNotDraw(false) } private fun initAttributes(attrs: AttributeSet, defStyle: Int) { attrs.let { val a = context.theme.obtainStyledAttributes(attrs, R.styleable.LPGPlotView, 0, defStyle) try { color = a.getInt(R.styleable.LPGPlotView_lpg_color, 0xFFFFFF) } catch (e: Exception) { Log.w("", e.message, e) } finally { a.recycle() } } } fun addData(index: Int, value: Pair<Long, Float>) { data.forEach { lineGraph -> if (lineGraph.index == index) { lineGraph.data[value.first] = value.second if (lineGraph.data.size > 30) { lineGraph.data.remove(lineGraph.data.toSortedMap().firstKey()) } invalidate() val listenerValue = ArrayList<Pair<LineGraph, String>>(data.size) data.forEach { lineGraph -> listenerValue.add(Pair(lineGraph, "${String.format("%.0f", lineGraph.data[lineGraph.data.keys.max()])} kb/s")) } listeners.forEach { it.onDataChanged(listenerValue) } } } } fun addListener(listener: PlotViewDataChangeListener) { listeners.add(listener) } fun removeListener(listener: PlotViewDataChangeListener) { listeners.remove(listener) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) maxsY.clear() maxsX.clear() minsX.clear() data.forEach { maxsY.add(it.data.maxBy { it.value }?.value ?: 0f) } val maxY = maxsY.max() ?: 0f data.forEach { maxsX.add(it.data.maxBy { it.key }?.key ?: 0L) } val maxX = maxsX.max() ?: 0L data.forEach { minsX.add(it.data.minBy { it.key }?.key ?: 0L) } val minX = minsX.min() ?: 0L drawLines(maxY, minX, maxX, canvas) drawGrid(canvas, maxY, minX, maxX) } private fun drawGrid(canvas: Canvas?, maxY: Float, minX: Long, maxX: Long) { canvas?.let { if (maxY <= 0F) return // it.drawText("0", 10F, it.height.toFloat() - 2.dp, textPaint) it.drawText("${String.format("%.0f", maxY)} kb/s", 10F, 10.dp.toFloat(), textPaint) var center = maxY / 2 center = getRoundedByUnit(center) if (BuildConfig.DEBUG) Log.d(this::class.java.simpleName, "Center: $center") val centerCoord = measuredHeight * ((maxY - center) / maxY) it.drawLine(0f, centerCoord, measuredWidth.toFloat(), centerCoord, textPaint) it.drawText("${String.format("%.0f", center)} kb/s", 10F, centerCoord - 2.dp, textPaint) //timestamps var index = maxX - 1000 if (BuildConfig.DEBUG) Log.d(this::class.java.simpleName, "FirstIndex: $index") while (index > minX) { val xCoord = (measuredWidth * ((index - minX).toDouble() / (maxX - minX).toDouble())).toFloat() it.drawLine(xCoord, 0F, xCoord, measuredHeight.toFloat() - 12.dp, textPaint) val formattedText = "${String.format("%.0f", getRoundedByUnit((index - maxX).toFloat()) / 1000)}s" it.drawText(formattedText, xCoord - (textPaint.measureText(formattedText) / 2), measuredHeight.toFloat(), textPaint) index -= 1000 } } } private fun getRoundedByUnit(number: Float): Float { val lengthX = log10(number.toDouble()).toInt() return (round(number / (10.0.pow(lengthX.toDouble()))) * (10.0.pow(lengthX.toDouble()))).toFloat() } private fun drawLines(maxY: Float, minX: Long, maxX: Long, canvas: Canvas?) { data.forEach { line -> var initialPoint: Pair<Float, Float>? = null line.data.toSortedMap().forEach { point -> if (initialPoint == null) { initialPoint = getCoordinates(point, maxY, minX, maxX, measuredWidth, measuredHeight) } else { val currentPoint = getCoordinates(point, maxY, minX, maxX, measuredWidth, measuredHeight) currentPoint.let { canvas?.drawLine(initialPoint!!.first, initialPoint!!.second, it.first, it.second, line.paint) initialPoint = it } } } } } // fun drawLines2(maxY: Float, minX: Long, maxX: Long, canvas: Canvas?) { // // // data.forEach { line -> // path.reset() // val points = line.data.map { // val coord = getCoordinates(it, maxY, minX, maxX, measuredWidth, measuredHeight) // GraphPoint(coord.first, coord.second) // }.sortedBy { it.x } // for (i in points.indices) { // val point = points[i] // val smoothing = 100 // when (i) { // 0 -> { // val next: GraphPoint = points[i + 1] // point.dx = (next.x - point.x) / smoothing // point.dy = (next.y - point.y) / smoothing // } // points.size - 1 -> { // val prev: GraphPoint = points[i - 1] // point.dx = (point.x - prev.x) / smoothing // point.dy = (point.y - prev.y) / smoothing // } // else -> { // val next: GraphPoint = points[i + 1] // val prev: GraphPoint = points[i - 1] // point.dx = next.x - prev.x / smoothing // point.dy = (next.y - prev.y) / smoothing // } // } // } // for (i in points.indices) { // val point: GraphPoint = points[i] // when { // i == 0 -> { // path.moveTo(point.x, point.y) // } // i < points.size - 1 -> { // val prev: GraphPoint = points[i - 1] // path.cubicTo(prev.x + prev.dx, prev.y + prev.dy, point.x - point.dx, point.y - point.dy, point.x, point.y) // canvas?.drawCircle(point.x, point.y, 2.dp.toFloat(), line.paint) // } // else -> { // path.lineTo(point.x, point.y) // } // } // } // canvas?.drawPath(path, line.paint) // } // // } private fun getCoordinates(point: Map.Entry<Long, Float>, maxY: Float, minX: Long, maxX: Long, measuredWidth: Int, measuredHeight: Int): Pair<Float, Float> = Pair((measuredWidth * ((point.key - minX).toDouble() / (maxX - minX).toDouble())).toFloat(), measuredHeight * ((maxY - point.value) / maxY)) fun clear() { data.forEach { it.data.clear() } } fun addLine(lineGraph: LineGraph) { if (!data.contains(lineGraph)) { data.add(lineGraph) } } } data class GraphPoint(val x: Float, val y: Float) { var dx: Float = 0F var dy: Float = 0F } interface PlotViewDataChangeListener { fun onDataChanged(data: List<Pair<LineGraph, String>>) }
gpl-2.0
a1021705be64e90cd768f11065ac1351
37.189723
302
0.531104
4.173218
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/HttpUrl.kt
1
70588
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetAddress import java.net.MalformedURLException import java.net.URI import java.net.URISyntaxException import java.net.URL import java.nio.charset.Charset import java.nio.charset.StandardCharsets.UTF_8 import java.util.Collections import java.util.LinkedHashSet import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.internal.canParseAsIpAddress import okhttp3.internal.delimiterOffset import okhttp3.internal.indexOfFirstNonAsciiWhitespace import okhttp3.internal.indexOfLastNonAsciiWhitespace import okhttp3.internal.parseHexDigit import okhttp3.internal.publicsuffix.PublicSuffixDatabase import okhttp3.internal.toCanonicalHost import okio.Buffer /** * A uniform resource locator (URL) with a scheme of either `http` or `https`. Use this class to * compose and decompose Internet addresses. For example, this code will compose and print a URL for * Google search: * * ``` * HttpUrl url = new HttpUrl.Builder() * .scheme("https") * .host("www.google.com") * .addPathSegment("search") * .addQueryParameter("q", "polar bears") * .build(); * System.out.println(url); * ``` * * which prints: * * ``` * https://www.google.com/search?q=polar%20bears * ``` * * As another example, this code prints the human-readable query parameters of a Twitter search: * * ``` * HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images"); * for (int i = 0, size = url.querySize(); i < size; i++) { * System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i)); * } * ``` * * which prints: * * ``` * q: cute #puppies * f: images * ``` * * In addition to composing URLs from their component parts and decomposing URLs into their * component parts, this class implements relative URL resolution: what address you'd reach by * clicking a relative link on a specified page. For example: * * ``` * HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos"); * HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc"); * System.out.println(link); * ``` * * which prints: * * ``` * https://www.youtube.com/watch?v=cbP2N1BQdYc * ``` * * ## What's in a URL? * * A URL has several components. * * ### Scheme * * Sometimes referred to as *protocol*, A URL's scheme describes what mechanism should be used to * retrieve the resource. Although URLs have many schemes (`mailto`, `file`, `ftp`), this class only * supports `http` and `https`. Use [java.net.URI][URI] for URLs with arbitrary schemes. * * ### Username and Password * * Username and password are either present, or the empty string `""` if absent. This class offers * no mechanism to differentiate empty from absent. Neither of these components are popular in * practice. Typically HTTP applications use other mechanisms for user identification and * authentication. * * ### Host * * The host identifies the webserver that serves the URL's resource. It is either a hostname like * `square.com` or `localhost`, an IPv4 address like `192.168.0.1`, or an IPv6 address like `::1`. * * Usually a webserver is reachable with multiple identifiers: its IP addresses, registered * domain names, and even `localhost` when connecting from the server itself. Each of a web server's * names is a distinct URL and they are not interchangeable. For example, even if * `http://square.github.io/dagger` and `http://google.github.io/dagger` are served by the same IP * address, the two URLs identify different resources. * * ### Port * * The port used to connect to the web server. By default this is 80 for HTTP and 443 for HTTPS. * This class never returns -1 for the port: if no port is explicitly specified in the URL then the * scheme's default is used. * * ### Path * * The path identifies a specific resource on the host. Paths have a hierarchical structure like * "/square/okhttp/issues/1486" and decompose into a list of segments like `["square", "okhttp", * "issues", "1486"]`. * * This class offers methods to compose and decompose paths by segment. It composes each path * from a list of segments by alternating between "/" and the encoded segment. For example the * segments `["a", "b"]` build "/a/b" and the segments `["a", "b", ""]` build "/a/b/". * * If a path's last segment is the empty string then the path ends with "/". This class always * builds non-empty paths: if the path is omitted it defaults to "/". The default path's segment * list is a single empty string: `[""]`. * * ### Query * * The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string * is subdivided into a collection of name-value parameters. This class offers methods to set the * query as the single string, or as individual name-value parameters. With name-value parameters * the values are optional and names may be repeated. * * ### Fragment * * The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and * query the fragment is not sent to the webserver: it's private to the client. * * ## Encoding * * Each component must be encoded before it is embedded in the complete URL. As we saw above, the * string `cute #puppies` is encoded as `cute%20%23puppies` when used as a query parameter value. * * ### Percent encoding * * Percent encoding replaces a character (like `\ud83c\udf69`) with its UTF-8 hex bytes (like * `%F0%9F%8D%A9`). This approach works for whitespace characters, control characters, non-ASCII * characters, and characters that already have another meaning in a particular context. * * Percent encoding is used in every URL component except for the hostname. But the set of * characters that need to be encoded is different for each component. For example, the path * component must escape all of its `?` characters, otherwise it could be interpreted as the * start of the URL's query. But within the query and fragment components, the `?` character * doesn't delimit anything and doesn't need to be escaped. * * ``` * HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder() * .addPathSegment("_Who?_") * .query("_Who?_") * .fragment("_Who?_") * .build(); * System.out.println(url); * ``` * * This prints: * * ``` * http://who-let-the-dogs.out/_Who%3F_?_Who?_#_Who?_ * ``` * * When parsing URLs that lack percent encoding where it is required, this class will percent encode * the offending characters. * * ### IDNA Mapping and Punycode encoding * * Hostnames have different requirements and use a different encoding scheme. It consists of IDNA * mapping and Punycode encoding. * * In order to avoid confusion and discourage phishing attacks, [IDNA Mapping][idna] transforms * names to avoid confusing characters. This includes basic case folding: transforming shouting * `SQUARE.COM` into cool and casual `square.com`. It also handles more exotic characters. For * example, the Unicode trademark sign (™) could be confused for the letters "TM" in * `http://ho™mail.com`. To mitigate this, the single character (™) maps to the string (tm). There * is similar policy for all of the 1.1 million Unicode code points. Note that some code points such * as "\ud83c\udf69" are not mapped and cannot be used in a hostname. * * [Punycode](http://ietf.org/rfc/rfc3492.txt) converts a Unicode string to an ASCII string to make * international domain names work everywhere. For example, "σ" encodes as "xn--4xa". The encoded * string is not human readable, but can be used with classes like [InetAddress] to establish * connections. * * ## Why another URL model? * * Java includes both [java.net.URL][URL] and [java.net.URI][URI]. We offer a new URL * model to address problems that the others don't. * * ### Different URLs should be different * * Although they have different content, `java.net.URL` considers the following two URLs * equal, and the [equals()][Object.equals] method between them returns true: * * * https://example.net/ * * * https://example.com/ * * This is because those two hosts share the same IP address. This is an old, bad design decision * that makes `java.net.URL` unusable for many things. It shouldn't be used as a [Map] key or in a * [Set]. Doing so is both inefficient because equality may require a DNS lookup, and incorrect * because unequal URLs may be equal because of how they are hosted. * * ### Equal URLs should be equal * * These two URLs are semantically identical, but `java.net.URI` disagrees: * * * http://host:80/ * * * http://host * * Both the unnecessary port specification (`:80`) and the absent trailing slash (`/`) cause URI to * bucket the two URLs separately. This harms URI's usefulness in collections. Any application that * stores information-per-URL will need to either canonicalize manually, or suffer unnecessary * redundancy for such URLs. * * Because they don't attempt canonical form, these classes are surprisingly difficult to use * securely. Suppose you're building a webservice that checks that incoming paths are prefixed * "/static/images/" before serving the corresponding assets from the filesystem. * * ``` * String attack = "http://example.com/static/images/../../../../../etc/passwd"; * System.out.println(new URL(attack).getPath()); * System.out.println(new URI(attack).getPath()); * System.out.println(HttpUrl.parse(attack).encodedPath()); * ``` * * By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that * checks only the path prefix may suffer! * * ``` * /static/images/../../../../../etc/passwd * /static/images/../../../../../etc/passwd * /etc/passwd * ``` * * ### If it works on the web, it should work in your application * * The `java.net.URI` class is strict around what URLs it accepts. It rejects URLs like * `http://example.com/abc|def` because the `|` character is unsupported. This class is more * forgiving: it will automatically percent-encode the `|'` yielding `http://example.com/abc%7Cdef`. * This kind behavior is consistent with web browsers. `HttpUrl` prefers consistency with major web * browsers over consistency with obsolete specifications. * * ### Paths and Queries should decompose * * Neither of the built-in URL models offer direct access to path segments or query parameters. * Manually using `StringBuilder` to assemble these components is cumbersome: do '+' characters get * silently replaced with spaces? If a query parameter contains a '&amp;', does that get escaped? * By offering methods to read and write individual query parameters directly, application * developers are saved from the hassles of encoding and decoding. * * ### Plus a modern API * * The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping * constructors. For example, there's no API to compose a URI with a custom port without also * providing a query and fragment. * * Instances of [HttpUrl] are well-formed and always have a scheme, host, and path. With * `java.net.URL` it's possible to create an awkward URL like `http:/` with scheme and path but no * hostname. Building APIs that consume such malformed values is difficult! * * This class has a modern API. It avoids punitive checked exceptions: [toHttpUrl] throws * [IllegalArgumentException] on invalid input or [toHttpUrlOrNull] returns null if the input is an * invalid URL. You can even be explicit about whether each component has been encoded already. * * [idna]: http://www.unicode.org/reports/tr46/#ToASCII */ class HttpUrl internal constructor( /** Either "http" or "https". */ @get:JvmName("scheme") val scheme: String, /** * The decoded username, or an empty string if none is present. * * | URL | `username()` | * | :------------------------------- | :----------- | * | `http://host/` | `""` | * | `http://username@host/` | `"username"` | * | `http://username:password@host/` | `"username"` | * | `http://a%20b:c%20d@host/` | `"a b"` | */ @get:JvmName("username") val username: String, /** * Returns the decoded password, or an empty string if none is present. * * | URL | `password()` | * | :------------------------------- | :----------- | * | `http://host/` | `""` | * | `http://username@host/` | `""` | * | `http://username:password@host/` | `"password"` | * | `http://a%20b:c%20d@host/` | `"c d"` | */ @get:JvmName("password") val password: String, /** * The host address suitable for use with [InetAddress.getAllByName]. May be: * * * A regular host name, like `android.com`. * * * An IPv4 address, like `127.0.0.1`. * * * An IPv6 address, like `::1`. Note that there are no square braces. * * * An encoded IDN, like `xn--n3h.net`. * * | URL | `host()` | * | :-------------------- | :-------------- | * | `http://android.com/` | `"android.com"` | * | `http://127.0.0.1/` | `"127.0.0.1"` | * | `http://[::1]/` | `"::1"` | * | `http://xn--n3h.net/` | `"xn--n3h.net"` | */ @get:JvmName("host") val host: String, /** * The explicitly-specified port if one was provided, or the default port for this URL's scheme. * For example, this returns 8443 for `https://square.com:8443/` and 443 for * `https://square.com/`. The result is in `[1..65535]`. * * | URL | `port()` | * | :------------------ | :------- | * | `http://host/` | `80` | * | `http://host:8000/` | `8000` | * | `https://host/` | `443` | */ @get:JvmName("port") val port: Int, /** * A list of path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This list is * never empty though it may contain a single empty string. * * | URL | `pathSegments()` | * | :----------------------- | :------------------ | * | `http://host/` | `[""]` | * | `http://host/a/b/c"` | `["a", "b", "c"]` | * | `http://host/a/b%20c/d"` | `["a", "b c", "d"]` | */ @get:JvmName("pathSegments") val pathSegments: List<String>, /** * Alternating, decoded query names and values, or null for no query. Names may be empty or * non-empty, but never null. Values are null if the name has no corresponding '=' separator, or * empty, or non-empty. */ private val queryNamesAndValues: List<String?>?, /** * This URL's fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has no * fragment. * * | URL | `fragment()` | * | :--------------------- | :----------- | * | `http://host/` | null | * | `http://host/#` | `""` | * | `http://host/#abc` | `"abc"` | * | `http://host/#abc|def` | `"abc|def"` | */ @get:JvmName("fragment") val fragment: String?, /** Canonical URL. */ private val url: String ) { val isHttps: Boolean = scheme == "https" /** Returns this URL as a [java.net.URL][URL]. */ @JvmName("url") fun toUrl(): URL { try { return URL(url) } catch (e: MalformedURLException) { throw RuntimeException(e) // Unexpected! } } /** * Returns this URL as a [java.net.URI][URI]. Because `URI` is more strict than this class, the * returned URI may be semantically different from this URL: * * * Characters forbidden by URI like `[` and `|` will be escaped. * * * Invalid percent-encoded sequences like `%xx` will be encoded like `%25xx`. * * * Whitespace and control characters in the fragment will be stripped. * * These differences may have a significant consequence when the URI is interpreted by a * web server. For this reason the [URI class][URI] and this method should be avoided. */ @JvmName("uri") fun toUri(): URI { val uri = newBuilder().reencodeForUri().toString() return try { URI(uri) } catch (e: URISyntaxException) { // Unlikely edge case: the URI has a forbidden character in the fragment. Strip it & retry. try { val stripped = uri.replace(Regex("[\\u0000-\\u001F\\u007F-\\u009F\\p{javaWhitespace}]"), "") URI.create(stripped) } catch (e1: Exception) { throw RuntimeException(e) // Unexpected! } } } /** * The username, or an empty string if none is set. * * | URL | `encodedUsername()` | * | :------------------------------- | :------------------ | * | `http://host/` | `""` | * | `http://username@host/` | `"username"` | * | `http://username:password@host/` | `"username"` | * | `http://a%20b:c%20d@host/` | `"a%20b"` | */ @get:JvmName("encodedUsername") val encodedUsername: String get() { if (username.isEmpty()) return "" val usernameStart = scheme.length + 3 // "://".length() == 3. val usernameEnd = url.delimiterOffset(":@", usernameStart, url.length) return url.substring(usernameStart, usernameEnd) } /** * The password, or an empty string if none is set. * * | URL | `encodedPassword()` | * | :--------------------------------| :------------------ | * | `http://host/` | `""` | * | `http://username@host/` | `""` | * | `http://username:password@host/` | `"password"` | * | `http://a%20b:c%20d@host/` | `"c%20d"` | */ @get:JvmName("encodedPassword") val encodedPassword: String get() { if (password.isEmpty()) return "" val passwordStart = url.indexOf(':', scheme.length + 3) + 1 val passwordEnd = url.indexOf('@') return url.substring(passwordStart, passwordEnd) } /** * The number of segments in this URL's path. This is also the number of slashes in this URL's * path, like 3 in `http://host/a/b/c`. This is always at least 1. * * | URL | `pathSize()` | * | :------------------- | :----------- | * | `http://host/` | `1` | * | `http://host/a/b/c` | `3` | * | `http://host/a/b/c/` | `4` | */ @get:JvmName("pathSize") val pathSize: Int get() = pathSegments.size /** * The entire path of this URL encoded for use in HTTP resource resolution. The returned path will * start with `"/"`. * * | URL | `encodedPath()` | * | :---------------------- | :-------------- | * | `http://host/` | `"/"` | * | `http://host/a/b/c` | `"/a/b/c"` | * | `http://host/a/b%20c/d` | `"/a/b%20c/d"` | */ @get:JvmName("encodedPath") val encodedPath: String get() { val pathStart = url.indexOf('/', scheme.length + 3) // "://".length() == 3. val pathEnd = url.delimiterOffset("?#", pathStart, url.length) return url.substring(pathStart, pathEnd) } /** * A list of encoded path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This * list is never empty though it may contain a single empty string. * * | URL | `encodedPathSegments()` | * | :---------------------- | :---------------------- | * | `http://host/` | `[""]` | * | `http://host/a/b/c` | `["a", "b", "c"]` | * | `http://host/a/b%20c/d` | `["a", "b%20c", "d"]` | */ @get:JvmName("encodedPathSegments") val encodedPathSegments: List<String> get() { val pathStart = url.indexOf('/', scheme.length + 3) val pathEnd = url.delimiterOffset("?#", pathStart, url.length) val result = mutableListOf<String>() var i = pathStart while (i < pathEnd) { i++ // Skip the '/'. val segmentEnd = url.delimiterOffset('/', i, pathEnd) result.add(url.substring(i, segmentEnd)) i = segmentEnd } return result } /** * The query of this URL, encoded for use in HTTP resource resolution. This string may be null * (for URLs with no query), empty (for URLs with an empty query) or non-empty (all other URLs). * * | URL | `encodedQuery()` | * | :-------------------------------- | :--------------------- | * | `http://host/` | null | * | `http://host/?` | `""` | * | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key+lime"` | * | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` | * | `http://host/?a=apple&b` | `"a=apple&b"` | */ @get:JvmName("encodedQuery") val encodedQuery: String? get() { if (queryNamesAndValues == null) return null // No query. val queryStart = url.indexOf('?') + 1 val queryEnd = url.delimiterOffset('#', queryStart, url.length) return url.substring(queryStart, queryEnd) } /** * This URL's query, like `"abc"` for `http://host/?abc`. Most callers should prefer * [queryParameterName] and [queryParameterValue] because these methods offer direct access to * individual query parameters. * * | URL | `query()` | * | :-------------------------------- | :--------------------- | * | `http://host/` | null | * | `http://host/?` | `""` | * | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key lime"` | * | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` | * | `http://host/?a=apple&b` | `"a=apple&b"` | */ @get:JvmName("query") val query: String? get() { if (queryNamesAndValues == null) return null // No query. val result = StringBuilder() queryNamesAndValues.toQueryString(result) return result.toString() } /** * The number of query parameters in this URL, like 2 for `http://host/?a=apple&b=banana`. If this * URL has no query this is 0. Otherwise it is one more than the number of `"&"` separators in the * query. * * | URL | `querySize()` | * | :-------------------------------- | :------------ | * | `http://host/` | `0` | * | `http://host/?` | `1` | * | `http://host/?a=apple&k=key+lime` | `2` | * | `http://host/?a=apple&a=apricot` | `2` | * | `http://host/?a=apple&b` | `2` | */ @get:JvmName("querySize") val querySize: Int get() { return if (queryNamesAndValues != null) queryNamesAndValues.size / 2 else 0 } /** * The first query parameter named `name` decoded using UTF-8, or null if there is no such query * parameter. * * | URL | `queryParameter("a")` | * | :-------------------------------- | :-------------------- | * | `http://host/` | null | * | `http://host/?` | null | * | `http://host/?a=apple&k=key+lime` | `"apple"` | * | `http://host/?a=apple&a=apricot` | `"apple"` | * | `http://host/?a=apple&b` | `"apple"` | */ fun queryParameter(name: String): String? { if (queryNamesAndValues == null) return null for (i in 0 until queryNamesAndValues.size step 2) { if (name == queryNamesAndValues[i]) { return queryNamesAndValues[i + 1] } } return null } /** * The distinct query parameter names in this URL, like `["a", "b"]` for * `http://host/?a=apple&b=banana`. If this URL has no query this is the empty set. * * | URL | `queryParameterNames()` | * | :-------------------------------- | :---------------------- | * | `http://host/` | `[]` | * | `http://host/?` | `[""]` | * | `http://host/?a=apple&k=key+lime` | `["a", "k"]` | * | `http://host/?a=apple&a=apricot` | `["a"]` | * | `http://host/?a=apple&b` | `["a", "b"]` | */ @get:JvmName("queryParameterNames") val queryParameterNames: Set<String> get() { if (queryNamesAndValues == null) return emptySet() val result = LinkedHashSet<String>() for (i in 0 until queryNamesAndValues.size step 2) { result.add(queryNamesAndValues[i]!!) } return Collections.unmodifiableSet(result) } /** * Returns all values for the query parameter `name` ordered by their appearance in this * URL. For example this returns `["banana"]` for `queryParameterValue("b")` on * `http://host/?a=apple&b=banana`. * * | URL | `queryParameterValues("a")` | `queryParameterValues("b")` | * | :-------------------------------- | :-------------------------- | :-------------------------- | * | `http://host/` | `[]` | `[]` | * | `http://host/?` | `[]` | `[]` | * | `http://host/?a=apple&k=key+lime` | `["apple"]` | `[]` | * | `http://host/?a=apple&a=apricot` | `["apple", "apricot"]` | `[]` | * | `http://host/?a=apple&b` | `["apple"]` | `[null]` | */ fun queryParameterValues(name: String): List<String?> { if (queryNamesAndValues == null) return emptyList() val result = mutableListOf<String?>() for (i in 0 until queryNamesAndValues.size step 2) { if (name == queryNamesAndValues[i]) { result.add(queryNamesAndValues[i + 1]) } } return Collections.unmodifiableList(result) } /** * Returns the name of the query parameter at `index`. For example this returns `"a"` * for `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if * `index` is not less than the [query size][querySize]. * * | URL | `queryParameterName(0)` | `queryParameterName(1)` | * | :-------------------------------- | :---------------------- | :---------------------- | * | `http://host/` | exception | exception | * | `http://host/?` | `""` | exception | * | `http://host/?a=apple&k=key+lime` | `"a"` | `"k"` | * | `http://host/?a=apple&a=apricot` | `"a"` | `"a"` | * | `http://host/?a=apple&b` | `"a"` | `"b"` | */ fun queryParameterName(index: Int): String { if (queryNamesAndValues == null) throw IndexOutOfBoundsException() return queryNamesAndValues[index * 2]!! } /** * Returns the value of the query parameter at `index`. For example this returns `"apple"` for * `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if `index` is not less * than the [query size][querySize]. * * | URL | `queryParameterValue(0)` | `queryParameterValue(1)` | * | :-------------------------------- | :----------------------- | :----------------------- | * | `http://host/` | exception | exception | * | `http://host/?` | null | exception | * | `http://host/?a=apple&k=key+lime` | `"apple"` | `"key lime"` | * | `http://host/?a=apple&a=apricot` | `"apple"` | `"apricot"` | * | `http://host/?a=apple&b` | `"apple"` | null | */ fun queryParameterValue(index: Int): String? { if (queryNamesAndValues == null) throw IndexOutOfBoundsException() return queryNamesAndValues[index * 2 + 1] } /** * This URL's encoded fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has * no fragment. * * | URL | `encodedFragment()` | * | :--------------------- | :------------------ | * | `http://host/` | null | * | `http://host/#` | `""` | * | `http://host/#abc` | `"abc"` | * | `http://host/#abc|def` | `"abc|def"` | */ @get:JvmName("encodedFragment") val encodedFragment: String? get() { if (fragment == null) return null val fragmentStart = url.indexOf('#') + 1 return url.substring(fragmentStart) } /** * Returns a string with containing this URL with its username, password, query, and fragment * stripped, and its path replaced with `/...`. For example, redacting * `http://username:[email protected]/path` returns `http://example.com/...`. */ fun redact(): String { return newBuilder("/...")!! .username("") .password("") .build() .toString() } /** * Returns the URL that would be retrieved by following `link` from this URL, or null if the * resulting URL is not well-formed. */ fun resolve(link: String): HttpUrl? = newBuilder(link)?.build() /** * Returns a builder based on this URL. */ fun newBuilder(): Builder { val result = Builder() result.scheme = scheme result.encodedUsername = encodedUsername result.encodedPassword = encodedPassword result.host = host // If we're set to a default port, unset it in case of a scheme change. result.port = if (port != defaultPort(scheme)) port else -1 result.encodedPathSegments.clear() result.encodedPathSegments.addAll(encodedPathSegments) result.encodedQuery(encodedQuery) result.encodedFragment = encodedFragment return result } /** * Returns a builder for the URL that would be retrieved by following `link` from this URL, * or null if the resulting URL is not well-formed. */ fun newBuilder(link: String): Builder? { return try { Builder().parse(this, link) } catch (_: IllegalArgumentException) { null } } override fun equals(other: Any?): Boolean { return other is HttpUrl && other.url == url } override fun hashCode(): Int = url.hashCode() override fun toString(): String = url /** * Returns the domain name of this URL's [host] that is one level beneath the public suffix by * consulting the [public suffix list](https://publicsuffix.org). Returns null if this URL's * [host] is an IP address or is considered a public suffix by the public suffix list. * * In general this method **should not** be used to test whether a domain is valid or routable. * Instead, DNS is the recommended source for that information. * * | URL | `topPrivateDomain()` | * | :---------------------------- | :------------------- | * | `http://google.com` | `"google.com"` | * | `http://adwords.google.co.uk` | `"google.co.uk"` | * | `http://square` | null | * | `http://co.uk` | null | * | `http://localhost` | null | * | `http://127.0.0.1` | null | */ fun topPrivateDomain(): String? { return if (host.canParseAsIpAddress()) { null } else { PublicSuffixDatabase.get().getEffectiveTldPlusOne(host) } } @JvmName("-deprecated_url") @Deprecated( message = "moved to toUrl()", replaceWith = ReplaceWith(expression = "toUrl()"), level = DeprecationLevel.ERROR) fun url() = toUrl() @JvmName("-deprecated_uri") @Deprecated( message = "moved to toUri()", replaceWith = ReplaceWith(expression = "toUri()"), level = DeprecationLevel.ERROR) fun uri() = toUri() @JvmName("-deprecated_scheme") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "scheme"), level = DeprecationLevel.ERROR) fun scheme(): String = scheme @JvmName("-deprecated_encodedUsername") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedUsername"), level = DeprecationLevel.ERROR) fun encodedUsername(): String = encodedUsername @JvmName("-deprecated_username") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "username"), level = DeprecationLevel.ERROR) fun username(): String = username @JvmName("-deprecated_encodedPassword") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPassword"), level = DeprecationLevel.ERROR) fun encodedPassword(): String = encodedPassword @JvmName("-deprecated_password") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "password"), level = DeprecationLevel.ERROR) fun password(): String = password @JvmName("-deprecated_host") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "host"), level = DeprecationLevel.ERROR) fun host(): String = host @JvmName("-deprecated_port") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "port"), level = DeprecationLevel.ERROR) fun port(): Int = port @JvmName("-deprecated_pathSize") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "pathSize"), level = DeprecationLevel.ERROR) fun pathSize(): Int = pathSize @JvmName("-deprecated_encodedPath") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPath"), level = DeprecationLevel.ERROR) fun encodedPath(): String = encodedPath @JvmName("-deprecated_encodedPathSegments") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPathSegments"), level = DeprecationLevel.ERROR) fun encodedPathSegments(): List<String> = encodedPathSegments @JvmName("-deprecated_pathSegments") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "pathSegments"), level = DeprecationLevel.ERROR) fun pathSegments(): List<String> = pathSegments @JvmName("-deprecated_encodedQuery") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedQuery"), level = DeprecationLevel.ERROR) fun encodedQuery(): String? = encodedQuery @JvmName("-deprecated_query") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "query"), level = DeprecationLevel.ERROR) fun query(): String? = query @JvmName("-deprecated_querySize") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "querySize"), level = DeprecationLevel.ERROR) fun querySize(): Int = querySize @JvmName("-deprecated_queryParameterNames") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "queryParameterNames"), level = DeprecationLevel.ERROR) fun queryParameterNames(): Set<String> = queryParameterNames @JvmName("-deprecated_encodedFragment") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedFragment"), level = DeprecationLevel.ERROR) fun encodedFragment(): String? = encodedFragment @JvmName("-deprecated_fragment") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "fragment"), level = DeprecationLevel.ERROR) fun fragment(): String? = fragment class Builder { internal var scheme: String? = null internal var encodedUsername = "" internal var encodedPassword = "" internal var host: String? = null internal var port = -1 internal val encodedPathSegments = mutableListOf<String>() internal var encodedQueryNamesAndValues: MutableList<String?>? = null internal var encodedFragment: String? = null init { encodedPathSegments.add("") // The default path is '/' which needs a trailing space. } /** * @param scheme either "http" or "https". */ fun scheme(scheme: String) = apply { when { scheme.equals("http", ignoreCase = true) -> this.scheme = "http" scheme.equals("https", ignoreCase = true) -> this.scheme = "https" else -> throw IllegalArgumentException("unexpected scheme: $scheme") } } fun username(username: String) = apply { this.encodedUsername = username.canonicalize(encodeSet = USERNAME_ENCODE_SET) } fun encodedUsername(encodedUsername: String) = apply { this.encodedUsername = encodedUsername.canonicalize( encodeSet = USERNAME_ENCODE_SET, alreadyEncoded = true ) } fun password(password: String) = apply { this.encodedPassword = password.canonicalize(encodeSet = PASSWORD_ENCODE_SET) } fun encodedPassword(encodedPassword: String) = apply { this.encodedPassword = encodedPassword.canonicalize( encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } /** * @param host either a regular hostname, International Domain Name, IPv4 address, or IPv6 * address. */ fun host(host: String) = apply { val encoded = host.percentDecode().toCanonicalHost() ?: throw IllegalArgumentException( "unexpected host: $host") this.host = encoded } fun port(port: Int) = apply { require(port in 1..65535) { "unexpected port: $port" } this.port = port } private fun effectivePort(): Int { return if (port != -1) port else defaultPort(scheme!!) } fun addPathSegment(pathSegment: String) = apply { push(pathSegment, 0, pathSegment.length, addTrailingSlash = false, alreadyEncoded = false) } /** * Adds a set of path segments separated by a slash (either `\` or `/`). If `pathSegments` * starts with a slash, the resulting URL will have empty path segment. */ fun addPathSegments(pathSegments: String): Builder = addPathSegments(pathSegments, false) fun addEncodedPathSegment(encodedPathSegment: String) = apply { push(encodedPathSegment, 0, encodedPathSegment.length, addTrailingSlash = false, alreadyEncoded = true) } /** * Adds a set of encoded path segments separated by a slash (either `\` or `/`). If * `encodedPathSegments` starts with a slash, the resulting URL will have empty path segment. */ fun addEncodedPathSegments(encodedPathSegments: String): Builder = addPathSegments(encodedPathSegments, true) private fun addPathSegments(pathSegments: String, alreadyEncoded: Boolean) = apply { var offset = 0 do { val segmentEnd = pathSegments.delimiterOffset("/\\", offset, pathSegments.length) val addTrailingSlash = segmentEnd < pathSegments.length push(pathSegments, offset, segmentEnd, addTrailingSlash, alreadyEncoded) offset = segmentEnd + 1 } while (offset <= pathSegments.length) } fun setPathSegment(index: Int, pathSegment: String) = apply { val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET) require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) { "unexpected path segment: $pathSegment" } encodedPathSegments[index] = canonicalPathSegment } fun setEncodedPathSegment(index: Int, encodedPathSegment: String) = apply { val canonicalPathSegment = encodedPathSegment.canonicalize( encodeSet = PATH_SEGMENT_ENCODE_SET, alreadyEncoded = true ) encodedPathSegments[index] = canonicalPathSegment require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) { "unexpected path segment: $encodedPathSegment" } } fun removePathSegment(index: Int) = apply { encodedPathSegments.removeAt(index) if (encodedPathSegments.isEmpty()) { encodedPathSegments.add("") // Always leave at least one '/'. } } fun encodedPath(encodedPath: String) = apply { require(encodedPath.startsWith("/")) { "unexpected encodedPath: $encodedPath" } resolvePath(encodedPath, 0, encodedPath.length) } fun query(query: String?) = apply { this.encodedQueryNamesAndValues = query?.canonicalize( encodeSet = QUERY_ENCODE_SET, plusIsSpace = true )?.toQueryNamesAndValues() } fun encodedQuery(encodedQuery: String?) = apply { this.encodedQueryNamesAndValues = encodedQuery?.canonicalize( encodeSet = QUERY_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true )?.toQueryNamesAndValues() } /** Encodes the query parameter using UTF-8 and adds it to this URL's query string. */ fun addQueryParameter(name: String, value: String?) = apply { if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf() encodedQueryNamesAndValues!!.add(name.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true )) encodedQueryNamesAndValues!!.add(value?.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true )) } /** Adds the pre-encoded query parameter to this URL's query string. */ fun addEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply { if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf() encodedQueryNamesAndValues!!.add(encodedName.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) encodedQueryNamesAndValues!!.add(encodedValue?.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) } fun setQueryParameter(name: String, value: String?) = apply { removeAllQueryParameters(name) addQueryParameter(name, value) } fun setEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply { removeAllEncodedQueryParameters(encodedName) addEncodedQueryParameter(encodedName, encodedValue) } fun removeAllQueryParameters(name: String) = apply { if (encodedQueryNamesAndValues == null) return this val nameToRemove = name.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true ) removeAllCanonicalQueryParameters(nameToRemove) } fun removeAllEncodedQueryParameters(encodedName: String) = apply { if (encodedQueryNamesAndValues == null) return this removeAllCanonicalQueryParameters(encodedName.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) } private fun removeAllCanonicalQueryParameters(canonicalName: String) { for (i in encodedQueryNamesAndValues!!.size - 2 downTo 0 step 2) { if (canonicalName == encodedQueryNamesAndValues!![i]) { encodedQueryNamesAndValues!!.removeAt(i + 1) encodedQueryNamesAndValues!!.removeAt(i) if (encodedQueryNamesAndValues!!.isEmpty()) { encodedQueryNamesAndValues = null return } } } } fun fragment(fragment: String?) = apply { this.encodedFragment = fragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET, unicodeAllowed = true ) } fun encodedFragment(encodedFragment: String?) = apply { this.encodedFragment = encodedFragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET, alreadyEncoded = true, unicodeAllowed = true ) } /** * Re-encodes the components of this URL so that it satisfies (obsolete) RFC 2396, which is * particularly strict for certain components. */ internal fun reencodeForUri() = apply { host = host?.replace(Regex("[\"<>^`{|}]"), "") for (i in 0 until encodedPathSegments.size) { encodedPathSegments[i] = encodedPathSegments[i].canonicalize( encodeSet = PATH_SEGMENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true ) } val encodedQueryNamesAndValues = this.encodedQueryNamesAndValues if (encodedQueryNamesAndValues != null) { for (i in 0 until encodedQueryNamesAndValues.size) { encodedQueryNamesAndValues[i] = encodedQueryNamesAndValues[i]?.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true, plusIsSpace = true ) } } encodedFragment = encodedFragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true, unicodeAllowed = true ) } fun build(): HttpUrl { @Suppress("UNCHECKED_CAST") // percentDecode returns either List<String?> or List<String>. return HttpUrl( scheme = scheme ?: throw IllegalStateException("scheme == null"), username = encodedUsername.percentDecode(), password = encodedPassword.percentDecode(), host = host ?: throw IllegalStateException("host == null"), port = effectivePort(), pathSegments = encodedPathSegments.map { it.percentDecode() }, queryNamesAndValues = encodedQueryNamesAndValues?.map { it?.percentDecode(plusIsSpace = true) }, fragment = encodedFragment?.percentDecode(), url = toString() ) } override fun toString(): String { return buildString { if (scheme != null) { append(scheme) append("://") } else { append("//") } if (encodedUsername.isNotEmpty() || encodedPassword.isNotEmpty()) { append(encodedUsername) if (encodedPassword.isNotEmpty()) { append(':') append(encodedPassword) } append('@') } if (host != null) { if (':' in host!!) { // Host is an IPv6 address. append('[') append(host) append(']') } else { append(host) } } if (port != -1 || scheme != null) { val effectivePort = effectivePort() if (scheme == null || effectivePort != defaultPort(scheme!!)) { append(':') append(effectivePort) } } encodedPathSegments.toPathString(this) if (encodedQueryNamesAndValues != null) { append('?') encodedQueryNamesAndValues!!.toQueryString(this) } if (encodedFragment != null) { append('#') append(encodedFragment) } } } internal fun parse(base: HttpUrl?, input: String): Builder { var pos = input.indexOfFirstNonAsciiWhitespace() val limit = input.indexOfLastNonAsciiWhitespace(pos) // Scheme. val schemeDelimiterOffset = schemeDelimiterOffset(input, pos, limit) if (schemeDelimiterOffset != -1) { when { input.startsWith("https:", ignoreCase = true, startIndex = pos) -> { this.scheme = "https" pos += "https:".length } input.startsWith("http:", ignoreCase = true, startIndex = pos) -> { this.scheme = "http" pos += "http:".length } else -> throw IllegalArgumentException("Expected URL scheme 'http' or 'https' but was '" + input.substring(0, schemeDelimiterOffset) + "'") } } else if (base != null) { this.scheme = base.scheme } else { throw IllegalArgumentException( "Expected URL scheme 'http' or 'https' but no colon was found") } // Authority. var hasUsername = false var hasPassword = false val slashCount = input.slashCount(pos, limit) if (slashCount >= 2 || base == null || base.scheme != this.scheme) { // Read an authority if either: // * The input starts with 2 or more slashes. These follow the scheme if it exists. // * The input scheme exists and is different from the base URL's scheme. // // The structure of an authority is: // username:password@host:port // // Username, password and port are optional. // [username[:password]@]host[:port] pos += slashCount authority@ while (true) { val componentDelimiterOffset = input.delimiterOffset("@/\\?#", pos, limit) val c = if (componentDelimiterOffset != limit) { input[componentDelimiterOffset].toInt() } else { -1 } when (c) { '@'.toInt() -> { // User info precedes. if (!hasPassword) { val passwordColonOffset = input.delimiterOffset(':', pos, componentDelimiterOffset) val canonicalUsername = input.canonicalize( pos = pos, limit = passwordColonOffset, encodeSet = USERNAME_ENCODE_SET, alreadyEncoded = true ) this.encodedUsername = if (hasUsername) { this.encodedUsername + "%40" + canonicalUsername } else { canonicalUsername } if (passwordColonOffset != componentDelimiterOffset) { hasPassword = true this.encodedPassword = input.canonicalize( pos = passwordColonOffset + 1, limit = componentDelimiterOffset, encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } hasUsername = true } else { this.encodedPassword = this.encodedPassword + "%40" + input.canonicalize( pos = pos, limit = componentDelimiterOffset, encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } pos = componentDelimiterOffset + 1 } -1, '/'.toInt(), '\\'.toInt(), '?'.toInt(), '#'.toInt() -> { // Host info precedes. val portColonOffset = portColonOffset(input, pos, componentDelimiterOffset) if (portColonOffset + 1 < componentDelimiterOffset) { host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost() port = parsePort(input, portColonOffset + 1, componentDelimiterOffset) require(port != -1) { "Invalid URL port: \"${input.substring(portColonOffset + 1, componentDelimiterOffset)}\"" } } else { host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost() port = defaultPort(scheme!!) } require(host != null) { "$INVALID_HOST: \"${input.substring(pos, portColonOffset)}\"" } pos = componentDelimiterOffset break@authority } } } } else { // This is a relative link. Copy over all authority components. Also maybe the path & query. this.encodedUsername = base.encodedUsername this.encodedPassword = base.encodedPassword this.host = base.host this.port = base.port this.encodedPathSegments.clear() this.encodedPathSegments.addAll(base.encodedPathSegments) if (pos == limit || input[pos] == '#') { encodedQuery(base.encodedQuery) } } // Resolve the relative path. val pathDelimiterOffset = input.delimiterOffset("?#", pos, limit) resolvePath(input, pos, pathDelimiterOffset) pos = pathDelimiterOffset // Query. if (pos < limit && input[pos] == '?') { val queryDelimiterOffset = input.delimiterOffset('#', pos, limit) this.encodedQueryNamesAndValues = input.canonicalize( pos = pos + 1, limit = queryDelimiterOffset, encodeSet = QUERY_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true ).toQueryNamesAndValues() pos = queryDelimiterOffset } // Fragment. if (pos < limit && input[pos] == '#') { this.encodedFragment = input.canonicalize( pos = pos + 1, limit = limit, encodeSet = FRAGMENT_ENCODE_SET, alreadyEncoded = true, unicodeAllowed = true ) } return this } private fun resolvePath(input: String, startPos: Int, limit: Int) { var pos = startPos // Read a delimiter. if (pos == limit) { // Empty path: keep the base path as-is. return } val c = input[pos] if (c == '/' || c == '\\') { // Absolute path: reset to the default "/". encodedPathSegments.clear() encodedPathSegments.add("") pos++ } else { // Relative path: clear everything after the last '/'. encodedPathSegments[encodedPathSegments.size - 1] = "" } // Read path segments. var i = pos while (i < limit) { val pathSegmentDelimiterOffset = input.delimiterOffset("/\\", i, limit) val segmentHasTrailingSlash = pathSegmentDelimiterOffset < limit push(input, i, pathSegmentDelimiterOffset, segmentHasTrailingSlash, true) i = pathSegmentDelimiterOffset if (segmentHasTrailingSlash) i++ } } /** Adds a path segment. If the input is ".." or equivalent, this pops a path segment. */ private fun push( input: String, pos: Int, limit: Int, addTrailingSlash: Boolean, alreadyEncoded: Boolean ) { val segment = input.canonicalize( pos = pos, limit = limit, encodeSet = PATH_SEGMENT_ENCODE_SET, alreadyEncoded = alreadyEncoded ) if (isDot(segment)) { return // Skip '.' path segments. } if (isDotDot(segment)) { pop() return } if (encodedPathSegments[encodedPathSegments.size - 1].isEmpty()) { encodedPathSegments[encodedPathSegments.size - 1] = segment } else { encodedPathSegments.add(segment) } if (addTrailingSlash) { encodedPathSegments.add("") } } private fun isDot(input: String): Boolean { return input == "." || input.equals("%2e", ignoreCase = true) } private fun isDotDot(input: String): Boolean { return input == ".." || input.equals("%2e.", ignoreCase = true) || input.equals(".%2e", ignoreCase = true) || input.equals("%2e%2e", ignoreCase = true) } /** * Removes a path segment. When this method returns the last segment is always "", which means * the encoded path will have a trailing '/'. * * Popping "/a/b/c/" yields "/a/b/". In this case the list of path segments goes from ["a", * "b", "c", ""] to ["a", "b", ""]. * * Popping "/a/b/c" also yields "/a/b/". The list of path segments goes from ["a", "b", "c"] * to ["a", "b", ""]. */ private fun pop() { val removed = encodedPathSegments.removeAt(encodedPathSegments.size - 1) // Make sure the path ends with a '/' by either adding an empty string or clearing a segment. if (removed.isEmpty() && encodedPathSegments.isNotEmpty()) { encodedPathSegments[encodedPathSegments.size - 1] = "" } else { encodedPathSegments.add("") } } companion object { internal const val INVALID_HOST = "Invalid URL host" /** * Returns the index of the ':' in `input` that is after scheme characters. Returns -1 if * `input` does not have a scheme that starts at `pos`. */ private fun schemeDelimiterOffset(input: String, pos: Int, limit: Int): Int { if (limit - pos < 2) return -1 val c0 = input[pos] if ((c0 < 'a' || c0 > 'z') && (c0 < 'A' || c0 > 'Z')) return -1 // Not a scheme start char. characters@ for (i in pos + 1 until limit) { return when (input[i]) { // Scheme character. Keep going. in 'a'..'z', in 'A'..'Z', in '0'..'9', '+', '-', '.' -> continue@characters // Scheme prefix! ':' -> i // Non-scheme character before the first ':'. else -> -1 } } return -1 // No ':'; doesn't start with a scheme. } /** Returns the number of '/' and '\' slashes in this, starting at `pos`. */ private fun String.slashCount(pos: Int, limit: Int): Int { var slashCount = 0 for (i in pos until limit) { val c = this[i] if (c == '\\' || c == '/') { slashCount++ } else { break } } return slashCount } /** Finds the first ':' in `input`, skipping characters between square braces "[...]". */ private fun portColonOffset(input: String, pos: Int, limit: Int): Int { var i = pos while (i < limit) { when (input[i]) { '[' -> { while (++i < limit) { if (input[i] == ']') break } } ':' -> return i } i++ } return limit // No colon. } private fun parsePort(input: String, pos: Int, limit: Int): Int { return try { // Canonicalize the port string to skip '\n' etc. val portString = input.canonicalize(pos = pos, limit = limit, encodeSet = "") val i = portString.toInt() if (i in 1..65535) i else -1 } catch (_: NumberFormatException) { -1 // Invalid port. } } } } companion object { private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') internal const val USERNAME_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#" internal const val PASSWORD_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#" internal const val PATH_SEGMENT_ENCODE_SET = " \"<>^`{}|/\\?#" internal const val PATH_SEGMENT_ENCODE_SET_URI = "[]" internal const val QUERY_ENCODE_SET = " \"'<>#" internal const val QUERY_COMPONENT_REENCODE_SET = " \"'<>#&=" internal const val QUERY_COMPONENT_ENCODE_SET = " !\"#$&'(),/:;<=>?@[]\\^`{|}~" internal const val QUERY_COMPONENT_ENCODE_SET_URI = "\\^`{|}" internal const val FORM_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#&!$(),~" internal const val FRAGMENT_ENCODE_SET = "" internal const val FRAGMENT_ENCODE_SET_URI = " \"#<>\\^`{|}" /** Returns 80 if `scheme.equals("http")`, 443 if `scheme.equals("https")` and -1 otherwise. */ @JvmStatic fun defaultPort(scheme: String): Int { return when (scheme) { "http" -> 80 "https" -> 443 else -> -1 } } /** Returns a path string for this list of path segments. */ internal fun List<String>.toPathString(out: StringBuilder) { for (i in 0 until size) { out.append('/') out.append(this[i]) } } /** Returns a string for this list of query names and values. */ internal fun List<String?>.toQueryString(out: StringBuilder) { for (i in 0 until size step 2) { val name = this[i] val value = this[i + 1] if (i > 0) out.append('&') out.append(name) if (value != null) { out.append('=') out.append(value) } } } /** * Cuts this string up into alternating parameter names and values. This divides a query string * like `subject=math&easy&problem=5-2=3` into the list `["subject", "math", "easy", null, * "problem", "5-2=3"]`. Note that values may be null and may contain '=' characters. */ internal fun String.toQueryNamesAndValues(): MutableList<String?> { val result = mutableListOf<String?>() var pos = 0 while (pos <= length) { var ampersandOffset = indexOf('&', pos) if (ampersandOffset == -1) ampersandOffset = length val equalsOffset = indexOf('=', pos) if (equalsOffset == -1 || equalsOffset > ampersandOffset) { result.add(substring(pos, ampersandOffset)) result.add(null) // No value for this name. } else { result.add(substring(pos, equalsOffset)) result.add(substring(equalsOffset + 1, ampersandOffset)) } pos = ampersandOffset + 1 } return result } /** * Returns a new [HttpUrl] representing this. * * @throws IllegalArgumentException If this is not a well-formed HTTP or HTTPS URL. */ @JvmStatic @JvmName("get") fun String.toHttpUrl(): HttpUrl = Builder().parse(null, this).build() /** * Returns a new `HttpUrl` representing `url` if it is a well-formed HTTP or HTTPS URL, or null * if it isn't. */ @JvmStatic @JvmName("parse") fun String.toHttpUrlOrNull(): HttpUrl? { return try { toHttpUrl() } catch (_: IllegalArgumentException) { null } } /** * Returns an [HttpUrl] for this if its protocol is `http` or `https`, or null if it has any * other protocol. */ @JvmStatic @JvmName("get") fun URL.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull() @JvmStatic @JvmName("get") fun URI.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrl()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrl"]), level = DeprecationLevel.ERROR) fun get(url: String): HttpUrl = url.toHttpUrl() @JvmName("-deprecated_parse") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun parse(url: String): HttpUrl? = url.toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun get(url: URL): HttpUrl? = url.toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "uri.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun get(uri: URI): HttpUrl? = uri.toHttpUrlOrNull() internal fun String.percentDecode( pos: Int = 0, limit: Int = length, plusIsSpace: Boolean = false ): String { for (i in pos until limit) { val c = this[i] if (c == '%' || c == '+' && plusIsSpace) { // Slow path: the character at i requires decoding! val out = Buffer() out.writeUtf8(this, pos, i) out.writePercentDecoded(this, pos = i, limit = limit, plusIsSpace = plusIsSpace) return out.readUtf8() } } // Fast path: no characters in [pos..limit) required decoding. return substring(pos, limit) } private fun Buffer.writePercentDecoded( encoded: String, pos: Int, limit: Int, plusIsSpace: Boolean ) { var codePoint: Int var i = pos while (i < limit) { codePoint = encoded.codePointAt(i) if (codePoint == '%'.toInt() && i + 2 < limit) { val d1 = encoded[i + 1].parseHexDigit() val d2 = encoded[i + 2].parseHexDigit() if (d1 != -1 && d2 != -1) { writeByte((d1 shl 4) + d2) i += 2 i += Character.charCount(codePoint) continue } } else if (codePoint == '+'.toInt() && plusIsSpace) { writeByte(' '.toInt()) i++ continue } writeUtf8CodePoint(codePoint) i += Character.charCount(codePoint) } } private fun String.isPercentEncoded(pos: Int, limit: Int): Boolean { return pos + 2 < limit && this[pos] == '%' && this[pos + 1].parseHexDigit() != -1 && this[pos + 2].parseHexDigit() != -1 } /** * Returns a substring of `input` on the range `[pos..limit)` with the following * transformations: * * * Tabs, newlines, form feeds and carriage returns are skipped. * * * In queries, ' ' is encoded to '+' and '+' is encoded to "%2B". * * * Characters in `encodeSet` are percent-encoded. * * * Control characters and non-ASCII characters are percent-encoded. * * * All other characters are copied without transformation. * * @param alreadyEncoded true to leave '%' as-is; false to convert it to '%25'. * @param strict true to encode '%' if it is not the prefix of a valid percent encoding. * @param plusIsSpace true to encode '+' as "%2B" if it is not already encoded. * @param unicodeAllowed true to leave non-ASCII codepoint unencoded. * @param charset which charset to use, null equals UTF-8. */ internal fun String.canonicalize( pos: Int = 0, limit: Int = length, encodeSet: String, alreadyEncoded: Boolean = false, strict: Boolean = false, plusIsSpace: Boolean = false, unicodeAllowed: Boolean = false, charset: Charset? = null ): String { var codePoint: Int var i = pos while (i < limit) { codePoint = codePointAt(i) if (codePoint < 0x20 || codePoint == 0x7f || codePoint >= 0x80 && !unicodeAllowed || codePoint.toChar() in encodeSet || codePoint == '%'.toInt() && (!alreadyEncoded || strict && !isPercentEncoded(i, limit)) || codePoint == '+'.toInt() && plusIsSpace) { // Slow path: the character at i requires encoding! val out = Buffer() out.writeUtf8(this, pos, i) out.writeCanonicalized( input = this, pos = i, limit = limit, encodeSet = encodeSet, alreadyEncoded = alreadyEncoded, strict = strict, plusIsSpace = plusIsSpace, unicodeAllowed = unicodeAllowed, charset = charset ) return out.readUtf8() } i += Character.charCount(codePoint) } // Fast path: no characters in [pos..limit) required encoding. return substring(pos, limit) } private fun Buffer.writeCanonicalized( input: String, pos: Int, limit: Int, encodeSet: String, alreadyEncoded: Boolean, strict: Boolean, plusIsSpace: Boolean, unicodeAllowed: Boolean, charset: Charset? ) { var encodedCharBuffer: Buffer? = null // Lazily allocated. var codePoint: Int var i = pos while (i < limit) { codePoint = input.codePointAt(i) if (alreadyEncoded && (codePoint == '\t'.toInt() || codePoint == '\n'.toInt() || codePoint == '\u000c'.toInt() || codePoint == '\r'.toInt())) { // Skip this character. } else if (codePoint == '+'.toInt() && plusIsSpace) { // Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'. writeUtf8(if (alreadyEncoded) "+" else "%2B") } else if (codePoint < 0x20 || codePoint == 0x7f || codePoint >= 0x80 && !unicodeAllowed || codePoint.toChar() in encodeSet || codePoint == '%'.toInt() && (!alreadyEncoded || strict && !input.isPercentEncoded(i, limit))) { // Percent encode this character. if (encodedCharBuffer == null) { encodedCharBuffer = Buffer() } if (charset == null || charset == UTF_8) { encodedCharBuffer.writeUtf8CodePoint(codePoint) } else { encodedCharBuffer.writeString(input, i, i + Character.charCount(codePoint), charset) } while (!encodedCharBuffer.exhausted()) { val b = encodedCharBuffer.readByte().toInt() and 0xff writeByte('%'.toInt()) writeByte(HEX_DIGITS[b shr 4 and 0xf].toInt()) writeByte(HEX_DIGITS[b and 0xf].toInt()) } } else { // This character doesn't need encoding. Just copy it over. writeUtf8CodePoint(codePoint) } i += Character.charCount(codePoint) } } } }
apache-2.0
fe493c042b4131a6495d58fa49cece18
36.804499
106
0.574744
4.20075
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/RendererDelegate.kt
1
3024
/***************************************************************************** * RendererDelegate.java * * Copyright © 2017 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc import kotlinx.coroutines.* import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.videolan.libvlc.RendererDiscoverer import org.videolan.libvlc.RendererItem import org.videolan.resources.AppContextProvider import org.videolan.resources.VLCInstance import org.videolan.tools.AppScope import org.videolan.tools.NetworkMonitor import org.videolan.tools.isAppStarted import org.videolan.tools.livedata.LiveDataset import org.videolan.tools.retry import java.util.* @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi object RendererDelegate : RendererDiscoverer.EventListener { private val TAG = "VLC/RendererDelegate" private val discoverers = ArrayList<RendererDiscoverer>() val renderers : LiveDataset<RendererItem> = LiveDataset() @Volatile private var started = false init { NetworkMonitor.getInstance(AppContextProvider.appContext).connectionFlow.onEach { if (it.connected) start() else stop() }.launchIn(AppScope) } suspend fun start() { if (started) return val libVlc = withContext(Dispatchers.IO) { VLCInstance.get(AppContextProvider.appContext) } started = true for (discoverer in RendererDiscoverer.list(libVlc)) { val rd = RendererDiscoverer(libVlc, discoverer.name) discoverers.add(rd) rd.setEventListener(this@RendererDelegate) retry(5, 1000L) { if (!rd.isReleased) rd.start() else false } } } fun stop() { if (!started) return started = false for (discoverer in discoverers) discoverer.stop() if (isAppStarted() || PlaybackService.instance?.run { !isPlaying } != false) { PlaybackService.renderer.value = null } clear() } private fun clear() { discoverers.clear() renderers.clear() } override fun onEvent(event: RendererDiscoverer.Event?) { when (event?.type) { RendererDiscoverer.Event.ItemAdded -> renderers.add(event.item) RendererDiscoverer.Event.ItemDeleted -> renderers.remove(event.item) } } }
gpl-2.0
0d2ddfb031eb6a3c9c06afe594fa9a0a
35.421687
148
0.694343
4.566465
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/snwx.kt
1
2648
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.ownLinesString import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern import cc.aoeiuv020.panovel.api.firstTwoIntPattern /** * * Created by AoEiuV020 on 2018.03.07-02:42:57. */ class Snwx : DslJsoupNovelContext() {init { hide = true site { name = "少年文学" baseUrl = "https://www.snwx3.com" logo = "https://www.snwx3.com/xiaoyi/images/logo.gif" } cookieFilter { // 删除cookie绕开搜索时间间隔限制, // 这网站只删除jieqiVisitTime已经没用了, removeAll { httpUrl.encodedPath().startsWith("/modules/article/search.php") } } search { get { charset = "GBK" url = "/modules/article/search.php" data { "searchkey" to it } } document { items("#newscontent > div.l > ul > li") { name("> span.s2 > a") author("> span.s4") } } } bookIdRegex = firstTwoIntPattern // https://www.snwxx.com/book/66/66076/ detailPageTemplate = "/book/%s/" detail { document { val div = element("#info") val title = element("> div.infotitle", parent = div) novel { name("> h1", parent = title) author("> i:nth-child(2)", parent = title, block = pickString("作\\s*者:(\\S*)")) } image("#fmimg > img") introduction("> div.intro", parent = div) { // 可能没有简介, it.textNodes().first { // TextNode不可避免的有空的, !it.isBlank && !it.wholeText.let { // 后面几个TextNode广告包含这些文字, it.startsWith("各位书友要是觉得《${novel?.name}》还不错的话请不要忘记向您QQ群和微博里的朋友推荐哦!") || it.startsWith("${novel?.name}最新章节,${novel?.name}无弹窗,${novel?.name}全文阅读.") } }.ownLinesString() } // 这网站详情页没有更新时间, } } chapters { document { items("#list > dl > dd > a") } } bookIdWithChapterIdRegex = firstThreeIntPattern contentPageTemplate = "/book/%s.html" content { document { items("#BookText") } } } }
gpl-3.0
9b3690f109ed1180132ecfc399701b6b
28.390244
108
0.494191
3.813291
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/search/SiteSettingsPresenter.kt
1
3806
package cc.aoeiuv020.panovel.search import cc.aoeiuv020.panovel.Presenter import cc.aoeiuv020.panovel.api.NovelContext import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.util.notNullOrReport import cc.aoeiuv020.regex.compileRegex import okhttp3.Cookie import okhttp3.Headers import okhttp3.HttpUrl import org.jetbrains.anko.* import java.nio.charset.Charset /** * Created by AoEiuV020 on 2019.05.01-19:56:11. */ class SiteSettingsPresenter( private val site: String ) : Presenter<SiteSettingsActivity>(), AnkoLogger { private lateinit var context: NovelContext fun start() { view?.doAsync({ e -> val message = "读取网站失败," Reporter.post(message, e) error(message, e) view?.runOnUiThread { view?.showError(message, e) view?.finish() } }) { context = DataManager.getNovelContextByName(site) uiThread { view -> view.init() } } } fun setCookie(input: (String) -> String?, success: () -> Unit) { view?.doAsync({ e -> val message = "设置Cookie失败," Reporter.post(message, e) error(message, e) view?.runOnUiThread { view?.showError(message, e) } }) { val oldCookie = context.cookies.values.joinToString("; ") { it.run { "${name()}=${value()}" } } val newCookie = input(oldCookie) ?: return@doAsync val cookieMap = newCookie.split(";").mapNotNull { cookiePair -> debug { "pull cookie: <$cookiePair>" } // 取出来的cookiePair只有name=value,Cookie.parse一定能通过,也因此可能有超时信息拿不出来的问题, Cookie.parse(HttpUrl.parse(context.site.baseUrl).notNullOrReport(), cookiePair)?.let { cookie -> cookie.name() to cookie } }.toMap() context.replaceCookies(cookieMap) uiThread { success() } } } fun setHeader(input: (String) -> String?, success: () -> Unit) { view?.doAsync({ e -> val message = "设置Header失败," Reporter.post(message, e) error(message, e) view?.runOnUiThread { view?.showError(message, e) } }) { val old = context.headers.toList().joinToString("\n") { (name, value) -> "$name: $value" } val new = input(old) ?: return@doAsync val headers: Headers = Headers.of(*new.split(compileRegex("\n|(: *)")).toTypedArray()) context.replaceHeaders(headers) uiThread { success() } } } fun setCharset(input: (String) -> String?, success: () -> Unit) { view?.doAsync({ e -> val message = "设置编码失败," Reporter.post(message, e) error(message, e) view?.runOnUiThread { view?.showError(message, e) } }) { val old = context.forceCharset ?: context.charset ?: context.defaultCharset val new = input(old) ?: return@doAsync if (new.isNotBlank()) { Charset.forName(new) } context.forceCharset = new uiThread { success() } } } fun getReason(): String { return context.reason } fun isUpkeep(): Boolean { return context.upkeep } }
gpl-3.0
323db6c45a29eb328b0c6e4cd2d31c9a
29.545455
112
0.517316
4.534969
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/content/provider/DefaultContentProvider.kt
1
2226
package com.fireflysource.net.http.server.impl.content.provider import com.fireflysource.common.io.BufferUtils import com.fireflysource.common.sys.ProjectVersion import com.fireflysource.net.http.common.model.HttpStatus import com.fireflysource.net.http.server.HttpServerContentProvider import com.fireflysource.net.http.server.RoutingContext import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util.* import java.util.concurrent.CompletableFuture class DefaultContentProvider( private val status: Int, private val exception: Throwable?, private val ctx: RoutingContext ) : HttpServerContentProvider { private val html = """ |<!DOCTYPE html> |<html> |<head> |<title>${getTitle()}</title> |</head> |<body> |<h1>${getTitle()}</h1> |<p>${getContent()}</p> |<hr/> |<footer><em>powered by Firefly ${ProjectVersion.getValue()}</em></footer> |</body> |</html> """.trimMargin() private val contentByteBuffer = BufferUtils.toBuffer(html, StandardCharsets.UTF_8) private val provider: ByteBufferContentProvider = ByteBufferContentProvider(contentByteBuffer) private fun getTitle(): String { return "$status ${getCode().message}" } private fun getCode(): HttpStatus.Code { return Optional.ofNullable(HttpStatus.getCode(status)).orElse(HttpStatus.Code.INTERNAL_SERVER_ERROR) } private fun getContent(): String { return when (getCode()) { HttpStatus.Code.NOT_FOUND -> "The resource ${ctx.uri.path} is not found" HttpStatus.Code.INTERNAL_SERVER_ERROR -> "The server internal error. <br/> ${exception?.message}" else -> "${getTitle()} <br/> ${exception?.message}" } } override fun length(): Long = provider.length() override fun isOpen(): Boolean = provider.isOpen override fun toByteBuffer(): ByteBuffer = provider.toByteBuffer() override fun closeAsync(): CompletableFuture<Void> = provider.closeAsync() override fun close() = provider.close() override fun read(byteBuffer: ByteBuffer): CompletableFuture<Int> = provider.read(byteBuffer) }
apache-2.0
9e5052b9ccf612fb750d6e8eca4ecb4b
34.349206
109
0.678347
4.627859
false
false
false
false
nickbutcher/plaid
core/src/test/java/io/plaidapp/core/designernews/TestData.kt
1
1296
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.designernews import io.plaidapp.core.designernews.data.stories.model.StoryLinks import io.plaidapp.core.designernews.data.users.model.User import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody.Companion.toResponseBody /** * Test data */ val user = User( id = 111L, firstName = "Plaicent", lastName = "van Plaid", displayName = "Plaicent van Plaid", portraitUrl = "www" ) val errorResponseBody = "Error".toResponseBody("".toMediaTypeOrNull()) const val userId = 123L val storyLinks = StoryLinks( user = userId, comments = listOf(1, 2, 3), upvotes = listOf(11, 22, 33), downvotes = listOf(111, 222, 333) )
apache-2.0
87549c4a2b6d71af9298399a79495fa5
27.8
75
0.72608
3.88024
false
false
false
false
goodwinnk/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestUtilKt.kt
1
15573
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.impl import com.intellij.diagnostic.MessagePool import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Ref import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.framework.toPrintable import com.intellij.ui.EngravedLabel import org.fest.swing.core.ComponentMatcher import org.fest.swing.core.GenericTypeMatcher import org.fest.swing.core.Robot import org.fest.swing.edt.GuiActionRunner import org.fest.swing.edt.GuiQuery import org.fest.swing.edt.GuiTask import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause import org.fest.swing.timing.Timeout import org.fest.swing.timing.Wait import java.awt.Component import java.awt.Container import java.awt.Window import java.util.* import java.util.concurrent.TimeUnit import javax.swing.JCheckBox import javax.swing.JDialog import javax.swing.JLabel import javax.swing.JRadioButton import kotlin.collections.ArrayList /** * @author Sergey Karashevich */ object GuiTestUtilKt { fun createTree(string: String): ImmutableTree<String> { val currentPath = ArrayList<String>() var lines = string.split("\n") if (lines.last().isEmpty()) lines = lines.subList(0, lines.lastIndex - 1) val tree: ImmutableTree<String> = ImmutableTree() var lastNode: ImmutableTreeNode<String>? = null try { for (line in lines) { if (currentPath.isEmpty()) { currentPath.add(line) tree.root = ImmutableTreeNode(line.withoutIndent(), null) lastNode = tree.root } else { if (currentPath.last() hasDiffIndentFrom line) { if (currentPath.last().getIndent() > line.getIndent()) { while (currentPath.last() hasDiffIndentFrom line) { currentPath.removeAt(currentPath.lastIndex) lastNode = lastNode!!.parent } currentPath.removeAt(currentPath.lastIndex) currentPath.add(line) lastNode = lastNode!!.parent!!.createChild(line.withoutIndent()) } else { currentPath.add(line) lastNode = lastNode!!.createChild(line.withoutIndent()) } } else { currentPath.removeAt(currentPath.lastIndex) currentPath.add(line) lastNode = lastNode!!.parent!!.createChild(line.withoutIndent()) } } } return tree } catch (e: Exception) { throw Exception("Unable to build a tree from given data. Check indents and ") } } private infix fun String.hasDiffIndentFrom(s: String): Boolean { return this.getIndent() != s.getIndent() } private fun String.getIndent() = this.indexOfFirst { it != ' ' } private fun String.withoutIndent() = this.substring(this.getIndent()) private operator fun String.times(n: Int): String { val sb = StringBuilder(n) for (i in 1..n) { sb.append(this) } return sb.toString() } class ImmutableTree<Value> { var root: ImmutableTreeNode<Value>? = null fun print() { if (root == null) throw Exception("Unable to print tree without root (or if root is null)") printRecursive(root!!, 0) } fun printRecursive(root: ImmutableTreeNode<Value>, indent: Int) { println(" " * indent + root.value) if (!root.isLeaf()) root.children.forEach { printRecursive(it, indent + 2) } } } data class ImmutableTreeNode<Value>(val value: Value, val parent: ImmutableTreeNode<Value>?, val children: LinkedList<ImmutableTreeNode<Value>> = LinkedList()) { fun createChild(childValue: Value): ImmutableTreeNode<Value> { val child = ImmutableTreeNode<Value>(childValue, this) children.add(child) return child } fun countChildren(): Int = children.count() fun isLeaf(): Boolean = (children.count() == 0) } fun Component.isTextComponent(): Boolean { val textComponentsTypes = arrayOf(JLabel::class.java, JRadioButton::class.java, JCheckBox::class.java) return textComponentsTypes.any { it.isInstance(this) } } fun Component.getComponentText(): String? { when (this) { is JLabel -> return this.text is JRadioButton -> return this.text is JCheckBox -> return this.text else -> return null } } private fun findComponentByText(robot: Robot, container: Container, text: String, timeout: Timeout = Timeouts.seconds30): Component { return withPauseWhenNull(timeout = timeout) { robot.finder().findAll(container, ComponentMatcher { component -> component!!.isShowing && component.isTextComponent() && component.getComponentText() == text }).firstOrNull() } } fun <BoundedComponent> findBoundedComponentByText(robot: Robot, container: Container, text: String, componentType: Class<BoundedComponent>, timeout: Timeout = Timeouts.seconds30): BoundedComponent { val componentWithText = findComponentByText(robot, container, text, timeout) if (componentWithText is JLabel && componentWithText.labelFor != null) { val labeledComponent = componentWithText.labelFor if (componentType.isInstance(labeledComponent)) return labeledComponent as BoundedComponent return robot.finder().find(labeledComponent as Container) { component -> componentType.isInstance(component) } as BoundedComponent } try { return withPauseWhenNull(timeout = timeout) { val componentsOfInstance = robot.finder().findAll(container, ComponentMatcher { component -> componentType.isInstance(component) }) componentsOfInstance.filter { it.isShowing && it.onHeightCenter(componentWithText, true) } .sortedBy { it.bounds.x } .firstOrNull() } as BoundedComponent } catch (e: WaitTimedOutError) { throw ComponentLookupException("Unable to find component of type: ${componentType.simpleName} in $container by text: $text") } } //Does the textComponent intersects horizontal line going through the center of this component and lays lefter than this component fun Component.onHeightCenter(textComponent: Component, onLeft: Boolean): Boolean { val centerXAxis = this.bounds.height / 2 + this.locationOnScreen.y val sideCheck = if (onLeft) textComponent.locationOnScreen.x < this.locationOnScreen.x else textComponent.locationOnScreen.x > this.locationOnScreen.x return (textComponent.locationOnScreen.y <= centerXAxis) && (textComponent.locationOnScreen.y + textComponent.bounds.height >= centerXAxis) && (sideCheck) } fun runOnEdt(task: () -> Unit) { GuiActionRunner.execute(object : GuiTask() { override fun executeInEDT() { task() } }) } /** * waits for 30 sec timeout when functionProbeToNull() not return null * * @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null" */ fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe will", timeout: Timeout = Timeouts.defaultTimeout, functionProbeToNull: () -> ReturnType?): ReturnType { var result: ReturnType? = null waitUntil("$conditionText will be not null", timeout) { result = functionProbeToNull() result != null } return result!! } fun waitUntil(condition: String, timeout: Timeout = Timeouts.defaultTimeout, conditionalFunction: () -> Boolean) { Pause.pause(object : Condition("${timeout.toPrintable()} until $condition") { override fun test() = conditionalFunction() }, timeout) } fun <R> tryWithPause(exceptionClass: Class<out Exception>, condition: String = "try block will not throw ${exceptionClass.name} exception", timeout: Timeout, tryBlock: () -> R): R { val exceptionRef: Ref<Exception> = Ref.create() try { return withPauseWhenNull (condition, timeout) { try { tryBlock() } catch (e: Exception) { if (exceptionClass.isInstance(e)) { exceptionRef.set(e) return@withPauseWhenNull null } throw e } } } catch (e: WaitTimedOutError) { throw Exception("Timeout for $condition exceeded ${timeout.toPrintable()}", exceptionRef.get()) } } fun silentWaitUntil(condition: String, timeoutInSeconds: Int = 60, conditionalFunction: () -> Boolean) { try { Pause.pause(object : Condition("$timeoutInSeconds second(s) until $condition silently") { override fun test() = conditionalFunction() }, Timeout.timeout(timeoutInSeconds.toLong(), TimeUnit.SECONDS)) } catch (ignore: WaitTimedOutError) { } } fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> { val result = LinkedList<ComponentType>() val queue: Queue<Component> = LinkedList() @Suppress("UNCHECKED_CAST") fun check(container: Component) { if (clazz.isInstance(container)) result.add(container as ComponentType) } queue.add(container) while (queue.isNotEmpty()) { val polled = queue.poll() check(polled) if (polled is Container) queue.addAll(polled.components) } return result } fun <ComponentType : Component> waitUntilGone(robot: Robot, timeout: Timeout = Timeouts.seconds30, root: Container? = null, matcher: GenericTypeMatcher<ComponentType>) { return GuiTestUtil.waitUntilGone(root, timeout, matcher) } fun GuiTestCase.waitProgressDialogUntilGone(dialogTitle: String, timeoutToAppear: Timeout = Timeouts.seconds05, timeoutToGone: Timeout = Timeouts.defaultTimeout) { waitProgressDialogUntilGone(this.robot(), dialogTitle, timeoutToAppear, timeoutToGone) } fun waitProgressDialogUntilGone(robot: Robot, progressTitle: String, timeoutToAppear: Timeout = Timeouts.seconds30, timeoutToGone: Timeout = Timeouts.defaultTimeout) { //wait dialog appearance. In a bad case we could pass dialog appearance. var dialog: JDialog? = null try { waitUntil("progress dialog with title $progressTitle will appear", timeoutToAppear) { dialog = findProgressDialog(robot, progressTitle) dialog != null } } catch (timeoutError: WaitTimedOutError) { return } waitUntil("progress dialog with title $progressTitle will gone", timeoutToGone) { dialog == null || !dialog!!.isShowing } } fun findProgressDialog(robot: Robot, progressTitle: String): JDialog? { return robot.finder().findAll(typeMatcher(JDialog::class.java) { findAllWithBFS(it, EngravedLabel::class.java).filter { it.isShowing && it.text == progressTitle }.any() }).firstOrNull() } fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>, matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> { return object : GenericTypeMatcher<ComponentType>(componentTypeClass) { override fun isMatching(component: ComponentType): Boolean = matcher(component) } } fun <ReturnType> computeOnEdt(query: () -> ReturnType): ReturnType? = GuiActionRunner.execute(object : GuiQuery<ReturnType>() { override fun executeInEDT(): ReturnType = query() }) fun <ReturnType> computeOnEdtWithTry(query: () -> ReturnType?): ReturnType? { val result = GuiActionRunner.execute(object : GuiQuery<Pair<ReturnType?, Throwable?>>() { override fun executeInEDT(): kotlin.Pair<ReturnType?, Throwable?> { return try { Pair(query(), null) } catch (e: Exception) { Pair(null, e) } } }) if (result?.second != null) throw result.second!! return result?.first } inline fun <T> ignoreComponentLookupException(action: () -> T): T? = try { action() } catch (ignore: ComponentLookupException) { null } fun ensureCreateHasDone(guiTestCase: GuiTestCase) { try { com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(), matcher = com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher( com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame::class.java) { it.isShowing }) } catch (timeoutError: WaitTimedOutError) { with(guiTestCase) { welcomeFrame { button("Create").clickWhenEnabled() } } } } fun windowsShowing(): List<Window> { val listBuilder = ArrayList<Window>() Window.getWindows().filterTo(listBuilder) { it.isShowing } return listBuilder } fun fatalErrorsFromIde(afterDate: Date = Date(0)): List<Error> { val errorMessages = MessagePool.getInstance().getFatalErrors(true, true) val freshErrorMessages = errorMessages.filter { it.date > afterDate } val errors = mutableListOf<Error>() for (errorMessage in freshErrorMessages) { val messageBuilder = StringBuilder(errorMessage.message ?: "") val additionalInfo: String? = errorMessage.additionalInfo if (additionalInfo != null && additionalInfo.isNotEmpty()) messageBuilder.append(System.getProperty("line.separator")).append("Additional Info: ").append(additionalInfo) val error = Error(messageBuilder.toString(), errorMessage.throwable) errors.add(error) } return Collections.unmodifiableList(errors) } fun waitForBackgroundTasks(robot: Robot, timeoutInSeconds: Int = 120) { Wait.seconds(timeoutInSeconds.toLong()).expecting("background tasks to finish") .until { robot.waitForIdle() val progressManager = ProgressManager.getInstance() !progressManager.hasModalProgressIndicator() && !progressManager.hasProgressIndicator() && !progressManager.hasUnsafeProgressIndicator() } } } fun main(args: Array<String>) { val tree = GuiTestUtilKt.createTree("project\n" + " src\n" + " com.username\n" + " Test1.java\n" + " Test2.java\n" + " lib\n" + " someLib1\n" + " someLib2") tree.print() }
apache-2.0
ab11d1618a545c2485ec1e5d46582fd4
37.262899
161
0.634945
4.935975
false
true
false
false
usbpc102/usbBot
src/main/kotlin/usbbot/config/DBCommand.kt
1
4390
package usbbot.config import org.apache.commons.dbutils.ResultSetHandler fun getCommandForGuild(guildID: Long, name: String) : DBCommand? = DatabaseConnection.queryRunner .query("SELECT * FROM commands WHERE guildid = ? AND name = ?", DBCommand.singleCommandHandler, guildID, name) fun getCommandsForGuild(guildID: Long) : Collection<DBCommand> = DatabaseConnection.queryRunner .query("SELECT * FROM commands WHERE guildid = ?", DBCommand.allCommandsHandler, guildID) fun createDBCommand(guildID: Long, name: String, rolemode: String, usermode: String) : DBCommand { val ID = DatabaseConnection.queryRunner .insert("INSERT INTO commands (guildid, name, rolemode, usermode) VALUES (?, ?, ?, ?)", DBCommand.insertHandler, guildID, name, rolemode, usermode) ?: throw IllegalStateException("ID shall not be NULL here") return DBCommand(ID, guildID, name, rolemode, usermode) } open class DBCommand(val ID: Int, val guildID: Long, val name: String, var rolemode: String, var usermode: String) : DatabaseEntry() { companion object { val insertHandler = ResultSetHandler { if (it.next()) { it.getInt(1) } else { null } } val allCommandsHandler = ResultSetHandler { val output = mutableListOf<DBCommand>() while (it.next()) { output.add( DBCommand( it.getInt(1), it.getLong(2), it.getString(3), it.getString(4), it.getString(5))) } output } val singleCommandHandler = ResultSetHandler { if (it.next()) { DBCommand( it.getInt(1), it.getLong(2), it.getString(3), it.getString(4), it.getString(5)) } else { null } } } fun getPermissionRoles() : Collection<Long> = DatabaseConnection.queryRunner .query("SELECT roleid FROM permissionRoles WHERE commandid = ?", MiscResultSetHandlers.longCollection, ID) fun getPermissionUsers() : Collection<Long> = DatabaseConnection.queryRunner .query("SELECT userid FROM permissionUsers WHERE commandid = ?", MiscResultSetHandlers.longCollection, ID) fun addUserToList(userID: Long) : Int = DatabaseConnection.queryRunner .update("INSERT INTO permissionusers (commandid, userid) values (?, ?)", ID, userID) fun delUserFromList(userID: Long) : Int = DatabaseConnection.queryRunner .update("DELETE FROM permissionusers WHERE commandid = ? AND userid = ?", ID, userID) fun addRoleToList(roleID: Long) : Int = DatabaseConnection.queryRunner .update("INSERT INTO permissionroles (commandid, roleid) values (?, ?)", ID, roleID) fun delRoleFromList(roleID: Long) : Int = DatabaseConnection.queryRunner .update("DELETE FROM permissionroles WHERE commandid = ? AND roleid = ?", ID, roleID) fun setRoleMode(roleMode: String) : Int { rolemode = roleMode return DatabaseConnection.queryRunner .update("UPDATE commands SET rolemode = ? WHERE commandid = ?", roleMode, ID) } fun setUserMode(userMode: String) : Int { usermode = userMode return DatabaseConnection.queryRunner .update("UPDATE commands SET usermode = ? WHERE commandid = ?", userMode, ID) } override fun delete() : Int = DatabaseConnection.queryRunner .update("DELETE FROM commands WHERE id = ?", ID) }
mit
37f5e8f7f4859747c184edbca829e9a9
37.182609
134
0.516856
5.373317
false
false
false
false
antoniolg/Bandhook-Kotlin
app/src/main/java/com/antonioleiva/bandhookkotlin/di/subcomponent/detail/ArtistActivityModule.kt
1
2246
package com.antonioleiva.bandhookkotlin.di.subcomponent.detail import com.antonioleiva.bandhookkotlin.di.ActivityModule import com.antonioleiva.bandhookkotlin.di.scope.ActivityScope import com.antonioleiva.bandhookkotlin.domain.interactor.GetArtistDetailInteractor import com.antonioleiva.bandhookkotlin.domain.interactor.GetTopAlbumsInteractor import com.antonioleiva.bandhookkotlin.domain.interactor.base.Bus import com.antonioleiva.bandhookkotlin.domain.interactor.base.InteractorExecutor import com.antonioleiva.bandhookkotlin.ui.entity.mapper.ArtistDetailDataMapper import com.antonioleiva.bandhookkotlin.ui.entity.mapper.ImageTitleDataMapper import com.antonioleiva.bandhookkotlin.ui.presenter.ArtistPresenter import com.antonioleiva.bandhookkotlin.ui.screens.detail.AlbumsFragment import com.antonioleiva.bandhookkotlin.ui.screens.detail.ArtistActivity import com.antonioleiva.bandhookkotlin.ui.screens.detail.BiographyFragment import com.antonioleiva.bandhookkotlin.ui.view.ArtistView import dagger.Module import dagger.Provides @Module class ArtistActivityModule(activity: ArtistActivity) : ActivityModule(activity) { @Provides @ActivityScope fun provideArtistView(): ArtistView = activity as ArtistView @Provides @ActivityScope fun provideArtistDataMapper() = ArtistDetailDataMapper() @Provides @ActivityScope fun provideImageTitleDataMapper() = ImageTitleDataMapper() @Provides @ActivityScope fun provideActivityPresenter(view: ArtistView, bus: Bus, artistDetailInteractor: GetArtistDetailInteractor, topAlbumsInteractor: GetTopAlbumsInteractor, interactorExecutor: InteractorExecutor, detailDataMapper: ArtistDetailDataMapper, imageTitleDataMapper: ImageTitleDataMapper) = ArtistPresenter(view, bus, artistDetailInteractor, topAlbumsInteractor, interactorExecutor, detailDataMapper, imageTitleDataMapper) @Provides @ActivityScope fun provideAlbumsFragment() = AlbumsFragment() @Provides @ActivityScope fun provideBiographyFragment() = BiographyFragment() }
apache-2.0
53aa06ab1ced8e9182205935a156989a
46.808511
85
0.767587
5.438257
false
false
false
false
Le-Chiffre/Yttrium
Server/src/com/rimmer/yttrium/server/Client.kt
2
2276
package com.rimmer.yttrium.server import io.netty.bootstrap.Bootstrap import io.netty.channel.* import io.netty.channel.epoll.Epoll import io.netty.channel.epoll.EpollEventLoopGroup import io.netty.channel.epoll.EpollSocketChannel import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioSocketChannel /** Connects to a remote server as a client. */ inline fun connect( loop: EventLoopGroup, host: String, port: Int, timeout: Int = 0, useNative: Boolean = false, crossinline pipeline: ChannelPipeline.() -> Unit, crossinline onFail: (Throwable?) -> Unit ): ChannelFuture { val channelType = if(useNative && Epoll.isAvailable()) { EpollSocketChannel::class.java } else { NioSocketChannel::class.java } val init = object: ChannelInitializer<SocketChannel>() { override fun initChannel(channel: SocketChannel) { pipeline(channel.pipeline()) } } val b = Bootstrap().group(loop).channel(channelType).handler(init) if(timeout > 0) b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout) val promise = b.connect(host, port) promise.addListener { if(!it.isSuccess) { onFail(it.cause()) } } return promise } /** * Runs a client by creating a server context and returning it. * @param threadCount The number of threads to use. If 0, one thread is created for each cpu. * @param useNative Use native transport instead of NIO if possible (Linux only). */ fun runClient(threadCount: Int = 0, useNative: Boolean = false): ServerContext { // Create the server thread pools to use for every module. // Use native Epoll if possible, since it gives much better performance for small packets. val handlerThreads = if(threadCount == 0) Runtime.getRuntime().availableProcessors() else threadCount val acceptorGroup: EventLoopGroup val handlerGroup: EventLoopGroup if(Epoll.isAvailable() && useNative) { acceptorGroup = EpollEventLoopGroup(1) handlerGroup = EpollEventLoopGroup(handlerThreads) } else { acceptorGroup = NioEventLoopGroup(1) handlerGroup = NioEventLoopGroup(handlerThreads) } return ServerContext(acceptorGroup, handlerGroup) }
mit
ba5b64a65c2762ddc86b4bbf696d39d8
35.142857
105
0.721441
4.254206
false
false
false
false
cashapp/sqldelight
sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/tests/GenerateSchemaTest.kt
1
2662
package app.cash.sqldelight.tests import app.cash.sqldelight.withCommonConfiguration import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Test import java.io.File class GenerateSchemaTest { @Test fun `schema file generates correctly`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withCommonConfiguration(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `generateSchema task can run twice`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withCommonConfiguration(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() val lastModified = schemaFile.lastModified() while (System.currentTimeMillis() - lastModified <= 1000) { // last modified only updates per second. Thread.yield() } GradleRunner.create() .withCommonConfiguration(fixtureRoot) .withArguments("clean", "--rerun-tasks", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() assertThat(schemaFile.lastModified()).isNotEqualTo(lastModified) schemaFile.delete() } @Test fun `schema file generates correctly with existing sqm files`() { val fixtureRoot = File("src/test/schema-file-sqm") GradleRunner.create() .withCommonConfiguration(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/3.db") assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `schema file generates correctly for android`() { val fixtureRoot = File("src/test/schema-file-android") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withCommonConfiguration(fixtureRoot) .withArguments("clean", "generateDebugDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() } }
apache-2.0
4d8286158995d504b1f6a6db2e8a5cd6
29.25
92
0.694215
4.436667
false
true
false
false
jitsi/jicofo
jicofo/src/test/kotlin/org/jitsi/jicofo/bridge/BridgePinTest.kt
1
5441
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2022-Present 8x8, 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 org.jitsi.jicofo.bridge import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import org.jitsi.jicofo.FocusManager import org.jitsi.utils.time.FakeClock import org.json.simple.JSONArray import org.json.simple.JSONObject import org.jxmpp.jid.impl.JidCreate import java.time.Duration /** * Test conference pin operations. */ class BridgePinTest : ShouldSpec() { private val conf1 = JidCreate.entityBareFrom("[email protected]") private val conf2 = JidCreate.entityBareFrom("[email protected]") private val conf3 = JidCreate.entityBareFrom("[email protected]") private val v1 = "1.1.1" private val v2 = "2.2.2" private val v3 = "3.3.3" init { context("basic functionality") { val clock = FakeClock() val focusManager = FocusManager(clock) focusManager.pinConference(conf1, v1, Duration.ofMinutes(10)) focusManager.pinConference(conf2, v2, Duration.ofMinutes(12)) focusManager.pinConference(conf3, v3, Duration.ofMinutes(14)) should("pin correctly") { getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 3 focusManager.getBridgeVersionForConference(conf1) shouldBe v1 focusManager.getBridgeVersionForConference(conf2) shouldBe v2 focusManager.getBridgeVersionForConference(conf3) shouldBe v3 } should("expire") { clock.elapse(Duration.ofMinutes(11)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2 focusManager.getBridgeVersionForConference(conf1) shouldBe null focusManager.getBridgeVersionForConference(conf2) shouldBe v2 focusManager.getBridgeVersionForConference(conf3) shouldBe v3 clock.elapse(Duration.ofMinutes(2)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 1 focusManager.getBridgeVersionForConference(conf1) shouldBe null focusManager.getBridgeVersionForConference(conf2) shouldBe null focusManager.getBridgeVersionForConference(conf3) shouldBe v3 clock.elapse(Duration.ofMinutes(2)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 0 focusManager.getBridgeVersionForConference(conf1) shouldBe null focusManager.getBridgeVersionForConference(conf2) shouldBe null focusManager.getBridgeVersionForConference(conf3) shouldBe null } } context("modifications") { val clock = FakeClock() val focusManager = FocusManager(clock) focusManager.pinConference(conf1, v1, Duration.ofMinutes(10)) focusManager.pinConference(conf2, v2, Duration.ofMinutes(12)) focusManager.pinConference(conf3, v3, Duration.ofMinutes(14)) should("unpin") { focusManager.unpinConference(conf3) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2 focusManager.getBridgeVersionForConference(conf1) shouldBe v1 focusManager.getBridgeVersionForConference(conf2) shouldBe v2 focusManager.getBridgeVersionForConference(conf3) shouldBe null } should("modify version and timeout") { clock.elapse(Duration.ofMinutes(4)) focusManager.pinConference(conf1, v3, Duration.ofMinutes(10)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 2 focusManager.getBridgeVersionForConference(conf1) shouldBe v3 focusManager.getBridgeVersionForConference(conf2) shouldBe v2 focusManager.getBridgeVersionForConference(conf3) shouldBe null clock.elapse(Duration.ofMinutes(9)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 1 focusManager.getBridgeVersionForConference(conf1) shouldBe v3 focusManager.getBridgeVersionForConference(conf2) shouldBe null focusManager.getBridgeVersionForConference(conf3) shouldBe null clock.elapse(Duration.ofMinutes(2)) getNumPins(focusManager.getPinnedConferencesJson()) shouldBe 0 focusManager.getBridgeVersionForConference(conf1) shouldBe null focusManager.getBridgeVersionForConference(conf2) shouldBe null focusManager.getBridgeVersionForConference(conf3) shouldBe null } } } } fun getNumPins(obj: JSONObject): Int { val pins = obj["pins"] if (pins is JSONArray) return pins.size else return -1 }
apache-2.0
b4ef639d181319b66f8fe389c2eb870e
43.235772
79
0.679471
4.634583
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/tests/EventBusTest.kt
1
1463
package tornadofx.tests import javafx.application.Platform import javafx.stage.Stage import org.junit.Test import org.testfx.api.FxToolkit import tornadofx.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertTrue class EventBusTest { val primaryStage: Stage = FxToolkit.registerPrimaryStage() private val success = AtomicBoolean(true) private val latch = Latch() init { FxToolkit.setupFixture { Thread.setDefaultUncaughtExceptionHandler { _, t -> t.printStackTrace() success.set(false) latch.countDown() } } } val iterations: Int = 100 val count = AtomicInteger(0) val view = object : View() { init { for (i in 1..iterations) { subscribe<FXEvent>(times = i) { callOnUndock() print(" ${count.getAndIncrement()} ") callOnDock() } } } override val root = vbox {} } @Test fun testUnsubscribe() { Platform.runLater { view.callOnDock() repeat(iterations / 2) { view.fire(FXEvent()) view.fire(FXEvent(EventBus.RunOn.BackgroundThread)) } latch.countDown() } latch.await() assertTrue(success.get()) } }
apache-2.0
c5171283ff0f0d819aa029fd81fe79b6
24.224138
67
0.557758
4.844371
false
true
false
false
jjtParadox/Barometer
src/test/kotlin/com/jjtparadox/barometer/test/BarometerExampleTest.kt
1
2552
package com.jjtparadox.barometer.test import com.jjtparadox.barometer.Barometer import com.jjtparadox.barometer.TestUtils import com.jjtparadox.barometer.tester.BarometerTester import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertSame import junit.framework.TestCase.assertTrue import junit.framework.TestCase.fail import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntityFurnace import net.minecraft.util.math.BlockPos import net.minecraft.world.World import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(BarometerTester::class) class BarometerExampleTest { @Test fun testThatThisHackWorks() { println("One test successful!") } lateinit var world: World @Before fun setUp() { world = Barometer.server.entityWorld } @Test fun testFurnacePlacement() { if (Blocks.FURNACE != null) { val pos = BlockPos.ORIGIN world.setBlockState(pos, Blocks.FURNACE.defaultState) val state = world.getBlockState(pos) val block = state.block assertEquals(block, Blocks.FURNACE) val tile = world.getTileEntity(pos) assertSame(tile?.javaClass, TileEntityFurnace::class.java) } else { fail("Blocks.FURNACE is null") } } @Test fun testFurnaceRemoval() { val pos = BlockPos.ORIGIN world.setBlockState(pos, Blocks.FURNACE.defaultState) world.setBlockToAir(pos) TestUtils.tickServer() assertTrue(world.getTileEntity(pos) == null) } @Test fun testFurnaceSmelt() { val pos = BlockPos.ORIGIN world.setBlockState(pos, Blocks.FURNACE.defaultState) val furnace = world.getTileEntity(pos) as TileEntityFurnace val coal = ItemStack(Items.COAL) val ore = ItemStack(Blocks.IRON_ORE) val ingot = ItemStack(Items.IRON_INGOT) val furnaceData = furnace.tileData var cookTime: Int // 0 = input, 1 = fuel, 2 = output furnace.setInventorySlotContents(0, ore) furnace.setInventorySlotContents(1, coal) for (i in 0..2399) { TestUtils.tickServer() cookTime = furnaceData.getInteger("CookTime") if (cookTime > 0 && !furnace.getStackInSlot(2).isEmpty) { break } } assertTrue(ingot.isItemEqual(furnace.getStackInSlot(2))) } }
lgpl-3.0
3d2d3604fb698fa9422a76372cc5ddaf
29.746988
70
0.668495
4.050794
false
true
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/content/AbsStatusDialogActivity.kt
1
3440
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.activity.content import android.content.Intent import android.os.Bundle import de.vanita5.twittnuker.TwittnukerConstants.REQUEST_SELECT_ACCOUNT import de.vanita5.twittnuker.activity.AccountSelectorActivity import de.vanita5.twittnuker.activity.BaseActivity import de.vanita5.twittnuker.constant.IntentConstants.* import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey abstract class AbsStatusDialogActivity : BaseActivity() { private val statusId: String? get() = intent.getStringExtra(EXTRA_STATUS_ID) private val accountKey: UserKey? get() = intent.getParcelableExtra(EXTRA_ACCOUNT_KEY) private val accountHost: String? get() = intent.getStringExtra(EXTRA_ACCOUNT_HOST) private val status: ParcelableStatus? get() = intent.getParcelableExtra(EXTRA_STATUS) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { val statusId = this.statusId ?: run { setResult(RESULT_CANCELED) finish() return } val accountKey = this.accountKey if (accountKey != null) { showDialogFragment(accountKey, statusId, status) } else { val intent = Intent(this, AccountSelectorActivity::class.java) intent.putExtra(EXTRA_SINGLE_SELECTION, true) intent.putExtra(EXTRA_SELECT_ONLY_ITEM_AUTOMATICALLY, true) intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost) startActivityForResult(intent, REQUEST_SELECT_ACCOUNT) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_SELECT_ACCOUNT -> { if (resultCode == RESULT_OK && data != null) { val statusId = this.statusId ?: run { setResult(RESULT_CANCELED) finish() return } val accountKey = data.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY) showDialogFragment(accountKey, statusId, status) return } } } finish() } protected abstract fun showDialogFragment(accountKey: UserKey, statusId: String, status: ParcelableStatus?) }
gpl-3.0
90366b47289f0e6c890d425a87ba9d56
37.662921
88
0.644186
4.921316
false
false
false
false
DarrenAtherton49/android-kotlin-base
app/src/main/kotlin/com/atherton/sample/presentation/features/settings/licenses/LicensesList.kt
1
12719
package com.atherton.sample.presentation.features.settings.licenses import android.content.Context import com.atherton.sample.R private const val APACHE_2_0_URL = "https://www.apache.org/licenses/LICENSE-2.0" private const val GROUPIE_LICENSE_URL = "https://github.com/lisawray/groupie/blob/master/LICENSE" private const val GLIDE_LICENSE_URL = "https://github.com/bumptech/glide/blob/master/LICENSE" internal fun generateLicenses(context: Context): List<License> { with(context) { var id = 0L val appCompat = License( id = ++id, name = getString(R.string.license_app_compat_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_app_compat_description), url = APACHE_2_0_URL ) val constraintLayout = License( id = ++id, name = getString(R.string.license_constraint_layout_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_constraint_layout_description), url = APACHE_2_0_URL ) val dagger2 = License( id = ++id, name = getString(R.string.license_dagger_2_name), contributor = getString(R.string.license_contributor_dagger_2_authors), description = getString(R.string.license_dagger_2_description), url = APACHE_2_0_URL ) val dagger2Compiler = License( id = ++id, name = getString(R.string.license_dagger_2_compiler_name), contributor = getString(R.string.license_contributor_dagger_2_authors), description = getString(R.string.license_dagger_2_compiler_description), url = APACHE_2_0_URL ) val glide = License( id = ++id, name = getString(R.string.license_glide_name), contributor = getString(R.string.license_contributor_google_inc), description = getString(R.string.license_glide_description), url = GLIDE_LICENSE_URL ) val glideCompiler = License( id = ++id, name = getString(R.string.license_glide_compiler_name), contributor = getString(R.string.license_contributor_google_inc), description = getString(R.string.license_glide_compiler_description), url = GLIDE_LICENSE_URL ) val groupie = License( id = ++id, name = getString(R.string.license_groupie_name), contributor = getString(R.string.license_contributor_lisa_wray), description = getString(R.string.license_groupie_description), url = GROUPIE_LICENSE_URL ) val kotlin = License( id = ++id, name = getString(R.string.license_kotlin_name), contributor = getString(R.string.license_contributor_jetbrains), description = getString(R.string.license_kotlin_description), url = APACHE_2_0_URL ) val kotlinReflect = License( id = ++id, name = getString(R.string.license_kotlin_reflect_name), contributor = getString(R.string.license_contributor_jetbrains), description = getString(R.string.license_kotlin_reflect_description), url = APACHE_2_0_URL ) val materialComponents = License( id = ++id, name = getString(R.string.license_material_components_name), contributor = getString(R.string.license_contributor_google_inc), description = getString(R.string.license_material_components_description), url = APACHE_2_0_URL ) val leakCanary = License( id = ++id, name = getString(R.string.license_leak_canary_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_leak_canary_description), url = APACHE_2_0_URL ) val leakCanaryFragment = License( id = ++id, name = getString(R.string.license_leak_canary_fragment_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_leak_canary_fragment_description), url = APACHE_2_0_URL ) val leakCanaryNoOp = License( id = ++id, name = getString(R.string.license_leak_canary_no_op_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_leak_canary_no_op_description), url = APACHE_2_0_URL ) val lifecycleCompiler = License( id = ++id, name = getString(R.string.license_lifecycle_compiler_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_lifecycle_compiler_description), url = APACHE_2_0_URL ) val lifecycleExtensions = License( id = ++id, name = getString(R.string.license_lifecycle_extensions_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_lifecycle_extensions_description), url = APACHE_2_0_URL ) val moshi = License( id = ++id, name = getString(R.string.license_moshi_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_moshi_description), url = APACHE_2_0_URL ) val moshiKotlin = License( id = ++id, name = getString(R.string.license_moshi_kotlin_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_moshi_kotlin_description), url = APACHE_2_0_URL ) val navigationFragment = License( id = ++id, name = getString(R.string.license_navigation_fragment_ktx_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_navigation_fragment_ktx_description), url = APACHE_2_0_URL ) val navigationUI = License( id = ++id, name = getString(R.string.license_navigation_ui_ktx_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_navigation_ui_ktx_description), url = APACHE_2_0_URL ) val okHttpLoggingInterceptor = License( id = ++id, name = getString(R.string.license_ok_http_logging_interceptor_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_ok_http_logging_interceptor_description), url = APACHE_2_0_URL ) val palette = License( id = ++id, name = getString(R.string.license_palette_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_palette_description), url = APACHE_2_0_URL ) val recyclerView = License( id = ++id, name = getString(R.string.license_recycler_view_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_recycler_view_description), url = APACHE_2_0_URL ) val retrofit = License( id = ++id, name = getString(R.string.license_retrofit_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_retrofit_description), url = APACHE_2_0_URL ) val retrofitMoshi = License( id = ++id, name = getString(R.string.license_retrofit_moshi_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_retrofit_moshi_description), url = APACHE_2_0_URL ) val retrofitRxJava2Adapter = License( id = ++id, name = getString(R.string.license_retrofit_rxjava_2_adapter_name), contributor = getString(R.string.license_contributor_square_inc), description = getString(R.string.license_retrofit_rxjava_2_adapter_description), url = APACHE_2_0_URL ) val roomRuntime = License( id = ++id, name = getString(R.string.license_room_runtime_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_room_runtime_description), url = APACHE_2_0_URL ) val roomCompiler = License( id = ++id, name = getString(R.string.license_room_compiler_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_room_compiler_description), url = APACHE_2_0_URL ) val roomRxJava2 = License( id = ++id, name = getString(R.string.license_room_rxjava2_name), contributor = getString(R.string.license_contributor_android_open_source), description = getString(R.string.license_room_rxjava2_description), url = APACHE_2_0_URL ) val roxie = License( id = ++id, name = getString(R.string.license_roxie_name), contributor = getString(R.string.license_contributor_ww_tech), description = getString(R.string.license_roxie_description), url = APACHE_2_0_URL ) val rxAndroid = License( id = ++id, name = getString(R.string.license_rx_android_name), contributor = getString(R.string.license_contributor_rx_android_authors), description = getString(R.string.license_rx_android_description), url = APACHE_2_0_URL ) val rxJava2 = License( id = ++id, name = getString(R.string.license_rxjava_2_name), contributor = getString(R.string.license_contributor_rxjava_2_authors), description = getString(R.string.license_rxjava_2_description), url = APACHE_2_0_URL ) val rxKotlin = License( id = ++id, name = getString(R.string.license_rxkotlin_name), contributor = getString(R.string.license_contributor_rxjava_2_authors), description = getString(R.string.license_rxkotlin_description), url = APACHE_2_0_URL ) val rxRelay = License( id = ++id, name = getString(R.string.license_rxrelay_name), contributor = getString(R.string.license_contributor_netflix_and_jake_wharton), description = getString(R.string.license_rxrelay_description), url = APACHE_2_0_URL ) val timber = License( id = ++id, name = getString(R.string.license_timber_name), contributor = getString(R.string.license_contributor_jake_wharton), description = getString(R.string.license_timber_description), url = APACHE_2_0_URL ) return listOf( appCompat, constraintLayout, dagger2, dagger2Compiler, glide, glideCompiler, groupie, kotlin, kotlinReflect, materialComponents, leakCanary, leakCanaryFragment, leakCanaryNoOp, lifecycleCompiler, lifecycleExtensions, moshi, moshiKotlin, navigationFragment, navigationUI, okHttpLoggingInterceptor, palette, recyclerView, retrofit, retrofitMoshi, retrofitRxJava2Adapter, roomRuntime, roomCompiler, roomRxJava2, roxie, rxAndroid, rxJava2, rxKotlin, rxRelay, timber ).sortedBy { it.name } } }
mit
3dfc840a8bfbec1ca4072e72b81c4812
43.010381
97
0.591399
4.355822
false
false
false
false
stripe/stripe-android
identity/src/test/java/com/stripe/android/identity/states/FaceDetectorTransitionerTest.kt
1
9802
package com.stripe.android.identity.states import com.google.common.truth.Truth.assertThat import com.stripe.android.camera.framework.time.ClockMark import com.stripe.android.camera.framework.time.milliseconds import com.stripe.android.core.model.StripeFilePurpose import com.stripe.android.identity.ml.AnalyzerInput import com.stripe.android.identity.ml.BoundingBox import com.stripe.android.identity.ml.FaceDetectorOutput import com.stripe.android.identity.networking.models.VerificationPageStaticContentSelfieCapturePage import com.stripe.android.identity.networking.models.VerificationPageStaticContentSelfieModels import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.same import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) internal class FaceDetectorTransitionerTest { private val mockNeverTimeoutClockMark = mock<ClockMark>().also { whenever(it.hasPassed()).thenReturn(false) } private val mockAlwaysTimeoutClockMark = mock<ClockMark>().also { whenever(it.hasPassed()).thenReturn(true) } private val mockReachedStateAt = mock<ClockMark>() private val mockSelfieFrameSaver = mock<FaceDetectorTransitioner.SelfieFrameSaver>() @Test fun `Initial transitions to TimeOut when timeout`() = runBlocking { val transitioner = FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockAlwaysTimeoutClockMark) assertThat( transitioner.transitionFromInitial( IdentityScanState.Initial( IdentityScanState.ScanType.SELFIE, transitioner ), mock(), mock<FaceDetectorOutput>() ) ).isInstanceOf(IdentityScanState.TimeOut::class.java) } @Test fun `Initial transitions to Found when face is valid and frame is saved`() = runBlocking { val transitioner = FaceDetectorTransitioner( SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark, selfieFrameSaver = mockSelfieFrameSaver ) val initialState = IdentityScanState.Initial( IdentityScanState.ScanType.SELFIE, transitioner ) val mockInput = mock<AnalyzerInput>() val resultState = transitioner.transitionFromInitial( initialState, mockInput, VALID_OUTPUT ) verify(mockSelfieFrameSaver).saveFrame( eq((mockInput to VALID_OUTPUT)), same(VALID_OUTPUT) ) assertThat( resultState ).isInstanceOf(IdentityScanState.Found::class.java) } @Test fun `Initial stays in Initial when face is invalid`() = runBlocking { val transitioner = FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark) val initialState = IdentityScanState.Initial( IdentityScanState.ScanType.SELFIE, transitioner ) val resultState = transitioner.transitionFromInitial( initialState, mock(), INVALID_OUTPUT ) assertThat( resultState ).isInstanceOf(IdentityScanState.Initial::class.java) } @Test fun `Found transitions to TimeOut when timeout`() = runBlocking { val transitioner = FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockAlwaysTimeoutClockMark) assertThat( transitioner.transitionFromFound( IdentityScanState.Found( IdentityScanState.ScanType.SELFIE, transitioner ), mock(), mock<FaceDetectorOutput>() ) ).isInstanceOf(IdentityScanState.TimeOut::class.java) } @Test fun `Found stays in to Found when sample interval not reached`() = runBlocking { val transitioner = FaceDetectorTransitioner(SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark) whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL - 10).milliseconds) val foundState = IdentityScanState.Found( IdentityScanState.ScanType.SELFIE, transitioner, reachedStateAt = mockReachedStateAt ) assertThat( transitioner.transitionFromFound( foundState, mock(), mock<FaceDetectorOutput>() ) ).isSameInstanceAs(foundState) } @Test fun `Found stays in to Found when face is valid and not enough selfie collected`() = runBlocking { val transitioner = FaceDetectorTransitioner( selfieCapturePage = SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark, selfieFrameSaver = mockSelfieFrameSaver ) whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds) whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES - 1) val foundState = IdentityScanState.Found( IdentityScanState.ScanType.SELFIE, transitioner, reachedStateAt = mockReachedStateAt ) val resultState = transitioner.transitionFromFound( foundState, mock(), VALID_OUTPUT ) assertThat(resultState).isNotSameInstanceAs(foundState) assertThat(resultState).isInstanceOf(IdentityScanState.Found::class.java) } @Test fun `Found transitions to Satisfed when face is valid and enough selfie collected`() = runBlocking { val transitioner = FaceDetectorTransitioner( selfieCapturePage = SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark, selfieFrameSaver = mockSelfieFrameSaver ) whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds) whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES) assertThat( transitioner.transitionFromFound( IdentityScanState.Found( IdentityScanState.ScanType.SELFIE, transitioner, reachedStateAt = mockReachedStateAt ), mock(), VALID_OUTPUT ) ).isInstanceOf(IdentityScanState.Satisfied::class.java) } @Test fun `Found stays in Found when face is invalid`() = runBlocking { val transitioner = FaceDetectorTransitioner( selfieCapturePage = SELFIE_CAPTURE_PAGE, timeoutAt = mockNeverTimeoutClockMark, selfieFrameSaver = mockSelfieFrameSaver ) whenever(mockReachedStateAt.elapsedSince()).thenReturn((SAMPLE_INTERVAL + 10).milliseconds) whenever(mockSelfieFrameSaver.selfieCollected()).thenReturn(NUM_SAMPLES - 1) val foundState = IdentityScanState.Found( IdentityScanState.ScanType.SELFIE, transitioner, reachedStateAt = mockReachedStateAt ) val resultState = transitioner.transitionFromFound( foundState, mock(), INVALID_OUTPUT ) assertThat(resultState).isNotSameInstanceAs(foundState) assertThat(resultState).isInstanceOf(IdentityScanState.Found::class.java) } private companion object { const val SCORE_THRESHOLD = 0.8f const val VALID_SCORE = SCORE_THRESHOLD + 0.1f const val INVALID_SCORE = SCORE_THRESHOLD - 0.1f const val SAMPLE_INTERVAL = 200 const val NUM_SAMPLES = 8 val SELFIE_CAPTURE_PAGE = VerificationPageStaticContentSelfieCapturePage( autoCaptureTimeout = 15000, filePurpose = StripeFilePurpose.IdentityPrivate.code, numSamples = NUM_SAMPLES, sampleInterval = SAMPLE_INTERVAL, models = VerificationPageStaticContentSelfieModels( faceDetectorUrl = "", faceDetectorMinScore = SCORE_THRESHOLD, faceDetectorIou = 0.5f ), maxCenteredThresholdX = 0.2f, maxCenteredThresholdY = 0.2f, minEdgeThreshold = 0.05f, minCoverageThreshold = 0.07f, maxCoverageThreshold = 0.8f, lowResImageMaxDimension = 800, lowResImageCompressionQuality = 0.82f, highResImageMaxDimension = 1440, highResImageCompressionQuality = 0.92f, highResImageCropPadding = 0.5f, consentText = "consent" ) val VALID_OUTPUT = FaceDetectorOutput( boundingBox = BoundingBox( 0.2f, 0.2f, 0.6f, 0.6f ), resultScore = VALID_SCORE ) val INVALID_OUTPUT = FaceDetectorOutput( boundingBox = BoundingBox( 0.2f, 0.2f, 0.6f, 0.6f ), resultScore = INVALID_SCORE ) } }
mit
06b81f8396779dfaa37bf82e154c015b
34.258993
103
0.604264
5.094595
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/events/RandomItemGenerationEvent.kt
1
2026
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.events import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier import org.bukkit.event.HandlerList import org.bukkit.inventory.ItemStack class RandomItemGenerationEvent(val tier: Tier, itemStack: ItemStack, val reason: ItemGenerationReason) : MythicDropsCancellableEvent() { companion object { @JvmStatic val handlerList = HandlerList() } var isModified: Boolean = false private set var itemStack: ItemStack = itemStack set(value) { field = value isModified = true } override fun getHandlers(): HandlerList = handlerList }
mit
f170ae36c324705f6de62f4ea1df5c89
43.043478
105
0.755183
4.722611
false
false
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/service/RESTMusicService.kt
1
35237
/* This file is part of Subsonic. Subsonic is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Subsonic is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009 (C) Sindre Mehus */ package org.moire.ultrasonic.service import android.content.Context import android.graphics.Bitmap import android.text.TextUtils import androidx.annotation.StringRes import java.io.BufferedWriter import java.io.File import java.io.FileOutputStream import java.io.FileWriter import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import org.moire.ultrasonic.R import org.moire.ultrasonic.api.subsonic.ApiNotSupportedException import org.moire.ultrasonic.api.subsonic.SubsonicAPIClient import org.moire.ultrasonic.api.subsonic.models.AlbumListType.Companion.fromName import org.moire.ultrasonic.api.subsonic.models.JukeboxAction import org.moire.ultrasonic.api.subsonic.response.StreamResponse import org.moire.ultrasonic.cache.PermanentFileStorage import org.moire.ultrasonic.cache.serializers.getIndexesSerializer import org.moire.ultrasonic.cache.serializers.getMusicFolderListSerializer import org.moire.ultrasonic.data.ActiveServerProvider import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isOffline import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isServerScalingEnabled import org.moire.ultrasonic.domain.Bookmark import org.moire.ultrasonic.domain.ChatMessage import org.moire.ultrasonic.domain.Genre import org.moire.ultrasonic.domain.Indexes import org.moire.ultrasonic.domain.JukeboxStatus import org.moire.ultrasonic.domain.Lyrics import org.moire.ultrasonic.domain.MusicDirectory import org.moire.ultrasonic.domain.MusicFolder import org.moire.ultrasonic.domain.Playlist import org.moire.ultrasonic.domain.PodcastsChannel import org.moire.ultrasonic.domain.SearchCriteria import org.moire.ultrasonic.domain.SearchResult import org.moire.ultrasonic.domain.Share import org.moire.ultrasonic.domain.UserInfo import org.moire.ultrasonic.domain.toDomainEntitiesList import org.moire.ultrasonic.domain.toDomainEntity import org.moire.ultrasonic.domain.toDomainEntityList import org.moire.ultrasonic.domain.toMusicDirectoryDomainEntity import org.moire.ultrasonic.util.CancellableTask import org.moire.ultrasonic.util.FileUtil import org.moire.ultrasonic.util.ProgressListener import org.moire.ultrasonic.util.Util import timber.log.Timber /** * @author Sindre Mehus */ open class RESTMusicService( private val subsonicAPIClient: SubsonicAPIClient, private val fileStorage: PermanentFileStorage, private val activeServerProvider: ActiveServerProvider, private val responseChecker: ApiCallResponseChecker ) : MusicService { @Throws(Exception::class) override fun ping(context: Context, progressListener: ProgressListener?) { updateProgressListener(progressListener, R.string.service_connecting) responseChecker.callWithResponseCheck { api -> api.ping().execute() } } @Throws(Exception::class) override fun isLicenseValid(context: Context, progressListener: ProgressListener?): Boolean { updateProgressListener(progressListener, R.string.service_connecting) val response = responseChecker.callWithResponseCheck { api -> api.getLicense().execute() } return response.body()!!.license.valid } @Throws(Exception::class) override fun getMusicFolders( refresh: Boolean, context: Context, progressListener: ProgressListener? ): List<MusicFolder> { val cachedMusicFolders = fileStorage.load( MUSIC_FOLDER_STORAGE_NAME, getMusicFolderListSerializer() ) if (cachedMusicFolders != null && !refresh) return cachedMusicFolders updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getMusicFolders().execute() } val musicFolders = response.body()!!.musicFolders.toDomainEntityList() fileStorage.store(MUSIC_FOLDER_STORAGE_NAME, musicFolders, getMusicFolderListSerializer()) return musicFolders } @Throws(Exception::class) override fun getIndexes( musicFolderId: String?, refresh: Boolean, context: Context, progressListener: ProgressListener? ): Indexes { val cachedIndexes = fileStorage.load(INDEXES_STORAGE_NAME, getIndexesSerializer()) if (cachedIndexes != null && !refresh) return cachedIndexes updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getIndexes(musicFolderId, null).execute() } val indexes = response.body()!!.indexes.toDomainEntity() fileStorage.store(INDEXES_STORAGE_NAME, indexes, getIndexesSerializer()) return indexes } @Throws(Exception::class) override fun getArtists( refresh: Boolean, context: Context, progressListener: ProgressListener? ): Indexes { val cachedArtists = fileStorage.load(ARTISTS_STORAGE_NAME, getIndexesSerializer()) if (cachedArtists != null && !refresh) return cachedArtists updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getArtists(null).execute() } val indexes = response.body()!!.indexes.toDomainEntity() fileStorage.store(ARTISTS_STORAGE_NAME, indexes, getIndexesSerializer()) return indexes } @Throws(Exception::class) override fun star( id: String?, albumId: String?, artistId: String?, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.star(id, albumId, artistId).execute() } } @Throws(Exception::class) override fun unstar( id: String?, albumId: String?, artistId: String?, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.unstar(id, albumId, artistId).execute() } } @Throws(Exception::class) override fun setRating( id: String, rating: Int, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.setRating(id, rating).execute() } } @Throws(Exception::class) override fun getMusicDirectory( id: String, name: String?, refresh: Boolean, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getMusicDirectory(id).execute() } return response.body()!!.musicDirectory.toDomainEntity() } @Throws(Exception::class) override fun getArtist( id: String, name: String?, refresh: Boolean, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getArtist(id).execute() } return response.body()!!.artist.toMusicDirectoryDomainEntity() } @Throws(Exception::class) override fun getAlbum( id: String, name: String?, refresh: Boolean, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getAlbum(id).execute() } return response.body()!!.album.toMusicDirectoryDomainEntity() } @Throws(Exception::class) override fun search( criteria: SearchCriteria, context: Context, progressListener: ProgressListener? ): SearchResult { return try { if ( !isOffline(context) && Util.getShouldUseId3Tags(context) ) search3(criteria, progressListener) else search2(criteria, progressListener) } catch (ignored: ApiNotSupportedException) { // Ensure backward compatibility with REST 1.3. searchOld(criteria, progressListener) } } /** * Search using the "search" REST method. */ @Throws(Exception::class) private fun searchOld( criteria: SearchCriteria, progressListener: ProgressListener? ): SearchResult { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.search(null, null, null, criteria.query, criteria.songCount, null, null) .execute() } return response.body()!!.searchResult.toDomainEntity() } /** * Search using the "search2" REST method, available in 1.4.0 and later. */ @Throws(Exception::class) private fun search2( criteria: SearchCriteria, progressListener: ProgressListener? ): SearchResult { requireNotNull(criteria.query) { "Query param is null" } updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.search2( criteria.query, criteria.artistCount, null, criteria.albumCount, null, criteria.songCount, null ).execute() } return response.body()!!.searchResult.toDomainEntity() } @Throws(Exception::class) private fun search3( criteria: SearchCriteria, progressListener: ProgressListener? ): SearchResult { requireNotNull(criteria.query) { "Query param is null" } updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.search3( criteria.query, criteria.artistCount, null, criteria.albumCount, null, criteria.songCount, null ).execute() } return response.body()!!.searchResult.toDomainEntity() } @Throws(Exception::class) override fun getPlaylist( id: String, name: String?, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getPlaylist(id).execute() } val playlist = response.body()!!.playlist.toMusicDirectoryDomainEntity() savePlaylist(name, context, playlist) return playlist } @Throws(IOException::class) private fun savePlaylist( name: String?, context: Context, playlist: MusicDirectory ) { val playlistFile = FileUtil.getPlaylistFile( context, activeServerProvider.getActiveServer().name, name ) val fw = FileWriter(playlistFile) val bw = BufferedWriter(fw) try { fw.write("#EXTM3U\n") for (e in playlist.getChildren()) { var filePath = FileUtil.getSongFile(context, e).absolutePath if (!File(filePath).exists()) { val ext = FileUtil.getExtension(filePath) val base = FileUtil.getBaseName(filePath) filePath = "$base.complete.$ext" } fw.write(filePath + "\n") } } catch (e: IOException) { Timber.w("Failed to save playlist: %s", name) throw e } finally { bw.close() fw.close() } } @Throws(Exception::class) override fun getPlaylists( refresh: Boolean, context: Context, progressListener: ProgressListener? ): List<Playlist> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getPlaylists(null).execute() } return response.body()!!.playlists.toDomainEntitiesList() } @Throws(Exception::class) override fun createPlaylist( id: String?, name: String?, entries: List<MusicDirectory.Entry>, context: Context, progressListener: ProgressListener? ) { val pSongIds: MutableList<String> = ArrayList(entries.size) for ((id1) in entries) { if (id1 != null) { pSongIds.add(id1) } } updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.createPlaylist(id, name, pSongIds.toList()).execute() } } @Throws(Exception::class) override fun deletePlaylist( id: String, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.deletePlaylist(id).execute() } } @Throws(Exception::class) override fun updatePlaylist( id: String, name: String?, comment: String?, pub: Boolean, context: Context?, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.updatePlaylist(id, name, comment, pub, null, null) .execute() } } @Throws(Exception::class) override fun getPodcastsChannels( refresh: Boolean, context: Context, progressListener: ProgressListener? ): List<PodcastsChannel> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getPodcasts(false, null).execute() } return response.body()!!.podcastChannels.toDomainEntitiesList() } @Throws(Exception::class) override fun getPodcastEpisodes( podcastChannelId: String?, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getPodcasts(true, podcastChannelId).execute() } val podcastEntries = response.body()!!.podcastChannels[0].episodeList val musicDirectory = MusicDirectory() for (podcastEntry in podcastEntries) { if ( "skipped" != podcastEntry.status && "error" != podcastEntry.status ) { val entry = podcastEntry.toDomainEntity() entry.track = null musicDirectory.addChild(entry) } } return musicDirectory } @Throws(Exception::class) override fun getLyrics( artist: String?, title: String?, context: Context, progressListener: ProgressListener? ): Lyrics { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getLyrics(artist, title).execute() } return response.body()!!.lyrics.toDomainEntity() } @Throws(Exception::class) override fun scrobble( id: String, submission: Boolean, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.scrobble(id, null, submission).execute() } } @Throws(Exception::class) override fun getAlbumList( type: String, size: Int, offset: Int, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getAlbumList(fromName(type), size, offset, null, null, null, null) .execute() } val childList = response.body()!!.albumList.toDomainEntityList() val result = MusicDirectory() result.addAll(childList) return result } @Throws(Exception::class) override fun getAlbumList2( type: String, size: Int, offset: Int, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getAlbumList2( fromName(type), size, offset, null, null, null, null ).execute() } val result = MusicDirectory() result.addAll(response.body()!!.albumList.toDomainEntityList()) return result } @Throws(Exception::class) override fun getRandomSongs( size: Int, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getRandomSongs( size, null, null, null, null ).execute() } val result = MusicDirectory() result.addAll(response.body()!!.songsList.toDomainEntityList()) return result } @Throws(Exception::class) override fun getStarred( context: Context, progressListener: ProgressListener? ): SearchResult { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getStarred(null).execute() } return response.body()!!.starred.toDomainEntity() } @Throws(Exception::class) override fun getStarred2( context: Context, progressListener: ProgressListener? ): SearchResult { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getStarred2(null).execute() } return response.body()!!.starred2.toDomainEntity() } @Throws(Exception::class) override fun getCoverArt( context: Context, entry: MusicDirectory.Entry?, size: Int, saveToFile: Boolean, highQuality: Boolean, progressListener: ProgressListener? ): Bitmap? { // Synchronize on the entry so that we don't download concurrently for // the same song. if (entry == null) { return null } synchronized(entry) { // Use cached file, if existing. var bitmap = FileUtil.getAlbumArtBitmap(context, entry, size, highQuality) val serverScaling = isServerScalingEnabled(context) if (bitmap == null) { Timber.d("Loading cover art for: %s", entry) val id = entry.coverArt if (TextUtils.isEmpty(id)) { return null // Can't load } val response = subsonicAPIClient.getCoverArt(id!!, size.toLong()) checkStreamResponseError(response) if (response.stream == null) { return null // Failed to load } var inputStream: InputStream? = null try { inputStream = response.stream val bytes = Util.toByteArray(inputStream) // If we aren't allowing server-side scaling, always save the file to disk // because it will be unmodified if (!serverScaling || saveToFile) { var outputStream: OutputStream? = null try { outputStream = FileOutputStream( FileUtil.getAlbumArtFile(context, entry) ) outputStream.write(bytes) } finally { Util.close(outputStream) } } bitmap = FileUtil.getSampledBitmap(bytes, size, highQuality) } finally { Util.close(inputStream) } } // Return scaled bitmap return Util.scaleBitmap(bitmap, size) } } @Throws(SubsonicRESTException::class, IOException::class) private fun checkStreamResponseError(response: StreamResponse) { if (response.hasError() || response.stream == null) { if (response.apiError != null) { throw SubsonicRESTException(response.apiError!!) } else { throw IOException( "Failed to make endpoint request, code: " + response.responseHttpCode ) } } } @Throws(Exception::class) override fun getDownloadInputStream( context: Context, song: MusicDirectory.Entry, offset: Long, maxBitrate: Int, task: CancellableTask ): Pair<InputStream, Boolean> { val songOffset = if (offset < 0) 0 else offset val response = subsonicAPIClient.stream(song.id!!, maxBitrate, songOffset) checkStreamResponseError(response) if (response.stream == null) { throw IOException("Null stream response") } val partial = response.responseHttpCode == 206 return Pair(response.stream!!, partial) } @Throws(Exception::class) override fun getVideoUrl( context: Context, id: String, useFlash: Boolean ): String { // This method should not exists as video should be loaded using stream method // Previous method implementation uses assumption that video will be available // by videoPlayer.view?id=<id>&maxBitRate=500&autoplay=true, but this url is not // official Subsonic API call. val expectedResult = arrayOfNulls<String>(1) expectedResult[0] = null val latch = CountDownLatch(1) Thread( { expectedResult[0] = subsonicAPIClient.getStreamUrl(id) + "&format=raw" latch.countDown() }, "Get-Video-Url" ).start() latch.await(3, TimeUnit.SECONDS) return expectedResult[0]!! } @Throws(Exception::class) override fun updateJukeboxPlaylist( ids: List<String>?, context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.SET, null, null, ids, null) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun skipJukebox( index: Int, offsetSeconds: Int, context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.SKIP, index, offsetSeconds, null, null) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun stopJukebox( context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.STOP, null, null, null, null) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun startJukebox( context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.START, null, null, null, null) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun getJukeboxStatus( context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.STATUS, null, null, null, null) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun setJukeboxGain( gain: Float, context: Context, progressListener: ProgressListener? ): JukeboxStatus { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.jukeboxControl(JukeboxAction.SET_GAIN, null, null, null, gain) .execute() } return response.body()!!.jukebox.toDomainEntity() } @Throws(Exception::class) override fun getShares( refresh: Boolean, context: Context, progressListener: ProgressListener? ): List<Share> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getShares().execute() } return response.body()!!.shares.toDomainEntitiesList() } @Throws(Exception::class) override fun getGenres( refresh: Boolean, context: Context, progressListener: ProgressListener? ): List<Genre> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getGenres().execute() } return response.body()!!.genresList.toDomainEntityList() } @Throws(Exception::class) override fun getSongsByGenre( genre: String, count: Int, offset: Int, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getSongsByGenre(genre, count, offset, null).execute() } val result = MusicDirectory() result.addAll(response.body()!!.songsList.toDomainEntityList()) return result } @Throws(Exception::class) override fun getUser( username: String, context: Context, progressListener: ProgressListener? ): UserInfo { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getUser(username).execute() } return response.body()!!.user.toDomainEntity() } @Throws(Exception::class) override fun getChatMessages( since: Long?, context: Context, progressListener: ProgressListener? ): List<ChatMessage> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getChatMessages(since).execute() } return response.body()!!.chatMessages.toDomainEntitiesList() } @Throws(Exception::class) override fun addChatMessage( message: String, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.addChatMessage(message).execute() } } @Throws(Exception::class) override fun getBookmarks( context: Context, progressListener: ProgressListener? ): List<Bookmark> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getBookmarks().execute() } return response.body()!!.bookmarkList.toDomainEntitiesList() } @Throws(Exception::class) override fun createBookmark( id: String, position: Int, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.createBookmark(id, position.toLong(), null).execute() } } @Throws(Exception::class) override fun deleteBookmark( id: String, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.deleteBookmark(id).execute() } } @Throws(Exception::class) override fun getVideos( refresh: Boolean, context: Context, progressListener: ProgressListener? ): MusicDirectory { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.getVideos().execute() } val musicDirectory = MusicDirectory() musicDirectory.addAll(response.body()!!.videosList.toDomainEntityList()) return musicDirectory } @Throws(Exception::class) override fun createShare( ids: List<String>, description: String?, expires: Long?, context: Context, progressListener: ProgressListener? ): List<Share> { updateProgressListener(progressListener, R.string.parser_reading) val response = responseChecker.callWithResponseCheck { api -> api.createShare(ids, description, expires).execute() } return response.body()!!.shares.toDomainEntitiesList() } @Throws(Exception::class) override fun deleteShare( id: String, context: Context, progressListener: ProgressListener? ) { updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.deleteShare(id).execute() } } @Throws(Exception::class) override fun updateShare( id: String, description: String?, expires: Long?, context: Context, progressListener: ProgressListener? ) { var expiresValue: Long? = expires if (expires != null && expires == 0L) { expiresValue = null } updateProgressListener(progressListener, R.string.parser_reading) responseChecker.callWithResponseCheck { api -> api.updateShare(id, description, expiresValue).execute() } } @Throws(Exception::class) override fun getAvatar( context: Context, username: String?, size: Int, saveToFile: Boolean, highQuality: Boolean, progressListener: ProgressListener? ): Bitmap? { // Synchronize on the username so that we don't download concurrently for // the same user. if (username == null) { return null } synchronized(username) { // Use cached file, if existing. var bitmap = FileUtil.getAvatarBitmap(context, username, size, highQuality) if (bitmap == null) { var inputStream: InputStream? = null try { updateProgressListener(progressListener, R.string.parser_reading) val response = subsonicAPIClient.getAvatar(username) if (response.hasError()) return null inputStream = response.stream val bytes = Util.toByteArray(inputStream) // If we aren't allowing server-side scaling, always save the file to disk // because it will be unmodified if (saveToFile) { var outputStream: OutputStream? = null try { outputStream = FileOutputStream( FileUtil.getAvatarFile(context, username) ) outputStream.write(bytes) } finally { Util.close(outputStream) } } bitmap = FileUtil.getSampledBitmap(bytes, size, highQuality) } finally { Util.close(inputStream) } } // Return scaled bitmap return Util.scaleBitmap(bitmap, size) } } private fun updateProgressListener( progressListener: ProgressListener?, @StringRes messageId: Int ) { progressListener?.updateProgress(messageId) } companion object { private const val MUSIC_FOLDER_STORAGE_NAME = "music_folder" private const val INDEXES_STORAGE_NAME = "indexes" private const val ARTISTS_STORAGE_NAME = "artists" } }
gpl-3.0
c1593e281ca2a340ef27a6fb7ab1adc0
31.209324
100
0.629906
4.972763
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/RsCachedTypeAlias.kt
2
1759
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve import org.rust.lang.core.crate.Crate import org.rust.lang.core.psi.RsTypeAlias import org.rust.lang.core.psi.ext.RsAbstractableOwner import org.rust.lang.core.psi.ext.RsTypeAliasImplMixin import org.rust.lang.core.psi.ext.owner import org.rust.lang.core.psi.isValidProjectMemberAndContainingCrate import org.rust.lang.core.types.consts.CtConstParameter import org.rust.lang.core.types.infer.constGenerics import org.rust.lang.core.types.infer.generics import org.rust.lang.core.types.ty.Ty import org.rust.lang.core.types.ty.TyTypeParameter import kotlin.LazyThreadSafetyMode.PUBLICATION /** * Used for optimization purposes, to reduce access to cache and PSI tree in some very hot places, * [ImplLookup.processTyFingerprintsWithAliases] in particular */ class RsCachedTypeAlias( val alias: RsTypeAlias ) { val name: String? = alias.name val isFreeAndValid: Boolean val containingCrate: Crate? val containingCrates: List<Crate> init { val (isValid, crate, crates) = alias.isValidProjectMemberAndContainingCrate this.containingCrate = crate this.containingCrates = crates this.isFreeAndValid = isValid && name != null && alias.owner is RsAbstractableOwner.Free } val typeAndGenerics: Triple<Ty, List<TyTypeParameter>, List<CtConstParameter>> by lazy(PUBLICATION) { Triple(alias.declaredType, alias.generics, alias.constGenerics) } companion object { fun forAlias(alias: RsTypeAlias): RsCachedTypeAlias { return (alias as RsTypeAliasImplMixin).cachedImplItem.value } } }
mit
49e3c2b8ad76e60264d1e2b064516a4f
32.188679
105
0.741899
3.997727
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/sighting/SightingSession.kt
1
11645
package nl.rsdt.japp.jotial.maps.sighting import android.annotation.SuppressLint import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.util.Pair import android.view.LayoutInflater import android.view.View import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import com.google.gson.Gson import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IMarker /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 13-7-2016 * Class for Sighting */ class SightingSession : Snackbar.Callback(), View.OnClickListener, DialogInterface.OnClickListener, IJotiMap.SnapshotReadyCallback, IJotiMap.OnMapClickListener, IJotiMap.CancelableCallback { /** * The type of the sighting. */ private var type: String? = null /** * The GoogleMap used to create markers. */ private var jotiMap: IJotiMap? = null /** * The Marker that indicates the location. */ private var marker: IMarker? = null /** * The Context used for creating dialogs etc. */ private var context: Context? = null /** * The view where the Snackbar is going to be made on. */ private var targetView: View? = null /** * The Snackbar that informs the user. */ private var snackbar: Snackbar? = null /** * The AlertDialog that asks for the users confirmation. */ private var dialog: AlertDialog? = null /** * The last LatLng that was selected. */ private var lastLatLng: LatLng? = null /** * The callback for when the sighting is completed; */ private var callback: OnSightingCompletedCallback? = null /** * The Deelgebied where the lastLatLng is in, null if none. */ private var deelgebied: Deelgebied? = null /** * The last koppel that was selected. */ private var extra: String = "" /** * Initializes the SightingSession. */ private fun initialize() { val bm: Bitmap? when (type) { SIGHT_HUNT -> bm = BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.vos_zwart_4) SIGHT_SPOT -> bm = BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.vos_zwart_3) else -> bm = null } snackbar = Snackbar.make(targetView!!, R.string.sighting_standard_text, Snackbar.LENGTH_INDEFINITE) snackbar!!.setAction(R.string.sighting_snackbar_action_text, this) snackbar!!.addCallback(this) marker = jotiMap!!.addMarker(Pair(MarkerOptions() .visible(false) .position(LatLng(0.0, 0.0)), bm)) val inflater = LayoutInflater.from(context) @SuppressLint("InflateParams") val view = inflater.inflate(R.layout.sighting_input_dialog, null) dialog = AlertDialog.Builder(context) .setCancelable(false) .setPositiveButton(R.string.confirm, this) .setNegativeButton(R.string.cancel, this) .setView(view) .create() //val et = dialog?.findViewById<EditText>(R.id.sighting_dialog_info_edit) //et?.setText(JappPreferences.defaultKoppel()) } override fun onDismissed(snackbar: Snackbar?, event: Int) { super.onDismissed(snackbar, event) if (event == BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_SWIPE) { if (callback != null) { callback!!.onSightingCompleted(null, null, null) } destroy() } } /** * Starts the SightingSession. */ fun start() { jotiMap!!.setOnMapClickListener(this) snackbar!!.show() } private fun updateDeelgebied(latLng: LatLng, onUpdate: (LatLng) -> Unit){ var updateMarker = false val deelgebieden = listOf("A", "B", "C", "D", "E", "F", "X").toTypedArray() val deelgebiedDialog = AlertDialog.Builder(targetView?.context) .setTitle("Welke Vos?") .setItems(deelgebieden) { _, whichDeelgebied -> val deelgebied = deelgebieden[whichDeelgebied] val newdeelgebied = Deelgebied.parse(deelgebied) if (newdeelgebied != this.deelgebied){ this.deelgebied = newdeelgebied onUpdate(latLng) } } .create() deelgebiedDialog.show() } private fun updateExtra(latLng: LatLng, onUpdate: (LatLng) -> Unit){ val koppels = listOf(JappPreferences.defaultKoppel(),"Onbekend", "1", "2", "3", "4", "5", "6").toTypedArray() val koppelDialog = AlertDialog.Builder(targetView?.context) .setTitle("Welk Koppel?") .setItems(koppels) { _, whichKoppel -> val koppel = koppels[whichKoppel] if (koppel != this.extra){ this.extra = koppel onUpdate(latLng) } } .create() koppelDialog.show() } override fun onMapClick(latLng: LatLng): Boolean { lastLatLng = latLng marker?.position = latLng updateDeelgebied(latLng) { updateExtra(it) { if (deelgebied != null) { var icon: String? = null when (type) { SIGHT_HUNT -> { marker!!.setIcon(deelgebied!!.drawableHunt) icon = deelgebied?.drawableHunt.toString() } SIGHT_SPOT -> { marker?.setIcon(deelgebied!!.drawableSpot) icon = deelgebied?.drawableSpot.toString() } } val identifier = MarkerIdentifier.Builder() .setType(MarkerIdentifier.TYPE_SIGHTING) .add("text", type) .add("icon", icon) .create() marker?.title = Gson().toJson(identifier) } } marker?.isVisible = true } return false } override fun onClick(dialogInterface: DialogInterface, i: Int) { when (i) { AlertDialog.BUTTON_POSITIVE -> if (callback != null) { callback!!.onSightingCompleted(lastLatLng, deelgebied, this.extra) destroy() } AlertDialog.BUTTON_NEGATIVE -> { snackbar!!.setText(R.string.sighting_standard_text) snackbar!!.show() } } } override fun onClick(view: View) { if (deelgebied == null) { deelgebied = Deelgebied.Xray } jotiMap!!.animateCamera(lastLatLng?:LatLng(0.0, 0.0), 12, this) } override fun onFinish() { dialog?.show() (dialog?.findViewById<View>(R.id.sighting_dialog_title) as TextView?)?.text = context!!.getString(R.string.confirm_type, type) (dialog?.findViewById<View>(R.id.sighting_dialog_team_label) as TextView?)?.text = context!!.getString(R.string.deelgebied_name, deelgebied!!.name) jotiMap?.snapshot(this@SightingSession) } override fun onCancel() { dialog?.show() (dialog?.findViewById<View>(R.id.sighting_dialog_title) as TextView).text = context!!.getString(R.string.confirm_type, type) (dialog?.findViewById<View>(R.id.sighting_dialog_team_label) as TextView).text = context!!.getString(R.string.deelgebied_name, deelgebied!!.name) jotiMap?.snapshot(this@SightingSession) } override fun onSnapshotReady(bitmap: Bitmap) { (dialog?.findViewById<View>(R.id.sighting_dialog_snapshot) as ImageView).setImageDrawable(BitmapDrawable(Japp.appResources, bitmap)) } /** * Destroys the SightingSession. */ fun destroy() { type = null if (jotiMap != null) { jotiMap!!.setOnMapClickListener(null) jotiMap = null } if (marker != null) { marker!!.remove() marker = null } if (dialog != null) { dialog!!.dismiss() dialog = null } if (snackbar != null) { snackbar!!.dismiss() snackbar = null } lastLatLng = null callback = null deelgebied = null } /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 13-7-2016 * Builder for the SightingSession. */ class Builder { /** * Buffer to hold the SightingSession. */ private val buffer = SightingSession() /** * Sets the GoogleMap of the SightingSession. */ fun setGoogleMap(jotiMap: IJotiMap?): Builder { buffer.jotiMap = jotiMap return this } /** * Sets the Type of the SightingSession. */ fun setType(type: String): Builder { buffer.type = type return this } /** * Sets the TargetView of the SightingSession. */ fun setTargetView(view: View): Builder { buffer.targetView = view return this } /** * Sets the Context for the Dialog of the SightingSession. */ fun setDialogContext(context: Context): Builder { buffer.context = context return this } /** * Sets the callback of the SightingSession. */ fun setOnSightingCompletedCallback(callback: OnSightingCompletedCallback): Builder { buffer.callback = callback return this } /** * Creates the SightingSession. */ fun create(): SightingSession { buffer.initialize() return buffer } } /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 13-7-2016 * Callback for when a SightingSession is completed. */ interface OnSightingCompletedCallback { /** * Gets invoked when a SightingSession has been completed. * * @param chosen The chosen LatLng. * @param deelgebied The Deelgebied where the LatLng is in, null if none. * @param optionalInfo The optional info the user can provide. */ fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?) } companion object { /** * Defines the SightingSession type HUNT. */ val SIGHT_HUNT = "HUNT" /** * Defines the SightingSession type SPOT. */ val SIGHT_SPOT = "SPOT" } }
apache-2.0
0df2e2020ed9fbafddce3f41b2f3ee20
29.725594
190
0.57398
4.727974
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/application/activities/PreLoginSplashActivity.kt
1
6043
package nl.rsdt.japp.application.activities import android.app.Activity import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import nl.rsdt.japp.BuildConfig import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.auth.Authentication import nl.rsdt.japp.jotial.io.AppData import nl.rsdt.japp.jotial.net.apis.AuthApi import org.acra.ACRA import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.IOException import java.net.SocketTimeoutException import java.net.UnknownHostException import com.android.volley.Request as VRequest import com.android.volley.Response as VResponse /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 8-7-2016 * Description... */ class PreLoginSplashActivity : Activity() { internal var permission_check: Int = 0 public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) /* * Checks if the Fresh-Start feature is enabled if so the data of the app is cleared. * */ if (JappPreferences.isFreshStart) { /* * Clear preferences. * */ JappPreferences.clear() /* * Clear all the data files * */ AppData.clear() } } override fun onResume() { super.onResume() checkLatestReleaseAndValidate() } private fun checkLatestReleaseAndValidate() { var currentVersionName = BuildConfig.VERSION_NAME val queue = Volley.newRequestQueue(this) val url = "https://api.github.com/repos/rsdt/japp/releases/latest" var dialog = AlertDialog.Builder(this) dialog.setNegativeButton("negeren") { dialogInterface: DialogInterface, i: Int -> validate()} // Request a string response from the provided URL. val stringRequest = StringRequest(VRequest.Method.GET, url, VResponse.Listener<String> { response -> var json = JSONObject(response) var newVersionName = json["name"] if (currentVersionName != newVersionName){ dialog.setTitle("Er is een nieuwe versie van de app: ${newVersionName}") dialog.setPositiveButton("Naar Download") { dialogInterface: DialogInterface, i: Int -> var url = "https://github.com/RSDT/Japp16/releases/latest" var myIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(myIntent) //validate() } dialog.create() dialog.show() }else{ validate() } }, VResponse.ErrorListener { dialog.setTitle("error bij het controleren op updates") dialog.create() dialog.show() }) // Add the request to thpreviewe RequestQueue. queue.add(stringRequest) } fun validate() { val api = Japp.getApi(AuthApi::class.java) api.validateKey(JappPreferences.accountKey).enqueue(object : Callback<Authentication.ValidateObject> { override fun onResponse(call: Call<Authentication.ValidateObject>, response: Response<Authentication.ValidateObject>) { if (response.code() == 200) { val `object` = response.body() if (`object` != null) { if (!`object`.exists()) { Authentication.startLoginActivity(this@PreLoginSplashActivity) } else { determineAndStartNewActivity() } } } else { Authentication.startLoginActivity(this@PreLoginSplashActivity) } } override fun onFailure(call: Call<Authentication.ValidateObject>, t: Throwable) { if (t is UnknownHostException) { determineAndStartNewActivity() } else if (t is SocketTimeoutException) { AlertDialog.Builder(this@PreLoginSplashActivity) .setTitle(getString(R.string.err_verification)) .setMessage(R.string.splash_activity_socket_timed_out) .setPositiveButton(R.string.try_again) { _, _ -> determineAndStartNewActivity() } .create() .show() } else { AlertDialog.Builder(this@PreLoginSplashActivity) .setTitle(getString(R.string.err_verification)) .setMessage(t.toString()) .setPositiveButton(getString(R.string.try_again)) { _, _ -> validate() } .create() .show() } ACRA.errorReporter.handleException(t) Log.e(TAG, t.toString(), t) } }) } fun determineAndStartNewActivity() { val key = JappPreferences.accountKey if (key?.isEmpty() != false) { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } else { val intent = Intent(this, SplashActivity::class.java) startActivity(intent) finish() } } companion object { val TAG = "PreLoginSplashActivity" val LOAD_ID = "LOAD_RESULTS" } }
apache-2.0
e9f0246bc5ac21e84d2c2d4331129c91
34.757396
131
0.561807
5.095278
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/layering/Layering.kt
3
3729
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE") package androidx.compose.integration.docs.layering import androidx.compose.animation.Animatable import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideTextStyle import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/layering * * No action required if it's modified. */ @Composable private fun LayeringSnippetControl1() { val color = animateColorAsState(if (condition) Color.Green else Color.Red) } @Composable private fun LayeringSnippetControl2() { val color = remember { Animatable(Color.Gray) } LaunchedEffect(condition) { color.animateTo(if (condition) Color.Green else Color.Red) } } @Composable private fun LayeringSnippetCustomization1() { @Composable fun Button( // … content: @Composable RowScope.() -> Unit ) { Surface(/* … */) { CompositionLocalProvider(/* LocalContentAlpha … */) { ProvideTextStyle(MaterialTheme.typography.button) { Row( // … content = content ) } } } } } @Composable private fun LayeringSnippetCustomization2() { @Composable fun GradientButton( // … background: List<Color>, content: @Composable RowScope.() -> Unit ) { Row( // … modifier = modifier .clickable(/* … */) .background( Brush.horizontalGradient(background) ) ) { // Use Material LocalContentAlpha & ProvideTextStyle CompositionLocalProvider(/* LocalContentAlpha … */) { ProvideTextStyle(MaterialTheme.typography.button) { content() } } } } } @Composable private fun LayeringSnippetCustomization3() { @Composable fun BespokeButton( // … content: @Composable RowScope.() -> Unit ) { // No Material components used Row( // … modifier = modifier .clickable(/* … */) .background(/* … */), content = content ) } } /* Fakes needed for snippets to build: */ private val condition = false private val modifier = Modifier private fun Modifier.clickable() = this private fun Modifier.background() = this
apache-2.0
884d5f0a386cfdd39ccc76994c61f2ef
27.72093
78
0.645884
4.774485
false
false
false
false
campos20/tnoodle
tnoodle-server/src/main/kotlin/org/worldcubeassociation/tnoodle/server/crypto/SymmetricCipher.kt
1
1025
package org.worldcubeassociation.tnoodle.server.crypto import javax.crypto.Cipher import javax.crypto.SecretKey import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec import javax.crypto.spec.SecretKeySpec object SymmetricCipher { const val CIPHER_SALT = "TNOODLE_WCA" const val CIPHER_KEY_ITERATIONS = 65536 const val CIPHER_KEY_LENGTH = 256 const val CIPHER_ALGORITHM = "AES" const val CIPHER_KEY_ALGORITHM = "PBKDF2WithHmacSHA$CIPHER_KEY_LENGTH" val CIPHER_CHARSET = Charsets.UTF_8 val CIPHER_INSTANCE = Cipher.getInstance(CIPHER_ALGORITHM) val CIPHER_KEY_FACTORY = SecretKeyFactory.getInstance(CIPHER_KEY_ALGORITHM) fun generateKey(password: String): SecretKey { val saltBytes = CIPHER_SALT.toByteArray(CIPHER_CHARSET) val spec = PBEKeySpec(password.toCharArray(), saltBytes, CIPHER_KEY_ITERATIONS, CIPHER_KEY_LENGTH) val key = CIPHER_KEY_FACTORY.generateSecret(spec) return SecretKeySpec(key.encoded, CIPHER_ALGORITHM) } }
gpl-3.0
da91b9af76fdfbd6c7de2c467b8f1f30
34.344828
106
0.755122
4.116466
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/surface/Surface.kt
1
1422
package de.westnordost.streetcomplete.quests.surface import de.westnordost.streetcomplete.quests.surface.Surface.* enum class Surface(val osmValue: String) { ASPHALT("asphalt"), CONCRETE("concrete"), FINE_GRAVEL("fine_gravel"), PAVING_STONES("paving_stones"), COMPACTED("compacted"), DIRT("dirt"), SETT("sett"), // https://forum.openstreetmap.org/viewtopic.php?id=61042 UNHEWN_COBBLESTONE("unhewn_cobblestone"), GRASS_PAVER("grass_paver"), WOOD("wood"), METAL("metal"), GRAVEL("gravel"), PEBBLES("pebblestone"), GRASS("grass"), SAND("sand"), ROCK("rock"), CLAY("clay"), ARTIFICIAL_TURF("artificial_turf"), TARTAN("tartan"), PAVED("paved"), UNPAVED("unpaved"), GROUND("ground"), } val PAVED_SURFACES = listOf( ASPHALT, CONCRETE, PAVING_STONES, SETT, UNHEWN_COBBLESTONE, GRASS_PAVER, WOOD, METAL ) val UNPAVED_SURFACES = listOf( COMPACTED, FINE_GRAVEL, GRAVEL, PEBBLES ) val GROUND_SURFACES = listOf( DIRT, GRASS, SAND, ROCK ) val PITCH_SURFACES = listOf( GRASS, ASPHALT, SAND, CONCRETE, CLAY, ARTIFICIAL_TURF, TARTAN, DIRT, FINE_GRAVEL, PAVING_STONES, COMPACTED, SETT, UNHEWN_COBBLESTONE, GRASS_PAVER, WOOD, METAL, GRAVEL, PEBBLES, ROCK ) val GENERIC_SURFACES = listOf( PAVED, UNPAVED, GROUND ) val Surface.shouldBeDescribed: Boolean get() = this == PAVED || this == UNPAVED
gpl-3.0
ba48940f8dc21fe25259f259a197363e
23.517241
79
0.663854
2.761165
false
false
false
false
worker8/TourGuide
tourguide/src/main/java/tourguide/tourguide/ToolTip.kt
2
4275
package tourguide.tourguide import android.graphics.Color import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.BounceInterpolator class ToolTip() { var title: String private set var description: String private set var mBackgroundColor: Int = 0 var mTextColor: Int = 0 var mEnterAnimation: Animation var mExitAnimation: Animation? = null var mShadow: Boolean = false var mGravity: Int = 0 var mOnClickListener: View.OnClickListener? = null var mCustomView: ViewGroup? = null var mWidth: Int = 0 init { /* default values */ title = "" description = "" mBackgroundColor = Color.parseColor("#3498db") mTextColor = Color.parseColor("#FFFFFF") mEnterAnimation = AlphaAnimation(0f, 1f) mEnterAnimation.duration = 1000 mEnterAnimation.fillAfter = true mEnterAnimation.interpolator = BounceInterpolator() mShadow = true mWidth = -1 // TODO: exit animation mGravity = Gravity.CENTER } constructor(init: ToolTip.() -> Unit) : this() { init() } fun title(block: () -> String) { title = block() } fun description(block: () -> String) { description = block() } fun backgroundColor(block: () -> Int) { mBackgroundColor = block() } fun textColor(block: () -> Int) { mTextColor = block() } fun gravity(block: () -> Int) { mGravity = block() } fun shadow(block: () -> Boolean) { mShadow = block() } fun enterAnimation(block: () -> Animation) { mEnterAnimation = block() } fun exitAnimation(block: () -> Animation) { mExitAnimation = block() } /** * Set title text * @param title * @return return ToolTip instance for chaining purpose */ fun setTitle(title: String): ToolTip { this.title = title return this } /** * Set description text * @param description * @return return ToolTip instance for chaining purpose */ fun setDescription(description: String): ToolTip { this.description = description return this } /** * Set background color * @param backgroundColor * @return return ToolTip instance for chaining purpose */ fun setBackgroundColor(backgroundColor: Int): ToolTip { mBackgroundColor = backgroundColor return this } /** * Set text color * @param textColor * @return return ToolTip instance for chaining purpose */ fun setTextColor(textColor: Int): ToolTip { mTextColor = textColor return this } /** * Set enter animation * @param enterAnimation * @return return ToolTip instance for chaining purpose */ fun setEnterAnimation(enterAnimation: Animation): ToolTip { mEnterAnimation = enterAnimation return this } /** * Set the gravity, the setGravity is centered relative to the targeted button * @param gravity Gravity.CENTER, Gravity.TOP, Gravity.BOTTOM, etc * @return return ToolTip instance for chaining purpose */ fun setGravity(gravity: Int): ToolTip { mGravity = gravity return this } /** * Set if you want to have setShadow * @param shadow * @return return ToolTip instance for chaining purpose */ fun setShadow(shadow: Boolean): ToolTip { mShadow = shadow return this } /** * Method to set the width of the ToolTip * @param px desired width of ToolTip in pixels * @return ToolTip instance for chaining purposes */ fun setWidth(px: Int): ToolTip { if (px >= 0) mWidth = px return this } fun setOnClickListener(onClickListener: View.OnClickListener): ToolTip { mOnClickListener = onClickListener return this } fun getCustomView(): ViewGroup? { return mCustomView } fun setCustomView(view: ViewGroup): ToolTip { mCustomView = view return this } }
mit
00f82f848a1b6f1a96ebb397be7d4c50
23.716763
82
0.613801
4.672131
false
false
false
false
andrewoma/kwery
core/src/main/kotlin/com/github/andrewoma/kwery/core/Session.kt
1
5413
/* * Copyright (c) 2015 Andrew O'Malley * * 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.github.andrewoma.kwery.core import com.github.andrewoma.kwery.core.dialect.Dialect import org.intellij.lang.annotations.Language import java.sql.Connection /** * Session is the key interface for querying the database in kwery. * * Sessions hold an underlying JDBC connection. */ interface Session { /** * The current transaction for the session if a transaction has been started */ val currentTransaction: Transaction? /** * The underlying JDBC connection */ val connection: Connection val dialect: Dialect /** * The default StatementOptions used for this session unless overridden explicitly on calls */ val defaultOptions: StatementOptions /** * Executes a query returning the results as `List` */ fun <R> select(@Language("SQL") sql: String, parameters: Map<String, Any?> = mapOf(), options: StatementOptions = defaultOptions, mapper: (Row) -> R): List<R> /** * Executes an update returning the count of rows affected by the statement */ fun update(@Language("SQL") sql: String, parameters: Map<String, Any?> = mapOf(), options: StatementOptions = defaultOptions): Int /** * Executes an insert statement with generated keys, returning the keys */ fun <K> insert(@Language("SQL") sql: String, parameters: Map<String, Any?> = mapOf(), options: StatementOptions = defaultOptions, f: (Row) -> K): Pair<Int, K> /** * Executes a batch of update statements returning the counts of each statement executed */ fun batchUpdate(@Language("SQL") sql: String, parametersList: List<Map<String, Any?>>, options: StatementOptions = defaultOptions): List<Int> /** * Executes a batch of insert statements with generated keys, returning the list of keys */ fun <K> batchInsert(@Language("SQL") sql: String, parametersList: List<Map<String, Any?>>, options: StatementOptions = defaultOptions, f: (Row) -> K): List<Pair<Int, K>> /** * Executes a query, providing the results as a sequence for streaming. * This is the most flexible method for handling large result sets without loading them into memory. */ fun <R> asSequence(@Language("SQL") sql: String, parameters: Map<String, Any?> = mapOf(), options: StatementOptions = defaultOptions, f: (Sequence<Row>) -> R): R /** * Executes a query, invoking the supplied function for each row returned. * This is suitable for handling large result sets without loading them into memory. */ fun forEach(@Language("SQL") sql: String, parameters: Map<String, Any?> = mapOf(), options: StatementOptions = defaultOptions, f: (Row) -> Unit): Unit /** * Binds parameters into a static SQL string. * * This can be used for logging, or (in the future) for direct execution bypassing prepared statements. * * Be careful not to introduce SQL injections if binding strings. The dialect will attempt to escape * strings so they are safe, but it is probably not reliable for untrusted strings. */ fun bindParameters(@Language("SQL") sql: String, parameters: Map<String, Any?>, closeParameters: Boolean = true, limit: Int = -1, consumeStreams: Boolean = true): String /** * Starts a transaction for the lifetime of the supplied function. * The transaction will be committed automatically unless an exception is thrown or `transaction.rollbackOnly` * is set to true */ fun <R> transaction(f: (Transaction) -> R): R /** * Starts a transaction, allowing manual control over whether the transaction is committed or rolled back. * The use of this method is discouraged and is intended for use by framework code - use the `transaction` * method instead where possible. */ fun manualTransaction(): ManualTransaction }
mit
d98609482a49d88bad9d162d29727030
39.395522
114
0.646961
4.872187
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/GyroscopeModule.kt
2
1779
// Copyright 2015-present 650 Industries. All rights reserved. package abi44_0_0.expo.modules.sensors.modules import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorManager import android.os.Bundle import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface import abi44_0_0.expo.modules.interfaces.sensors.services.GyroscopeServiceInterface import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.ExpoMethod class GyroscopeModule(reactContext: Context?) : BaseSensorModule(reactContext) { override val eventName: String = "gyroscopeDidUpdate" override fun getName(): String = "ExponentGyroscope" override fun getSensorService(): SensorServiceInterface { return moduleRegistry.getModule(GyroscopeServiceInterface::class.java) } override fun eventToMap(sensorEvent: SensorEvent): Bundle { return Bundle().apply { putDouble("x", sensorEvent.values[0].toDouble()) putDouble("y", sensorEvent.values[1].toDouble()) putDouble("z", sensorEvent.values[2].toDouble()) } } @ExpoMethod fun startObserving(promise: Promise) { super.startObserving() promise.resolve(null) } @ExpoMethod fun stopObserving(promise: Promise) { super.stopObserving() promise.resolve(null) } @ExpoMethod fun setUpdateInterval(updateInterval: Int, promise: Promise) { super.setUpdateInterval(updateInterval) promise.resolve(null) } @ExpoMethod fun isAvailableAsync(promise: Promise) { val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null promise.resolve(isAvailable) } }
bsd-3-clause
dba096a6cc675e5e5673fbfdb203f0c2
31.345455
90
0.768409
4.195755
false
false
false
false
kronenpj/iqtimesheet
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/SectionFragment.kt
1
14005
package com.github.kronenpj.iqtimesheet.IQTimeSheet import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.Button import android.widget.ListView import android.widget.TextView import com.github.kronenpj.iqtimesheet.TimeHelpers /** * A fragment representing a section of the application. */ class SectionFragment : Fragment() { /* * (non-Javadoc) * * @see com.github.rtyley.android.sherlock.roboguice.activity. * RoboFragmentActivity#onCreateView(LayoutInflater, ViewGroup, * Bundle) */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.d(TAG, "in onCreateView (SectionFragment)") when (arguments!!.getInt(ARG_SECTION_NUMBER)) { 1 -> return setupTaskListFragment(inflater, container!!) 2 -> return setupDayReportFragment(inflater, container!!) 3 -> return setupWeekReportFragment(inflater, container!!) } return null } /** * Set up the task list fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupTaskListFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupTaskListFragment") val db = TimeSheetDbAdapter(activity!!.applicationContext) val rootView = inflater.inflate(R.layout.fragment_tasklist, container, false) val myTaskList = rootView.findViewById<ListView>(R.id.tasklistfragment) // Populate the ListView with an array adapter with the task items. (activity as TimeSheetActivity).refreshTaskListAdapter(myTaskList) // Make list items selectable. myTaskList.isEnabled = true myTaskList.choiceMode = ListView.CHOICE_MODE_SINGLE (activity as TimeSheetActivity).setSelected(myTaskList) registerForContextMenu(myTaskList) myTaskList.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val taskName = parent.getItemAtPosition(position) as String val taskID = db.getTaskIDByName(taskName) Log.i(TAG, "Processing change for task: $taskName / $taskID") if (db.processChange(taskID)) { val timeIn = db.timeInForLastClockEntry() (activity as TimeSheetActivity).startNotification(db.getTaskNameByID(taskID)!!, timeIn) (activity as TimeSheetActivity).setSelected() } else { (activity as TimeSheetActivity).clearSelected(myTaskList) Log.d(TAG, "Closed task ID: $taskID") (activity as TimeSheetActivity).stopNotification() } } // This can't be closed because of the onItemClickListener routine // above. // This probably leaks something, but I'll deal with that later. // TODO: See if not closing the DB causes problems.. // try { // db.close(); // } catch (Exception e) { // Log.i(TAG, "setupTaskListFragment db.close: " + e.toString()); // } return rootView } /** * Set up the day report fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupDayReportFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupDayReportFragment") //val db = TimeSheetDbAdapter(activity.applicationContext) //try { // db.open(); //} catch (Exception e) { // Log.i(TAG, "Database open threw exception" + e); //} val rootView = inflater.inflate(R.layout.fragment_reportlist, container, false) val reportList = rootView.findViewById(R.id.reportList) as ListView (activity as TimeSheetActivity).refreshReportListAdapter(reportList) val footerView = rootView.findViewById(R.id.reportfooter) as TextView try { footerView.textSize = TimeSheetActivity.prefs!!.totalsFontSize } catch (e: NullPointerException) { Log.d(TAG, "setupDayReportFragment: NullPointerException prefs: $e") } val child = arrayOf(rootView.findViewById(R.id.previous) as Button, rootView.findViewById(R.id.today) as Button, rootView.findViewById(R.id.next) as Button) /** * This method is what is registered with the button to cause an * action to occur when it is pressed. */ val mButtonListener = View.OnClickListener { v -> Log.d(TAG, "onClickListener view id: " + v.id) when (v.id) { R.id.previous -> { Log.d(TAG, "onClickListener button: previous") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") if (TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day) != TimeSheetActivity.prefs!!.weekStartDay) { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { if (TimeHelpers.millisToHour(TimeSheetActivity.day) < TimeSheetActivity.prefs!!.weekStartHour) { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) + TimeSheetActivity.prefs!!.weekStartHour * 3600 * 1000 - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } } R.id.today -> { Log.d(TAG, "onClickListener button: today") TimeSheetActivity.day = TimeHelpers.millisNow() } R.id.next -> { Log.d(TAG, "onClickListener button: next") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") if (TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day) != TimeSheetActivity.prefs!!.weekStartDay) { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { if (TimeHelpers.millisToHour(TimeSheetActivity.day) > TimeSheetActivity.prefs!!.weekStartHour) { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + (TimeSheetActivity.prefs!!.weekStartHour * 3600 * 1000).toLong() + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } } } val headerView = v.rootView .findViewById(R.id.reportheader) as TextView val date = TimeHelpers.millisToDate(TimeSheetActivity.day) headerView.text = "Day Report - $date" Log.d(TAG, "New day is: $date") (activity as TimeSheetActivity).refreshReportListAdapter(v.rootView .findViewById(R.id.reportList) as ListView) } for (aChild in child) { try { aChild.setOnClickListener(mButtonListener) } catch (e: NullPointerException) { Log.e(TAG, "setOnClickListener: $e") } } return rootView } /** * Set up the week report fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupWeekReportFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupWeekReportFragment") //val db = TimeSheetDbAdapter(activity.applicationContext) //try { // db.open(); //} catch (Exception e) { // Log.i(TAG, "Database open threw exception" + e); //} val rootView = inflater.inflate(R.layout.fragment_weekreportlist, container, false) val reportList = rootView.findViewById(R.id.weekList) as ListView (activity as TimeSheetActivity).refreshWeekReportListAdapter(reportList) val footerView = rootView.findViewById(R.id.weekfooter) as TextView try { footerView.textSize = TimeSheetActivity.prefs!!.totalsFontSize } catch (e: NullPointerException) { Log.d(TAG, "setupWeekeportFragment: NullPointerException prefs: $e") } val child = arrayOf(rootView.findViewById(R.id.wprevious) as Button, rootView.findViewById(R.id.wtoday) as Button, rootView.findViewById(R.id.wnext) as Button) /** * This method is what is registered with the button to cause an * action to occur when it is pressed. */ val mButtonListener = View.OnClickListener { v -> Log.d(TAG, "onClickListener view id: " + v.id) when (v.id) { R.id.wprevious -> { Log.d(TAG, "onClickListener button: wprevious") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") // TimeSheetActivity.day = TimeHelpers.millisToStartOfWeek(TimeSheetActivity.day) - 1000; TimeSheetActivity.day = TimeHelpers.millisToStartOfWeek(TimeSheetActivity.day, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } R.id.wtoday -> { TimeSheetActivity.day = TimeHelpers.millisNow() Log.d(TAG, "onClickListener button: wtoday") } R.id.wnext -> { Log.d(TAG, "onClickListener button: wnext") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") // TimeSheetActivity.day = TimeHelpers.millisToEndOfWeek(TimeSheetActivity.day) + 1000; TimeSheetActivity.day = TimeHelpers.millisToEndOfWeek(TimeSheetActivity.day, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } val headerView = v.rootView .findViewById(R.id.weekheader) as TextView val date = TimeHelpers.millisToDate(TimeSheetActivity.day) headerView.text = "Week Report - $date" Log.d(TAG, "New day is: $date") (activity as TimeSheetActivity).refreshWeekReportListAdapter(v.rootView .findViewById(R.id.weekList) as ListView) } for (aChild in child) { try { aChild.setOnClickListener(mButtonListener) } catch (e: NullPointerException) { Log.e(TAG, "setOnClickListener: $e") } } return rootView } companion object { private const val TAG = "SectionFragment" /** * The fragment argument representing the section number for this * fragment. */ const val ARG_SECTION_NUMBER = "section_number" } }
apache-2.0
e6814f511085e5935109efb76bf0ab57
44.470779
168
0.601071
4.696512
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt
1
17094
package info.nightscout.androidaps.plugins.general.nsclient import android.content.Context import android.os.SystemClock import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.DeviceStatus import info.nightscout.androidaps.database.transactions.* import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.DataSyncSelector.* import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject class NSClientAddAckWorker( context: Context, params: WorkerParameters ) : Worker(context, params) { @Inject lateinit var dataWorker: DataWorker @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var repository: AppRepository @Inject lateinit var rxBus: RxBus @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP override fun doWork(): Result { var ret = Result.success() val ack = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as NSAddAck? ?: return Result.failure(workDataOf("Error" to "missing input data")) if (sp.getBoolean(R.string.key_ns_sync_slow, false)) SystemClock.sleep(1000) when (ack.originalObject) { is PairTemporaryTarget -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTemporaryTargetTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryTarget failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TemporaryTarget " + pair.value) dataSyncSelector.confirmLastTempTargetsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TemporaryTarget " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTempTargetsCompat() } is PairGlucoseValue -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdGlucoseValueTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of GlucoseValue failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of GlucoseValue " + pair.value) dataSyncSelector.confirmLastGlucoseValueIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked GlucoseValue " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedGlucoseValuesCompat() } is PairFood -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdFoodTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Food failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Food " + pair.value) dataSyncSelector.confirmLastFoodIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Food " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedFoodsCompat() } is PairTherapyEvent -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTherapyEventTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TherapyEvent failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TherapyEvent " + pair.value) dataSyncSelector.confirmLastTherapyEventIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TherapyEvent " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTherapyEventsCompat() } is PairBolus -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Bolus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Bolus " + pair.value) dataSyncSelector.confirmLastBolusIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Bolus " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedBolusesCompat() } is PairCarbs -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdCarbsTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Carbs failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Carbs " + pair.value) dataSyncSelector.confirmLastCarbsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Carbs " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedCarbsCompat() } is PairBolusCalculatorResult -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdBolusCalculatorResultTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of BolusCalculatorResult failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of BolusCalculatorResult " + pair.value) dataSyncSelector.confirmLastBolusCalculatorResultsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked BolusCalculatorResult " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedBolusCalculatorResultsCompat() } is PairTemporaryBasal -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTemporaryBasalTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryBasal failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TemporaryBasal " + pair.value) dataSyncSelector.confirmLastTemporaryBasalIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TemporaryBasal " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTemporaryBasalsCompat() } is PairExtendedBolus -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdExtendedBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ExtendedBolus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of ExtendedBolus " + pair.value) dataSyncSelector.confirmLastExtendedBolusIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ExtendedBolus " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedExtendedBolusesCompat() } is PairProfileSwitch -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdProfileSwitchTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ProfileSwitch failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of ProfileSwitch " + pair.value) dataSyncSelector.confirmLastProfileSwitchIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ProfileSwitch " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedProfileSwitchesCompat() } is PairEffectiveProfileSwitch -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdEffectiveProfileSwitchTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of EffectiveProfileSwitch failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of EffectiveProfileSwitch " + pair.value) dataSyncSelector.confirmLastEffectiveProfileSwitchIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked EffectiveProfileSwitch " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedEffectiveProfileSwitchesCompat() } is DeviceStatus -> { val deviceStatus = ack.originalObject deviceStatus.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdDeviceStatusTransaction(deviceStatus)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of DeviceStatus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to deviceStatus.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of DeviceStatus $deviceStatus") dataSyncSelector.confirmLastDeviceStatusIdIfGreater(deviceStatus.id) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked DeviceStatus " + deviceStatus.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedDeviceStatusesCompat() } is PairProfileStore -> { dataSyncSelector.confirmLastProfileStore(ack.originalObject.timestampSync) rxBus.send(EventNSClientNewLog("DBADD", "Acked ProfileStore " + ack.id)) } is PairOfflineEvent -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdOfflineEventTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of OfflineEvent failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of OfflineEvent " + pair.value) dataSyncSelector.confirmLastOfflineEventIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked OfflineEvent " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedOfflineEventsCompat() } } return ret } init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) } }
agpl-3.0
de61fbd10630ac5dca84ee6df5bf889c
54.866013
128
0.58541
5.406072
false
false
false
false
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/textview/TextViewExtensions.kt
1
709
package io.github.feelfreelinux.wykopmobilny.utils.textview import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.widget.TextView import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi fun TextView.prepareBody(html: String, handler : WykopLinkHandlerApi) { val sequence = html.toSpannable() val strBuilder = SpannableStringBuilder(sequence) val urls = strBuilder.getSpans(0, strBuilder.length, URLSpan::class.java) urls.forEach { span -> strBuilder.makeLinkClickable(span, handler) } text = strBuilder movementMethod = LinkMovementMethod.getInstance() }
mit
1e7d50667fb379b2ed6730df54146651
38.444444
88
0.794076
4.574194
false
false
false
false
exponentjs/exponent
packages/expo-sqlite/android/src/main/java/expo/modules/sqlite/SQLiteModule.kt
2
5369
// Copyright 2015-present 650 Industries. All rights reserved. package expo.modules.sqlite import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import expo.modules.core.ExportedModule import expo.modules.core.Promise import expo.modules.core.interfaces.ExpoMethod import java.io.File import java.io.IOException import java.util.* private val TAG = SQLiteModule::class.java.simpleName private val EMPTY_ROWS = arrayOf<Array<Any?>>() private val EMPTY_COLUMNS = arrayOf<String?>() private val EMPTY_RESULT = SQLiteModule.SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null) private val DATABASES: MutableMap<String, SQLiteDatabase?> = HashMap() class SQLiteModule(private val mContext: Context) : ExportedModule(mContext) { override fun getName(): String { return "ExponentSQLite" } @ExpoMethod fun exec(dbName: String, queries: ArrayList<ArrayList<Any>>, readOnly: Boolean, promise: Promise) { try { val db = getDatabase(dbName) val results = queries.map { sqlQuery -> val sql = sqlQuery[0] as String val bindArgs = convertParamsToStringArray(sqlQuery[1] as ArrayList<Any?>) try { if (isSelect(sql)) { doSelectInBackgroundAndPossiblyThrow(sql, bindArgs, db) } else { // update/insert/delete if (readOnly) { SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, ReadOnlyException()) } else { doUpdateInBackgroundAndPossiblyThrow(sql, bindArgs, db) } } } catch (e: Throwable) { SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e) } } val data = pluginResultsToPrimitiveData(results) promise.resolve(data) } catch (e: Exception) { promise.reject("SQLiteError", e) } } @ExpoMethod fun close(dbName: String, promise: Promise) { DATABASES .remove(dbName) ?.close() promise.resolve(null) } // do a update/delete/insert operation private fun doUpdateInBackgroundAndPossiblyThrow( sql: String, bindArgs: Array<String?>?, db: SQLiteDatabase ): SQLitePluginResult { return db.compileStatement(sql).use { statement -> if (bindArgs != null) { for (i in bindArgs.size downTo 1) { if (bindArgs[i - 1] == null) { statement.bindNull(i) } else { statement.bindString(i, bindArgs[i - 1]) } } } if (isInsert(sql)) { val insertId = statement.executeInsert() val rowsAffected = if (insertId >= 0) 1 else 0 SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null) } else if (isDelete(sql) || isUpdate(sql)) { val rowsAffected = statement.executeUpdateDelete() SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null) } else { // in this case, we don't need rowsAffected or insertId, so we can have a slight // perf boost by just executing the query statement.execute() EMPTY_RESULT } } } // do a select operation private fun doSelectInBackgroundAndPossiblyThrow( sql: String, bindArgs: Array<String?>, db: SQLiteDatabase ): SQLitePluginResult { return db.rawQuery(sql, bindArgs).use { cursor -> val numRows = cursor.count if (numRows == 0) { return EMPTY_RESULT } val numColumns = cursor.columnCount val columnNames = cursor.columnNames val rows: Array<Array<Any?>> = Array(numRows) { arrayOfNulls(numColumns) } var i = 0 while (cursor.moveToNext()) { val row = rows[i] for (j in 0 until numColumns) { row[j] = getValueFromCursor(cursor, j, cursor.getType(j)) } rows[i] = row i++ } SQLitePluginResult(rows, columnNames, 0, 0, null) } } private fun getValueFromCursor(cursor: Cursor, index: Int, columnType: Int): Any? { return when (columnType) { Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(index) Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(index) Cursor.FIELD_TYPE_BLOB -> // convert byte[] to binary string; it's good enough, because // WebSQL doesn't support blobs anyway String(cursor.getBlob(index)) Cursor.FIELD_TYPE_STRING -> cursor.getString(index) else -> null } } @Throws(IOException::class) private fun pathForDatabaseName(name: String): String { val directory = File("${mContext.filesDir}${File.separator}SQLite") ensureDirExists(directory) return "$directory${File.separator}$name" } @Throws(IOException::class) private fun getDatabase(name: String): SQLiteDatabase { var database: SQLiteDatabase? = null val path = pathForDatabaseName(name) if (File(path).exists()) { database = DATABASES[name] } if (database == null) { DATABASES.remove(name) database = SQLiteDatabase.openOrCreateDatabase(path, null) DATABASES[name] = database } return database!! } internal class SQLitePluginResult( val rows: Array<Array<Any?>>, val columns: Array<String?>, val rowsAffected: Int, val insertId: Long, val error: Throwable? ) private class ReadOnlyException : Exception("could not prepare statement (23 not authorized)") }
bsd-3-clause
487c67dad5f802ab7655558fff5d90b1
31.737805
101
0.650214
4.274682
false
false
false
false
jgrandja/spring-security
config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDslTests.kt
2
4247
/* * Copyright 2002-2020 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.web.servlet.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.web.servlet.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get /** * Tests for [ContentSecurityPolicyDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ContentSecurityPolicyDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `headers when content security policy configured then header in response`() { this.spring.register(ContentSecurityPolicyConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'") } } } @EnableWebSecurity open class ContentSecurityPolicyConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { } } } } } @Test fun `headers when content security policy configured with custom policy directives then custom directives in header`() { this.spring.register(CustomPolicyDirectivesConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'; script-src trustedscripts.example.com") } } } @EnableWebSecurity open class CustomPolicyDirectivesConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { policyDirectives = "default-src 'self'; script-src trustedscripts.example.com" } } } } } @Test fun `headers when report only content security policy report only header in response`() { this.spring.register(ReportOnlyConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY, "default-src 'self'") } } } @EnableWebSecurity open class ReportOnlyConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { reportOnly = true } } } } } }
apache-2.0
e351108eb2b842089a04cf1ce0246ca6
35.299145
160
0.672475
5.198286
false
true
false
false
PolymerLabs/arcs
javatests/arcs/showcase/inline/ArcsStorage.kt
1
1309
package arcs.showcase.inline import arcs.android.integration.IntegrationEnvironment import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout /** Container for WriteRecipe specific things */ @OptIn(ExperimentalCoroutinesApi::class) class ArcsStorage(private val env: IntegrationEnvironment) { // This is a helper for public methods to dispatcher the suspend calls onto a coroutine and // wait for the result, and to wrap the suspend methods in a timeout, converting a potential // test timeout into a more specific test failure. private inline fun <T> run(crossinline block: suspend () -> T) = runBlocking { withTimeout(30000) { block() } } fun all0(): List<MyLevel0> = run { env.getParticle<Reader0>(WriteRecipePlan).read() } fun put0(item: MyLevel0) = run { env.getParticle<Writer0>(WriteRecipePlan).write(item) } fun all1(): List<MyLevel1> = run { env.getParticle<Reader1>(WriteRecipePlan).read() } fun put1(item: MyLevel1) = run { env.getParticle<Writer1>(WriteRecipePlan).write(item) } fun all2(): List<MyLevel2> = run { env.getParticle<Reader2>(WriteRecipePlan).read() } fun put2(item: MyLevel2) = run { env.getParticle<Writer2>(WriteRecipePlan).write(item) } }
bsd-3-clause
8f256d615313d7861b1c8f8f46e2f7e9
30.166667
94
0.734148
3.872781
false
false
false
false
blindpirate/gradle
subprojects/docs/src/samples/templates/structuring-software-projects/android-app/app/src/main/java/com/example/myproduct/app/MyProductAppActivity.kt
3
1676
package com.example.myproduct.app import android.app.Activity import android.os.AsyncTask import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import com.example.myproduct.user.table.TableBuilder class MyProductAppActivity : Activity() { class DownloadTask: AsyncTask<Void, Void, List<MutableList<String>>>() { override fun doInBackground(vararg params: Void): List<MutableList<String>> { return TableBuilder.build() } override fun onPostExecute(result: List<MutableList<String>>) { } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val data = DownloadTask().execute().get() val scrollView = ScrollView(this) val table = TableLayout(this) scrollView.addView(table); data.forEach { rowData -> val row = TableRow(this@MyProductAppActivity) rowData.forEach { cellData -> row.addView(TextView(this@MyProductAppActivity).apply { setPadding(6, 6, 6, 6) if (cellData.contains("https://")) { movementMethod = LinkMovementMethod.getInstance() text = Html.fromHtml("<a href='$cellData'>$cellData</a>", Html.FROM_HTML_MODE_LEGACY) } else { text = cellData } }) } table.addView(row) } setContentView(scrollView) } }
apache-2.0
4d1b4d6a7fbbf8e7d9c0f609329fc355
31.230769
109
0.619332
4.900585
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/scan/SearchSuccessCallback.kt
1
3563
package org.ligi.passandroid.scan import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import androidx.core.app.NotificationCompat import androidx.core.graphics.scale import org.ligi.passandroid.R import org.ligi.passandroid.model.PassBitmapDefinitions import org.ligi.passandroid.model.PassStore import org.ligi.passandroid.model.pass.Pass import org.ligi.passandroid.ui.PassViewActivity import org.ligi.passandroid.ui.PassViewActivityBase import org.ligi.passandroid.ui.UnzipPassController import org.threeten.bp.ZonedDateTime import java.io.File internal class SearchSuccessCallback(private val context: Context, private val passStore: PassStore, private val foundList: MutableList<Pass>, private val findNotificationBuilder: NotificationCompat.Builder, private val file: File, private val notifyManager: NotificationManager) : UnzipPassController.SuccessCallback { override fun call(uuid: String) { val pass = passStore.getPassbookForId(uuid) val isDuplicate = foundList.any { it.id == uuid } if (pass != null && !isDuplicate) { foundList.add(pass) val iconBitmap = pass.getBitmap(passStore, PassBitmapDefinitions.BITMAP_ICON) passStore.classifier.moveToTopic(pass, getInitialTopic(pass)) if (iconBitmap != null) { val bitmap = scale2maxSize(iconBitmap, context.resources.getDimensionPixelSize(R.dimen.finger)) findNotificationBuilder.setLargeIcon(bitmap) } val foundString = context.getString(R.string.found_pass, pass.description) findNotificationBuilder.setContentTitle(foundString) if (foundList.size > 1) { val foundMoreString = context.getString(R.string.found__pass, foundList.size - 1) findNotificationBuilder.setContentText(foundMoreString) } else { findNotificationBuilder.setContentText(file.absolutePath) } val intent = Intent(context, PassViewActivity::class.java) intent.putExtra(PassViewActivityBase.EXTRA_KEY_UUID, uuid) findNotificationBuilder.setContentIntent(PendingIntent.getActivity(context, SearchPassesIntentService.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)) notifyManager.notify(SearchPassesIntentService.FOUND_NOTIFICATION_ID, findNotificationBuilder.build()) } } private fun scale2maxSize(bitmap: Bitmap, dimensionPixelSize: Int): Bitmap { val scale = dimensionPixelSize.toFloat() / if (bitmap.width > bitmap.height) bitmap.width else bitmap.height return bitmap.scale((bitmap.width * scale).toInt(), (bitmap.height * scale).toInt(), filter = false) } private fun getInitialTopic(pass: Pass): String { val passDate = getDateOfPassForComparison(pass) if (passDate != null && passDate.isBefore(ZonedDateTime.now())) { return context.getString(R.string.topic_archive) } return context.getString(R.string.topic_new) } private fun getDateOfPassForComparison(pass: Pass): ZonedDateTime? { if (pass.calendarTimespan != null && pass.calendarTimespan!!.from != null) { return pass.calendarTimespan!!.from } else if (pass.validTimespans != null && pass.validTimespans!!.isNotEmpty() && pass.validTimespans!![0].to != null) { return pass.validTimespans!![0].to } return null } }
gpl-3.0
54f72c02b9d4d4a4df44dd62cf9f0bc0
47.148649
319
0.714286
4.538854
false
false
false
false
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/SeriesListRelations.kt
1
446
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.Embedded import androidx.room.Relation data class SeriesListRelations( @Embedded var seriesListEntity: SeriesListEntity = SeriesListEntity(), @Relation( parentColumn = "series_list_id", entityColumn = "summary_series_list_id", entity = SummaryEntity::class ) var seriesListSummary: List<SummaryEntity> = mutableListOf() )
mit
37d6aa81e714a15a33709385323504b9
23.777778
64
0.724215
4.372549
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/localcontentmigration/ReaderSavedPostsProviderHelper.kt
1
825
package org.wordpress.android.localcontentmigration import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper import org.wordpress.android.localcontentmigration.LocalContentEntityData.ReaderPostsData import org.wordpress.android.models.ReaderTag import org.wordpress.android.models.ReaderTagType.BOOKMARKED import javax.inject.Inject class ReaderSavedPostsProviderHelper @Inject constructor( private val readerPostTableWrapper: ReaderPostTableWrapper, ): LocalDataProviderHelper { override fun getData(localEntityId: Int?): LocalContentEntityData = readerPostTableWrapper.getPostsWithTag( readerTag = ReaderTag("", "", "", "", BOOKMARKED), maxRows = 0, excludeTextColumn = false ).let { ReaderPostsData(posts = it) } }
gpl-2.0
f19652e176baba51d8653db99e59e239
44.833333
89
0.745455
5.15625
false
false
false
false
edwardharks/Aircraft-Recognition
recognition/src/main/kotlin/com/edwardharker/aircraftrecognition/model/Aircraft.kt
1
484
package com.edwardharker.aircraftrecognition.model data class Aircraft( val id: String = "", val name: String = "", val shortDescription: String = "", val longDescription: String = "", val attribution: String = "", val attributionUrl: String = "", val metaData: Map<String, String> = emptyMap(), val filterOptions: Map<String, String> = emptyMap(), val images: List<Image> = emptyList(), val youtubeVideos: List<YoutubeVideo> = emptyList() )
gpl-3.0
7d0e40bb49b9bbe7ab10c53ecc8ddc24
31.266667
56
0.661157
4.36036
false
false
false
false
KotlinNLP/SimpleDNN
examples/mnist/helpers/MNISTSequenceExampleExtractor.kt
1
1447
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package mnist.helpers import com.beust.klaxon.JsonArray import com.beust.klaxon.JsonBase import com.beust.klaxon.JsonObject import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import utils.SequenceExampleWithFinalOutput import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import utils.exampleextractor.ExampleExtractor /** * */ class MNISTSequenceExampleExtractor(val outputSize: Int) : ExampleExtractor<SequenceExampleWithFinalOutput<DenseNDArray>> { /** * */ override fun extract(jsonElement: JsonBase): SequenceExampleWithFinalOutput<DenseNDArray> { val jsonObject = jsonElement as JsonObject val outputGold = DenseNDArrayFactory.oneHotEncoder(length = 10, oneAt = jsonObject.int("digit")!!) val featuresList: List<DenseNDArray> = jsonElement.array<JsonArray<*>>("sequence_data")!!.map { val deltaX = (it[0] as Int).toDouble() val deltaY = (it[1] as Int).toDouble() DenseNDArrayFactory.arrayOf(doubleArrayOf(deltaX, deltaY)) } return SequenceExampleWithFinalOutput(featuresList, outputGold) } }
mpl-2.0
8667515e16c635944c7fed2382ad847e
35.175
102
0.724948
4.371601
false
false
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImage.kt
5
2906
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.hasType class MarkdownImage(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement, MarkdownLink { val exclamationMark: PsiElement? get() = firstChild val link: MarkdownInlineLink? get() = findChildByType(MarkdownElementTypes.INLINE_LINK) override val linkText: MarkdownLinkText? get() = link?.children()?.filterIsInstance<MarkdownLinkText>()?.firstOrNull() override val linkDestination: MarkdownLinkDestination? get() = link?.children()?.filterIsInstance<MarkdownLinkDestination>()?.firstOrNull() val linkTitle: PsiElement? get() = link?.children()?.find { it.hasType(MarkdownElementTypes.LINK_TITLE) } fun collectLinkDescriptionText(): String? { return linkText?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET) } } fun collectLinkTitleText(): String? { return linkTitle?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE) } } private fun collectTextFromWrappedBlock(element: PsiElement, prefix: IElementType? = null, suffix: IElementType? = null): String? { val children = element.firstChild?.siblings(withSelf = true)?.toList() ?: return null val left = when (children.first().elementType) { prefix -> 1 else -> 0 } val right = when (children.last().elementType) { suffix -> children.size - 1 else -> children.size } val elements = children.subList(left, right) val content = elements.joinToString(separator = "") { it.text } return content.takeIf { it.isNotEmpty() } } companion object { /** * Useful for determining if some element is an actual image by it's leaf child. */ fun getByLeadingExclamationMark(exclamationMark: PsiElement): MarkdownImage? { if (!exclamationMark.hasType(MarkdownTokenTypes.EXCLAMATION_MARK)) { return null } val image = exclamationMark.parent ?: return null if (!image.hasType(MarkdownElementTypes.IMAGE) || image.firstChild != exclamationMark) { return null } return image as? MarkdownImage } } }
apache-2.0
1e65374c38cd680385a203202dc4f8fd
38.27027
158
0.737784
4.590837
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/BookmarkTypeChooser.kt
1
9798
// 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.ide.bookmark.actions import com.intellij.ide.bookmark.BookmarkBundle.message import com.intellij.ide.bookmark.BookmarkType import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ExperimentalUI import com.intellij.ui.JBColor.namedColor import com.intellij.ui.components.JBTextField import com.intellij.ui.components.panels.RowGridLayout import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBUI import com.intellij.util.ui.RegionPaintIcon import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.Nls import java.awt.* import java.awt.RenderingHints.KEY_ANTIALIASING import java.awt.RenderingHints.VALUE_ANTIALIAS_ON import java.awt.event.KeyEvent import java.awt.event.KeyListener import javax.swing.* private val ASSIGNED_FOREGROUND = namedColor("Bookmark.MnemonicAssigned.foreground", 0x000000, 0xBBBBBB) private val ASSIGNED_BACKGROUND = namedColor("Bookmark.MnemonicAssigned.background", 0xF7C777, 0x665632) private val CURRENT_FOREGROUND = namedColor("Bookmark.MnemonicCurrent.foreground", 0xFFFFFF, 0xFEFEFE) private val CURRENT_BACKGROUND = namedColor("Bookmark.MnemonicCurrent.background", 0x389FD6, 0x345F85) private val SHARED_CURSOR by lazy { Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } private val SHARED_LAYOUT by lazy { object : RowGridLayout(0, 4, 2, SwingConstants.CENTER) { override fun getCellSize(sizes: List<Dimension>) = when { ExperimentalUI.isNewUI() -> Dimension(JBUI.scale(30), JBUI.scale(34)) else -> Dimension(JBUI.scale(24), JBUI.scale(28)) } } } private object MySpacingConfiguration: IntelliJSpacingConfiguration() { override val verticalComponentGap: Int get() = 0 override val verticalSmallGap: Int get() = JBUI.scale(if (ExperimentalUI.isNewUI()) 16 else 8) } internal class BookmarkTypeChooser( private var current: BookmarkType?, assigned: Set<BookmarkType>, private var description: String?, private val onChosen: (BookmarkType, String) -> Unit ): JPanel(FlowLayout(FlowLayout.CENTER, 0, 0)) { private val bookmarkLayoutGrid = BookmarkLayoutGrid( current, assigned, { if (current == it) save() else current = it }, { save() } ) private lateinit var descriptionField: JBTextField val firstButton = bookmarkLayoutGrid.buttons().first() init { add(panel { customizeSpacingConfiguration(MySpacingConfiguration) { row { val lineLength = if (ExperimentalUI.isNewUI()) 63 else 55 comment(message("mnemonic.chooser.comment"), lineLength).apply { if (ExperimentalUI.isNewUI()) border = JBUI.Borders.empty(2, 4, 0, 4) } }.bottomGap(BottomGap.SMALL) row { cell(bookmarkLayoutGrid) .horizontalAlign(HorizontalAlign.CENTER) }.bottomGap(BottomGap.SMALL) row { descriptionField = textField() .horizontalAlign(HorizontalAlign.FILL) .applyToComponent { text = description ?: "" emptyText.text = message("mnemonic.chooser.description") isOpaque = false addKeyListener(object : KeyListener { override fun keyTyped(e: KeyEvent?) = Unit override fun keyReleased(e: KeyEvent?) = Unit override fun keyPressed(e: KeyEvent?) { if (e != null && e.modifiersEx == 0 && e.keyCode == KeyEvent.VK_ENTER) { save() } } }) } .component }.bottomGap(BottomGap.SMALL) row { cell(createLegend(ASSIGNED_BACKGROUND, message("mnemonic.chooser.legend.assigned.bookmark"))) cell(createLegend(CURRENT_BACKGROUND, message("mnemonic.chooser.legend.current.bookmark"))) } } }.apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.empty(0, 20, 14, 20) else -> JBUI.Borders.empty(12, 11) } isOpaque = false isFocusCycleRoot = true focusTraversalPolicy = object: LayoutFocusTraversalPolicy() { override fun accept(aComponent: Component?): Boolean { return super.accept(aComponent) && (aComponent !is JButton || aComponent == firstButton) } } }) border = JBUI.Borders.empty() background = namedColor("Popup.background") } private fun createLegend(color: Color, @Nls text: String) = JLabel(text).apply { icon = RegionPaintIcon(8) { g, x, y, width, height, _ -> g.color = color g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON) g.fillOval(x, y, width, height) }.withIconPreScaled(false) } private fun save() { current?.let { onChosen(it, descriptionField.text) } } } private class BookmarkLayoutGrid( current: BookmarkType?, private val assigned: Set<BookmarkType>, private val onChosen: (BookmarkType) -> Unit, private val save: () -> Unit ) : BorderLayoutPanel(), KeyListener { companion object { const val TYPE_KEY: String = "BookmarkLayoutGrid.Type" } init { addToLeft(JPanel(SHARED_LAYOUT).apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.emptyRight(14) else -> JBUI.Borders.empty(5) } isOpaque = false BookmarkType.values() .filter { it.mnemonic.isDigit() } .forEach { add(createButton(it)) } }) addToRight(JPanel(SHARED_LAYOUT).apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.empty() else -> JBUI.Borders.empty(5) } isOpaque = false BookmarkType.values() .filter { it.mnemonic.isLetter() } .forEach { add(createButton(it)) } }) isOpaque = false updateButtons(current) } fun buttons() = UIUtil.uiTraverser(this).traverse().filter(JButton::class.java) fun createButton(type: BookmarkType) = JButton(type.mnemonic.toString()).apply { setMnemonic(type.mnemonic) isOpaque = false putClientProperty("ActionToolbar.smallVariant", true) putClientProperty(TYPE_KEY, type) addPropertyChangeListener { repaint() } addActionListener { onChosen(type) updateButtons(type) } inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released") inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed") cursor = SHARED_CURSOR addKeyListener(this@BookmarkLayoutGrid) } fun updateButtons(current: BookmarkType?) { buttons().forEach { val type = it.getClientProperty(TYPE_KEY) as? BookmarkType when { type == current -> { it.putClientProperty("JButton.textColor", CURRENT_FOREGROUND) it.putClientProperty("JButton.backgroundColor", CURRENT_BACKGROUND) it.putClientProperty("JButton.borderColor", CURRENT_BACKGROUND) } assigned.contains(type) -> { it.putClientProperty("JButton.textColor", ASSIGNED_FOREGROUND) it.putClientProperty("JButton.backgroundColor", ASSIGNED_BACKGROUND) it.putClientProperty("JButton.borderColor", ASSIGNED_BACKGROUND) } else -> { it.putClientProperty("JButton.textColor", UIManager.getColor("Bookmark.MnemonicAvailable.foreground")) it.putClientProperty("JButton.backgroundColor", UIManager.getColor("Popup.background")) it.putClientProperty("JButton.borderColor", UIManager.getColor("Bookmark.MnemonicAvailable.borderColor")) } } } } private fun offset(delta: Int, size: Int) = when { delta < 0 -> delta delta > 0 -> delta + size else -> size / 2 } private fun next(source: Component, dx: Int, dy: Int): Component? { val point = SwingUtilities.convertPoint(source, offset(dx, source.width), offset(dy, source.height), this) val component = next(source, dx, dy, point) if (component != null || !Registry.`is`("ide.bookmark.mnemonic.chooser.cyclic.scrolling.allowed")) return component if (dx > 0) point.x = 0 if (dx < 0) point.x = dx + width if (dy > 0) point.y = 0 if (dy < 0) point.y = dy + height return next(source, dx, dy, point) } private fun next(source: Component, dx: Int, dy: Int, point: Point): Component? { while (contains(point)) { val component = SwingUtilities.getDeepestComponentAt(this, point.x, point.y) if (component is JButton) return component point.translate(dx * source.width / 2, dy * source.height / 2) } return null } override fun keyTyped(event: KeyEvent) = Unit override fun keyReleased(event: KeyEvent) = Unit override fun keyPressed(event: KeyEvent) { if (event.modifiersEx == 0) { when (event.keyCode) { KeyEvent.VK_UP, KeyEvent.VK_KP_UP -> next(event.component, 0, -1)?.requestFocus() KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN -> next(event.component, 0, 1)?.requestFocus() KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT -> next(event.component, -1, 0)?.requestFocus() KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT -> next(event.component, 1, 0)?.requestFocus() KeyEvent.VK_ENTER -> { val button = next(event.component, 0, 0) as? JButton button?.doClick() save() } else -> { val type = BookmarkType.get(event.keyCode.toChar()) if (type != BookmarkType.DEFAULT) { onChosen(type) save() } } } } } }
apache-2.0
426cef5e3b2f919f0fc03e22f9214344
35.423792
120
0.66534
4.243395
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/attribute/AttributeListViewController.kt
1
15641
package io.ipoli.android.player.attribute import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorInt import android.support.annotation.DrawableRes import android.support.v4.view.ViewPager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.ListPopupWindow import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.view.* import io.ipoli.android.common.view.pager.BasePagerAdapter import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.player.attribute.AttributeListViewState.StateType.* import io.ipoli.android.player.data.AndroidAttribute import io.ipoli.android.player.data.Player import io.ipoli.android.tag.Tag import kotlinx.android.synthetic.main.controller_attribute_list.view.* import kotlinx.android.synthetic.main.item_attribute_bonus.view.* import kotlinx.android.synthetic.main.item_attribute_list.view.* import kotlinx.android.synthetic.main.view_default_toolbar.view.* /** * Created by Polina Zhelyazkova <[email protected]> * on 9/13/18. */ class AttributeListViewController(args: Bundle? = null) : ReduxViewController<AttributeListAction, AttributeListViewState, AttributeListReducer>(args) { override val reducer = AttributeListReducer private var attribute: Player.AttributeType? = null override var helpConfig: HelpConfig? = HelpConfig( io.ipoli.android.R.string.help_dialog_attribute_list_title, io.ipoli.android.R.string.help_dialog_attribute_list_message ) private val onPageChangeListener = object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { val vm = (view!!.attributePager.adapter as AttributeAdapter).itemAt(position) colorLayout(vm) } } constructor(attribute: Player.AttributeType) : this() { this.attribute = attribute } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = inflater.inflate(R.layout.controller_attribute_list, container, false) view.attributePager.addOnPageChangeListener(onPageChangeListener) view.attributePager.adapter = AttributeAdapter() view.attributePager.clipToPadding = false view.attributePager.pageMargin = ViewUtils.dpToPx(8f, view.context).toInt() return view } override fun onCreateLoadAction() = AttributeListAction.Load(attribute) override fun onAttach(view: View) { super.onAttach(view) setToolbar(view.toolbar) showBackButton() toolbarTitle = stringRes(R.string.attributes) } override fun onDestroyView(view: View) { view.attributePager.removeOnPageChangeListener(onPageChangeListener) super.onDestroyView(view) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { return router.handleBack() } return super.onOptionsItemSelected(item) } override fun render(state: AttributeListViewState, view: View) { when (state.type) { LOADING -> { } DATA_LOADED -> { val vms = state.attributeViewModels (view.attributePager.adapter as AttributeAdapter).updateAll(vms) view.attributePager.currentItem = state.firstSelectedIndex!! colorLayout(vms[state.firstSelectedIndex]) } DATA_CHANGED -> { (view.attributePager.adapter as AttributeAdapter).updateAll(state.attributeViewModels) } } } private fun colorLayout(vm: AttributeViewModel) { view!!.toolbar.setBackgroundColor(vm.backgroundColor) activity?.window?.navigationBarColor = vm.backgroundColor activity?.window?.statusBarColor = vm.darkBackgroundColor } data class AttributeViewModel( val name: String, val attributeType: Player.AttributeType, val description: String, val level: String, val isActive: Boolean, val progress: Int, val max: Int, val currentProgress: String, @ColorInt val progressColor: Int, @ColorInt val secondaryProgressColor: Int, @ColorInt val backgroundColor: Int, @ColorInt val darkBackgroundColor: Int, @DrawableRes val background: Int, @DrawableRes val icon: Int, val attributeTags: List<Tag>, val tags: List<Tag>, val showTag1: Boolean, val showTag2: Boolean, val showTag3: Boolean, val showAddTag: Boolean, val bonuses: List<BonusViewModel> ) data class BonusViewModel( override val id: String, val title: String, val description: String, val isLocked: Boolean ) : RecyclerViewViewModel inner class BonusAdapter : BaseRecyclerViewAdapter<BonusViewModel>(R.layout.item_attribute_bonus) { override fun onBindViewModel(vm: BonusViewModel, view: View, holder: SimpleViewHolder) { view.bonusIcon.setImageResource( if (vm.isLocked) R.drawable.ic_lock_red_24dp else R.drawable.ic_done_green_24dp ) view.bonusTitle.text = vm.title view.bonusDescription.text = vm.description } } inner class AttributeAdapter : BasePagerAdapter<AttributeViewModel>() { override fun layoutResourceFor(item: AttributeViewModel) = R.layout.item_attribute_list override fun bindItem(item: AttributeViewModel, view: View) { view.attributeName.text = item.name view.attributeDescription.text = item.description view.attributeLevel.text = item.level view.attributeIconBack.setBackgroundResource(item.background) view.attributeIcon.setImageResource(item.icon) val square = view.attributeLevel.background as GradientDrawable square.mutate() square.color = ColorStateList.valueOf(item.darkBackgroundColor) view.attributeLevel.background = square if (item.isActive) { view.progressGroup.visible() view.hintGroup.invisible() view.attributeProgress.progressTintList = ColorStateList.valueOf(item.progressColor) view.attributeProgress.secondaryProgressTintList = ColorStateList.valueOf(item.secondaryProgressColor) view.attributeProgress.progress = item.progress view.attributeProgress.max = item.max view.attributeProgressText.text = item.currentProgress } else { view.progressGroup.invisible() view.hintGroup.visible() view.attributeHintIcon.setImageDrawable( IconicsDrawable(view.context) .icon(GoogleMaterial.Icon.gmd_info_outline) .color(attrData(R.attr.colorAccent)) .sizeDp(24) ) } renderTags(item, view) view.attributeBonusList.layoutManager = LinearLayoutManager(view.context) view.attributeBonusList.adapter = BonusAdapter() view.attributeBonusList.isNestedScrollingEnabled = false (view.attributeBonusList.adapter as BonusAdapter).updateAll(item.bonuses) } private fun renderTags( item: AttributeViewModel, view: View ) { if (item.showTag1) { view.tag1.visible() view.tag1.text = item.attributeTags[0].name renderTagIndicatorColor(view.tag1, item.attributeTags[0]) } else view.tag1.gone() if (item.showTag2) { view.tag2.visible() view.tag2.text = item.attributeTags[1].name renderTagIndicatorColor(view.tag2, item.attributeTags[1]) } else view.tag2.gone() if (item.showTag3) { view.tag3.visible() view.tag3.text = item.attributeTags[2].name renderTagIndicatorColor(view.tag3, item.attributeTags[2]) } else view.tag3.gone() view.tag1.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[0] ) ) } view.tag2.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[1] ) ) } view.tag3.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[2] ) ) } if (item.showAddTag) { view.addTag.visible() val background = view.addTag.background as GradientDrawable background.setColor(item.backgroundColor) val popupWindow = ListPopupWindow(activity!!) popupWindow.anchorView = view.addTag popupWindow.width = ViewUtils.dpToPx(200f, activity!!).toInt() popupWindow.setAdapter(TagAdapter(item.tags)) popupWindow.setOnItemClickListener { _, _, position, _ -> dispatch(AttributeListAction.AddTag(item.attributeType, item.tags[position])) popupWindow.dismiss() } view.addTag.onDebounceClick { popupWindow.show() } } else view.addTag.gone() } private fun renderTagIndicatorColor(view: TextView, tag: Tag) { val indicator = view.compoundDrawablesRelative[0] as GradientDrawable indicator.mutate() indicator.setColor(colorRes(AndroidColor.valueOf(tag.color.name).color500)) view.setCompoundDrawablesRelativeWithIntrinsicBounds( indicator, null, view.compoundDrawablesRelative[2], null ) } inner class TagAdapter(tags: List<Tag>) : ArrayAdapter<Tag>( activity!!, R.layout.item_tag_popup, tags ) { override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup) = bindView(position, convertView, parent) override fun getView(position: Int, convertView: View?, parent: ViewGroup) = bindView(position, convertView, parent) private fun bindView(position: Int, convertView: View?, parent: ViewGroup): View { val view = if (convertView == null) { val inflater = LayoutInflater.from(context) inflater.inflate(R.layout.item_tag_popup, parent, false) as TextView } else { convertView as TextView } val item = getItem(position) view.text = item.name val color = AndroidColor.valueOf(item.color.name).color500 val indicator = view.compoundDrawablesRelative[0] as GradientDrawable indicator.mutate() val size = ViewUtils.dpToPx(8f, view.context).toInt() indicator.setSize(size, size) indicator.setColor(colorRes(color)) view.setCompoundDrawablesRelativeWithIntrinsicBounds( indicator, null, null, null ) return view } } } private val AttributeListViewState.attributeViewModels: List<AttributeViewModel> get() { val tagToCount = tags!!.map { it to 0 }.toMap().toMutableMap() attributes!!.forEach { it.tags.forEach { t -> tagToCount[t] = tagToCount[t]!! + 1 } } return attributes.map { val attr = AndroidAttribute.valueOf(it.type.name) val attributeTags = it.tags val tagCount = attributeTags.size val availableTags = tags.filter { t -> tagToCount[t]!! < 3 && !attributeTags.contains(t) } val attrRank = AttributeRank.of(it.level, rank!!) val lastRankIndex = Math.min(attrRank.ordinal + 2, Player.Rank.values().size) AttributeViewModel( name = stringRes(attr.title), attributeType = it.type, description = stringRes(attr.description), level = it.level.toString(), isActive = tagCount > 0, progress = ((it.progressForLevel * 100f) / it.progressForNextLevel).toInt(), max = 100, currentProgress = "${it.progressForLevel}/${it.progressForNextLevel}", progressColor = colorRes(attr.colorPrimaryDark), secondaryProgressColor = colorRes(attr.colorPrimary), backgroundColor = colorRes(attr.colorPrimary), darkBackgroundColor = colorRes(attr.colorPrimaryDark), background = attr.background, icon = attr.whiteIcon, attributeTags = attributeTags, tags = availableTags, showTag1 = tagCount > 0, showTag2 = tagCount > 1, showTag3 = tagCount > 2, showAddTag = tagCount < 3 && availableTags.isNotEmpty(), bonuses = Player.Rank.values().toList().subList( 1, lastRankIndex ).mapIndexed { i, r -> BonusViewModel( id = r.name, title = "Level ${(i + 1) * 10}: ${stringRes(attr.bonusNames[r]!!)}", description = stringRes(attr.bonusDescriptions[r]!!), isLocked = !(attrRank == Player.Rank.DIVINITY || i + 1 < lastRankIndex - 1) ) }.reversed() ) } } }
gpl-3.0
d5a0964216351e002fa0eb555699806f
37.15122
103
0.590435
5.173999
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt
4
3945
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtSecondaryConstructor import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryConstructor) : KotlinQuickFixAction<KtSecondaryConstructor>(element) { override fun getText() = KotlinBundle.message("fix.insert.delegation.call", keywordToUse) override fun getFamilyName() = KotlinBundle.message("insert.explicit.delegation.call") private val keywordToUse = if (isThis) "this" else "super" override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val newDelegationCall = element.replaceImplicitDelegationCallWithExplicit(isThis) val resolvedCall = newDelegationCall.resolveToCall(BodyResolveMode.FULL) val descriptor = element.unsafeResolveToDescriptor() // if empty call is ok and it's resolved to another constructor, do not move caret if (resolvedCall?.isReallySuccess() == true && resolvedCall.candidateDescriptor.original != descriptor) return val leftParOffset = newDelegationCall.valueArgumentList!!.leftParenthesis!!.textOffset editor?.moveCaret(leftParOffset + 1) } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false return element.hasImplicitDelegationCall() } object InsertThisDelegationCallFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType<KtSecondaryConstructor> { secondaryConstructor -> return if (secondaryConstructor.getContainingClassOrObject().getConstructorsCount() <= 1 || !secondaryConstructor.hasImplicitDelegationCall() ) null else InsertDelegationCallQuickfix(isThis = true, element = secondaryConstructor) } private fun KtClassOrObject.getConstructorsCount() = (descriptor as ClassDescriptor).constructors.size } object InsertSuperDelegationCallFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val secondaryConstructor = diagnostic.psiElement.getNonStrictParentOfType<KtSecondaryConstructor>() ?: return null if (!secondaryConstructor.hasImplicitDelegationCall()) return null val klass = secondaryConstructor.getContainingClassOrObject() as? KtClass ?: return null if (klass.hasPrimaryConstructor()) return null return InsertDelegationCallQuickfix(isThis = false, element = secondaryConstructor) } } }
apache-2.0
36e3051efe2f180dc52629344339867a
50.907895
158
0.767554
5.396717
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/highlighting/src/org/jetbrains/kotlin/idea/base/highlighting/KotlinNameHighlightingStateUtils.kt
4
1147
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("KotlinNameHighlightingStateUtils") package org.jetbrains.kotlin.idea.base.highlighting import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly private val NAME_HIGHLIGHTING_STATE_KEY = Key<Boolean>("KOTLIN_NAME_HIGHLIGHTING_STATE") @get:ApiStatus.Internal @set:ApiStatus.Internal var Project.isNameHighlightingEnabled: Boolean get() = getUserData(NAME_HIGHLIGHTING_STATE_KEY) ?: true internal set(value) { // Avoid storing garbage in the user data val valueToPut = if (!value) false else null putUserData(NAME_HIGHLIGHTING_STATE_KEY, valueToPut) } @TestOnly @ApiStatus.Internal fun Project.withNameHighlightingDisabled(block: () -> Unit) { val oldValue = isNameHighlightingEnabled try { isNameHighlightingEnabled = false block() } finally { isNameHighlightingEnabled = oldValue } }
apache-2.0
2f820443f4e908d11f08a5f637d79db1
32.764706
158
0.751526
4.201465
false
true
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyvalue/AccountValues.kt
1
17395
package org.thoughtcrime.securesms.keyvalue import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import androidx.annotation.VisibleForTesting import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.IdentityKeyPair import org.signal.libsignal.protocol.ecc.Curve import org.signal.libsignal.protocol.util.Medium import org.signal.libsignal.zkgroup.profiles.PniCredential import org.thoughtcrime.securesms.crypto.IdentityKeyUtil import org.thoughtcrime.securesms.crypto.MasterCipher import org.thoughtcrime.securesms.crypto.ProfileKeyUtil import org.thoughtcrime.securesms.crypto.storage.PreKeyMetadataStore import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.service.KeyCachingService import org.thoughtcrime.securesms.util.Base64 import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.Util import org.whispersystems.signalservice.api.push.ACI import org.whispersystems.signalservice.api.push.PNI import org.whispersystems.signalservice.api.push.SignalServiceAddress import java.security.SecureRandom internal class AccountValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(AccountValues::class.java) private const val KEY_SERVICE_PASSWORD = "account.service_password" private const val KEY_REGISTRATION_ID = "account.registration_id" private const val KEY_FCM_ENABLED = "account.fcm_enabled" private const val KEY_FCM_TOKEN = "account.fcm_token" private const val KEY_FCM_TOKEN_VERSION = "account.fcm_token_version" private const val KEY_FCM_TOKEN_LAST_SET_TIME = "account.fcm_token_last_set_time" private const val KEY_DEVICE_NAME = "account.device_name" private const val KEY_DEVICE_ID = "account.device_id" private const val KEY_ACI_IDENTITY_PUBLIC_KEY = "account.aci_identity_public_key" private const val KEY_ACI_IDENTITY_PRIVATE_KEY = "account.aci_identity_private_key" private const val KEY_ACI_SIGNED_PREKEY_REGISTERED = "account.aci_signed_prekey_registered" private const val KEY_ACI_NEXT_SIGNED_PREKEY_ID = "account.aci_next_signed_prekey_id" private const val KEY_ACI_ACTIVE_SIGNED_PREKEY_ID = "account.aci_active_signed_prekey_id" private const val KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT = "account.aci_signed_prekey_failure_count" private const val KEY_ACI_NEXT_ONE_TIME_PREKEY_ID = "account.aci_next_one_time_prekey_id" private const val KEY_PNI_IDENTITY_PUBLIC_KEY = "account.pni_identity_public_key" private const val KEY_PNI_IDENTITY_PRIVATE_KEY = "account.pni_identity_private_key" private const val KEY_PNI_SIGNED_PREKEY_REGISTERED = "account.pni_signed_prekey_registered" private const val KEY_PNI_NEXT_SIGNED_PREKEY_ID = "account.pni_next_signed_prekey_id" private const val KEY_PNI_ACTIVE_SIGNED_PREKEY_ID = "account.pni_active_signed_prekey_id" private const val KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT = "account.pni_signed_prekey_failure_count" private const val KEY_PNI_NEXT_ONE_TIME_PREKEY_ID = "account.pni_next_one_time_prekey_id" private const val KEY_PNI_CREDENTIAL = "account.pni_credential" @VisibleForTesting const val KEY_E164 = "account.e164" @VisibleForTesting const val KEY_ACI = "account.aci" @VisibleForTesting const val KEY_PNI = "account.pni" @VisibleForTesting const val KEY_IS_REGISTERED = "account.is_registered" } init { if (!store.containsKey(KEY_ACI)) { migrateFromSharedPrefsV1(ApplicationDependencies.getApplication()) } if (!store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { migrateFromSharedPrefsV2(ApplicationDependencies.getApplication()) } } public override fun onFirstEverAppLaunch() = Unit public override fun getKeysToIncludeInBackup(): List<String> { return listOf( KEY_ACI_IDENTITY_PUBLIC_KEY, KEY_ACI_IDENTITY_PRIVATE_KEY, KEY_PNI_IDENTITY_PUBLIC_KEY, KEY_PNI_IDENTITY_PRIVATE_KEY, ) } /** The local user's [ACI]. */ val aci: ACI? get() = ACI.parseOrNull(getString(KEY_ACI, null)) /** The local user's [ACI]. Will throw if not present. */ fun requireAci(): ACI { return ACI.parseOrThrow(getString(KEY_ACI, null)) } fun setAci(aci: ACI) { putString(KEY_ACI, aci.toString()) } /** The local user's [PNI]. */ val pni: PNI? get() = PNI.parseOrNull(getString(KEY_PNI, null)) /** The local user's [PNI]. Will throw if not present. */ fun requirePni(): PNI { return PNI.parseOrThrow(getString(KEY_PNI, null)) } fun setPni(pni: PNI) { putString(KEY_PNI, pni.toString()) } fun getServiceIds(): ServiceIds { return ServiceIds(requireAci(), pni) } /** The local user's E164. */ val e164: String? get() = getString(KEY_E164, null) fun setE164(e164: String) { putString(KEY_E164, e164) } /** The password for communicating with the Signal service. */ val servicePassword: String? get() = getString(KEY_SERVICE_PASSWORD, null) fun setServicePassword(servicePassword: String) { putString(KEY_SERVICE_PASSWORD, servicePassword) } /** A randomly-generated value that represents this registration instance. Helps the server know if you reinstalled. */ var registrationId: Int by integerValue(KEY_REGISTRATION_ID, 0) /** The identity key pair for the ACI identity. */ val aciIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, null)) ) } /** The identity key pair for the PNI identity. */ val pniIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, null)) ) } fun hasAciIdentityKey(): Boolean { return store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the ACI identity. Should only be done once. */ fun generateAciIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate an ANI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new ACI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } fun hasPniIdentityKey(): Boolean { return store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the PNI identity if one doesn't already exist. */ fun generatePniIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate a PNI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new PNI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } /** When acting as a linked device, this method lets you store the identity keys sent from the primary device */ fun setIdentityKeysFromPrimaryDevice(aciKeys: IdentityKeyPair) { synchronized(this) { require(isLinkedDevice) { "Must be a linked device!" } store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, aciKeys.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, aciKeys.privateKey.serialize()) .commit() } } /** Only to be used when restoring an identity public key from an old backup */ fun restoreLegacyIdentityPublicKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity public key from backup.") putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, Base64.decode(base64)) } /** Only to be used when restoring an identity private key from an old backup */ fun restoreLegacyIdentityPrivateKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity private key from backup.") putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, Base64.decode(base64)) } @get:JvmName("aciPreKeys") val aciPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_ACI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_ACI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } @get:JvmName("pniPreKeys") val pniPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_PNI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_PNI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_PNI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_PNI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } /** Indicates whether the user has the ability to receive FCM messages. Largely coupled to whether they have Play Service. */ @get:JvmName("isFcmEnabled") var fcmEnabled: Boolean by booleanValue(KEY_FCM_ENABLED, false) /** The FCM token, which allows the server to send us FCM messages. */ var fcmToken: String? get() { val tokenVersion: Int = getInteger(KEY_FCM_TOKEN_VERSION, 0) return if (tokenVersion == Util.getCanonicalVersionCode()) { getString(KEY_FCM_TOKEN, null) } else { null } } set(value) { store.beginWrite() .putString(KEY_FCM_TOKEN, value) .putInteger(KEY_FCM_TOKEN_VERSION, Util.getCanonicalVersionCode()) .putLong(KEY_FCM_TOKEN_LAST_SET_TIME, System.currentTimeMillis()) .apply() } /** When we last set the [fcmToken] */ val fcmTokenLastSetTime: Long get() = getLong(KEY_FCM_TOKEN_LAST_SET_TIME, 0) /** Whether or not the user is registered with the Signal service. */ val isRegistered: Boolean get() = getBoolean(KEY_IS_REGISTERED, false) fun setRegistered(registered: Boolean) { Log.i(TAG, "Setting push registered: $registered", Throwable()) val previous = isRegistered putBoolean(KEY_IS_REGISTERED, registered) ApplicationDependencies.getIncomingMessageObserver().notifyRegistrationChanged() if (previous != registered) { Recipient.self().live().refresh() } if (previous && !registered) { clearLocalCredentials(ApplicationDependencies.getApplication()) } } val deviceName: String? get() = getString(KEY_DEVICE_NAME, null) fun setDeviceName(deviceName: String) { putString(KEY_DEVICE_NAME, deviceName) } var deviceId: Int by integerValue(KEY_DEVICE_ID, SignalServiceAddress.DEFAULT_DEVICE_ID) val isPrimaryDevice: Boolean get() = deviceId == SignalServiceAddress.DEFAULT_DEVICE_ID val isLinkedDevice: Boolean get() = !isPrimaryDevice var pniCredential: PniCredential? set(value) = putBlob(KEY_PNI_CREDENTIAL, value?.serialize()) get() = getBlob(KEY_PNI_CREDENTIAL, null)?.let { PniCredential(it) } private fun clearLocalCredentials(context: Context) { putString(KEY_SERVICE_PASSWORD, Util.getSecret(18)) val newProfileKey = ProfileKeyUtil.createNew() val self = Recipient.self() SignalDatabase.recipients.setProfileKey(self.id, newProfileKey) ApplicationDependencies.getGroupsV2Authorization().clear() } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV1(context: Context) { Log.i(TAG, "[V1] Migrating account values from shared prefs.") putString(KEY_ACI, TextSecurePreferences.getStringPreference(context, "pref_local_uuid", null)) putString(KEY_E164, TextSecurePreferences.getStringPreference(context, "pref_local_number", null)) putString(KEY_SERVICE_PASSWORD, TextSecurePreferences.getStringPreference(context, "pref_gcm_password", null)) putBoolean(KEY_IS_REGISTERED, TextSecurePreferences.getBooleanPreference(context, "pref_gcm_registered", false)) putInteger(KEY_REGISTRATION_ID, TextSecurePreferences.getIntegerPreference(context, "pref_local_registration_id", 0)) putBoolean(KEY_FCM_ENABLED, !TextSecurePreferences.getBooleanPreference(context, "pref_gcm_disabled", false)) putString(KEY_FCM_TOKEN, TextSecurePreferences.getStringPreference(context, "pref_gcm_registration_id", null)) putInteger(KEY_FCM_TOKEN_VERSION, TextSecurePreferences.getIntegerPreference(context, "pref_gcm_registration_id_version", 0)) putLong(KEY_FCM_TOKEN_LAST_SET_TIME, TextSecurePreferences.getLongPreference(context, "pref_gcm_registration_id_last_set_time", 0)) } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV2(context: Context) { Log.i(TAG, "[V2] Migrating account values from shared prefs.") val masterSecretPrefs: SharedPreferences = context.getSharedPreferences("SecureSMS-Preferences", 0) val defaultPrefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val storeWriter: KeyValueStore.Writer = store.beginWrite() if (masterSecretPrefs.hasStringData("pref_identity_public_v3")) { Log.i(TAG, "Migrating modern identity key.") val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_v3", null)!!) val identityPrivate = Base64.decode(masterSecretPrefs.getString("pref_identity_private_v3", null)!!) storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else if (masterSecretPrefs.hasStringData("pref_identity_public_curve25519")) { Log.i(TAG, "Migrating legacy identity key.") val masterCipher = MasterCipher(KeyCachingService.getMasterSecret(context)) val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_curve25519", null)!!) val identityPrivate = masterCipher.decryptKey(Base64.decode(masterSecretPrefs.getString("pref_identity_private_curve25519", null)!!)).serialize() storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else { Log.w(TAG, "No pre-existing identity key! No migration.") } storeWriter .putInteger(KEY_ACI_NEXT_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_next_signed_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_active_signed_pre_key_id", -1)) .putInteger(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, defaultPrefs.getInt("pref_next_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, defaultPrefs.getInt("pref_signed_prekey_failure_count", 0)) .putBoolean(KEY_ACI_SIGNED_PREKEY_REGISTERED, defaultPrefs.getBoolean("pref_signed_prekey_registered", false)) .commit() masterSecretPrefs .edit() .remove("pref_identity_public_v3") .remove("pref_identity_private_v3") .remove("pref_identity_public_curve25519") .remove("pref_identity_private_curve25519") .commit() defaultPrefs .edit() .remove("pref_local_uuid") .remove("pref_identity_public_v3") .remove("pref_next_signed_pre_key_id") .remove("pref_active_signed_pre_key_id") .remove("pref_signed_prekey_failure_count") .remove("pref_signed_prekey_registered") .remove("pref_next_pre_key_id") .remove("pref_gcm_password") .remove("pref_gcm_registered") .remove("pref_local_registration_id") .remove("pref_gcm_disabled") .remove("pref_gcm_registration_id") .remove("pref_gcm_registration_id_version") .remove("pref_gcm_registration_id_last_set_time") .commit() } private fun SharedPreferences.hasStringData(key: String): Boolean { return this.getString(key, null) != null } }
gpl-3.0
9b62b15c681a54efb8cc81dffb9abb43
41.530562
151
0.727623
3.751348
false
false
false
false
jk1/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/RunConfigurationOptions.kt
2
1458
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.execution.configurations import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.annotations.* open class RunConfigurationOptions : BaseState() { @Tag("output_file") class OutputFileOptions : BaseState() { @get:Attribute("path") var fileOutputPath: String? by string() @get:Attribute("is_save") var isSaveOutput: Boolean by property(false) } // we use object instead of 2 fields because XML serializer cannot reuse tag for several fields @get:Property(surroundWithTag = false) var fileOutput: OutputFileOptions by property(OutputFileOptions()) @get:Attribute("show_console_on_std_out") var isShowConsoleOnStdOut: Boolean by property(false) @get:Attribute("show_console_on_std_err") var isShowConsoleOnStdErr: Boolean by property(false) @get:Property(surroundWithTag = false) @get:XCollection var logFiles: MutableList<LogFileOptions> by list<LogFileOptions>() } open class LocatableRunConfigurationOptions : RunConfigurationOptions() { @get:Attribute("nameIsGenerated") var isNameGenerated: Boolean by property(false) } open class ModuleBasedConfigurationOptions : LocatableRunConfigurationOptions() { @get:OptionTag(tag = "module", valueAttribute = "name", nameAttribute = "") var module: String? by string() }
apache-2.0
f8f64a64b28186ecf918749d8969e740
36.410256
140
0.763374
4.189655
false
true
false
false
marius-m/wt4
remote/src/main/java/lt/markmerkk/JiraNetworkUtils.kt
1
1769
package lt.markmerkk import lt.markmerkk.exceptions.AuthException import net.rcarz.jiraclient.JiraException import net.rcarz.jiraclient.RestException import org.slf4j.Logger object JiraNetworkUtils { } inline fun <reified T: Exception> Throwable.findException(): T? { val exceptions = mutableListOf<Throwable>() var iterableThrowable: Throwable? = this do { if (iterableThrowable != null) { exceptions.add(iterableThrowable) iterableThrowable = iterableThrowable.cause } else { iterableThrowable = null } } while (iterableThrowable != null) return exceptions .mapNotNull { if (it is T) { it } else { null } }.firstOrNull() } fun Throwable.isAuthException(): Boolean { val restAuthException = findException<RestException>()?.httpStatusCode == 401 val isAuthException = findException<AuthException>() != null return restAuthException || isAuthException } fun Logger.warnWithJiraException(message: String, throwable: Throwable) { val authException = throwable.findException<AuthException>() val restException = throwable.findException<RestException>() when { authException != null -> this.warn("$message / Authorization error") restException != null && restException.httpStatusCode == 401 -> this.warn("$message / Authorization error (401)!") restException != null -> this.warn("$message / Rest error (${restException.httpStatusCode}): ${restException.httpResult}") throwable is JiraException -> this.warn("$message / Jira error: ${throwable.message}") else -> this.warn(message, throwable) } }
apache-2.0
eb34eea381c9e9ab100541d58137c0dd
35.854167
130
0.653477
4.88674
false
false
false
false
Shoebill/shoebill-common
src/main/java/net/gtaun/shoebill/common/AbstractShoebillContext.kt
1
1257
package net.gtaun.shoebill.common import net.gtaun.shoebill.entities.Destroyable import net.gtaun.util.event.EventManager import net.gtaun.util.event.EventManagerNode import java.util.HashSet @AllOpen abstract class AbstractShoebillContext(parentEventManager: EventManager) : Destroyable { private var isInitialized = false protected var eventManagerNode: EventManagerNode = parentEventManager.createChildNode() private val destroyables = mutableSetOf<Destroyable>() fun addDestroyable(destroyable: Destroyable) = destroyables.add(destroyable) fun removeDestroyable(destroyable: Destroyable) = destroyables.remove(destroyable) fun init() { if (isInitialized) return try { onInit() isInitialized = true } catch (e: Throwable) { e.printStackTrace() destroy() } } override fun destroy() { if (isDestroyed) return onDestroy() destroyables.forEach { it.destroy() } destroyables.clear() eventManagerNode.destroy() isInitialized = false } override val isDestroyed: Boolean get() = !isInitialized protected abstract fun onInit() protected abstract fun onDestroy() }
apache-2.0
bca58097752b99423b4a8362e7f9010e
24.14
91
0.683373
4.816092
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/adapter/EditPlaylistAdapter.kt
2
2969
package io.casey.musikcube.remote.ui.tracks.adapter import android.content.SharedPreferences import android.text.TextUtils import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.websocket.model.ITrack import io.casey.musikcube.remote.ui.shared.extension.fallback import io.casey.musikcube.remote.ui.shared.extension.titleEllipsizeMode import io.casey.musikcube.remote.ui.tracks.model.EditPlaylistViewModel class EditPlaylistAdapter( private val viewModel: EditPlaylistViewModel, private val touchHelper: ItemTouchHelper, prefs: SharedPreferences) : RecyclerView.Adapter<EditPlaylistAdapter.ViewHolder>() { private val ellipsizeMode = titleEllipsizeMode(prefs) override fun getItemCount(): Int { return viewModel.count } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.edit_playlist_track_row, parent, false) val holder = ViewHolder(view, ellipsizeMode) val drag = view.findViewById<View>(R.id.dragHandle) val swipe = view.findViewById<View>(R.id.swipeHandle) view.setOnClickListener(emptyClickListener) drag.setOnTouchListener(dragTouchHandler) swipe.setOnTouchListener(dragTouchHandler) drag.tag = holder swipe.tag = holder return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(viewModel[position]) } private val emptyClickListener = { _: View -> } private val dragTouchHandler = object: View.OnTouchListener { override fun onTouch(view: View, event: MotionEvent?): Boolean { if (event?.actionMasked == MotionEvent.ACTION_DOWN) { if (view.id == R.id.dragHandle) { touchHelper.startDrag(view.tag as RecyclerView.ViewHolder) } else if (view.id == R.id.swipeHandle) { touchHelper.startSwipe(view.tag as RecyclerView.ViewHolder) return true } } return false } } class ViewHolder internal constructor(view: View, ellipsizeMode: TextUtils.TruncateAt) : RecyclerView.ViewHolder(view) { private val title = itemView.findViewById<TextView>(R.id.title) private val subtitle = itemView.findViewById<TextView>(R.id.subtitle) init { title.ellipsize = ellipsizeMode } fun bind(track: ITrack) { title.text = fallback(track.title, "-") subtitle.text = fallback(track.albumArtist, "-") } } }
bsd-3-clause
d9ecc798a1725f6241f2acbc98ee83f9
37.076923
124
0.6871
4.660911
false
false
false
false