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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PolymerLabs/arcs
|
java/arcs/core/allocator/ArcHostLookup.kt
|
1
|
4012
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.allocator
import arcs.core.common.ArcId
import arcs.core.common.CompositeException
import arcs.core.data.Plan
import arcs.core.host.ArcHost
import arcs.core.host.ArcState
import arcs.core.host.ArcStateChangeRegistration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
/** Denotes a component capable of looking up [ArcHost] instances by their id. */
interface ArcHostLookup {
/** Looks up an [ArcHost] given a [hostId] and returns it. */
suspend fun lookupArcHost(hostId: String): ArcHost
}
/**
* Builds a [Flow] of [ArcState]s where each emitted value is the combined [ArcState] across all of
* the [partitions]' [ArcHost]s.
*/
@ExperimentalCoroutinesApi
fun ArcHostLookup.createArcStateFlow(
arcId: ArcId,
partitions: Collection<Plan.Partition>,
cleanupScope: CoroutineScope
): Flow<ArcState> {
// Initial state values for each partition's arc host.
val initialHostStates = partitions.associate { it.arcHost to ArcState.NeverStarted }
// Construct a flow of ArcHost-ArcState pairs, where each value is the state of the arc on a
// particular arc host.
val baseFlow = callbackFlow {
// Register callbacks with all of the arc hosts for state-change notifications coming from
// the provided arcId.
val registrations: Map<String, ArcStateChangeRegistration> =
partitions.associate { partition ->
val registration = lookupArcHost(partition.arcHost)
.addOnArcStateChange(arcId) { _, state ->
if (isClosedForSend) return@addOnArcStateChange
offer(partition.arcHost to state)
}
partition.arcHost to registration
}
// Keep collecting state changes until the flow collection is stopped, then clean-up our
// registrations.
awaitClose {
cleanupScope.launch {
registrations.forEach { (host, registration) ->
lookupArcHost(host).removeOnArcStateChange(registration)
}
}
}
}
// Return a flow consisting of a single computed ArcState by finding consensus across the states
// at each arc host.
return baseFlow
.scan(initialHostStates) { states, hostToState -> states + hostToState }
.map { it.values.computeArcState() }
}
/**
* Determines an overall [ArcState] from the values contained within the receiving [Collection].
*
* * If any member is [ArcState.Deleted] or [ArcState.Error], that state is returned.
* * If all states are the same, that state is returned.
* * If there are states which are not equal to each other within the receiving [Collection],
* returns [ArcState.Indeterminate].
*/
fun Collection<ArcState>.computeArcState(): ArcState {
var commonState = ArcState.Indeterminate
val errorsFound = mutableListOf<Throwable>()
var anyDeleted = false
var anyErrored = false
var anyMismatched = false
forEach { state ->
when {
state == ArcState.Deleted -> anyDeleted = true
state == ArcState.Error -> {
state.cause?.let(errorsFound::add)
anyErrored = true
}
commonState == ArcState.Indeterminate -> commonState = state
state != commonState -> anyMismatched = true
}
}
if (anyDeleted) return ArcState.Deleted
if (anyErrored) {
if (errorsFound.size <= 1) return ArcState.errorWith(errorsFound.firstOrNull())
return ArcState.errorWith(CompositeException(errorsFound))
}
if (anyMismatched) return ArcState.Indeterminate
return commonState
}
|
bsd-3-clause
|
5444fecd49c769d3671c1ae081703b92
| 34.504425 | 99 | 0.727817 | 4.375136 | false | false | false | false |
DanilaFe/abacus
|
core/src/main/kotlin/org/nwapw/abacus/number/range/NumberRange.kt
|
1
|
1134
|
package org.nwapw.abacus.number.range
import org.nwapw.abacus.Abacus
import org.nwapw.abacus.number.NumberInterface
/**
* A closed range designed specifically for [NumberInterface]
*
* Besides providing the usual functionality of a [ClosedRange], this range
* also handles promotion - that is, it's safe to use it with numbers of different
* implementations, even as starting and ending points.
*
* @property abacus the abacus instance used for promotion.
* @property start the starting point of the range.
* @property endInclusive the ending point of the range.
*/
class NumberRange(val abacus: Abacus,
override val start: NumberInterface,
override val endInclusive: NumberInterface): ClosedRange<NumberInterface> {
override operator fun contains(value: NumberInterface): Boolean {
val promotionResult = abacus.promotionManager.promote(start, endInclusive, value)
val newStart = promotionResult.items[0]
val newEnd = promotionResult.items[1]
val newValue = promotionResult.items[2]
return newValue >= newStart && newValue <= newEnd
}
}
|
mit
|
59462c1589d7651aefc50eadf1017ed7
| 38.137931 | 93 | 0.726631 | 4.231343 | false | false | false | false |
pyamsoft/pydroid
|
ui/src/main/java/com/pyamsoft/pydroid/ui/PYDroid.kt
|
1
|
4941
|
/*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.ui
import android.app.Activity
import android.app.Application
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import com.pyamsoft.pydroid.core.Logger
import com.pyamsoft.pydroid.core.PYDroidLogger
import com.pyamsoft.pydroid.ui.app.ComposeThemeProvider
import com.pyamsoft.pydroid.ui.internal.app.NoopTheme
import com.pyamsoft.pydroid.ui.internal.app.invoke
import com.pyamsoft.pydroid.ui.theme.ThemeProvider
import com.pyamsoft.pydroid.ui.theme.Theming
/**
* A Compose theme provider which does nothing
*
* Can't use object literal or we lose @Composable context
*/
private object NoopThemeProvider : ComposeThemeProvider {
@Composable
override fun Render(
activity: Activity,
themeProvider: ThemeProvider,
content: @Composable () -> Unit,
) {
NoopTheme(activity, content)
}
}
/** PYDroid library entry point */
public class PYDroid
private constructor(
private val instance: PYDroidInitializer,
) {
/** Resolve and return exposed Modules for this PYDroid instance */
@CheckResult
public fun modules(): ModuleProvider.Modules {
return instance.moduleProvider.get()
}
/** Override Application.getSystemService() with this to get the PYDroid object graph */
@CheckResult
public fun getSystemService(name: String): Any? =
when (name) {
PYDroidComponent::class.java.name -> instance.component
Theming::class.java.name -> modules().theming()
else -> null
}
/** PYDroid parameters */
public data class Parameters
@JvmOverloads
public constructor(
/** URL to view application source code */
override val viewSourceUrl: String,
/** URL to submit application bug reports */
override val bugReportUrl: String,
/** URL for privacy policy */
override val privacyPolicyUrl: String,
/** URL for TOS */
override val termsConditionsUrl: String,
/** Application version code */
override val version: Int,
/** Logger implementation */
override val logger: PYDroidLogger? = null,
/** Theme for Composables */
internal val theme: ComposeThemeProvider = NoopThemeProvider,
/** Debug options */
internal val debug: DebugParameters? = null,
) : BaseParameters
/** PYDroid debugging parameters */
public data class DebugParameters(
/** Is general debugging enabled (log messages, testing behaviors) */
internal val enabled: Boolean,
/** Is there an upgrade ready to install? */
internal val upgradeAvailable: Boolean,
/** Should the user be prompted to rate the application? */
internal val ratingAvailable: Boolean,
)
/** Base parameters for PYDroid */
internal interface BaseParameters {
val viewSourceUrl: String
val bugReportUrl: String
val privacyPolicyUrl: String
val termsConditionsUrl: String
val version: Int
val logger: PYDroidLogger?
}
/** Static methods */
public companion object {
/**
* Initialize the library
*
* Track the Instance at the application level, such as:
*
* ```
* Application.kt
*
* private var pydroid: PYDroid? = null
*
* override fun onCreate() {
* this.pydroid = PYDroid.init(
* this,
* PYDroid.Parameters(
* name = getString(R.string.app_name),
* bugReportUrl = getString(R.string.bug_report),
* version = BuildConfig.VERSION_CODE,
* debug = PYDroid.DebugParameters( ... ),
* ),
* )
* }
*
* override fun getSystemService(name: String): Any? {
* return pydroid?.getSystemService(name) ?: super.getSystemService(name)
* }
* ```
*
* Generally speaking, you should treat a PYDroid instance as a Singleton. If you create more
* than one instance and attempt to swap them out at runtime, the behavior of the library and
* its dependent components is completely undefined.
*/
@JvmStatic
@CheckResult
public fun init(
application: Application,
params: Parameters,
): PYDroid {
val instance = PYDroidInitializer.create(application, params)
Logger.d("Initialize new PYDroid instance: $instance")
return PYDroid(instance)
}
}
}
|
apache-2.0
|
952b6669a0d91616ac90538fadcaecaa
| 28.945455 | 97 | 0.67962 | 4.455365 | false | false | false | false |
Turbo87/intellij-rust
|
src/main/kotlin/org/rust/lang/core/resolve/RustResolveEngine.kt
|
1
|
13347
|
package org.rust.lang.core.resolve
import com.intellij.openapi.module.Module
import org.rust.cargo.project.module.util.rootMod
import org.rust.lang.core.names.RustAnonymousId
import org.rust.lang.core.names.RustFileModuleId
import org.rust.lang.core.names.RustQualifiedName
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.impl.RustFileImpl
import org.rust.lang.core.psi.impl.mixin.basePath
import org.rust.lang.core.psi.impl.mixin.letDeclarationsVisibleAt
import org.rust.lang.core.psi.util.*
import org.rust.lang.core.resolve.scope.RustResolveScope
import org.rust.lang.core.resolve.util.RustResolveUtil
import java.util.*
object RustResolveEngine {
open class ResolveResult private constructor(val resolved: RustNamedElement?) : com.intellij.psi.ResolveResult {
override fun getElement(): RustNamedElement? = resolved
override fun isValidResult(): Boolean = resolved != null
/**
* Designates resolve-engine failure to properly resolve item
*/
object Unresolved : ResolveResult(null)
/**
* Designates resolve-engine failure to properly recognise target item
* among the possible candidates
*/
class Ambiguous(val candidates: Collection<RustNamedElement>) : ResolveResult(null)
/**
* Designates resolve-engine successfully resolved given target
*/
class Resolved(resolved: RustNamedElement) : ResolveResult(resolved)
}
/**
* Resolves abstract `qualified-names`
*
* NOTE: Those names are treated as implicitly _fully-qualified_ once
* therefore none of them may contain `super`, `self` references
*/
fun resolve(name: RustQualifiedName, crate: Module): ResolveResult =
crate.rootMod?.let { crateRoot ->
Resolver().resolve(name, crateRoot)
} ?: ResolveResult.Unresolved
/**
* Resolves `qualified-reference` bearing PSI-elements
*
* NOTE: This operate on PSI to extract all the necessary (yet implicit) resolving-context
*/
fun resolve(ref: RustQualifiedReferenceElement): ResolveResult =
Resolver().resolve(ref)
//
// TODO(kudinkin): Unify following?
//
fun resolveModDecl(ref: RustModDeclItem): ResolveResult =
Resolver().resolveModDecl(ref)
fun resolveUseGlob(ref: RustUseGlob): ResolveResult =
Resolver().resolveUseGlob(ref)
}
private class Resolver {
private val seen: MutableSet<RustNamedElement> = HashSet()
/**
* Resolves abstract qualified-names
*
* For more details check out `RustResolveEngine.resolve`
*/
fun resolve(name: RustQualifiedName, root: RustModItem): RustResolveEngine.ResolveResult {
if (name == RustAnonymousId) {
return RustResolveEngine.ResolveResult.Resolved(root)
} else if (name is RustFileModuleId) {
return name.part.path.findModuleIn(root.project)?.let {
RustResolveEngine.ResolveResult.Resolved(it)
} ?: RustResolveEngine.ResolveResult.Unresolved
}
return resolve(name.qualifier!!, root).element?.let {
when (it) {
is RustResolveScope -> resolveIn(sequenceOf(it), by(name))
else -> null
}
} ?: RustResolveEngine.ResolveResult.Unresolved
}
/**
* Resolves `qualified-reference` bearing PSI-elements
*
* For more details check out `RustResolveEngine.resolve`
*/
fun resolve(ref: RustQualifiedReferenceElement): RustResolveEngine.ResolveResult {
val qual = ref.qualifier
if (qual != null) {
val parent = if (qual.isModulePrefix) {
resolveModulePrefix(qual)
} else {
resolve(qual).element
}
return when (parent) {
is RustResolveScope -> resolveIn(sequenceOf(parent), by(ref))
else -> RustResolveEngine.ResolveResult.Unresolved
}
}
return resolveIn(enumerateScopesFor(ref), by(ref))
}
/**
* Looks-up file corresponding to particular module designated by `mod-declaration-item`:
*
* ```
* // foo.rs
* pub mod bar; // looks up `bar.rs` or `bar/mod.rs` in the same dir
*
* pub mod nested {
* pub mod baz; // looks up `nested/baz.rs` or `nested/baz/mod.rs`
* }
*
* ```
*
* | A module without a body is loaded from an external file, by default with the same name as the module,
* | plus the '.rs' extension. When a nested sub-module is loaded from an external file, it is loaded
* | from a subdirectory path that mirrors the module hierarchy.
*
* Reference:
* https://github.com/rust-lang/rust/blob/master/src/doc/reference.md#modules
*/
fun resolveModDecl(ref: RustModDeclItem): RustResolveEngine.ResolveResult {
val parent = ref.containingMod
val name = ref.name
if (parent == null || name == null || !parent.ownsDirectory) {
return RustResolveEngine.ResolveResult.Unresolved
}
val dir = parent.ownedDirectory
// Lookup `name.rs` module
val fileName = "$name.rs"
val fileMod = dir?.findFile(fileName) as? RustFileImpl
// Lookup `name/mod.rs` module
val dirMod = dir?.findSubdirectory(name)?.findFile(RustModules.MOD_RS) as? RustFileImpl
val resolved = listOf(fileMod, dirMod).mapNotNull { it?.mod }
return when (resolved.size) {
0 -> RustResolveEngine.ResolveResult.Unresolved
1 -> RustResolveEngine.ResolveResult.Resolved (resolved.single())
else -> RustResolveEngine.ResolveResult.Ambiguous (resolved)
}
}
/**
* Resolves `use-glob`s, ie:
*
* ```
* use foo::bar::{baz as boo}
* use foo::*
* ```
*/
fun resolveUseGlob(ref: RustUseGlob): RustResolveEngine.ResolveResult {
val basePath = ref.basePath ?: return RustResolveEngine.ResolveResult.Unresolved
//
// This is not necessarily a module, e.g.
//
// ```
// fn foo() {}
//
// mod inner {
// use foo::{self};
// }
// ```
//
val baseItem = resolve(basePath).element
// `use foo::{self}`
if (ref.self != null && baseItem != null) {
return RustResolveEngine.ResolveResult.Resolved(baseItem)
}
// `use foo::{bar}`
val scope = baseItem as? RustResolveScope ?: return RustResolveEngine.ResolveResult.Unresolved
return resolveIn(sequenceOf(scope), by(ref))
}
private fun resolveModulePrefix(ref: RustQualifiedReferenceElement): RustModItem? {
return if (ref.isSelf) {
ref.containingMod
} else {
val qual = ref.qualifier
val mod = if (qual != null) resolveModulePrefix(qual) else ref.containingMod
mod?.`super`
}
}
/**
* Hook to compose non-local resolving-context to resolve (ie module-level) _items_ in a
* context-free manner: it's essentially just scraping the whole scope seeking for the
* given name
*
* @name name to be sought after
*/
private fun by(name: RustQualifiedName) =
ResolveContext.Companion.Trivial(ResolveNonLocalScopesVisitor(name.part.identifier))
/**
* Hook to compose _total_ (ie including both local & non-local) context to resolve
* any items, taking into account what lexical point we're particularly looking that name up from,
* therefore effectively ignoring items being declared 'lexically-after' lookup-point
*/
private fun by(e: RustNamedElement) =
e.name?.let {
ResolveContext.Companion.Trivial(ResolveLocalScopesVisitor(e))
} ?: ResolveContext.Companion.Empty
/**
* Resolve-context wrapper
*/
interface ResolveContext {
fun accept(scope: RustResolveScope): RustNamedElement?
companion object {
class Trivial(val v: ResolveScopeVisitor) : ResolveContext {
override fun accept(scope: RustResolveScope): RustNamedElement? {
scope.accept(v)
return v.matched
}
}
object Empty : ResolveContext {
override fun accept(scope: RustResolveScope): RustNamedElement? = null
}
}
}
private fun resolveIn(scopes: Sequence<RustResolveScope>, ctx: ResolveContext): RustResolveEngine.ResolveResult {
for (s in scopes) {
s.resolveUsing(ctx)?.let {
return RustResolveEngine.ResolveResult.Resolved(it)
}
}
return RustResolveEngine.ResolveResult.Unresolved
}
/**
* Abstract resolving-scope-visitor
*/
abstract inner class ResolveScopeVisitor : RustVisitor() {
/**
* Matched resolve-target
*/
abstract var matched: RustNamedElement?
}
/**
* This particular visitor visits _non-local_ scopes only (!)
*/
open inner class ResolveNonLocalScopesVisitor(protected val name: String) : ResolveScopeVisitor() {
override var matched: RustNamedElement? = null
override fun visitModItem(o: RustModItem) {
seek(o.itemList)
}
private fun addToSeen(element: RustNamedElement): Boolean {
val result = element in seen
seen += element
return result
}
protected fun seek(elem: RustDeclaringElement) = seek(listOf(elem))
protected fun seek(decls: Collection<RustDeclaringElement>) {
decls.flatMap { it.boundElements }
.find { match(it) }
?.let { found(it) }
}
protected fun found(elem: RustNamedElement) {
matched =
when (elem) {
// mod-decl-items constitute a (sub-) _tree_
// inside the crate's module-tree, therefore
// there is no need to mark them as seen
is RustModDeclItem ->
elem.reference?.let { it.resolve() }
// Check whether resolved element (being path-part, use-glob, or alias)
// could be further resolved
is RustPathPart ->
if (!addToSeen(elem)) resolve(elem).element
else null
is RustUseGlob ->
if (!addToSeen(elem)) resolveUseGlob(elem).element
else null
is RustAlias -> {
val parent = elem.parent
when (parent) {
is RustViewPath ->
parent.pathPart?.let {
if (!addToSeen(it)) resolve(it).element
else null
}
is RustUseGlob ->
if (!addToSeen(parent)) resolveUseGlob(parent).element
else null
else -> elem
}
}
else -> elem
}
}
protected fun match(elem: RustNamedElement): Boolean =
elem.nameElement?.textMatches(name) ?: false
}
/**
* This particular visitor traverses both local & non-local scopes
*/
inner class ResolveLocalScopesVisitor(ref: RustNamedElement) : ResolveNonLocalScopesVisitor(ref.name!!) {
private val context: RustCompositeElement = ref
override fun visitForExpr (o: RustForExpr) = seek(o.scopedForDecl)
override fun visitScopedLetExpr (o: RustScopedLetExpr) = visitResolveScope(o)
override fun visitLambdaExpr (o: RustLambdaExpr) = visitResolveScope(o)
override fun visitMethod (o: RustMethod) = visitResolveScope(o)
override fun visitFnItem (o: RustFnItem) = visitResolveScope(o)
override fun visitResolveScope (scope: RustResolveScope) = seek(scope.declarations)
override fun visitBlock(o: RustBlock) {
o.letDeclarationsVisibleAt(context)
.flatMap { it.boundElements.asSequence() }
.filter { match(it) }
.firstOrNull()
?.let { found(it) }
}
}
}
fun enumerateScopesFor(ref: RustQualifiedReferenceElement): Sequence<RustResolveScope> {
if (ref.isFullyQualified) {
return listOfNotNull(RustResolveUtil.getCrateRootModFor(ref)).asSequence()
}
return sequence(RustResolveUtil.getResolveScopeFor(ref)) { parent ->
when (parent) {
is RustModItem -> null
else -> RustResolveUtil.getResolveScopeFor(parent)
}
}
}
private fun RustResolveScope.resolveUsing(c: Resolver.ResolveContext): RustNamedElement? = c.accept(this)
|
mit
|
b34a2564bc2264643e390a74ede2e543
| 33.667532 | 117 | 0.586349 | 4.741385 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/management/InsightsManagementViewModel.kt
|
1
|
4938
|
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.management
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.store.StatsStore
import org.wordpress.android.fluxc.store.StatsStore.InsightType
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.INSIGHTS_USE_CASE
import org.wordpress.android.ui.stats.refresh.lists.BaseListUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.insights.management.InsightsManagementViewModel.InsightListItem.Type.HEADER
import org.wordpress.android.ui.stats.refresh.lists.sections.insights.management.InsightsManagementViewModel.InsightListItem.Type.INSIGHT
import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider
import org.wordpress.android.ui.stats.refresh.utils.trackWithType
import org.wordpress.android.ui.stats.refresh.utils.trackWithTypes
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.ScopedViewModel
import org.wordpress.android.viewmodel.SingleLiveEvent
import javax.inject.Inject
import javax.inject.Named
class InsightsManagementViewModel @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val defaultDispatcher: CoroutineDispatcher,
@Named(INSIGHTS_USE_CASE) val insightsUseCase: BaseListUseCase,
private val siteProvider: StatsSiteProvider,
private val statsStore: StatsStore,
private val insightsManagementMapper: InsightsManagementMapper,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) : ScopedViewModel(mainDispatcher) {
private val _addedInsights = MutableLiveData<List<InsightListItem>>()
val addedInsights: LiveData<List<InsightListItem>> = _addedInsights
private val _closeInsightsManagement = SingleLiveEvent<Unit>()
val closeInsightsManagement: LiveData<Unit> = _closeInsightsManagement
private val _isMenuVisible = MutableLiveData<Boolean>()
val isMenuVisible: LiveData<Boolean> = _isMenuVisible
private val addedInsightTypes: MutableSet<InsightType> = mutableSetOf()
private var isInitialized = false
fun start(localSiteId: Int?) {
if (!isInitialized) {
isInitialized = true
_isMenuVisible.value = false
localSiteId?.let {
siteProvider.start(localSiteId)
}
loadInsights()
}
}
private fun loadInsights() {
launch {
addedInsightTypes.clear()
addedInsightTypes.addAll(statsStore.getAddedInsights(siteProvider.siteModel))
displayInsights()
}
}
private fun displayInsights() {
launch {
_addedInsights.value = insightsManagementMapper.buildUIModel(
addedInsightTypes,
this@InsightsManagementViewModel::onItemButtonClicked
)
}
}
fun onSaveInsights() {
analyticsTrackerWrapper.trackWithTypes(Stat.STATS_INSIGHTS_MANAGEMENT_SAVED, addedInsightTypes)
insightsUseCase.launch(defaultDispatcher) {
statsStore.updateTypes(siteProvider.siteModel, addedInsightTypes.toList())
insightsUseCase.loadData()
}
_closeInsightsManagement.call()
}
private fun onItemButtonClicked(insight: InsightType) {
if (addedInsightTypes.contains(insight)) {
analyticsTrackerWrapper.trackWithType(
Stat.STATS_INSIGHTS_MANAGEMENT_TYPE_REMOVED,
insight
)
addedInsightTypes.removeAll { it == insight }
} else {
analyticsTrackerWrapper.trackWithType(
Stat.STATS_INSIGHTS_MANAGEMENT_TYPE_ADDED,
insight
)
addedInsightTypes.add(insight)
}
displayInsights()
_isMenuVisible.value = true
}
fun onBackPressed() {
analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_MANAGEMENT_DISMISSED)
_closeInsightsManagement.call()
}
sealed class InsightListItem(val type: Type) {
enum class Type {
HEADER, INSIGHT
}
data class Header(@StringRes val text: Int) : InsightListItem(HEADER)
data class InsightModel(
val insightType: InsightType,
val name: Int?,
val status: Status,
val onClick: ListItemInteraction
) : InsightListItem(INSIGHT) {
enum class Status {
ADDED,
REMOVED
}
}
}
}
|
gpl-2.0
|
765bb6617a398b14f4f75b117fba7bf3
| 37.578125 | 137 | 0.707169 | 4.812865 | false | false | false | false |
DiUS/pact-jvm
|
core/model/src/main/kotlin/au/com/dius/pact/core/model/HttpPart.kt
|
1
|
2901
|
package au.com.dius.pact.core.model
import au.com.dius.pact.core.model.generators.Generators
import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.support.isNotEmpty
import au.com.dius.pact.core.support.json.JsonValue
import mu.KLogging
import java.nio.charset.Charset
import java.util.Base64
/**
* Base trait for an object that represents part of an http message
*/
abstract class HttpPart {
abstract var body: OptionalBody
abstract var headers: MutableMap<String, List<String>>
abstract var matchingRules: MatchingRules
abstract var generators: Generators
@Deprecated("use method that returns a content type object",
replaceWith = ReplaceWith("determineContentType"))
fun contentType(): String? = contentTypeHeader()?.split(Regex("\\s*;\\s*"))?.first()
?: body.contentType.asString()
fun determineContentType(): ContentType {
val headerValue = contentTypeHeader()?.split(Regex("\\s*;\\s*"))?.first()
return if (headerValue.isNullOrEmpty())
body.contentType
else
ContentType(headerValue)
}
fun contentTypeHeader(): String? {
val contentTypeKey = headers.keys.find { CONTENT_TYPE.equals(it, ignoreCase = true) }
return headers[contentTypeKey]?.first()
}
fun jsonBody() = determineContentType().isJson()
fun xmlBody() = determineContentType().isXml()
fun setDefaultContentType(contentType: String) {
if (headers.keys.find { it.equals(CONTENT_TYPE, ignoreCase = true) } == null) {
headers[CONTENT_TYPE] = listOf(contentType)
}
}
fun charset(): Charset? {
return when {
body.isPresent() -> body.contentType.asCharset()
else -> {
val contentType = contentTypeHeader()
if (contentType.isNotEmpty()) {
ContentType(contentType!!).asCharset()
} else {
null
}
}
}
}
companion object : KLogging() {
private const val CONTENT_TYPE = "Content-Type"
@JvmStatic
fun extractBody(json: JsonValue.Object, contentType: ContentType): OptionalBody {
return when (val b = json["body"]) {
is JsonValue.Null -> OptionalBody.nullBody()
is JsonValue.StringValue -> decodeBody(b.asString(), contentType)
else -> decodeBody(b.serialise(), contentType)
}
}
private fun decodeBody(body: String, contentType: ContentType): OptionalBody {
return when {
contentType.isBinaryType() || contentType.isMultipart() -> try {
OptionalBody.body(Base64.getDecoder().decode(body), contentType)
} catch (ex: IllegalArgumentException) {
logger.warn(ex) { "Expected body for content type $contentType to be base64 encoded" }
OptionalBody.body(body.toByteArray(contentType.asCharset()), contentType)
}
else -> OptionalBody.body(body.toByteArray(contentType.asCharset()), contentType)
}
}
}
}
|
apache-2.0
|
26e24c6acacd77fc376a439457b9ff54
| 32.344828 | 96 | 0.681834 | 4.368976 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/AbstractRangeInspection.kt
|
1
|
2311
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.hints.RangeKtExpressionType
import org.jetbrains.kotlin.idea.codeInsight.hints.getRangeBinaryExpressionType
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class AbstractRangeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitBinaryExpression(binaryExpression: KtBinaryExpression) {
visitRange(binaryExpression, holder)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
visitRange(expression, holder)
}
}
private fun visitRange(expression: KtExpression, holder: ProblemsHolder) {
val context = lazy { expression.analyze(BodyResolveMode.PARTIAL) }
visitRange(expression, context, expression.getRangeBinaryExpressionType(context) ?: return, holder)
}
abstract fun visitRange(range: KtExpression, context: Lazy<BindingContext>, type: RangeKtExpressionType, holder: ProblemsHolder)
companion object {
fun KtExpression.constantValueOrNull(context: BindingContext? = null): ConstantValue<Any?>? {
val c = context ?: this.analyze(BodyResolveMode.PARTIAL)
val constant = ConstantExpressionEvaluator.getConstant(this, c) ?: return null
return constant.toConstantValue(getType(c) ?: return null)
}
}
}
|
apache-2.0
|
0ffb827ec7986c6388898c1dd5bbe3e8
| 48.170213 | 158 | 0.782778 | 4.969892 | false | false | false | false |
hermantai/samples
|
android/jetpack/ColorChanger/app/src/main/java/com/gmail/htaihm/colorchanger/MainActivity.kt
|
1
|
2142
|
package com.gmail.htaihm.colorchanger
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import java.util.*
/**
* Demo viewmodel, live data.
*/
class MainActivity : AppCompatActivity() {
private lateinit var colorChangerViewModel: ColorChangerViewModel
private var fruitIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mainActivityRootView = findViewById<View>(R.id.root_view)
val changeColorButton = findViewById<Button>(R.id.change_color_button)
val display = findViewById<TextView>(R.id.display_text)
val refreshFruits = findViewById<Button>(R.id.refresh_fruits_button)
colorChangerViewModel = ViewModelProviders.of(this).get(ColorChangerViewModel::class.java)
mainActivityRootView.setBackgroundColor(colorChangerViewModel.getColorResource())
changeColorButton.setOnClickListener {
val color = generateRandomColor()
mainActivityRootView.setBackgroundColor(color)
colorChangerViewModel.setColorResource(color)
}
val userViewModel = ViewModelProviders.of(this).get(UserProfileViewModel::class.java)
userViewModel.user.name = "hello"
val model = ViewModelProviders.of(this).get(FruitViewModel::class.java)
model.getFruitList().observe(this, Observer<List<String>>{ fruitlist ->
Log.i("MainActivity", "Got list of fruits {$fruitlist}")
display.setText(fruitlist!!.get(fruitIndex))
fruitIndex = (fruitIndex + 1) % fruitlist.size
})
refreshFruits.setOnClickListener {
model.loadFruits()
}
}
private fun generateRandomColor(): Int {
val rnd = Random()
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
}
}
|
apache-2.0
|
c09f78dc1bafe5512fb4aa847aea81de
| 35.931034 | 98 | 0.712418 | 4.518987 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/opal/OpalSubscription.kt
|
1
|
2135
|
/*
* OpalSubscription.kt
*
* Copyright 2015-2018 Michael Farrell <[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 au.id.micolous.metrodroid.transit.opal
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Subscription
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.Daystamp
import au.id.micolous.metrodroid.time.Month
/**
* Class describing auto-topup on Opal.
*
*
* Opal has no concept of subscriptions, but when auto-topup is enabled, you no longer need to
* manually refill the card with credit.
*
*
* Dates given are not valid.
*/
@Suppress("PLUGIN_WARNING")
@Parcelize
internal class OpalSubscription private constructor() : Subscription() {
// Start of Opal trial
override val validFrom: Timestamp?
get() = Daystamp(2012, Month.DECEMBER, 7)
// Maximum possible date representable on the card
override val validTo: Timestamp?
get() = Daystamp(2159, Month.JUNE, 6)
override val subscriptionName: String?
get() = Localizer.localizeString(R.string.opal_automatic_top_up)
override val paymentMethod: Subscription.PaymentMethod
get() = Subscription.PaymentMethod.CREDIT_CARD
override fun getAgencyName(isShort: Boolean) = Localizer.localizeFormatted(R.string.opal_agency_tfnsw)
companion object {
val instance = OpalSubscription()
}
}
|
gpl-3.0
|
2d3cf6876389bd2ca0c213c07ffc8257
| 33.435484 | 106 | 0.743326 | 4.058935 | false | false | false | false |
hermantai/samples
|
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/data/BaseballConverters.kt
|
3
|
2369
|
package dev.mfazio.abl.data
import androidx.room.TypeConverter
import dev.mfazio.abl.players.Hand
import dev.mfazio.abl.players.Position
import dev.mfazio.abl.scoreboard.OccupiedBases
import dev.mfazio.abl.scoreboard.ScheduledGameStatus
import dev.mfazio.abl.standings.WinLoss
import dev.mfazio.abl.teams.Division
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class BaseballConverters {
private val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
@TypeConverter
fun fromDivision(division: Division?) =
division?.ordinal ?: Division.Unknown.ordinal
@TypeConverter
fun toDivision(divisionOrdinal: Int?) =
if (divisionOrdinal != null) {
Division.values()[divisionOrdinal]
} else {
Division.Unknown
}
@TypeConverter
fun fromWinLoss(winLoss: WinLoss?) =
winLoss?.ordinal ?: WinLoss.Unknown.ordinal
@TypeConverter
fun toWinLoss(winLossOrdinal: Int?) =
if (winLossOrdinal != null) {
WinLoss.values()[winLossOrdinal]
} else {
WinLoss.Unknown
}
@TypeConverter
fun toLocalDateTime(value: String?) = value?.let {
formatter.parse(it, LocalDateTime::from)
}
@TypeConverter
fun fromLocalDateTime(date: LocalDateTime?) = date?.format(formatter)
@TypeConverter
fun fromScheduledGameStatus(status: ScheduledGameStatus) = status.ordinal
@TypeConverter
fun toScheduledGameStatus(statusOrdinal: Int) = ScheduledGameStatus.values()[statusOrdinal]
@TypeConverter
fun fromOccupiedBases(bases: OccupiedBases?) = bases?.toStringList()
@TypeConverter
fun toOccupiedBases(basesStringList: String?) = OccupiedBases.fromStringList(basesStringList)
@TypeConverter
fun fromHand(hand: Hand?) =
hand?.ordinal ?: Hand.Right.ordinal
@TypeConverter
fun toHand(handOrdinal: Int?) =
if (handOrdinal != null) {
Hand.values()[handOrdinal]
} else {
Hand.Right
}
@TypeConverter
fun fromPosition(position: Position?) =
position?.ordinal ?: Position.Unknown.ordinal
@TypeConverter
fun toPosition(positionOrdinal: Int?) =
if (positionOrdinal != null) {
Position.values()[positionOrdinal]
} else {
Position.Unknown
}
}
|
apache-2.0
|
75b01871f0da21e246c2030102c91b5d
| 27.554217 | 97 | 0.678345 | 4.547025 | false | false | false | false |
GunoH/intellij-community
|
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMLSearchSession.kt
|
2
|
6564
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.*
import com.intellij.ide.actions.searcheverywhere.ml.features.FeaturesProviderCacheDataProvider
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereContextFeaturesProvider
import com.intellij.ide.actions.searcheverywhere.ml.features.statistician.SearchEverywhereContributorStatistician
import com.intellij.ide.actions.searcheverywhere.ml.features.statistician.SearchEverywhereStatisticianService
import com.intellij.ide.actions.searcheverywhere.ml.id.SearchEverywhereMlItemIdProvider
import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereModelProvider
import com.intellij.ide.actions.searcheverywhere.ml.performance.PerformanceTracker
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.NonUrgentExecutor
import java.util.concurrent.atomic.AtomicReference
internal class SearchEverywhereMLSearchSession(project: Project?,
val mixedListInfo: SearchEverywhereMixedListInfo,
private val sessionId: Int,
private val loggingRandomisation: FeaturesLoggingRandomisation) {
val itemIdProvider = SearchEverywhereMlItemIdProvider()
private val sessionStartTime: Long = System.currentTimeMillis()
private val providersCache = FeaturesProviderCacheDataProvider().getDataToCache(project)
private val modelProviderWithCache: SearchEverywhereModelProvider = SearchEverywhereModelProvider()
// context features are calculated once per Search Everywhere session
val cachedContextInfo: SearchEverywhereMLContextInfo = SearchEverywhereMLContextInfo(project)
// search state is updated on each typing, tab or setting change
// element features & ML score are also re-calculated on each typing because some of them might change, e.g. matching degree
private val currentSearchState: AtomicReference<SearchEverywhereMlSearchState?> = AtomicReference<SearchEverywhereMlSearchState?>()
private val logger: SearchEverywhereMLStatisticsCollector = SearchEverywhereMLStatisticsCollector()
private val performanceTracker = PerformanceTracker()
fun onSearchRestart(project: Project?,
experimentStrategy: SearchEverywhereMlExperiment,
reason: SearchRestartReason,
tabId: String,
orderByMl: Boolean,
keysTyped: Int,
backspacesTyped: Int,
searchQuery: String,
previousElementsProvider: () -> List<SearchEverywhereFoundElementInfoWithMl>) {
val prevTimeToResult = performanceTracker.timeElapsed
val prevState = currentSearchState.getAndUpdate { prevState ->
val startTime = System.currentTimeMillis()
val searchReason = if (prevState == null) SearchRestartReason.SEARCH_STARTED else reason
val nextSearchIndex = (prevState?.searchIndex ?: 0) + 1
val experimentGroup = experimentStrategy.experimentGroup
performanceTracker.start()
SearchEverywhereMlSearchState(
sessionStartTime, startTime, nextSearchIndex, searchReason,
tabId, experimentGroup, orderByMl,
keysTyped, backspacesTyped, searchQuery, modelProviderWithCache, providersCache
)
}
if (prevState != null && experimentStrategy.isLoggingEnabledForTab(prevState.tabId)) {
val shouldLogFeatures = loggingRandomisation.shouldLogFeatures(prevState.tabId)
logger.onSearchRestarted(
project, sessionId, prevState.searchIndex,
shouldLogFeatures, itemIdProvider, cachedContextInfo,
prevState, prevTimeToResult, mixedListInfo, previousElementsProvider
)
}
}
fun onItemSelected(project: Project?, experimentStrategy: SearchEverywhereMlExperiment,
indexes: IntArray, selectedItems: List<Any>, closePopup: Boolean,
elementsProvider: () -> List<SearchEverywhereFoundElementInfoWithMl>) {
val state = getCurrentSearchState()
if (state != null && experimentStrategy.isLoggingEnabledForTab(state.tabId)) {
if (project != null) {
val statisticianService = service<SearchEverywhereStatisticianService>()
selectedItems.forEach { statisticianService.increaseUseCount(it) }
if (state.tabId == SearchEverywhereManagerImpl.ALL_CONTRIBUTORS_GROUP_ID) {
elementsProvider.invoke()
.slice(indexes.asIterable())
.forEach { SearchEverywhereContributorStatistician.increaseUseCount(it.contributor.searchProviderId) }
}
}
val shouldLogFeatures = loggingRandomisation.shouldLogFeatures(state.tabId)
logger.onItemSelected(
project, sessionId, state.searchIndex,
shouldLogFeatures, state.experimentGroup,
state.orderByMl, itemIdProvider, cachedContextInfo,
state, indexes, selectedItems,
closePopup, performanceTracker.timeElapsed, mixedListInfo, elementsProvider
)
}
}
fun onSearchFinished(project: Project?,
experimentStrategy: SearchEverywhereMlExperiment,
elementsProvider: () -> List<SearchEverywhereFoundElementInfoWithMl>) {
val state = getCurrentSearchState()
if (state != null && experimentStrategy.isLoggingEnabledForTab(state.tabId)) {
val shouldLogFeatures = loggingRandomisation.shouldLogFeatures(state.tabId)
logger.onSearchFinished(
project, sessionId, state.searchIndex,
shouldLogFeatures, state.experimentGroup,
state.orderByMl, itemIdProvider, cachedContextInfo,
state, performanceTracker.timeElapsed, mixedListInfo, elementsProvider
)
}
}
fun notifySearchResultsUpdated() {
performanceTracker.stop()
}
fun getCurrentSearchState() = currentSearchState.get()
}
internal class SearchEverywhereMLContextInfo(project: Project?) {
val features: List<EventPair<*>> by lazy {
SearchEverywhereContextFeaturesProvider().getContextFeatures(project)
}
init {
NonUrgentExecutor.getInstance().execute {
features // We don't care about the value, we just want the features to be computed
}
}
}
|
apache-2.0
|
b2c56742d2eb7f2c05d0305fd4034247
| 49.114504 | 158 | 0.738422 | 5.520606 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/inferParameterInfo.kt
|
4
|
17644
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.builtins.createFunctionType
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.pseudocode.SingleType
import org.jetbrains.kotlin.cfg.pseudocode.getElementValuesRecursively
import org.jetbrains.kotlin.cfg.pseudocode.getExpectedTypePredicate
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.InstructionWithReceivers
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.psi.psiUtil.isInsideOf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.hasBothReceivers
import org.jetbrains.kotlin.resolve.calls.tasks.isSynthesizedInvoke
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
import org.jetbrains.kotlin.types.CommonSupertypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
internal class ParametersInfo {
var errorMessage: AnalysisResult.ErrorMessage? = null
val originalRefToParameter = MultiMap.create<KtSimpleNameExpression, MutableParameter>()
val parameters = LinkedHashSet<MutableParameter>()
val typeParameters = HashSet<TypeParameter>()
val nonDenotableTypes = HashSet<KotlinType>()
val replacementMap = MultiMap.create<KtSimpleNameExpression, Replacement>()
}
internal fun ExtractionData.inferParametersInfo(
virtualBlock: KtBlockExpression,
commonParent: PsiElement,
pseudocode: Pseudocode,
bindingContext: BindingContext,
targetScope: LexicalScope,
modifiedVarDescriptors: Set<VariableDescriptor>
): ParametersInfo {
val info = ParametersInfo()
val extractedDescriptorToParameter = LinkedHashMap<DeclarationDescriptor, MutableParameter>()
for (refInfo in getBrokenReferencesInfo(virtualBlock)) {
val ref = refInfo.refExpr
val selector = (ref.parent as? KtCallExpression) ?: ref
val superExpr = (selector.parent as? KtQualifiedExpression)?.receiverExpression as? KtSuperExpression
if (superExpr != null) {
info.errorMessage = AnalysisResult.ErrorMessage.SUPER_CALL
return info
}
val resolvedCall = refInfo.resolveResult.resolvedCall
val extensionReceiver = resolvedCall?.extensionReceiver
val receiverToExtract = (if (extensionReceiver == null || isSynthesizedInvoke(refInfo.resolveResult.descriptor)) {
resolvedCall?.dispatchReceiver
} else {
extensionReceiver
})
val twoReceivers = resolvedCall != null && resolvedCall.hasBothReceivers()
val dispatchReceiverDescriptor = (resolvedCall?.dispatchReceiver as? ImplicitReceiver)?.declarationDescriptor
if (options.canWrapInWith
&& twoReceivers
&& resolvedCall!!.extensionReceiver is ExpressionReceiver
&& DescriptorUtils.isObject(dispatchReceiverDescriptor)
) {
info.replacementMap.putValue(
refInfo.resolveResult.originalRefExpr,
WrapObjectInWithReplacement(dispatchReceiverDescriptor as ClassDescriptor)
)
continue
}
if (!refInfo.shouldSkipPrimaryReceiver) {
extractReceiver(
receiverToExtract,
info,
targetScope,
refInfo,
extractedDescriptorToParameter,
pseudocode,
bindingContext,
false
)
}
if (options.canWrapInWith && twoReceivers) {
extractReceiver(
resolvedCall!!.dispatchReceiver,
info,
targetScope,
refInfo,
extractedDescriptorToParameter,
pseudocode,
bindingContext,
true
)
}
}
val varNameValidator = Fe10KotlinNewDeclarationNameValidator(
commonParent.getNonStrictParentOfType<KtExpression>()!!,
physicalElements.firstOrNull(),
KotlinNameSuggestionProvider.ValidatorTarget.PARAMETER
)
val existingParameterNames = hashSetOf<String>()
for ((descriptorToExtract, parameter) in extractedDescriptorToParameter) {
if (!parameter
.parameterType
.processTypeIfExtractable(info.typeParameters, info.nonDenotableTypes, options, targetScope)
) continue
with(parameter) {
if (currentName == null) {
currentName = Fe10KotlinNameSuggester.suggestNamesByType(parameterType, varNameValidator, "p").first()
}
require(currentName != null)
if ("$currentName" in existingParameterNames) {
var index = 0
while ("$currentName$index" in existingParameterNames) {
index++
}
currentName = "$currentName$index"
}
mirrorVarName = if (descriptorToExtract in modifiedVarDescriptors) Fe10KotlinNameSuggester.suggestNameByName(
name,
varNameValidator
) else null
info.parameters.add(this)
currentName?.let { existingParameterNames += it }
}
}
for (typeToCheck in info.typeParameters.flatMapTo(HashSet()) { it.collectReferencedTypes(bindingContext) }) {
typeToCheck.processTypeIfExtractable(info.typeParameters, info.nonDenotableTypes, options, targetScope)
}
return info
}
private fun ExtractionData.extractReceiver(
receiverToExtract: ReceiverValue?,
info: ParametersInfo,
targetScope: LexicalScope,
refInfo: ResolvedReferenceInfo,
extractedDescriptorToParameter: HashMap<DeclarationDescriptor, MutableParameter>,
pseudocode: Pseudocode,
bindingContext: BindingContext,
isMemberExtension: Boolean
) {
val (originalRef, originalDeclaration, originalDescriptor, resolvedCall) = refInfo.resolveResult
val thisDescriptor = (receiverToExtract as? ImplicitReceiver)?.declarationDescriptor
val hasThisReceiver = thisDescriptor != null
val thisExpr = refInfo.refExpr.parent as? KtThisExpression
if (hasThisReceiver
&& DescriptorToSourceUtilsIde.getAllDeclarations(project, thisDescriptor!!).all { it.isInsideOf(physicalElements) }
) {
return
}
val referencedClassifierDescriptor: ClassifierDescriptor? = (thisDescriptor ?: originalDescriptor).let {
when (it) {
is ClassDescriptor ->
when (it.kind) {
ClassKind.OBJECT, ClassKind.ENUM_CLASS -> it
ClassKind.ENUM_ENTRY -> it.containingDeclaration as? ClassDescriptor
else -> if (refInfo.refExpr.getNonStrictParentOfType<KtTypeReference>() != null) it else null
}
is TypeParameterDescriptor -> it
is ConstructorDescriptor -> it.containingDeclaration
else -> null
}
}
if (referencedClassifierDescriptor != null) {
if (!referencedClassifierDescriptor.defaultType.processTypeIfExtractable(
info.typeParameters, info.nonDenotableTypes, options, targetScope, referencedClassifierDescriptor is TypeParameterDescriptor
)
) return
if (options.canWrapInWith
&& resolvedCall != null
&& resolvedCall.hasBothReceivers()
&& DescriptorUtils.isObject(referencedClassifierDescriptor)
) {
info.replacementMap.putValue(originalRef, WrapObjectInWithReplacement(referencedClassifierDescriptor as ClassDescriptor))
} else if (referencedClassifierDescriptor is ClassDescriptor) {
info.replacementMap.putValue(originalRef, FqNameReplacement(originalDescriptor.getImportableDescriptor().fqNameSafe))
}
} else {
val extractThis = (hasThisReceiver && refInfo.smartCast == null) || thisExpr != null
val extractOrdinaryParameter =
originalDeclaration is KtDestructuringDeclarationEntry ||
originalDeclaration is KtProperty ||
originalDeclaration is KtParameter
val extractFunctionRef =
options.captureLocalFunctions
&& originalRef.getReferencedName() == originalDescriptor.name.asString() // to forbid calls by convention
&& originalDeclaration is KtNamedFunction && originalDeclaration.isLocal
&& targetScope.findFunction(originalDescriptor.name, NoLookupLocation.FROM_IDE) { it == originalDescriptor } == null
val descriptorToExtract = (if (extractThis) thisDescriptor else null) ?: originalDescriptor
val extractParameter = extractThis || extractOrdinaryParameter || extractFunctionRef
if (extractParameter) {
val parameterExpression = when {
receiverToExtract is ExpressionReceiver -> {
val receiverExpression = receiverToExtract.expression
// If p.q has a smart-cast, then extract entire qualified expression
if (refInfo.smartCast != null) receiverExpression.parent as KtExpression else receiverExpression
}
receiverToExtract != null && refInfo.smartCast == null -> null
else -> (originalRef.parent as? KtThisExpression) ?: originalRef
}
val parameterType = suggestParameterType(
extractFunctionRef,
originalDescriptor,
parameterExpression,
receiverToExtract,
resolvedCall,
true,
bindingContext
)
val parameter = extractedDescriptorToParameter.getOrPut(descriptorToExtract) {
var argumentText =
if (hasThisReceiver && extractThis) {
val label = if (descriptorToExtract is ClassDescriptor) "@${descriptorToExtract.name.asString()}" else ""
"this$label"
} else {
val argumentExpr = (thisExpr ?: refInfo.refExpr).getQualifiedExpressionForSelectorOrThis()
if (argumentExpr is KtOperationReferenceExpression) {
val nameElement = argumentExpr.getReferencedNameElement()
val nameElementType = nameElement.node.elementType
(nameElementType as? KtToken)?.let {
OperatorConventions.getNameForOperationSymbol(it)?.asString()
} ?: nameElement.text
} else argumentExpr.text
?: throw AssertionError("reference shouldn't be empty: code fragment = $codeFragmentText")
}
if (extractFunctionRef) {
val receiverTypeText = (originalDeclaration as KtCallableDeclaration).receiverTypeReference?.text ?: ""
argumentText = "$receiverTypeText::$argumentText"
}
val originalType = suggestParameterType(
extractFunctionRef,
originalDescriptor,
parameterExpression,
receiverToExtract,
resolvedCall,
false,
bindingContext
)
MutableParameter(argumentText, descriptorToExtract, extractThis, targetScope, originalType, refInfo.possibleTypes)
}
if (!extractThis) {
parameter.currentName = when (originalDeclaration) {
is PsiNameIdentifierOwner -> originalDeclaration.nameIdentifier?.text
else -> null
}
}
parameter.refCount++
info.originalRefToParameter.putValue(originalRef, parameter)
parameter.addDefaultType(parameterType)
if (extractThis && thisExpr == null) {
val callElement = resolvedCall!!.call.callElement
val instruction = pseudocode.getElementValue(callElement)?.createdAt as? InstructionWithReceivers
val receiverValue = instruction?.receiverValues?.entries?.singleOrNull { it.value == receiverToExtract }?.key
if (receiverValue != null) {
parameter.addTypePredicate(
getExpectedTypePredicate(
receiverValue,
bindingContext,
targetScope.ownerDescriptor.builtIns
)
)
}
} else if (extractFunctionRef) {
parameter.addTypePredicate(SingleType(parameterType))
} else {
pseudocode.getElementValuesRecursively(originalRef).forEach {
parameter.addTypePredicate(getExpectedTypePredicate(it, bindingContext, targetScope.ownerDescriptor.builtIns))
}
}
val replacement = when {
isMemberExtension -> WrapParameterInWithReplacement(parameter)
hasThisReceiver && extractThis -> AddPrefixReplacement(parameter)
else -> RenameReplacement(parameter)
}
info.replacementMap.putValue(originalRef, replacement)
}
}
}
private fun suggestParameterType(
extractFunctionRef: Boolean,
originalDescriptor: DeclarationDescriptor,
parameterExpression: KtExpression?,
receiverToExtract: ReceiverValue?,
resolvedCall: ResolvedCall<*>?,
useSmartCastsIfPossible: Boolean, bindingContext: BindingContext
): KotlinType {
val builtIns = originalDescriptor.builtIns
return when {
extractFunctionRef -> {
originalDescriptor as FunctionDescriptor
createFunctionType(
builtIns,
Annotations.EMPTY,
originalDescriptor.extensionReceiverParameter?.type,
originalDescriptor.contextReceiverParameters.map { it.type },
originalDescriptor.valueParameters.map { it.type },
originalDescriptor.valueParameters.map { it.name },
originalDescriptor.returnType ?: builtIns.defaultReturnType
)
}
parameterExpression != null ->
(if (useSmartCastsIfPossible) bindingContext[BindingContext.SMARTCAST, parameterExpression]?.defaultType else null)
?: bindingContext.getType(parameterExpression)
?: (parameterExpression as? KtReferenceExpression)?.let {
(bindingContext[BindingContext.REFERENCE_TARGET, it] as? CallableDescriptor)?.returnType
}
?: receiverToExtract?.type
receiverToExtract is ImplicitReceiver -> {
val typeByDataFlowInfo = if (useSmartCastsIfPossible) {
val callElement = resolvedCall!!.call.callElement
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(callElement)
val dataFlowValueFactory = callElement.getResolutionFacade().dataFlowValueFactory
val possibleTypes = dataFlowInfo.getCollectedTypes(
dataFlowValueFactory.createDataFlowValueForStableReceiver(receiverToExtract),
callElement.languageVersionSettings
)
if (possibleTypes.isNotEmpty()) CommonSupertypes.commonSupertype(possibleTypes) else null
} else null
typeByDataFlowInfo ?: receiverToExtract.type
}
else -> receiverToExtract?.type
} ?: builtIns.defaultParameterType
}
|
apache-2.0
|
84688a51f2285248c300613d1d1289bc
| 44.591731 | 158 | 0.663682 | 6.107304 | false | false | false | false |
moshbit/Kotlift
|
test-src/16_listExtensions.kt
|
2
|
1236
|
import java.util.*
fun Float.timesTen(): Float {
return this * 10
}
fun List<Float>.avg(): Float {
if (this.size == 0) {
return 0f
}
var sum = 0.0f
for (item in this) {
// SWIFT: sum += item as! Double
sum += item
}
return sum / this.size
}
class Person(val name: String, val age: Int) {
}
fun List<Person>.countAdults(): Int {
var adultCounter = 0
for (person in this) {
if (person.age >= 18) {
adultCounter++
}
}
return adultCounter
}
fun main(args: Array<String>) {
val list = ArrayList<Float>()
list.add(1.5f.timesTen())
list.add(1f.timesTen())
list.add(11.858502f)
list.add(3.1415f)
val avg1 = list.avg()
println("avg1 = $avg1 (should be 10.0)")
val list2 = LinkedList<Float>()
list2.add(15.0f)
list2.add(5.0f)
println("avg2 = ${list2.avg()} (should be 10.0)")
val people = ArrayList<Person>()
people.add(Person(name = "Steve", age = 14))
people.add(Person(name = "Bob", age = 16))
people.add(Person(name = "John", age = 18))
people.add(Person(name = "Lena", age = 20))
people.add(Person(name = "Denise", age = 22))
people.add(Person(name = "Alex", age = 24))
println("${people.countAdults()} people may enter the club (should be 4)")
}
|
apache-2.0
|
2d5e8341d656c14e72702dd80ed6d4e1
| 21.472727 | 76 | 0.61246 | 2.874419 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseHeaders.kt
|
1
|
2232
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.response
import io.ktor.http.*
/**
* Server's response headers.
* @see [ApplicationResponse.headers]
*/
public abstract class ResponseHeaders {
/**
* A set of headers that is managed by an engine and should not be modified manually.
*/
protected open val managedByEngineHeaders: Set<String> = emptySet()
/**
* Checks whether a [name] response header is set.
*/
public operator fun contains(name: String): Boolean = get(name) != null
/**
* Gets a first response header with the specified [name] or returns `null`.
*/
public open operator fun get(name: String): String? = getEngineHeaderValues(name).firstOrNull()
/**
* Gets values of a response header with the specified [name].
*/
public fun values(name: String): List<String> = getEngineHeaderValues(name)
/***
* Builds a [Headers] instance from a response header values.
*/
public fun allValues(): Headers = Headers.build {
getEngineHeaderNames().forEach {
appendAll(it, getEngineHeaderValues(it))
}
}
/**
* Appends a response header with the specified [name] and [value].
* @param safeOnly prevents from setting unsafe headers; `true` by default
*/
public fun append(name: String, value: String, safeOnly: Boolean = true) {
if (managedByEngineHeaders.contains(name)) {
return
}
if (safeOnly && HttpHeaders.isUnsafe(name)) {
throw UnsafeHeaderException(name)
}
HttpHeaders.checkHeaderName(name)
HttpHeaders.checkHeaderValue(value)
engineAppendHeader(name, value)
}
/**
* An engine's header appending implementation.
*/
protected abstract fun engineAppendHeader(name: String, value: String)
/**
* An engine's response header names extractor.
*/
protected abstract fun getEngineHeaderNames(): List<String>
/**
* An engine's response header values extractor.
*/
protected abstract fun getEngineHeaderValues(name: String): List<String>
}
|
apache-2.0
|
5058643319dac5991d6abfd716bc649f
| 29.162162 | 118 | 0.652778 | 4.385069 | false | false | false | false |
AntonovAlexander/activecore
|
kernelip/rtl/src/module.kt
|
1
|
22057
|
/*
* hw_module.kt
*
* Created on: 05.06.2019
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package rtl
import hwast.*
import kotlin.reflect.jvm.internal.impl.types.TypeConstructorSubstitution
open class module(val name : String) : hw_astc_stdif() {
val OP_CPROC = hw_opcode("cproc")
override var GenNamePrefix = "rtl"
var Include_filenames = ArrayList<String>()
var Combs = ArrayList<hw_var>()
var Mems = ArrayList<hw_mem>()
var SyncBufs = ArrayList<hw_syncbuf>()
var Cprocs = ArrayList<hw_exec>()
var Submodules = mutableMapOf<String, hw_submodule>()
fun submodule(inst_name : String, new_submod : module) : hw_submodule {
if (FROZEN_FLAG) ERROR("Failed to add submodule " + inst_name + ": ASTC frozen")
if (Submodules.containsKey(inst_name)) ERROR("Naming conflict for instance: " + inst_name)
var new_inst = hw_submodule(inst_name, new_submod, this, false, true)
Submodules.put(inst_name, new_inst)
return new_inst
}
fun submodule_bb(inst_name : String, new_submod : module, include_needed : Boolean) : hw_submodule {
if (FROZEN_FLAG) ERROR("Failed to add submodule " + inst_name + ": ASTC frozen")
if (Submodules.containsKey(inst_name)) ERROR("Naming conflict for instance: " + inst_name)
var new_inst = hw_submodule(inst_name, new_submod, this, true, include_needed)
Submodules.put(inst_name, new_inst)
return new_inst
}
private fun add_comb(new_comb : hw_var) {
if (FROZEN_FLAG) ERROR("Failed to add comb " + new_comb.name + ": ASTC frozen")
if (wrvars.containsKey(new_comb.name)) ERROR("Naming conflict for comb: " + new_comb.name)
if (rdvars.containsKey(new_comb.name)) ERROR("Naming conflict for comb: " + new_comb.name)
wrvars.put(new_comb.name, new_comb)
rdvars.put(new_comb.name, new_comb)
Combs.add(new_comb)
new_comb.default_astc = this
}
fun comb(name : String, vartype : hw_type, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, vartype, defimm)
add_comb(ret_var)
return ret_var
}
fun comb(name : String, vartype : hw_type, defval : String) : hw_var {
var ret_var = hw_var(name, vartype, defval)
add_comb(ret_var)
return ret_var
}
fun comb(name : String, src_struct : hw_struct, dimensions : hw_dim_static) : hw_var {
var ret_var = hw_var(name, src_struct, dimensions)
add_comb(ret_var)
return ret_var
}
fun comb(name : String, src_struct : hw_struct) : hw_var {
var ret_var = hw_var(name, src_struct)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, dimensions : hw_dim_static, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, dimensions, defimm)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, dimensions : hw_dim_static, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, dimensions, defval)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, msb: Int, lsb: Int, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, msb, lsb, defimm)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, msb: Int, lsb: Int, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, msb, lsb, defval)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, defimm)
add_comb(ret_var)
return ret_var
}
fun ucomb(name : String, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_UNSIGNED, defval)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, dimensions : hw_dim_static, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, dimensions, defimm)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, dimensions : hw_dim_static, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, dimensions, defval)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, msb: Int, lsb: Int, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, msb, lsb, defimm)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, msb: Int, lsb: Int, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, msb, lsb, defval)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, defimm : hw_imm) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, defimm)
add_comb(ret_var)
return ret_var
}
fun scomb(name : String, defval : String) : hw_var {
var ret_var = hw_var(name, DATA_TYPE.BV_SIGNED, defval)
add_comb(ret_var)
return ret_var
}
private fun add_mem(new_mem : hw_mem) {
if (FROZEN_FLAG) ERROR("Failed to add mem " + new_mem.name + ": ASTC frozen")
if (rdvars.containsKey(new_mem.name)) ERROR("Naming conflict for mem: " + new_mem.name)
rdvars.put(new_mem.name, new_mem)
Mems.add(new_mem)
}
fun mem(name : String, vartype : hw_type, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, vartype, sync_type)
add_mem(ret_var)
return ret_var
}
fun mem(name : String, src_struct : hw_struct, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, hw_type(src_struct), sync_type)
add_mem(ret_var)
return ret_var
}
fun umem(name : String, dimensions : hw_dim_static, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), sync_type)
add_mem(ret_var)
return ret_var
}
fun umem(name : String, msb: Int, lsb: Int, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), sync_type)
add_mem(ret_var)
return ret_var
}
fun smem(name : String, dimensions : hw_dim_static, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), sync_type)
add_mem(ret_var)
return ret_var
}
fun smem(name : String, msb: Int, lsb: Int, sync_type : SYNC_TYPE) : hw_mem {
var ret_var = hw_mem(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), sync_type)
add_mem(ret_var)
return ret_var
}
private fun add_syncbuf(new_syncbuf : hw_syncbuf) {
if (FROZEN_FLAG) ERROR("Failed to add syncbuf " + new_syncbuf.name + ": ASTC frozen")
if (wrvars.containsKey(new_syncbuf.name)) ERROR("Naming conflict for syncbuf: " + new_syncbuf.name)
if (rdvars.containsKey(new_syncbuf.name)) ERROR("Naming conflict for syncbuf: " + new_syncbuf.name)
wrvars.put(new_syncbuf.name, new_syncbuf)
rdvars.put(new_syncbuf.name, new_syncbuf)
SyncBufs.add(new_syncbuf)
Combs.add(new_syncbuf)
Mems.add(new_syncbuf.buf)
new_syncbuf.default_astc = this
}
fun buffered(name : String, vartype : hw_type, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, vartype, defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, vartype : hw_type, defval : String, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, vartype, defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, src_struct : hw_struct, dimensions : hw_dim_static, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(src_struct, dimensions), "0", clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, src_struct : hw_struct, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(src_struct), "0", clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, vartype : hw_type, defimm: hw_imm, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, vartype, defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, vartype : hw_type, defval : String, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, vartype, defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, src_struct : hw_struct, dimensions : hw_dim_static, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(src_struct, dimensions), "0", clk)
add_syncbuf(ret_var)
return ret_var
}
fun buffered(name : String, src_struct : hw_struct, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(src_struct), "0", clk)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ubuffered(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var, rst : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sbuffered(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var) : hw_buffered {
var ret_var = hw_buffered(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, vartype : hw_type, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, vartype, defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, vartype : hw_type, defval : String, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, vartype, defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, src_struct : hw_struct, dimensions : hw_dim_static, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(src_struct, dimensions), "0", clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, src_struct : hw_struct, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(src_struct), "0", clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, vartype : hw_type, defimm: hw_imm, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, vartype, defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, vartype : hw_type, defval : String, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, vartype, defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, src_struct : hw_struct, dimensions : hw_dim_static, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(src_struct, dimensions), "0", clk)
add_syncbuf(ret_var)
return ret_var
}
fun sticky(name : String, src_struct : hw_struct, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(src_struct), "0", clk)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, dimensions), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun usticky(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_UNSIGNED, msb, lsb), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defimm, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var, rst : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defval, clk, rst)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, dimensions : hw_dim_static, defimm: hw_imm, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, dimensions : hw_dim_static, defval : String, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, dimensions), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, msb: Int, lsb: Int, defimm: hw_imm, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defimm, clk)
add_syncbuf(ret_var)
return ret_var
}
fun ssticky(name : String, msb: Int, lsb: Int, defval : String, clk : hw_var) : hw_sticky {
var ret_var = hw_sticky(name, hw_type(DATA_TYPE.BV_SIGNED, msb, lsb), defval, clk)
add_syncbuf(ret_var)
return ret_var
}
// initiate new cproc
fun cproc_begin() : hw_exec {
var new_cproc = hw_exec(OP_CPROC)
this.add(new_cproc)
return new_cproc
}
// finalize cproc
fun cproc_end() {
if (this.size != 1) ERROR("Cproc ASTC inconsistent!")
var cproc = this[0]
if (cproc.opcode != OP_CPROC) ERROR("Cproc ASTC inconsistent!")
cproc.SetCursor(0)
// asserting defaults to iftargets
for (iftarget in cproc.iftargets) {
assign(iftarget, iftarget.defimm)
}
// restoring stickies
var wrvars_sticky = ArrayList<hw_sticky>()
for (wrvar in cproc.wrvars) {
if (wrvar is hw_sticky) wrvars_sticky.add(wrvar)
}
for (wrvar_sticky in wrvars_sticky) {
wrvar_sticky.assign(wrvar_sticky.buf)
}
// adding generated combs
for (genvar in cproc.genvars) {
Combs.add(genvar)
}
cproc.ResetCursor()
Cprocs.add(cproc)
clear()
}
fun validate_cproc(cproc : hw_exec) : Boolean {
return (cproc.opcode == OP_CPROC)
}
fun validate() {
for (cproc in Cprocs) validate_cproc(cproc)
// TODO: cproc wrvars and submodules intersection
for (wrvar in wrvars) {
if (!wrvar.value.write_done) WARNING("signal " + wrvar.value.name + " is not initialized")
}
for (rdvar in rdvars) {
if (!rdvar.value.read_done) WARNING("signal " + rdvar.value.name + " is not used!")
}
println("Validation complete!")
}
fun end() {
for (port in Ports) {
if (port.vartype.DataType == DATA_TYPE.STRUCTURED) {
port.vartype.src_struct.MarkStructInterface()
}
}
validate()
freeze()
}
fun export_to_sv(pathname : String, debug_lvl : DEBUG_LEVEL) {
NEWLINE()
MSG("#################################")
MSG("#### Starting RTL generation ####")
MSG("#### module: " + name)
MSG("#################################")
validate()
var writer = SvWriter(this)
writer.write(pathname, debug_lvl)
MSG("##################################")
MSG("#### RTL generation complete! ####")
MSG("#### module: " + name)
MSG("##################################")
}
}
val DUMMY_MODULE = module("DUMMY")
|
apache-2.0
|
e51b8b16e0397a4bea9fbdf9fc819b14
| 36.835334 | 127 | 0.593508 | 3.168654 | false | false | false | false |
DemonWav/MinecraftDev
|
src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt
|
1
|
1625
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiReference
import com.intellij.psi.javadoc.CustomJavadocTagProvider
import com.intellij.psi.javadoc.JavadocTagInfo
import com.intellij.psi.javadoc.PsiDocTagValue
class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider {
override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason)
private sealed class InjectorTag : JavadocTagInfo {
override fun isInline() = false
override fun isValidInContext(element: PsiElement?): Boolean {
val modifierList = (element as? PsiMethod)?.modifierList ?: return false
return MixinConstants.Annotations.ENTRY_POINTS.any {
modifierList.findAnnotation(it) != null
}
}
override fun checkTagValue(value: PsiDocTagValue?): String? = null
override fun getReference(value: PsiDocTagValue?): PsiReference? = null
object Author : InjectorTag() {
override fun getName() = "author"
override fun checkTagValue(value: PsiDocTagValue?): String? {
return "The @author JavaDoc tag must be filled in.".takeIf { value?.text?.trim().isNullOrEmpty() }
}
}
object Reason : InjectorTag() {
override fun getName() = "reason"
}
}
}
|
mit
|
ebf0140386b4dd407e8b8a80e6229c42
| 29.660377 | 114 | 0.683692 | 4.564607 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/platform-impl/src/com/intellij/idea/ApplicationLoader.kt
|
2
|
20260
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("ApplicationLoader")
@file:ApiStatus.Internal
@file:Suppress("ReplacePutWithAssignment")
package com.intellij.idea
import com.intellij.BundleBase
import com.intellij.diagnostic.*
import com.intellij.diagnostic.StartUpMeasurer.Activities
import com.intellij.diagnostic.opentelemetry.TraceManager
import com.intellij.icons.AllIcons
import com.intellij.ide.*
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.ide.plugins.StartupAbortedException
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.html.GlobalStyleSheetHolder
import com.intellij.ide.ui.laf.darcula.DarculaLaf
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.AbstractProgressIndicatorBase
import com.intellij.openapi.ui.DialogEarthquakeShaker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemPropertyBean
import com.intellij.openapi.util.io.OSAgnosticPathUtil
import com.intellij.openapi.wm.WeakFocusStackManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.AppIcon
import com.intellij.util.PlatformUtils
import com.intellij.util.TimeoutUtil
import com.intellij.util.io.URLUtil
import com.intellij.util.io.createDirectories
import com.intellij.util.io.storage.HeavyProcessLatch
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.EDT
import net.miginfocom.layout.PlatformDefaults
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.VisibleForTesting
import java.awt.EventQueue
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.*
import java.util.function.BiFunction
import javax.swing.LookAndFeel
import javax.swing.UIManager
import kotlin.system.exitProcess
private val SAFE_JAVA_ENV_PARAMETERS = arrayOf(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY)
@Suppress("SSBasedInspection")
private val LOG = Logger.getInstance("#com.intellij.idea.ApplicationLoader")
// for non-technical reasons this method cannot return CompletableFuture
fun initApplication(rawArgs: List<String>, prepareUiFuture: CompletionStage<Any>) {
val initAppActivity = StartupUtil.startupStart.endAndStart(Activities.INIT_APP)
val isInternal = java.lang.Boolean.getBoolean(ApplicationManagerEx.IS_INTERNAL_PROPERTY)
if (isInternal) {
ForkJoinPool.commonPool().execute {
initAppActivity.runChild("assert on missed keys enabling") {
BundleBase.assertOnMissedKeys(true)
}
}
}
initAppActivity.runChild("disposer debug mode enabling if needed") {
if (isInternal || Disposer.isDebugDisposerOn()) {
Disposer.setDebugMode(true)
}
}
val args = processProgramArguments(rawArgs)
// event queue is replaced as part of "prepareUiFuture" task - application must be created only after that
val prepareUiFutureWaitActivity = initAppActivity.startChild("prepare ui waiting")
val block = (prepareUiFuture as CompletableFuture<Any>).thenComposeAsync(
{ baseLaf ->
prepareUiFutureWaitActivity.end()
val setBaseLafFuture = CompletableFuture.runAsync(
{
initAppActivity.runChild("base laf passing") {
DarculaLaf.setPreInitializedBaseLaf(baseLaf as LookAndFeel)
}
},
ForkJoinPool.commonPool()
)
if (!Main.isHeadless()) {
ForkJoinPool.commonPool().execute {
EventQueue.invokeLater {
WeakFocusStackManager.getInstance()
}
}
}
val app = initAppActivity.runChild("app instantiation") {
ApplicationImpl(isInternal, Main.isHeadless(), Main.isCommandLine(), EDT.getEventDispatchThread())
}
ForkJoinPool.commonPool().execute {
initAppActivity.runChild("opentelemetry configuration") {
TraceManager.init()
}
}
if (!Main.isHeadless()) {
app.invokeLater({
val patchingActivity = StartUpMeasurer.startActivity("html style patching")
// patch html styles
val uiDefaults = UIManager.getDefaults()
// create a separate copy for each case
uiDefaults.put("javax.swing.JLabel.userStyleSheet", GlobalStyleSheetHolder.getGlobalStyleSheet())
uiDefaults.put("HTMLEditorKit.jbStyleSheet", GlobalStyleSheetHolder.getGlobalStyleSheet())
patchingActivity.end()
}, ModalityState.any())
}
val pluginSetFutureWaitActivity = initAppActivity.startChild("plugin descriptor init waiting")
PluginManagerCore.getInitPluginFuture().thenApply {
pluginSetFutureWaitActivity.end()
Pair(it, setBaseLafFuture)
}
}, Executor {
if (EDT.isCurrentThreadEdt()) ForkJoinPool.commonPool().execute(it) else it.run()
}
)
.thenCompose { (pluginSet, setBaseLafFuture) ->
val app = ApplicationManager.getApplication() as ApplicationImpl
initAppActivity.runChild("app component registration") {
app.registerComponents(modules = pluginSet.getEnabledModules(),
app = app,
precomputedExtensionModel = null,
listenerCallbacks = null)
}
// initSystemProperties or RegistryKeyBean.addKeysFromPlugins maybe not yet performed,
// but it is OK, because registry is not and should not be used.
initConfigurationStore(app)
app.invokeLater({
// ensure that base laf is set before initialization of LafManagerImpl
runActivity("base laf waiting") {
setBaseLafFuture.join()
}
runActivity("laf initialization") {
LafManager.getInstance()
}
}, ModalityState.any())
val starter = initAppActivity.runChild("app starter creation") {
findAppStarter(args)
}
val preloadSyncServiceFuture = preloadServices(pluginSet.getEnabledModules(), app, activityPrefix = "")
prepareStart(app, initAppActivity, preloadSyncServiceFuture).thenApply {
starter
}
}
block.thenAcceptAsync({ addActivateAndWindowsCliListeners() }, ForkJoinPool.commonPool())
block.thenAccept { starter ->
initAppActivity.end()
if (starter.requiredModality == ApplicationStarter.NOT_IN_EDT) {
starter.main(args)
// no need to use pool once plugins are loaded
ZipFilePool.POOL = null
}
else {
ApplicationManager.getApplication().invokeLater {
(TransactionGuard.getInstance() as TransactionGuardImpl).performUserActivity {
starter.main(args)
}
}
}
}
block.join()
}
private fun prepareStart(app: ApplicationImpl,
initAppActivity: Activity,
preloadSyncServiceFuture: CompletableFuture<*>): CompletableFuture<*> {
val loadComponentInEdtFutureTask = initAppActivity.runChild("old component init task creating") {
app.createInitOldComponentsTask()
}
val loadComponentInEdtFuture: CompletableFuture<*>
if (loadComponentInEdtFutureTask == null) {
loadComponentInEdtFuture = CompletableFuture.completedFuture(null)
}
else {
val placeOnEventQueueActivity = initAppActivity.startChild(Activities.PLACE_ON_EVENT_QUEUE)
loadComponentInEdtFuture = CompletableFuture.runAsync(
{
placeOnEventQueueActivity.end()
loadComponentInEdtFutureTask.run()
},
Executor(app::invokeLater)
)
}
loadComponentInEdtFuture.thenRun {
StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_LOADED)
}
return CompletableFuture.allOf(loadComponentInEdtFuture, preloadSyncServiceFuture, StartupUtil.getServerFuture()).thenComposeAsync(
{
val pool = ForkJoinPool.commonPool()
val future = CompletableFuture.runAsync({
initAppActivity.runChild("app initialized callback") {
ForkJoinTask.invokeAll(callAppInitialized(app))
}
}, pool)
if (!app.isUnitTestMode && !app.isHeadlessEnvironment &&
java.lang.Boolean.parseBoolean(System.getProperty("enable.activity.preloading", "true"))) {
pool.execute { executePreloadActivities(app) }
}
pool.execute {
runActivity("create locator file") {
createAppLocatorFile()
}
}
if (!Main.isLightEdit()) {
// this functionality should be used only by plugin functionality that is used after start-up
pool.execute {
runActivity("system properties setting") {
SystemPropertyBean.initSystemProperties()
}
}
}
pool.execute {
PluginManagerMain.checkThirdPartyPluginsAllowed()
}
if (!app.isHeadlessEnvironment) {
pool.execute {
runActivity("icons preloading") {
if (app.isInternal) {
IconLoader.setStrictGlobally(true)
}
AsyncProcessIcon("")
AnimatedIcon.Blinking(AllIcons.Ide.FatalError)
AnimatedIcon.FS()
}
runActivity("migLayout") {
// IDEA-170295
PlatformDefaults.setLogicalPixelBase(PlatformDefaults.BASE_FONT_SIZE)
}
}
}
future
},
Executor {
// if `loadComponentInEdtFuture` is completed after `preloadSyncServiceFuture`,
// then this task will be executed in EDT, so force execution out of EDT
if (EDT.isCurrentThreadEdt()) ForkJoinPool.commonPool().execute(it) else it.run()
}
)
}
private fun findAppStarter(args: List<String>): ApplicationStarter {
val first = args.firstOrNull()
// first argument maybe a project path
if (first == null) {
return IdeStarter()
}
else if (args.size == 1 && OSAgnosticPathUtil.isAbsolute(first)) {
return createDefaultAppStarter()
}
var starter: ApplicationStarter? = null
val point = ApplicationStarter.EP_NAME.point as ExtensionPointImpl<ApplicationStarter>
for (adapter in point.sortedAdapters) {
if (adapter.orderId == first) {
starter = adapter.createInstance(point.componentManager)
}
}
if (starter == null) {
// `ApplicationStarter` is an extension, so to find a starter, extensions must be registered first
starter = point.firstOrNull { it == null || it.commandName == first } ?: createDefaultAppStarter()
}
if (Main.isHeadless() && !starter.isHeadless) {
val commandName = starter.commandName
val message = IdeBundle.message(
"application.cannot.start.in.a.headless.mode",
when {
starter is IdeStarter -> 0
commandName != null -> 1
else -> 2
},
commandName,
starter.javaClass.name,
if (args.isEmpty()) 0 else 1,
args.joinToString(" ")
)
Main.showMessage(IdeBundle.message("main.startup.error"), message, true)
exitProcess(Main.NO_GRAPHICS)
}
starter.premain(args)
return starter
}
private fun createDefaultAppStarter(): ApplicationStarter {
return if (PlatformUtils.getPlatformPrefix() == "LightEdit") IdeStarter.StandaloneLightEditStarter() else IdeStarter()
}
@VisibleForTesting
internal fun createAppLocatorFile() {
val locatorFile = Path.of(PathManager.getSystemPath(), ApplicationEx.LOCATOR_FILE_NAME)
try {
locatorFile.parent?.createDirectories()
Files.writeString(locatorFile, PathManager.getHomePath(), StandardCharsets.UTF_8)
}
catch (e: IOException) {
LOG.warn("Can't store a location in '$locatorFile'", e)
}
}
fun preloadServices(modules: Sequence<IdeaPluginDescriptorImpl>,
container: ComponentManagerImpl,
activityPrefix: String,
onlyIfAwait: Boolean = false): CompletableFuture<*> {
val result = container.preloadServices(modules, activityPrefix, onlyIfAwait)
fun logError(future: CompletableFuture<*>): CompletableFuture<*> {
return future
.whenComplete { _, error ->
if (error != null && error !is ProcessCanceledException) {
StartupAbortedException.processException(error)
}
}
}
logError(result.async)
return result.sync
}
private fun addActivateAndWindowsCliListeners() {
StartupUtil.addExternalInstanceListener { rawArgs ->
LOG.info("External instance command received")
val (args, currentDirectory) = if (rawArgs.isEmpty()) emptyList<String>() to null else rawArgs.subList(1, rawArgs.size) to rawArgs[0]
val result = handleExternalCommand(args, currentDirectory)
result.future
}
StartupUtil.LISTENER = BiFunction { currentDirectory, args ->
LOG.info("External Windows command received")
if (args.isEmpty()) {
return@BiFunction 0
}
val result = handleExternalCommand(args.toList(), currentDirectory)
CliResult.unmap(result.future, Main.ACTIVATE_ERROR).exitCode
}
ApplicationManager.getApplication().messageBus.simpleConnect().subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener {
override fun appWillBeClosed(isRestart: Boolean) {
StartupUtil.addExternalInstanceListener { CliResult.error(Main.ACTIVATE_DISPOSING, IdeBundle.message("activation.shutting.down")) }
StartupUtil.LISTENER = BiFunction { _, _ -> Main.ACTIVATE_DISPOSING }
}
})
}
private fun handleExternalCommand(args: List<String>, currentDirectory: String?): CommandLineProcessorResult {
val result = if (args.isNotEmpty() && args[0].contains(URLUtil.SCHEME_SEPARATOR)) {
CommandLineProcessor.processProtocolCommand(args[0])
CommandLineProcessorResult(null, CommandLineProcessor.OK_FUTURE)
}
else {
CommandLineProcessor.processExternalCommandLine(args, currentDirectory)
}
ApplicationManager.getApplication().invokeLater {
if (result.hasError) {
result.showErrorIfFailed()
}
else {
val windowManager = WindowManager.getInstance()
if (result.project == null) {
windowManager.findVisibleFrame()?.let { frame ->
frame.toFront()
DialogEarthquakeShaker.shake(frame)
}
}
else {
windowManager.getIdeFrame(result.project)?.let {
AppIcon.getInstance().requestFocus(it)
}
}
}
}
return result
}
fun findStarter(key: String) = ApplicationStarter.EP_NAME.iterable.find { it == null || it.commandName == key }
fun initConfigurationStore(app: ApplicationImpl) {
var activity = StartUpMeasurer.startActivity("beforeApplicationLoaded")
val configPath = PathManager.getConfigDir()
for (listener in ApplicationLoadListener.EP_NAME.iterable) {
try {
(listener ?: break).beforeApplicationLoaded(app, configPath)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
activity = activity.endAndStart("init app store")
// we set it after beforeApplicationLoaded call, because the app store can depend on stream provider state
app.stateStore.setPath(configPath)
StartUpMeasurer.setCurrentState(LoadingState.CONFIGURATION_STORE_INITIALIZED)
activity.end()
}
/**
* The method looks for `-Dkey=value` program arguments and stores some of them in system properties.
* We should use it for a limited number of safe keys; one of them is a list of required plugins.
*
* @see SAFE_JAVA_ENV_PARAMETERS
*/
@Suppress("SpellCheckingInspection")
private fun processProgramArguments(args: List<String>): List<String> {
if (args.isEmpty()) {
return Collections.emptyList()
}
val arguments = mutableListOf<String>()
for (arg in args) {
if (arg.startsWith("-D")) {
val keyValue = arg.substring(2).split('=')
if (keyValue.size == 2 && SAFE_JAVA_ENV_PARAMETERS.contains(keyValue[0])) {
System.setProperty(keyValue[0], keyValue[1])
continue
}
}
if (!CommandLineArgs.isKnownArgument(arg)) {
arguments.add(arg)
}
}
return arguments
}
fun callAppInitialized(app: ApplicationImpl): List<ForkJoinTask<*>> {
val extensionArea = app.extensionArea
val extensionPoint = extensionArea.getExtensionPoint<ApplicationInitializedListener>("com.intellij.applicationInitializedListener")
val result = ArrayList<ForkJoinTask<*>>(extensionPoint.size())
extensionPoint.processImplementations(/* shouldBeSorted = */ false) { supplier, _ ->
result.add(ForkJoinTask.adapt {
try {
supplier.get()?.componentsInitialized()
}
catch (e: Throwable) {
LOG.error(e)
}
})
}
extensionPoint.reset()
return result
}
private fun checkHeavyProcessRunning() {
if (HeavyProcessLatch.INSTANCE.isRunning) {
TimeoutUtil.sleep(1)
}
}
private fun executePreloadActivity(activity: PreloadingActivity, descriptor: PluginDescriptor?, app: ApplicationImpl) {
checkHeavyProcessRunning()
val indicator = AbstractProgressIndicatorBase()
if (app.isDisposed) {
return
}
val isDebugEnabled = LOG.isDebugEnabled
ProgressManager.getInstance().executeProcessUnderProgress({
val measureActivity = if (descriptor == null) {
null
}
else {
StartUpMeasurer.startActivity(activity.javaClass.name, ActivityCategory.PRELOAD_ACTIVITY, descriptor.pluginId.idString)
}
try {
indicator.start()
activity.preload(object : AbstractProgressIndicatorBase() {
override fun checkCanceled() {
checkHeavyProcessRunning()
indicator.checkCanceled()
}
override fun isCanceled() = indicator.isCanceled || app.isDisposed
})
if (isDebugEnabled) {
LOG.debug("${activity.javaClass.name} finished")
}
}
catch (ignore: ProcessCanceledException) {
return@executeProcessUnderProgress
}
finally {
measureActivity?.end()
if (indicator.isRunning) {
indicator.stop()
}
}
}, indicator)
}
private fun executePreloadActivities(app: ApplicationImpl) {
val activity = StartUpMeasurer.startActivity("preloading activity executing")
val list = mutableListOf<Pair<PreloadingActivity, PluginDescriptor>>()
val extensionPoint = app.extensionArea.getExtensionPoint<PreloadingActivity>("com.intellij.preloadingActivity")
extensionPoint.processImplementations(/* shouldBeSorted = */ false) { supplier, pluginDescriptor ->
val preloadingActivity: PreloadingActivity
try {
preloadingActivity = supplier.get() ?: return@processImplementations
}
catch (e: Throwable) {
LOG.error(e)
return@processImplementations
}
list.add(Pair(preloadingActivity, pluginDescriptor))
}
extensionPoint.reset()
if (list.isEmpty()) {
return
}
// do not execute as a single long task, make sure that other more important tasks may slip in between
ForkJoinPool.commonPool().execute(object : Runnable {
private var index = 0
override fun run() {
if (app.isDisposed) {
return
}
val item = list[index++]
executePreloadActivity(item.first, item.second, app)
if (index == list.size || app.isDisposed) {
activity.end()
}
else {
ForkJoinPool.commonPool().execute(this)
}
}
})
}
|
apache-2.0
|
4e1d708478e5ce367b9c46b79fbeb7a8
| 33.632479 | 137 | 0.696446 | 4.732539 | false | false | false | false |
cdietze/klay
|
tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/anim/FlickerDemo.kt
|
1
|
2068
|
package tripleklay.demo.core.anim
import klay.core.Font
import klay.scene.GroupLayer
import klay.scene.ImageLayer
import tripleklay.anim.Flicker
import tripleklay.demo.core.DemoScreen
import tripleklay.ui.Group
import tripleklay.ui.Root
import tripleklay.util.StyledText
import tripleklay.util.TextStyle
/**
* Demonstrates the flicker.
*/
class FlickerDemo : DemoScreen() {
override fun name(): String {
return "Flicker"
}
override fun title(): String {
return "Flicker Demo"
}
override fun createIface(root: Root): Group? {
val width = 410f
val height = 400f
val clip = GroupLayer(410f, 400f)
layer.addAt(clip, (size().width - width) / 2f, (size().height - height) / 2f)
val scroll = GroupLayer()
clip.add(scroll)
// add a bunch of image layers to our root layer
var y = 0f
for (ii in 0..IMG_COUNT - 1) {
val image = graphics().createCanvas(width, IMG_HEIGHT)
val text = StringBuilder()
if (ii == 0)
text.append("Tap & fling")
else if (ii == IMG_COUNT - 1)
text.append("Good job!")
else
for (tt in 0..24) text.append(ii)
StyledText.span(graphics(), text.toString(), TEXT).render(image, 0f, 0f)
val layer = ImageLayer(image.toTexture())
scroll.addAt(layer, 0f, y)
y += layer.scaledHeight()
}
val flicker = object : Flicker(0f, height - IMG_HEIGHT * IMG_COUNT, 0f) {
override fun friction(): Float {
return 0.001f
}
}
clip.events().connect(flicker)
flicker.changed.connect({ flicker: Flicker ->
scroll.setTy(flicker.position)
})
closeOnHide(paint.connect(flicker.onPaint))
return null
}
companion object {
protected val IMG_HEIGHT = 100f
protected val IMG_COUNT = 20
protected val TEXT = TextStyle.DEFAULT.withFont(Font("Helvetiva", 72f))
}
}
|
apache-2.0
|
0c0060f293357866953d0c148950821a
| 28.971014 | 85 | 0.584623 | 3.954111 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer
|
app/src/main/java/de/ph1b/audiobook/features/audio/LoudnessDialog.kt
|
1
|
2512
|
package de.ph1b.audiobook.features.audio
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import de.ph1b.audiobook.R
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.injection.appComponent
import de.ph1b.audiobook.misc.DialogController
import de.ph1b.audiobook.misc.DialogLayoutContainer
import de.ph1b.audiobook.misc.getUUID
import de.ph1b.audiobook.misc.progressChangedStream
import de.ph1b.audiobook.misc.putUUID
import de.ph1b.audiobook.playback.PlayerController
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.loudness.*
import java.text.DecimalFormat
import java.util.UUID
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
* Dialog for controlling the loudness.
*/
class LoudnessDialog(args: Bundle) : DialogController(args) {
@Inject
lateinit var repo: BookRepository
@Inject
lateinit var player: PlayerController
private val dbFormat = DecimalFormat("0.0 dB")
@SuppressLint("InflateParams")
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
appComponent.inject(this)
val container = DialogLayoutContainer(
activity!!.layoutInflater.inflate(R.layout.loudness, null, false)
)
val bookId = args.getUUID(NI_BOOK_ID)
val book = repo.bookById(bookId)
?: return emptyDialog()
container.seekBar.max = LoudnessGain.MAX_MB
container.seekBar.progress = book.content.loudnessGain
container.seekBar.progressChangedStream()
.throttleLast(200, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe {
player.setLoudnessGain(it)
container.currentValue.text = format(it)
}
.disposeOnDestroyDialog()
container.currentValue.text = format(book.content.loudnessGain)
container.maxValue.text = format(container.seekBar.max)
return MaterialDialog(activity!!).apply {
title(R.string.volume_boost)
customView(view = container.containerView, scrollable = true)
}
}
private fun emptyDialog(): Dialog {
return MaterialDialog(activity!!)
}
private fun format(milliDb: Int) = dbFormat.format(milliDb / 100.0)
companion object {
private const val NI_BOOK_ID = "ni#bookId"
operator fun invoke(bookId: UUID) = LoudnessDialog(
Bundle().apply {
putUUID(NI_BOOK_ID, bookId)
}
)
}
}
|
lgpl-3.0
|
ae04f5405651dc8767f4a8a9c45088b2
| 30.012346 | 79 | 0.755971 | 4.038585 | false | false | false | false |
BreakOutEvent/breakout-backend
|
src/test/java/backend/model/location/LocationTest.kt
|
1
|
2228
|
package backend.model.location
import backend.model.event.Event
import backend.model.event.Team
import backend.model.misc.Coord
import backend.model.user.Participant
import backend.util.distanceCoordsKM
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.time.LocalDateTime
import kotlin.test.assertNull
@RunWith(PowerMockRunner::class)
@PrepareForTest(Participant::class, Team::class, Event::class)
class LocationTest {
private lateinit var event: Event
private lateinit var coord: Coord
private lateinit var participant: Participant
private lateinit var team: Team
private lateinit var location: Location
private lateinit var date: LocalDateTime
@Before
fun setUp() {
coord = Coord(0.0, 1.1)
team = PowerMockito.mock(Team::class.java)
participant = PowerMockito.mock(Participant::class.java)
event = PowerMockito.mock(Event::class.java)
date = PowerMockito.mock(LocalDateTime::class.java)
Mockito.`when`(participant.getCurrentTeam()).thenReturn(team)
Mockito.`when`(team.event).thenReturn(event)
Mockito.`when`(event.startingLocation).thenReturn(Coord(100.0, 203.7))
location = Location(coord, participant, date, mapOf("COUNTRY" to "Germany"))
}
@Test
fun testGetPoint() {
assertEquals(coord, location.coord)
}
@Test
fun testGetUploader() {
assertEquals(participant, location.uploader)
}
@Test
fun testGetTeam() {
assertEquals(team, location.team)
}
@Test
fun testGetCoord() {
assertEquals(coord, location.coord)
}
@Test
fun testGetPosting() {
assertNull(location.posting)
}
@Test
fun testGetDate() {
assertEquals(date, location.date)
}
@Test
fun testGetDistance() {
val distance = distanceCoordsKM(from = Coord(100.0, 203.7), to = coord)
assertEquals(distance, location.distance, 0.0)
}
}
|
agpl-3.0
|
c9daa3accca2746e36b2398e5a2c3777
| 26.170732 | 84 | 0.702873 | 4.24381 | false | true | false | false |
nielsutrecht/adventofcode
|
src/main/kotlin/com/nibado/projects/advent/y2017/Day04.kt
|
1
|
499
|
package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceLines
object Day04 : Day {
val lines = resourceLines(2017, 4).map {
it.split(" ").toList()
}.toList()
override fun part1() =
lines.filter { it.size == it.toSet().size }.count().toString()
override fun part2() =
lines.map { it.map { it.toList().sorted().toString() } }.filter { it.size == it.toSet().size }.count().toString()
}
|
mit
|
ad6bd45404e275b1100ff4284412c7f5
| 30.25 | 125 | 0.631263 | 3.615942 | false | false | false | false |
JetBrains/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/util/ClassSet.kt
|
1
|
2914
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.util
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.map2Array
import java.util.concurrent.ConcurrentHashMap
interface ClassSet<out T> {
fun isEmpty(): Boolean
operator fun contains(element: Class<out @UnsafeVariance T>): Boolean
fun toList(): List<Class<out @UnsafeVariance T>>
}
fun <T> T?.isInstanceOf(classSet: ClassSet<T>): Boolean =
this?.let { classSet.contains(it.javaClass) } ?: false
fun <T> ClassSet<T>.hasClassOf(instance: T?): Boolean =
instance?.let { contains(it.javaClass) } ?: false
private class ClassSetImpl<out T>(val initialClasses: List<Class<out T>>) : ClassSet<T> {
private val internalMapping: MutableMap<String, Boolean> = ConcurrentHashMap<String, Boolean>().apply {
for (initialClass in initialClasses) {
this[initialClass.name] = true
}
}
override fun isEmpty(): Boolean = initialClasses.isEmpty()
override operator fun contains(element: Class<out @UnsafeVariance T>): Boolean {
return internalMapping[element.name]
?: initialClasses.any { it.isAssignableFrom(element) }.also { internalMapping[element.name] = it }
}
override fun toString(): String {
return "ClassSetImpl($initialClasses)"
}
override fun toList(): List<Class<out @UnsafeVariance T>> = initialClasses
}
private class SimpleClassSetImpl<out T>(val initialClasses: List<Class<out T>>) : ClassSet<T> {
override fun isEmpty(): Boolean = initialClasses.isEmpty()
override operator fun contains(element: Class<out @UnsafeVariance T>): Boolean {
return initialClasses.any { it.isAssignableFrom(element) }
}
override fun toString(): String {
return "SimpleClassSetImpl($initialClasses)"
}
override fun toList(): List<Class<out @UnsafeVariance T>> = initialClasses
}
fun <T> classSetOf(vararg classes: Class<out T>): ClassSet<T> {
if (classes.isEmpty()) return emptyClassSet
return if (classes.size <= SIMPLE_CLASS_SET_LIMIT)
SimpleClassSetImpl(classes.toList())
else
ClassSetImpl(classes.toList())
}
private val emptyClassSet: ClassSet<Nothing> = object : ClassSet<Nothing> {
override fun isEmpty() = true
override fun contains(element: Class<out Nothing>): Boolean = false
override fun toList(): List<Class<out Nothing>> = emptyList()
}
fun <T> emptyClassSet(): ClassSet<T> = emptyClassSet
class ClassSetsWrapper<out T>(val sets: Array<ClassSet<@UnsafeVariance T>>) : ClassSet<T> {
override fun isEmpty(): Boolean = sets.all { it.isEmpty() }
override operator fun contains(element: Class<out @UnsafeVariance T>): Boolean = sets.any { it.contains(element) }
override fun toList(): List<Class<out T>> = ContainerUtil.concat(*sets.map2Array { it.toList() })
}
private const val SIMPLE_CLASS_SET_LIMIT = 5
|
apache-2.0
|
bc402a5793d0472a03f22535440ffbf3
| 36.371795 | 140 | 0.731297 | 3.829172 | false | false | false | false |
SimpleMobileTools/Simple-Gallery
|
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/Config.kt
|
1
|
25574
|
package com.simplemobiletools.gallery.pro.helpers
import android.content.Context
import android.content.res.Configuration
import android.os.Environment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.models.AlbumCover
import java.util.*
class Config(context: Context) : BaseConfig(context) {
companion object {
fun newInstance(context: Context) = Config(context)
}
var directorySorting: Int
get(): Int = prefs.getInt(DIRECTORY_SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING)
set(order) = prefs.edit().putInt(DIRECTORY_SORT_ORDER, order).apply()
fun saveFolderGrouping(path: String, value: Int) {
if (path.isEmpty()) {
groupBy = value
} else {
prefs.edit().putInt(GROUP_FOLDER_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderGrouping(path: String): Int {
var groupBy = prefs.getInt(GROUP_FOLDER_PREFIX + path.toLowerCase(), groupBy)
if (path != SHOW_ALL && groupBy and GROUP_BY_FOLDER != 0) {
groupBy -= GROUP_BY_FOLDER + 1
}
return groupBy
}
fun removeFolderGrouping(path: String) {
prefs.edit().remove(GROUP_FOLDER_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomGrouping(path: String) = prefs.contains(GROUP_FOLDER_PREFIX + path.toLowerCase())
fun saveFolderViewType(path: String, value: Int) {
if (path.isEmpty()) {
viewTypeFiles = value
} else {
prefs.edit().putInt(VIEW_TYPE_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderViewType(path: String) = prefs.getInt(VIEW_TYPE_PREFIX + path.toLowerCase(), viewTypeFiles)
fun removeFolderViewType(path: String) {
prefs.edit().remove(VIEW_TYPE_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomViewType(path: String) = prefs.contains(VIEW_TYPE_PREFIX + path.toLowerCase())
var wasHideFolderTooltipShown: Boolean
get() = prefs.getBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, false)
set(wasShown) = prefs.edit().putBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, wasShown).apply()
var shouldShowHidden = showHiddenMedia || temporarilyShowHidden
var showHiddenMedia: Boolean
get() = prefs.getBoolean(SHOW_HIDDEN_MEDIA, false)
set(showHiddenFolders) = prefs.edit().putBoolean(SHOW_HIDDEN_MEDIA, showHiddenFolders).apply()
var temporarilyShowHidden: Boolean
get() = prefs.getBoolean(TEMPORARILY_SHOW_HIDDEN, false)
set(temporarilyShowHidden) = prefs.edit().putBoolean(TEMPORARILY_SHOW_HIDDEN, temporarilyShowHidden).apply()
var temporarilyShowExcluded: Boolean
get() = prefs.getBoolean(TEMPORARILY_SHOW_EXCLUDED, false)
set(temporarilyShowExcluded) = prefs.edit().putBoolean(TEMPORARILY_SHOW_EXCLUDED, temporarilyShowExcluded).apply()
var isThirdPartyIntent: Boolean
get() = prefs.getBoolean(IS_THIRD_PARTY_INTENT, false)
set(isThirdPartyIntent) = prefs.edit().putBoolean(IS_THIRD_PARTY_INTENT, isThirdPartyIntent).apply()
var pinnedFolders: Set<String>
get() = prefs.getStringSet(PINNED_FOLDERS, HashSet<String>())!!
set(pinnedFolders) = prefs.edit().putStringSet(PINNED_FOLDERS, pinnedFolders).apply()
var showAll: Boolean
get() = prefs.getBoolean(SHOW_ALL, false)
set(showAll) = prefs.edit().putBoolean(SHOW_ALL, showAll).apply()
fun addPinnedFolders(paths: Set<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.addAll(paths)
pinnedFolders = currPinnedFolders.filter { it.isNotEmpty() }.toHashSet()
if (paths.contains(RECYCLE_BIN)) {
showRecycleBinLast = false
}
}
fun removePinnedFolders(paths: Set<String>) {
val currPinnedFolders = HashSet<String>(pinnedFolders)
currPinnedFolders.removeAll(paths)
pinnedFolders = currPinnedFolders
}
fun addExcludedFolder(path: String) {
addExcludedFolders(HashSet<String>(Arrays.asList(path)))
}
fun addExcludedFolders(paths: Set<String>) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.addAll(paths)
excludedFolders = currExcludedFolders.filter { it.isNotEmpty() }.toHashSet()
}
fun removeExcludedFolder(path: String) {
val currExcludedFolders = HashSet<String>(excludedFolders)
currExcludedFolders.remove(path)
excludedFolders = currExcludedFolders
}
var excludedFolders: MutableSet<String>
get() = prefs.getStringSet(EXCLUDED_FOLDERS, HashSet())!!
set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply()
var isExcludedPasswordProtectionOn: Boolean
get() = prefs.getBoolean(EXCLUDED_PASSWORD_PROTECTION, false)
set(isExcludedPasswordProtectionOn) = prefs.edit().putBoolean(EXCLUDED_PASSWORD_PROTECTION, isExcludedPasswordProtectionOn).apply()
var excludedPasswordHash: String
get() = prefs.getString(EXCLUDED_PASSWORD_HASH, "")!!
set(excludedPasswordHash) = prefs.edit().putString(EXCLUDED_PASSWORD_HASH, excludedPasswordHash).apply()
var excludedProtectionType: Int
get() = prefs.getInt(EXCLUDED_PROTECTION_TYPE, PROTECTION_PATTERN)
set(excludedProtectionType) = prefs.edit().putInt(EXCLUDED_PROTECTION_TYPE, excludedProtectionType).apply()
fun addIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.add(path)
includedFolders = currIncludedFolders
}
fun addIncludedFolders(paths: Set<String>) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.addAll(paths)
includedFolders = currIncludedFolders.filter { it.isNotEmpty() }.toHashSet()
}
fun removeIncludedFolder(path: String) {
val currIncludedFolders = HashSet<String>(includedFolders)
currIncludedFolders.remove(path)
includedFolders = currIncludedFolders
}
var includedFolders: MutableSet<String>
get() = prefs.getStringSet(INCLUDED_FOLDERS, HashSet<String>())!!
set(includedFolders) = prefs.edit().remove(INCLUDED_FOLDERS).putStringSet(INCLUDED_FOLDERS, includedFolders).apply()
var autoplayVideos: Boolean
get() = prefs.getBoolean(AUTOPLAY_VIDEOS, false)
set(autoplayVideos) = prefs.edit().putBoolean(AUTOPLAY_VIDEOS, autoplayVideos).apply()
var animateGifs: Boolean
get() = prefs.getBoolean(ANIMATE_GIFS, false)
set(animateGifs) = prefs.edit().putBoolean(ANIMATE_GIFS, animateGifs).apply()
var maxBrightness: Boolean
get() = prefs.getBoolean(MAX_BRIGHTNESS, false)
set(maxBrightness) = prefs.edit().putBoolean(MAX_BRIGHTNESS, maxBrightness).apply()
var cropThumbnails: Boolean
get() = prefs.getBoolean(CROP_THUMBNAILS, true)
set(cropThumbnails) = prefs.edit().putBoolean(CROP_THUMBNAILS, cropThumbnails).apply()
var showThumbnailVideoDuration: Boolean
get() = prefs.getBoolean(SHOW_THUMBNAIL_VIDEO_DURATION, false)
set(showThumbnailVideoDuration) = prefs.edit().putBoolean(SHOW_THUMBNAIL_VIDEO_DURATION, showThumbnailVideoDuration).apply()
var showThumbnailFileTypes: Boolean
get() = prefs.getBoolean(SHOW_THUMBNAIL_FILE_TYPES, true)
set(showThumbnailFileTypes) = prefs.edit().putBoolean(SHOW_THUMBNAIL_FILE_TYPES, showThumbnailFileTypes).apply()
var markFavoriteItems: Boolean
get() = prefs.getBoolean(MARK_FAVORITE_ITEMS, true)
set(markFavoriteItems) = prefs.edit().putBoolean(MARK_FAVORITE_ITEMS, markFavoriteItems).apply()
var screenRotation: Int
get() = prefs.getInt(SCREEN_ROTATION, ROTATE_BY_SYSTEM_SETTING)
set(screenRotation) = prefs.edit().putInt(SCREEN_ROTATION, screenRotation).apply()
var fileLoadingPriority: Int
get() = prefs.getInt(FILE_LOADING_PRIORITY, PRIORITY_SPEED)
set(fileLoadingPriority) = prefs.edit().putInt(FILE_LOADING_PRIORITY, fileLoadingPriority).apply()
var loopVideos: Boolean
get() = prefs.getBoolean(LOOP_VIDEOS, false)
set(loop) = prefs.edit().putBoolean(LOOP_VIDEOS, loop).apply()
var openVideosOnSeparateScreen: Boolean
get() = prefs.getBoolean(OPEN_VIDEOS_ON_SEPARATE_SCREEN, false)
set(openVideosOnSeparateScreen) = prefs.edit().putBoolean(OPEN_VIDEOS_ON_SEPARATE_SCREEN, openVideosOnSeparateScreen).apply()
var displayFileNames: Boolean
get() = prefs.getBoolean(DISPLAY_FILE_NAMES, false)
set(display) = prefs.edit().putBoolean(DISPLAY_FILE_NAMES, display).apply()
var blackBackground: Boolean
get() = prefs.getBoolean(BLACK_BACKGROUND, false)
set(blackBackground) = prefs.edit().putBoolean(BLACK_BACKGROUND, blackBackground).apply()
var filterMedia: Int
get() = prefs.getInt(FILTER_MEDIA, getDefaultFileFilter())
set(filterMedia) = prefs.edit().putInt(FILTER_MEDIA, filterMedia).apply()
var dirColumnCnt: Int
get() = prefs.getInt(getDirectoryColumnsField(), getDefaultDirectoryColumnCount())
set(dirColumnCnt) = prefs.edit().putInt(getDirectoryColumnsField(), dirColumnCnt).apply()
var defaultFolder: String
get() = prefs.getString(DEFAULT_FOLDER, "")!!
set(defaultFolder) = prefs.edit().putString(DEFAULT_FOLDER, defaultFolder).apply()
var allowInstantChange: Boolean
get() = prefs.getBoolean(ALLOW_INSTANT_CHANGE, false)
set(allowInstantChange) = prefs.edit().putBoolean(ALLOW_INSTANT_CHANGE, allowInstantChange).apply()
private fun getDirectoryColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
DIR_HORIZONTAL_COLUMN_CNT
} else {
DIR_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
DIR_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultDirectoryColumnCount() = context.resources.getInteger(
if (scrollHorizontally) {
R.integer.directory_columns_horizontal_scroll
} else {
R.integer.directory_columns_vertical_scroll
}
)
var mediaColumnCnt: Int
get() = prefs.getInt(getMediaColumnsField(), getDefaultMediaColumnCount())
set(mediaColumnCnt) = prefs.edit().putInt(getMediaColumnsField(), mediaColumnCnt).apply()
private fun getMediaColumnsField(): String {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
if (scrollHorizontally) {
MEDIA_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_COLUMN_CNT
}
} else {
if (scrollHorizontally) {
MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT
} else {
MEDIA_LANDSCAPE_COLUMN_CNT
}
}
}
private fun getDefaultMediaColumnCount() = context.resources.getInteger(
if (scrollHorizontally) {
R.integer.media_columns_horizontal_scroll
} else {
R.integer.media_columns_vertical_scroll
}
)
var albumCovers: String
get() = prefs.getString(ALBUM_COVERS, "")!!
set(albumCovers) = prefs.edit().putString(ALBUM_COVERS, albumCovers).apply()
fun parseAlbumCovers(): ArrayList<AlbumCover> {
val listType = object : TypeToken<List<AlbumCover>>() {}.type
return Gson().fromJson<ArrayList<AlbumCover>>(albumCovers, listType) ?: ArrayList(1)
}
var hideSystemUI: Boolean
get() = prefs.getBoolean(HIDE_SYSTEM_UI, false)
set(hideSystemUI) = prefs.edit().putBoolean(HIDE_SYSTEM_UI, hideSystemUI).apply()
var deleteEmptyFolders: Boolean
get() = prefs.getBoolean(DELETE_EMPTY_FOLDERS, false)
set(deleteEmptyFolders) = prefs.edit().putBoolean(DELETE_EMPTY_FOLDERS, deleteEmptyFolders).apply()
var allowPhotoGestures: Boolean
get() = prefs.getBoolean(ALLOW_PHOTO_GESTURES, false)
set(allowPhotoGestures) = prefs.edit().putBoolean(ALLOW_PHOTO_GESTURES, allowPhotoGestures).apply()
var allowVideoGestures: Boolean
get() = prefs.getBoolean(ALLOW_VIDEO_GESTURES, true)
set(allowVideoGestures) = prefs.edit().putBoolean(ALLOW_VIDEO_GESTURES, allowVideoGestures).apply()
var slideshowInterval: Int
get() = prefs.getInt(SLIDESHOW_INTERVAL, SLIDESHOW_DEFAULT_INTERVAL)
set(slideshowInterval) = prefs.edit().putInt(SLIDESHOW_INTERVAL, slideshowInterval).apply()
var slideshowIncludeVideos: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_VIDEOS, false)
set(slideshowIncludeVideos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_VIDEOS, slideshowIncludeVideos).apply()
var slideshowIncludeGIFs: Boolean
get() = prefs.getBoolean(SLIDESHOW_INCLUDE_GIFS, false)
set(slideshowIncludeGIFs) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_GIFS, slideshowIncludeGIFs).apply()
var slideshowRandomOrder: Boolean
get() = prefs.getBoolean(SLIDESHOW_RANDOM_ORDER, false)
set(slideshowRandomOrder) = prefs.edit().putBoolean(SLIDESHOW_RANDOM_ORDER, slideshowRandomOrder).apply()
var slideshowMoveBackwards: Boolean
get() = prefs.getBoolean(SLIDESHOW_MOVE_BACKWARDS, false)
set(slideshowMoveBackwards) = prefs.edit().putBoolean(SLIDESHOW_MOVE_BACKWARDS, slideshowMoveBackwards).apply()
var slideshowAnimation: Int
get() = prefs.getInt(SLIDESHOW_ANIMATION, SLIDESHOW_ANIMATION_SLIDE)
set(slideshowAnimation) = prefs.edit().putInt(SLIDESHOW_ANIMATION, slideshowAnimation).apply()
var loopSlideshow: Boolean
get() = prefs.getBoolean(SLIDESHOW_LOOP, false)
set(loopSlideshow) = prefs.edit().putBoolean(SLIDESHOW_LOOP, loopSlideshow).apply()
var tempFolderPath: String
get() = prefs.getString(TEMP_FOLDER_PATH, "")!!
set(tempFolderPath) = prefs.edit().putString(TEMP_FOLDER_PATH, tempFolderPath).apply()
var viewTypeFolders: Int
get() = prefs.getInt(VIEW_TYPE_FOLDERS, VIEW_TYPE_GRID)
set(viewTypeFolders) = prefs.edit().putInt(VIEW_TYPE_FOLDERS, viewTypeFolders).apply()
var viewTypeFiles: Int
get() = prefs.getInt(VIEW_TYPE_FILES, VIEW_TYPE_GRID)
set(viewTypeFiles) = prefs.edit().putInt(VIEW_TYPE_FILES, viewTypeFiles).apply()
var showExtendedDetails: Boolean
get() = prefs.getBoolean(SHOW_EXTENDED_DETAILS, false)
set(showExtendedDetails) = prefs.edit().putBoolean(SHOW_EXTENDED_DETAILS, showExtendedDetails).apply()
var hideExtendedDetails: Boolean
get() = prefs.getBoolean(HIDE_EXTENDED_DETAILS, false)
set(hideExtendedDetails) = prefs.edit().putBoolean(HIDE_EXTENDED_DETAILS, hideExtendedDetails).apply()
var extendedDetails: Int
get() = prefs.getInt(EXTENDED_DETAILS, EXT_RESOLUTION or EXT_LAST_MODIFIED or EXT_EXIF_PROPERTIES)
set(extendedDetails) = prefs.edit().putInt(EXTENDED_DETAILS, extendedDetails).apply()
var wasNewAppShown: Boolean
get() = prefs.getBoolean(WAS_NEW_APP_SHOWN, false)
set(wasNewAppShown) = prefs.edit().putBoolean(WAS_NEW_APP_SHOWN, wasNewAppShown).apply()
var lastFilepickerPath: String
get() = prefs.getString(LAST_FILEPICKER_PATH, "")!!
set(lastFilepickerPath) = prefs.edit().putString(LAST_FILEPICKER_PATH, lastFilepickerPath).apply()
var tempSkipDeleteConfirmation: Boolean
get() = prefs.getBoolean(TEMP_SKIP_DELETE_CONFIRMATION, false)
set(tempSkipDeleteConfirmation) = prefs.edit().putBoolean(TEMP_SKIP_DELETE_CONFIRMATION, tempSkipDeleteConfirmation).apply()
var wereFavoritesPinned: Boolean
get() = prefs.getBoolean(WERE_FAVORITES_PINNED, false)
set(wereFavoritesPinned) = prefs.edit().putBoolean(WERE_FAVORITES_PINNED, wereFavoritesPinned).apply()
var wasRecycleBinPinned: Boolean
get() = prefs.getBoolean(WAS_RECYCLE_BIN_PINNED, false)
set(wasRecycleBinPinned) = prefs.edit().putBoolean(WAS_RECYCLE_BIN_PINNED, wasRecycleBinPinned).apply()
var wasSVGShowingHandled: Boolean
get() = prefs.getBoolean(WAS_SVG_SHOWING_HANDLED, false)
set(wasSVGShowingHandled) = prefs.edit().putBoolean(WAS_SVG_SHOWING_HANDLED, wasSVGShowingHandled).apply()
var groupBy: Int
get() = prefs.getInt(GROUP_BY, GROUP_BY_NONE)
set(groupBy) = prefs.edit().putInt(GROUP_BY, groupBy).apply()
var useRecycleBin: Boolean
get() = prefs.getBoolean(USE_RECYCLE_BIN, true)
set(useRecycleBin) = prefs.edit().putBoolean(USE_RECYCLE_BIN, useRecycleBin).apply()
var bottomActions: Boolean
get() = prefs.getBoolean(BOTTOM_ACTIONS, true)
set(bottomActions) = prefs.edit().putBoolean(BOTTOM_ACTIONS, bottomActions).apply()
fun removeLastVideoPosition(path: String) {
prefs.edit().remove("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}").apply()
}
fun saveLastVideoPosition(path: String, value: Int) {
if (path.isNotEmpty()) {
prefs.edit().putInt("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}", value).apply()
}
}
fun getLastVideoPosition(path: String) = prefs.getInt("$LAST_VIDEO_POSITION_PREFIX${path.toLowerCase()}", 0)
fun getAllLastVideoPositions() = prefs.all.filterKeys {
it.startsWith(LAST_VIDEO_POSITION_PREFIX)
}
var rememberLastVideoPosition: Boolean
get() = prefs.getBoolean(REMEMBER_LAST_VIDEO_POSITION, false)
set(rememberLastVideoPosition) {
if (!rememberLastVideoPosition) {
getAllLastVideoPositions().forEach {
prefs.edit().remove(it.key).apply()
}
}
prefs.edit().putBoolean(REMEMBER_LAST_VIDEO_POSITION, rememberLastVideoPosition).apply()
}
var visibleBottomActions: Int
get() = prefs.getInt(VISIBLE_BOTTOM_ACTIONS, DEFAULT_BOTTOM_ACTIONS)
set(visibleBottomActions) = prefs.edit().putInt(VISIBLE_BOTTOM_ACTIONS, visibleBottomActions).apply()
// if a user hides a folder, then enables temporary hidden folder displaying, make sure we show it properly
var everShownFolders: Set<String>
get() = prefs.getStringSet(EVER_SHOWN_FOLDERS, getEverShownFolders())!!
set(everShownFolders) = prefs.edit().putStringSet(EVER_SHOWN_FOLDERS, everShownFolders).apply()
private fun getEverShownFolders() = hashSetOf(
internalStoragePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath,
"${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath}/Screenshots",
"$internalStoragePath/WhatsApp/Media/WhatsApp Images",
"$internalStoragePath/WhatsApp/Media/WhatsApp Images/Sent",
"$internalStoragePath/WhatsApp/Media/WhatsApp Video",
"$internalStoragePath/WhatsApp/Media/WhatsApp Video/Sent",
)
var showRecycleBinAtFolders: Boolean
get() = prefs.getBoolean(SHOW_RECYCLE_BIN_AT_FOLDERS, true)
set(showRecycleBinAtFolders) = prefs.edit().putBoolean(SHOW_RECYCLE_BIN_AT_FOLDERS, showRecycleBinAtFolders).apply()
var allowZoomingImages: Boolean
get() = prefs.getBoolean(ALLOW_ZOOMING_IMAGES, true)
set(allowZoomingImages) = prefs.edit().putBoolean(ALLOW_ZOOMING_IMAGES, allowZoomingImages).apply()
var lastBinCheck: Long
get() = prefs.getLong(LAST_BIN_CHECK, 0L)
set(lastBinCheck) = prefs.edit().putLong(LAST_BIN_CHECK, lastBinCheck).apply()
var showHighestQuality: Boolean
get() = prefs.getBoolean(SHOW_HIGHEST_QUALITY, false)
set(showHighestQuality) = prefs.edit().putBoolean(SHOW_HIGHEST_QUALITY, showHighestQuality).apply()
var showRecycleBinLast: Boolean
get() = prefs.getBoolean(SHOW_RECYCLE_BIN_LAST, false)
set(showRecycleBinLast) = prefs.edit().putBoolean(SHOW_RECYCLE_BIN_LAST, showRecycleBinLast).apply()
var allowDownGesture: Boolean
get() = prefs.getBoolean(ALLOW_DOWN_GESTURE, true)
set(allowDownGesture) = prefs.edit().putBoolean(ALLOW_DOWN_GESTURE, allowDownGesture).apply()
var lastEditorCropAspectRatio: Int
get() = prefs.getInt(LAST_EDITOR_CROP_ASPECT_RATIO, ASPECT_RATIO_FREE)
set(lastEditorCropAspectRatio) = prefs.edit().putInt(LAST_EDITOR_CROP_ASPECT_RATIO, lastEditorCropAspectRatio).apply()
var lastEditorCropOtherAspectRatioX: Float
get() = prefs.getFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X, 2f)
set(lastEditorCropOtherAspectRatioX) = prefs.edit().putFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X, lastEditorCropOtherAspectRatioX).apply()
var lastEditorCropOtherAspectRatioY: Float
get() = prefs.getFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y, 1f)
set(lastEditorCropOtherAspectRatioY) = prefs.edit().putFloat(LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y, lastEditorCropOtherAspectRatioY).apply()
var groupDirectSubfolders: Boolean
get() = prefs.getBoolean(GROUP_DIRECT_SUBFOLDERS, false)
set(groupDirectSubfolders) = prefs.edit().putBoolean(GROUP_DIRECT_SUBFOLDERS, groupDirectSubfolders).apply()
var showWidgetFolderName: Boolean
get() = prefs.getBoolean(SHOW_WIDGET_FOLDER_NAME, true)
set(showWidgetFolderName) = prefs.edit().putBoolean(SHOW_WIDGET_FOLDER_NAME, showWidgetFolderName).apply()
var allowOneToOneZoom: Boolean
get() = prefs.getBoolean(ALLOW_ONE_TO_ONE_ZOOM, false)
set(allowOneToOneZoom) = prefs.edit().putBoolean(ALLOW_ONE_TO_ONE_ZOOM, allowOneToOneZoom).apply()
var allowRotatingWithGestures: Boolean
get() = prefs.getBoolean(ALLOW_ROTATING_WITH_GESTURES, true)
set(allowRotatingWithGestures) = prefs.edit().putBoolean(ALLOW_ROTATING_WITH_GESTURES, allowRotatingWithGestures).apply()
var lastEditorDrawColor: Int
get() = prefs.getInt(LAST_EDITOR_DRAW_COLOR, primaryColor)
set(lastEditorDrawColor) = prefs.edit().putInt(LAST_EDITOR_DRAW_COLOR, lastEditorDrawColor).apply()
var lastEditorBrushSize: Int
get() = prefs.getInt(LAST_EDITOR_BRUSH_SIZE, 50)
set(lastEditorBrushSize) = prefs.edit().putInt(LAST_EDITOR_BRUSH_SIZE, lastEditorBrushSize).apply()
var showNotch: Boolean
get() = prefs.getBoolean(SHOW_NOTCH, true)
set(showNotch) = prefs.edit().putBoolean(SHOW_NOTCH, showNotch).apply()
var spamFoldersChecked: Boolean
get() = prefs.getBoolean(SPAM_FOLDERS_CHECKED, false)
set(spamFoldersChecked) = prefs.edit().putBoolean(SPAM_FOLDERS_CHECKED, spamFoldersChecked).apply()
var editorBrushColor: Int
get() = prefs.getInt(EDITOR_BRUSH_COLOR, -1)
set(editorBrushColor) = prefs.edit().putInt(EDITOR_BRUSH_COLOR, editorBrushColor).apply()
var editorBrushHardness: Float
get() = prefs.getFloat(EDITOR_BRUSH_HARDNESS, 0.5f)
set(editorBrushHardness) = prefs.edit().putFloat(EDITOR_BRUSH_HARDNESS, editorBrushHardness).apply()
var editorBrushSize: Float
get() = prefs.getFloat(EDITOR_BRUSH_SIZE, 0.05f)
set(editorBrushSize) = prefs.edit().putFloat(EDITOR_BRUSH_SIZE, editorBrushSize).apply()
var wereFavoritesMigrated: Boolean
get() = prefs.getBoolean(WERE_FAVORITES_MIGRATED, false)
set(wereFavoritesMigrated) = prefs.edit().putBoolean(WERE_FAVORITES_MIGRATED, wereFavoritesMigrated).apply()
var showFolderMediaCount: Int
get() = prefs.getInt(FOLDER_MEDIA_COUNT, FOLDER_MEDIA_CNT_LINE)
set(showFolderMediaCount) = prefs.edit().putInt(FOLDER_MEDIA_COUNT, showFolderMediaCount).apply()
var folderStyle: Int
get() = prefs.getInt(FOLDER_THUMBNAIL_STYLE, FOLDER_STYLE_SQUARE)
set(folderStyle) = prefs.edit().putInt(FOLDER_THUMBNAIL_STYLE, folderStyle).apply()
var limitFolderTitle: Boolean
get() = prefs.getBoolean(LIMIT_FOLDER_TITLE, false)
set(limitFolderTitle) = prefs.edit().putBoolean(LIMIT_FOLDER_TITLE, limitFolderTitle).apply()
var thumbnailSpacing: Int
get() = prefs.getInt(THUMBNAIL_SPACING, 1)
set(thumbnailSpacing) = prefs.edit().putInt(THUMBNAIL_SPACING, thumbnailSpacing).apply()
var fileRoundedCorners: Boolean
get() = prefs.getBoolean(FILE_ROUNDED_CORNERS, false)
set(fileRoundedCorners) = prefs.edit().putBoolean(FILE_ROUNDED_CORNERS, fileRoundedCorners).apply()
var customFoldersOrder: String
get() = prefs.getString(CUSTOM_FOLDERS_ORDER, "")!!
set(customFoldersOrder) = prefs.edit().putString(CUSTOM_FOLDERS_ORDER, customFoldersOrder).apply()
var avoidShowingAllFilesPrompt: Boolean
get() = prefs.getBoolean(AVOID_SHOWING_ALL_FILES_PROMPT, false)
set(avoidShowingAllFilesPrompt) = prefs.edit().putBoolean(AVOID_SHOWING_ALL_FILES_PROMPT, avoidShowingAllFilesPrompt).apply()
}
|
gpl-3.0
|
e80806231a3bb0686a9623ca28656f4c
| 45.245931 | 148 | 0.699617 | 4.186968 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/view/streak/notification/StreakNotificationDelegate.kt
|
1
|
8329
|
package org.stepik.android.view.streak.notification
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.TaskStackBuilder
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.DateTimeHelper
import org.stepic.droid.util.StepikUtil
import org.stepik.android.domain.base.analytic.BUNDLEABLE_ANALYTIC_EVENT
import org.stepik.android.domain.base.analytic.toBundle
import org.stepik.android.domain.streak.analytic.StreakNotificationClicked
import org.stepik.android.domain.streak.analytic.StreakNotificationDismissed
import org.stepik.android.domain.streak.analytic.StreakNotificationShown
import org.stepik.android.domain.user_activity.repository.UserActivityRepository
import org.stepik.android.view.base.receiver.DismissedNotificationReceiver
import org.stepik.android.view.notification.NotificationDelegate
import org.stepik.android.view.notification.StepikNotificationManager
import org.stepik.android.view.notification.helpers.NotificationHelper
import org.stepik.android.view.profile.ui.activity.ProfileActivity
import org.stepik.android.view.streak.model.StreakNotificationType
import java.util.Calendar
import javax.inject.Inject
class StreakNotificationDelegate
@Inject
constructor(
private val context: Context,
private val analytic: Analytic,
private val userActivityRepository: UserActivityRepository,
private val screenManager: ScreenManager,
private val sharedPreferenceHelper: SharedPreferenceHelper,
private val notificationHelper: NotificationHelper,
stepikNotificationManager: StepikNotificationManager
) : NotificationDelegate("show_streak_notification", stepikNotificationManager) {
companion object {
const val STREAK_NOTIFICATION_CLICKED = "streak_notification_clicked"
private const val STREAK_NOTIFICATION_ID = 3214L
}
override fun onNeedShowNotification() {
if (sharedPreferenceHelper.isStreakNotificationEnabled) {
scheduleStreakNotification()
val numberOfStreakNotifications = sharedPreferenceHelper.numberOfStreakNotifications
if (numberOfStreakNotifications < AppConstants.MAX_NUMBER_OF_NOTIFICATION_STREAK) {
try {
val pins: ArrayList<Long> = userActivityRepository.getUserActivities(sharedPreferenceHelper.profile?.id ?: throw Exception("User is not auth"))
.blockingGet()
.firstOrNull()
?.pins!!
val (currentStreak, isSolvedToday) = StepikUtil.getCurrentStreakExtended(pins)
if (currentStreak <= 0) {
analytic.reportEvent(Analytic.Streak.GET_ZERO_STREAK_NOTIFICATION)
showNotificationWithoutStreakInfo(StreakNotificationType.ZERO)
} else {
// if current streak is > 0 -> streaks works! -> continue send it
// it will reset before sending, after sending it will be incremented
sharedPreferenceHelper.resetNumberOfStreakNotifications()
if (isSolvedToday) {
showNotificationStreakImprovement(currentStreak)
} else {
showNotificationWithStreakCallToAction(currentStreak)
}
}
} catch (exception: Exception) {
// no internet || cant get streaks -> show some notification without streak information.
analytic.reportEvent(Analytic.Streak.GET_NO_INTERNET_NOTIFICATION)
showNotificationWithoutStreakInfo(StreakNotificationType.NO_INTERNET)
return
} finally {
sharedPreferenceHelper.incrementNumberOfNotifications()
}
} else {
// too many ignored notifications about streaks
streakNotificationNumberIsOverflow()
}
}
}
fun scheduleStreakNotification() {
if (sharedPreferenceHelper.isStreakNotificationEnabled) {
// plan new alarm
val hour = sharedPreferenceHelper.timeNotificationCode
val now = DateTimeHelper.nowUtc()
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
var nextNotificationMillis = calendar.timeInMillis
if (nextNotificationMillis < now) {
nextNotificationMillis += AppConstants.MILLIS_IN_24HOURS
}
scheduleNotificationAt(nextNotificationMillis)
}
}
private fun showNotificationStreakImprovement(currentStreak: Int) {
val message = context.resources.getString(R.string.streak_notification_message_improvement, currentStreak)
showNotificationStreakBase(message, StreakNotificationType.SOLVED_TODAY)
}
private fun showNotificationWithStreakCallToAction(currentStreak: Int) {
val message = context.resources.getQuantityString(R.plurals.streak_notification_message_call_to_action, currentStreak, currentStreak)
showNotificationStreakBase(message, StreakNotificationType.NOT_SOLVED_TODAY)
}
private fun showNotificationWithoutStreakInfo(notificationType: StreakNotificationType) {
val message = context.resources.getString(R.string.streak_notification_empty_number)
showNotificationStreakBase(message, notificationType)
}
private fun showNotificationStreakBase(message: String, notificationType: StreakNotificationType) {
val taskBuilder: TaskStackBuilder = getStreakNotificationTaskBuilder(notificationType)
val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification = null,
justText = message,
taskBuilder = taskBuilder,
title = context.getString(R.string.time_to_learn_notification_title),
deleteIntent = getDeleteIntentForStreaks(notificationType), id = STREAK_NOTIFICATION_ID
)
analytic.report(StreakNotificationShown(notificationType.type))
showNotification(STREAK_NOTIFICATION_ID, notification.build())
}
private fun getStreakNotificationTaskBuilder(notificationType: StreakNotificationType): TaskStackBuilder {
val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(context)
val myCoursesIntent = screenManager.getMyCoursesIntent(context) // This opens MainFeedActivity
myCoursesIntent.action = STREAK_NOTIFICATION_CLICKED
myCoursesIntent.putExtra(BUNDLEABLE_ANALYTIC_EVENT, StreakNotificationClicked(notificationType.type).toBundle())
taskBuilder.addNextIntent(myCoursesIntent)
return taskBuilder
}
private fun streakNotificationNumberIsOverflow() {
sharedPreferenceHelper.isStreakNotificationEnabled = false
val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(context)
val profileIntent = screenManager.getProfileIntent(context)
taskBuilder.addParentStack(ProfileActivity::class.java)
taskBuilder.addNextIntent(profileIntent)
val message = context.getString(R.string.streak_notification_not_working)
val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification = null,
justText = message,
taskBuilder = taskBuilder,
title = context.getString(R.string.time_to_learn_notification_title), id = STREAK_NOTIFICATION_ID
)
showNotification(STREAK_NOTIFICATION_ID, notification.build())
}
private fun getDeleteIntentForStreaks(notificationType: StreakNotificationType): PendingIntent {
val deleteIntent = DismissedNotificationReceiver.createStreakNotificationIntent(context, StreakNotificationDismissed(notificationType.type).toBundle())
return PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT)
}
}
|
apache-2.0
|
12464c7998118d17d71c48d467fe1462
| 51.721519 | 163 | 0.715332 | 5.418998 | false | false | false | false |
allotria/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/CommitDetailsListPanel.kt
|
3
|
5534
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.ui.details
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.vcs.ui.FontUtil
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.ui.details.commit.CommitDetailsPanel
import com.intellij.vcs.log.ui.details.commit.getCommitDetailsBackground
import org.jetbrains.annotations.Nls
import java.awt.*
import javax.swing.ScrollPaneConstants
import kotlin.math.max
import kotlin.math.min
abstract class CommitDetailsListPanel<Panel : CommitDetailsPanel>(parent: Disposable) :
BorderLayoutPanel(),
EditorColorsListener,
ComponentWithEmptyText {
companion object {
private const val MAX_ROWS = 50
private const val MIN_SIZE = 20
}
private val commitDetailsList = mutableListOf<Panel>()
private val viewPanel = ViewPanel()
private val loadingPanel = object : JBLoadingPanel(BorderLayout(), parent, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) {
override fun getBackground(): Color = getCommitDetailsBackground()
}.apply {
val scrollPane = JBScrollPane(
viewPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
)
scrollPane.border = JBUI.Borders.empty()
scrollPane.viewportBorder = JBUI.Borders.empty()
add(scrollPane, BorderLayout.CENTER)
}
private val mainContentPanel = object : BorderLayoutPanel() {
init {
isOpaque = false
addToCenter(loadingPanel)
}
val statusText: StatusText = object : StatusText(this) {
override fun isStatusVisible(): Boolean = isEmptyStatusVisible()
}
override fun paintChildren(g: Graphics) {
if (isEmptyStatusVisible()) {
statusText.paint(this, g)
}
else {
super.paintChildren(g)
}
}
}
init {
addToCenter(mainContentPanel)
}
fun startLoadingDetails() {
loadingPanel.startLoading()
}
fun stopLoadingDetails() {
loadingPanel.stopLoading()
}
fun setStatusText(@Nls(capitalization = Nls.Capitalization.Sentence) text: String) {
mainContentPanel.statusText.text = text
}
protected fun rebuildPanel(rows: Int): Int {
val oldRowsCount = commitDetailsList.size
val newRowsCount = min(rows, MAX_ROWS)
for (i in oldRowsCount until newRowsCount) {
val panel = getCommitDetailsPanel()
if (i != 0) {
viewPanel.add(SeparatorComponent(0, OnePixelDivider.BACKGROUND, null))
}
viewPanel.add(panel)
commitDetailsList.add(panel)
}
// clear superfluous items
while (viewPanel.componentCount != 0 && viewPanel.componentCount > 2 * newRowsCount - 1) {
viewPanel.remove(viewPanel.componentCount - 1)
}
while (commitDetailsList.size > newRowsCount) {
commitDetailsList.removeAt(commitDetailsList.size - 1)
}
if (rows > MAX_ROWS) {
viewPanel.add(SeparatorComponent(0, OnePixelDivider.BACKGROUND, null))
val label = JBLabel(VcsLogBundle.message("vcs.log.details.showing.selected.commits", MAX_ROWS, rows)).apply {
font = FontUtil.getCommitMetadataFont()
border = JBUI.Borders.emptyLeft(CommitDetailsPanel.SIDE_BORDER)
}
viewPanel.add(label)
}
revalidate()
repaint()
return newRowsCount
}
fun forEachPanelIndexed(f: (Int, Panel) -> Unit) {
commitDetailsList.forEachIndexed(f)
update()
}
fun setCommits(commits: List<VcsCommitMetadata>) {
rebuildPanel(commits.size)
forEachPanelIndexed { i, panel ->
val commit = commits[i]
panel.setCommit(commit)
}
}
fun update() {
commitDetailsList.forEach { it.update() }
}
protected open fun navigate(commitId: CommitId) {}
protected abstract fun getCommitDetailsPanel(): Panel
protected open fun isEmptyStatusVisible(): Boolean = commitDetailsList.isEmpty()
override fun getEmptyText(): StatusText = mainContentPanel.statusText
override fun globalSchemeChange(scheme: EditorColorsScheme?) {
update()
}
override fun getBackground(): Color = getCommitDetailsBackground()
override fun getMinimumSize(): Dimension {
val minimumSize = super.getMinimumSize()
return Dimension(max(minimumSize.width, JBUIScale.scale(MIN_SIZE)), max(minimumSize.height, JBUIScale.scale(MIN_SIZE)))
}
private inner class ViewPanel : ScrollablePanel(
VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)
) {
init {
isOpaque = false
border = JBUI.Borders.empty()
}
override fun getBackground(): Color = getCommitDetailsBackground()
}
}
|
apache-2.0
|
8debdb16f99bb8c1f593f4666275943a
| 30.448864 | 140 | 0.73708 | 4.326818 | false | false | false | false |
neo4j-graphql/neo4j-graphql
|
src/test/java/org/neo4j/graphql/GraphQLSchemaBuilderTest.kt
|
1
|
8038
|
package org.neo4j.graphql
import graphql.Scalars.GraphQLInt
import graphql.Scalars.GraphQLString
import graphql.language.ObjectTypeDefinition
import graphql.parser.Parser
import graphql.schema.*
import org.antlr.v4.runtime.misc.ParseCancellationException
import org.antlr.v4.runtime.InputMismatchException
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GraphQLSchemaBuilderTest {
@Test
fun emptyNode() {
GraphSchemaScanner.schema = null
GraphSchemaScanner.allTypes.clear()
val md = MetaData("Actor")
val schema = GraphQLSchemaBuilder(listOf(md))
val type: GraphQLObjectType = schema.toGraphQLObjectType(md)
assertEquals("Actor", type.name)
assertEquals(listOf("_id"), type.fieldDefinitions.map { it.name })
val queryType = schema.queryFields(listOf(md)).first()
assertEquals("Actor", queryType.name)
assertEquals(setOf("_id","_ids","first","offset"), queryType.arguments.map { it.name }.toSet())
val graphQLSchema = schema.buildSchema()
val ordering = graphQLSchema.getType("_ActorOrdering") as GraphQLEnumType?
assertNull(ordering)
}
@Test
fun mutationField() {
GraphSchemaScanner.schema = null
GraphSchemaScanner.allTypes.clear()
val md = MetaData("Actor")
md.addLabel("Person")
md.addProperty("name", MetaData.PropertyType("String", nonNull = 1))
val mutationFields = GraphQLSchemaBuilder(listOf(md)).mutationField(md, emptySet())
assertEquals(1,mutationFields.size)
assertEquals("createActor", mutationFields[0].name)
}
@Test
fun mutationFieldID() {
GraphSchemaScanner.schema = null
GraphSchemaScanner.allTypes.clear()
val md = MetaData("Actor")
md.addLabel("Person")
md.addProperty("name", MetaData.PropertyType("ID", nonNull = 1))
val mutationFields = GraphQLSchemaBuilder(listOf(md)).mutationField(md, emptySet())
assertEquals(4,mutationFields.size)
assertEquals("createActor", mutationFields[0].name)
assertEquals("updateActor", mutationFields[1].name)
assertEquals("mergeActor", mutationFields[2].name)
assertEquals("deleteActor", mutationFields[3].name)
}
@Test
fun inputType() {
val input = """
enum Gender { Female, Male }
input Test {
name: String = "Foo"
age: Int = 42
sex: Gender = Female
}
"""
val document = Parser().parseDocument(input)
val builder = GraphQLSchemaBuilder(emptyList())
val enums = builder.enumsFromDefinitions(document.definitions)
val inputTypes = builder.inputTypesFromDefinitions(document.definitions,enums)
assertEquals(1,inputTypes.size)
val type = inputTypes["Test"]!!
assertEquals("Test", type.name)
assertEquals(listOf("age","name","sex"), type.fields.map { it.name })
assertEquals(listOf(42L,"Foo","Female"), type.fields.map { it.defaultValue })
assertEquals(listOf(GraphQLInt, GraphQLString,enums.get("Gender")), type.fields.map { it.type })
}
@Test
fun descriptions() {
val idl = """
# GenderDesc
enum Gender {
# FemaleDesc
Female
}
# InputDesc
input Test {
# InputNameDesc
name: String = "Foo"
}
# TestObjectDesc
type TestObject {
# nameDesc
name: String
# otherDesc
other: [TestObject]
}
type QueryType {
# someQueryDesc
someQuery(
# someQueryNameDesc
name: String): [TestObject]
}
type MutationType {
# someUpdateDesc
someUpdate(
# someUpdateNameDesc
name: String): String
}
schema {
query: QueryType
mutation: MutationType
}
"""
try {
GraphSchemaScanner.allTypes.clear()
GraphSchemaScanner.schema = idl
val document = Parser().parseDocument(idl)
val builder = GraphQLSchemaBuilder(IDLParser.parse(idl).values)
val schema = builder.buildSchema()
val enum = builder.enumsFromDefinitions(document.definitions).values.first()
assertEquals("GenderDesc", enum.description)
assertEquals("FemaleDesc", enum.values.first().description)
val inputType = builder.inputTypesFromDefinitions(document.definitions).values.first()
assertEquals("InputDesc", inputType.description)
assertEquals("InputNameDesc", inputType.fields.first().description)
val mutation = schema.mutationType
val someUpdate = mutation.getFieldDefinition("someUpdate")
assertEquals("someUpdateDesc", someUpdate.description)
assertEquals("someUpdateNameDesc", someUpdate.getArgument("name").description)
val someQuery = schema.queryType.getFieldDefinition("someQuery")
assertEquals("someQueryDesc", someQuery.description)
assertEquals("someQueryNameDesc", someQuery.getArgument("name").description)
val type = schema.getType("TestObject") as GraphQLObjectType
assertEquals("TestObjectDesc", type.description)
assertEquals("nameDesc", type.getFieldDefinition("name").description)
assertEquals("otherDesc", type.getFieldDefinition("other").description)
} catch (e:ParseCancellationException) {
println("${e.message} cause: ${(e.cause as InputMismatchException?)?.offendingToken}")
throw e
}
}
@Test
fun mandatoryRelationship() {
val idl = """
type TestObject {
name: String
other: TestObject! @relation(name:"TEST")
}
"""
try {
GraphSchemaScanner.allTypes.clear()
GraphSchemaScanner.schema = idl
val document = Parser().parseDocument(idl)
val builder = GraphQLSchemaBuilder(IDLParser.parse(idl).values)
val schema = builder.buildSchema()
val other = (schema.getType("TestObject") as GraphQLObjectType).getFieldDefinition("other")
assertTrue(other.type is GraphQLNonNull)
assertEquals("TestObject",other.type.inner().name)
} catch (e:ParseCancellationException) {
println("${e.message} cause: ${(e.cause as InputMismatchException?)?.offendingToken}")
throw e
}
}
@Test
fun nestedInputType() {
val input = """
input Gender { female: Boolean }
input Test {
name: String = "Foo"
age: Int = 42
sex: Gender = { female: true }
}
type QueryType {
field(test:Test) : String
}
"""
val document = Parser().parseDocument(input)
val builder = GraphQLSchemaBuilder(emptyList())
val definitions = document.definitions
val inputTypes = builder.inputTypesFromDefinitions(definitions)
assertEquals(2,inputTypes.size)
val type = inputTypes["Test"]!!
assertEquals("Test", type.name)
assertEquals(listOf("age","name","sex"), type.fields.map { it.name })
assertEquals(listOf(42L, "Foo", mapOf("female" to true)), type.fields.map { it.defaultValue })
assertEquals(listOf("Int","String", "Gender"), type.fields.map { it.type }.map { when (it) {
is GraphQLScalarType -> it.name
is GraphQLTypeReference -> it.name
else -> null
} })
val queryFields = builder.toDynamicQueryOrMutationFields(definitions.filterIsInstance<ObjectTypeDefinition>().first().fieldDefinitions, inputTypes)
assertEquals(type, queryFields.values.first().getArgument("test").type)
}
@Test
fun enums() {
val input = """
enum Gender { Female, Male }
"""
val document = Parser().parseDocument(input)
val builder = GraphQLSchemaBuilder(emptyList())
val enums = builder.enumsFromDefinitions(document.definitions)
assertEquals(1,enums.size)
val type = enums["Gender"]!!
assertEquals("Gender", type.name)
assertEquals(listOf("Female", "Male"), type.values.map { it.name })
}
}
|
apache-2.0
|
e2c8c979770faae75c184ce39a61e47a
| 33.497854 | 155 | 0.658124 | 4.480491 | false | true | false | false |
grover-ws-1/http4k
|
http4k-core/src/test/kotlin/org/http4k/core/RequestTest.kt
|
1
|
657
|
package org.http4k.core
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Method.GET
import org.junit.Test
class RequestTest {
@Test
fun extracts_query_parameters() {
assertThat(requestWithQuery("foo=one&foo=two").queries("foo"), equalTo(listOf<String?>("one", "two")))
assertThat(requestWithQuery("foo=one&foo=two").query("foo")!!, equalTo("one"))
assertThat(requestWithQuery("foo=one&foo&foo=two").queries("foo"), equalTo(listOf("one", null, "two")))
}
private fun requestWithQuery(query: String) = Request(GET, Uri.of("http://ignore/?$query"))
}
|
apache-2.0
|
6d882efbf4896d5d92d1ab12fe5439ad
| 28.863636 | 111 | 0.697108 | 3.629834 | false | true | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-server/src/main/kotlin/slatekit/server/ktor/KtorUtils.kt
|
1
|
2936
|
package slatekit.server.ktor
import io.ktor.http.HttpMethod
import io.ktor.http.content.PartData
import io.ktor.request.*
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import slatekit.common.ext.toId
import slatekit.common.types.*
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
object KtorUtils {
/**
* Load json from the post/put body using json-simple
*/
fun loadJson(body: String, req: ApplicationRequest, addQueryParams: Boolean = false): JSONObject {
val isMultiPart = req.isMultipart()
val isBodyAllowed = isBodyAllowed(req.httpMethod)
val json = if (isBodyAllowed && !isMultiPart && !body.isNullOrEmpty()) {
val parser = JSONParser()
val root = parser.parse(body)
root as JSONObject
// Add query params
if (addQueryParams && !req.queryParameters.isEmpty()) {
req.queryParameters.names().forEach { key ->
root.put(key, req.queryParameters.get(key))
}
}
root
} else {
JSONObject()
}
return json
}
fun buildDoc(part: PartData.FileItem, stream: InputStream):ContentFile {
val bis = BufferedInputStream(stream)
val buf = ByteArrayOutputStream()
var ris = bis.read()
while (ris != -1) {
buf.write(ris.toByte().toInt())
ris = bis.read()
}
val defaultName = part.name ?: "file"
val name = cleanName(part.originalFileName, defaultName)
val contentType = when {
part.contentType?.contentType == null -> ContentTypes.Octet
part.contentType?.contentSubtype == null -> ContentTypes.Octet
else -> ContentType(part.contentType?.contentType + "/" + part.contentType?.contentSubtype, part.contentType?.contentSubtype ?: "")
}
val doc = ContentFile(name, buf.toByteArray(), null, contentType)
return doc
}
fun isBodyAllowed(method: HttpMethod): Boolean {
return when(method) {
HttpMethod.Post, HttpMethod.Put, HttpMethod.Patch, HttpMethod.Delete -> true
else -> false
}
}
fun cleanName(suppliedName:String?, fileName:String): String {
val fullname = when {
suppliedName == null -> fileName
suppliedName.isNullOrEmpty() -> fileName
else -> suppliedName
}
val info = extractInfo(fullname)
val name = info.first.toId()
return name
}
/**
* Remove this in place of some file utilities or Path
*/
fun extractInfo(fullName:String):Pair<String, String> {
val ndxDot = fullName.lastIndexOf(".")
val ext = fullName.substring(ndxDot + 1)
val name = fullName.substring(0, ndxDot)
return Pair(name, ext)
}
}
|
apache-2.0
|
1ae6227343464acfcd711c93b97863ca
| 32 | 144 | 0.611035 | 4.5875 | false | false | false | false |
zdary/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/LinkExtractor.kt
|
1
|
2684
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2LinkedFile
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Package
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Scm
internal class LinkExtractor(private val standardV2Package: StandardV2Package) {
fun scm(): InfoLink.ScmRepository? {
val scm = standardV2Package.scm ?: return null
val (scmUrl, isGitHub) = extractScmUrl(scm)
return when {
isGitHub -> InfoLink.ScmRepository.GitHub(scmUrl, standardV2Package.gitHub?.stars)
else -> InfoLink.ScmRepository.Generic(scmUrl)
}
}
private fun extractScmUrl(scm: StandardV2Scm): ScmUrl {
val scmUrl = scm.url
val isGitHub = scmUrl.contains("github.com", true)
val normalizedUrl = if (isGitHub) {
// Try to extract the GitHub URL from the SCM URL, since it looks like a GitHub URL
scmUrl.replace("((?:ssh|https)://)[email protected]".toRegex(RegexOption.IGNORE_CASE), "https://github.com")
.replace("github.com:", "github.com/")
.trim()
} else {
scmUrl.trim()
}
return ScmUrl(normalizedUrl, isGitHub)
}
private data class ScmUrl(val url: String, val isGitHub: Boolean)
fun projectWebsite(): InfoLink.ProjectWebsite? {
if (standardV2Package.url == null) return null
return InfoLink.ProjectWebsite(standardV2Package.url)
}
fun documentation(): InfoLink.Documentation? {
if (standardV2Package.gitHub?.communityProfile?.documentationUrl == null) return null
return InfoLink.Documentation(standardV2Package.gitHub.communityProfile.documentationUrl)
}
fun readme(): InfoLink.Readme? {
if (standardV2Package.gitHub?.communityProfile?.files?.readme == null) return null
val readmeUrl = standardV2Package.gitHub.communityProfile.files.readme.htmlUrl
?: standardV2Package.gitHub.communityProfile.files.readme.url
return InfoLink.Readme(readmeUrl)
}
fun licenses(): List<InfoLink.License> {
if (standardV2Package.licenses == null) return emptyList()
val otherLicenses = standardV2Package.licenses.otherLicenses?.map { it.asLicenseInfoLink() }
?: emptyList()
return listOf(standardV2Package.licenses.mainLicense.asLicenseInfoLink()) + otherLicenses
}
private fun StandardV2LinkedFile.asLicenseInfoLink() = InfoLink.License(
url = htmlUrl ?: url,
licenseName = name
)
}
|
apache-2.0
|
73d0fb6fcf1eb8610f0e0a3b20baa109
| 37.342857 | 118 | 0.690015 | 4.240126 | false | false | false | false |
leafclick/intellij-community
|
platform/statistics/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt
|
1
|
9824
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.utils
import com.intellij.ide.plugins.PluginInfoProvider
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.beans.*
import com.intellij.internal.statistic.eventLog.EventLogConfiguration
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.getProjectCacheFileName
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Getter
import com.intellij.openapi.util.TimeoutCachedValue
import com.intellij.util.containers.ObjectIntHashMap
import gnu.trove.THashSet
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
fun getProjectId(project: Project): String {
return EventLogConfiguration.anonymize(project.getProjectCacheFileName())
}
fun addPluginInfoTo(info: PluginInfo, data : MutableMap<String, Any>) {
data["plugin_type"] = info.type.name
if (!info.type.isSafeToReport()) return
val id = info.id
if (!id.isNullOrEmpty()) {
data["plugin"] = id
}
val version = info.version
if (!version.isNullOrEmpty()) {
data["plugin_version"] = version
}
}
fun isDevelopedByJetBrains(pluginId: PluginId?): Boolean {
val plugin = PluginManagerCore.getPlugin(pluginId)
return plugin == null || PluginManager.isDevelopedByJetBrains(plugin.vendor)
}
/**
* @deprecated will be deleted in 2019.3
*
* Report setting name as event id and enabled/disabled state in event data with MetricEvent class.
* @see newBooleanMetric(java.lang.String, boolean)*
*/
@Deprecated("Report enabled or disabled setting as MetricEvent")
fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor {
return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1)
}
/**
* @deprecated will be deleted in 2019.3
*
* Report setting name as event id and setting value in event data with MetricEvent class.
* @see newMetric(java.lang.String, Enum)*
*/
@Deprecated("Report enum settings as MetricEvent")
fun getEnumUsage(key: String, value: Enum<*>?): UsageDescriptor {
return UsageDescriptor(key + "." + value?.name?.toLowerCase(Locale.ENGLISH), 1)
}
/**
* @deprecated will be deleted in 2019.3
* This method should be used only for a transition period for existing counter metrics.
* New metrics should report absolute counter value by
* @see newCounterMetric(java.lang.String, int)
*
* Constructs a proper UsageDescriptor for a counting value.
* NB:
* (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined.
* (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported:
* `git.commit.count.<1`.
*
* @key The key prefix which will be appended with "." and range code.
* @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly.
* @value Value to be checked among the given ranges.
*/
fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor {
return UsageDescriptor("$key." + getCountingStepName(value, steps), 1)
}
fun getCountingStepName(value: Int, steps: List<Int>): String {
if (steps.isEmpty()) return value.toString()
if (value < steps[0]) return "<" + steps[0]
var stepIndex = 0
while (stepIndex < steps.size - 1) {
if (value < steps[stepIndex + 1]) break
stepIndex++
}
val step = steps[stepIndex]
val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1
return humanize(step) + if (addPlus) "+" else ""
}
/**
* [getCountingUsage] with steps (0, 1, 2, 3, 5, 10, 15, 30, 50, 100, 500, 1000, 5000, 10000, ...)
*/
fun getCountingUsage(key: String, value: Int): UsageDescriptor {
if (value > Int.MAX_VALUE / 10) return UsageDescriptor("$key.MANY", 1)
if (value < 0) return UsageDescriptor("$key.<0", 1)
if (value < 3) return UsageDescriptor("$key.$value", 1)
val fixedSteps = listOf(3, 5, 10, 15, 30, 50)
var step = fixedSteps.last { it <= value }
while (true) {
if (value < step * 2) break
step *= 2
if (value < step * 5) break
step *= 5
}
val stepName = humanize(step)
return UsageDescriptor("$key.$stepName+", 1)
}
private const val kilo = 1000
private val mega = kilo * kilo
private fun humanize(number: Int): String {
if (number == 0) return "0"
val m = number / mega
val k = (number % mega) / kilo
val r = (number % kilo)
val ms = if (m > 0) "${m}M" else ""
val ks = if (k > 0) "${k}K" else ""
val rs = if (r > 0) "${r}" else ""
return ms + ks + rs
}
/**
* @deprecated will be deleted in 2019.3
*
* Report setting name as event id and setting value in event data with MetricEvent class.
*
* @see addIfDiffers
* @see addBoolIfDiffers
* @see addCounterIfDiffers
*/
fun <T> addIfDiffers(set: MutableSet<in UsageDescriptor>, settingsBean: T, defaultSettingsBean: T,
valueFunction: (T) -> Any, featureIdPrefix: String) {
addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, { "$featureIdPrefix.$it" })
}
/**
* @deprecated will be deleted in 2019.3
*
* Report setting name as event id and setting value in event data with MetricEvent class.
*
* @see addIfDiffers
* @see addBoolIfDiffers
* @see addCounterIfDiffers
*/
fun <T, V> addIfDiffers(set: MutableSet<in UsageDescriptor>, settingsBean: T, defaultSettingsBean: T,
valueFunction: (T) -> V,
featureIdFunction: (V) -> String) {
val value = valueFunction(settingsBean)
val defaultValue = valueFunction(defaultSettingsBean)
if (!Comparing.equal(value, defaultValue)) {
set.add(UsageDescriptor(featureIdFunction(value), 1))
}
}
fun toUsageDescriptors(result: ObjectIntHashMap<String>): Set<UsageDescriptor> {
if (result.isEmpty) {
return emptySet()
}
else {
val descriptors = THashSet<UsageDescriptor>(result.size())
result.forEachEntry { key, value ->
descriptors.add(UsageDescriptor(key, value))
true
}
return descriptors
}
}
fun merge(first: Set<UsageDescriptor>, second: Set<UsageDescriptor>): Set<UsageDescriptor> {
if (first.isEmpty()) {
return second
}
if (second.isEmpty()) {
return first
}
val merged = ObjectIntHashMap<String>()
addAll(merged, first)
addAll(merged, second)
return toUsageDescriptors(merged)
}
private fun addAll(result: ObjectIntHashMap<String>, usages: Set<UsageDescriptor>) {
for (usage in usages) {
val key = usage.key
result.put(key, result.get(key, 0) + usage.value)
}
}
private val pluginIdsFromOfficialJbPluginRepo: Getter<Set<PluginId>> = TimeoutCachedValue(1, TimeUnit.HOURS) {
// before loading default repository plugins lets check it's not changed, and is really official JetBrains repository
try {
val cached = getPluginInfoProvider()?.loadCachedPlugins()
if (cached != null) {
return@TimeoutCachedValue cached.mapNotNullTo(HashSet(cached.size)) { it.pluginId }
}
}
catch (ignored: IOException) {
}
// schedule plugins loading, will take them the next time
ApplicationManager.getApplication().executeOnPooledThread {
try {
getPluginInfoProvider()?.loadPlugins(null) ?: emptySet<PluginId>()
}
catch (ignored: IOException) {
}
}
//report nothing until repo plugins loaded
emptySet<PluginId>()
}
fun getPluginInfoProvider(): PluginInfoProvider? {
return ApplicationManager.getApplication()?.let { ServiceManager.getService(PluginInfoProvider::class.java) }
}
/**
* Checks this plugin is created by JetBrains or from official repository, so API from it may be reported
*/
internal fun isSafeToReportFrom(descriptor: PluginDescriptor): Boolean {
if (PluginManager.isDevelopedByJetBrains(descriptor)) {
return true
}
else if (descriptor.isBundled) {
// bundled, but not from JetBrains, so, some custom unknown plugin
return false
}
// only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance -
// they are also considered bundled) would be reported
val pluginId = descriptor.pluginId ?: return false
return isPluginFromOfficialJbPluginRepo(pluginId)
}
internal fun isPluginFromOfficialJbPluginRepo(pluginId: PluginId?): Boolean {
// not official JetBrains repository - is used, so, not safe to report
if (!ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
return false
}
// if in official JetBrains repository, then it is safe to report
return pluginIdsFromOfficialJbPluginRepo.get().contains(pluginId)
}
/**
* Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository,
* so API from it may be reported
*/
fun getPluginType(clazz: Class<*>): PluginType {
val plugin = PluginManagerCore.getPluginDescriptorOrPlatformByClassName(clazz.name) ?: return PluginType.PLATFORM
if (PluginManager.isDevelopedByJetBrains(plugin)) {
return if (plugin.isBundled) PluginType.JB_BUNDLED else PluginType.JB_NOT_BUNDLED
}
// only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance -
// they are also considered bundled) would be reported
val listed = !plugin.isBundled && isSafeToReportFrom(plugin)
return if (listed) PluginType.LISTED else PluginType.NOT_LISTED
}
|
apache-2.0
|
31ec9bc7290235d0575949734877edc5
| 34.215054 | 140 | 0.725265 | 4.037813 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/writer/Writer.kt
|
1
|
5451
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.utils.writer
import slatekit.common.newline
interface Writer {
val SPACE: String get() = " "
val TAB: String get() = " "
val NEWLINE: String get() = newline
/**
* Map the text type to functions that can implement it.
*/
val lookup: Map<TextType, (String, Boolean) -> Unit> get() = mapOf(
TextType.Title to this::title,
TextType.Subtitle to this::subTitle,
TextType.Url to this::url,
TextType.Important to this::important,
TextType.Highlight to this::highlight,
TextType.Success to this::success,
TextType.Failure to this::failure,
TextType.Text to this::text
)
/**
* Write many items based on the semantic modes
*
* @param items
*/
fun writeItems(items: List<TextOutput>) {
items.forEach { item -> writeItem(item.textType, item.msg, item.endLine) }
}
/**
* Write a single item based on the semantic textType
*
* @param mode
* @param msg
* @param endLine
*/
fun writeItem(mode: TextType, msg: String, endLine: Boolean) {
lookup[mode]?.invoke(msg, endLine)
}
/**
* Writes the text using the TextType
*
* @param mode
* @param text
* @param endLine
*/
fun write(mode: TextType, text: String, endLine: Boolean = true)
/**
* prints a empty line
*/
fun line() = write(TextType.NewLine, NEWLINE, false)
/**
* prints a empty line
*/
fun lines(count: Int) = (0..count).forEach { line() }
/**
* prints a tab count times
*
* @param count
*/
fun tab(count: Int = 1) = (0..count).forEach { write(TextType.Tab, TAB, false) }
/**
* prints text in title format ( UPPERCASE and BLUE )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun title(text: String, endLine: Boolean = true): Unit = write(TextType.Title, text, endLine)
/**
* prints text in subtitle format ( CYAN )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun subTitle(text: String, endLine: Boolean = true): Unit = write(TextType.Subtitle, text, endLine)
/**
* prints text in url format ( BLUE )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun url(text: String, endLine: Boolean = true): Unit = write(TextType.Url, text, endLine)
/**
* prints text in important format ( RED )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun important(text: String, endLine: Boolean = true): Unit = write(TextType.Important, text, endLine)
/**
* prints text in highlight format ( YELLOW )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun highlight(text: String, endLine: Boolean = true): Unit = write(TextType.Highlight, text, endLine)
/**
* prints text in title format ( UPPERCASE and BLUE )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun success(text: String, endLine: Boolean = true): Unit = write(TextType.Success, text, endLine)
/**
* prints text in error format ( RED )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun failure(text: String, endLine: Boolean = true): Unit = write(TextType.Failure, text, endLine)
/**
* prints text in normal format ( WHITE )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun text(text: String, endLine: Boolean = true): Unit = write(TextType.Text, text, endLine)
/**
* prints text in normal format ( WHITE )
*
* @param text : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun label(text: String, endLine: Boolean = true):Unit = write(TextType.Label, text, endLine)
/**
* Prints a list of items with indentation
*
* @param items
* @param isOrdered
*/
fun list(items: List<Any>, isOrdered: Boolean = false) {
for (ndx in 0..items.size) {
val item = items[ndx]
val value = item.toString()
val prefix = if (isOrdered) (ndx + 1).toString() + ". " else "- "
text(TAB + prefix + value, endLine = true)
}
line()
}
/**
* prints text using a label : value format
*
* @param key:
* @param value : the text to print
* @param endLine : whether or not to include a newline at the end
*/
fun keyValue(key: String, value: String, endLine: Boolean = true) {
label("$key = ", false)
text(value, endLine)
}
}
|
apache-2.0
|
32fe75ecbd1bbe77fbda8d2cdc9c867d
| 28.464865 | 105 | 0.592001 | 3.984649 | false | false | false | false |
AndroidX/androidx
|
glance/glance/src/androidMain/kotlin/androidx/glance/session/InteractiveFrameClock.kt
|
3
|
4452
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.session
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.BroadcastFrameClock
import androidx.compose.runtime.MonotonicFrameClock
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
/**
* A frame clock implementation that supports interactive mode.
*
* By default, this frame clock sends frames at its baseline rate. When startInteractive() is
* called, the frame clock sends frames at its interactive rate so that awaiters can respond more
* quickly to user interactions. After the interactive timeout is passed, the frame rate is reset to
* its baseline.
*/
internal class InteractiveFrameClock(
private val scope: CoroutineScope,
private val baselineHz: Int = 5,
private val interactiveHz: Int = 20,
private val interactiveTimeoutMs: Long = 5_000,
private val nanoTime: () -> Long = { System.nanoTime() }
) : MonotonicFrameClock {
companion object {
private const val NANOSECONDS_PER_SECOND = 1_000_000_000L
private const val NANOSECONDS_PER_MILLISECOND = 1_000_000L
private const val TAG = "InteractiveFrameClock"
private const val DEBUG = false
}
private val frameClock: BroadcastFrameClock = BroadcastFrameClock { onNewAwaiters() }
private val lock = Any()
private var currentHz = baselineHz
private var lastFrame = 0L
private var interactiveCoroutine: CancellableContinuation<Unit>? = null
/**
* Set the frame rate to [interactiveHz]. After [interactiveTimeoutMs] has passed, the frame
* rate is reset to [baselineHz]. If this function is called concurrently with itself, the
* previous call is cancelled and a new interactive period is started.
*/
suspend fun startInteractive() = withTimeoutOrNull(interactiveTimeoutMs) {
stopInteractive()
suspendCancellableCoroutine { co ->
if (DEBUG) Log.d(TAG, "Starting interactive mode at ${interactiveHz}hz")
synchronized(lock) {
currentHz = interactiveHz
interactiveCoroutine = co
}
co.invokeOnCancellation {
if (DEBUG) Log.d(TAG, "Resetting frame rate to baseline at ${baselineHz}hz")
synchronized(lock) {
currentHz = baselineHz
interactiveCoroutine = null
}
}
}
}
/**
* Cancel the call to startInteractive() if running, and reset the frame rate to baseline.
*/
fun stopInteractive() {
synchronized(lock) {
interactiveCoroutine?.cancel()
}
}
override suspend fun <R> withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R {
if (DEBUG) Log.d(TAG, "received frame to run")
return frameClock.withFrameNanos(onFrame)
}
private fun onNewAwaiters() {
val now = nanoTime()
val period: Long
val minPeriod: Long
synchronized(lock) {
period = now - lastFrame
minPeriod = NANOSECONDS_PER_SECOND / currentHz
}
if (period >= minPeriod) {
sendFrame(now)
} else {
scope.launch {
delay((minPeriod - period) / NANOSECONDS_PER_MILLISECOND)
sendFrame(nanoTime())
}
}
}
private fun sendFrame(now: Long) {
if (DEBUG) Log.d(TAG, "Sending next frame")
frameClock.sendFrame(now)
synchronized(lock) {
lastFrame = now
}
}
@VisibleForTesting
internal fun currentHz() = synchronized(lock) { currentHz }
}
|
apache-2.0
|
28b0693f3c23d8ba68326f8389b02bea
| 35.203252 | 100 | 0.667116 | 4.66178 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansLoginActivity.kt
|
1
|
4814
|
package info.nightscout.androidaps.plugins.general.openhumans
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.browser.customtabs.CustomTabsIntent
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class OpenHumansLoginActivity : NoSplashAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_open_humans_login)
val button = findViewById<Button>(R.id.button)
val checkbox = findViewById<CheckBox>(R.id.checkbox)
button.setOnClickListener {
if (checkbox.isChecked) {
CustomTabsIntent.Builder().build().launchUrl(this, Uri.parse(OpenHumansUploader.AUTH_URL))
} else {
Toast.makeText(this, R.string.you_need_to_accept_the_of_use_first, Toast.LENGTH_SHORT).show()
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val code = intent.data?.getQueryParameter("code")
if (supportFragmentManager.fragments.size == 0 && code != null) {
ExchangeAuthTokenDialog(code).show(supportFragmentManager, "ExchangeAuthTokenDialog")
}
}
class ExchangeAuthTokenDialog : DaggerDialogFragment() {
@Inject
lateinit var openHumansUploader: OpenHumansUploader
private var disposable: Disposable? = null
init {
isCancelable = false
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setTitle(R.string.completing_login)
.setMessage(R.string.please_wait)
.create()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
disposable = openHumansUploader.login(arguments?.getString("authToken")!!).subscribeOn(Schedulers.io()).subscribe({
dismiss()
SetupDoneDialog().show(parentFragmentManager, "SetupDoneDialog")
}, {
dismiss()
ErrorDialog(it.message).show(parentFragmentManager, "ErrorDialog")
})
}
override fun onDestroy() {
disposable?.dispose()
super.onDestroy()
}
companion object {
operator fun invoke(authToken: String): ExchangeAuthTokenDialog {
val dialog = ExchangeAuthTokenDialog()
val args = Bundle()
args.putString("authToken", authToken)
dialog.arguments = args
return dialog
}
}
}
class ErrorDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val message = arguments?.getString("message")
val shownMessage = if (message == null) getString(R.string.there_was_an_error)
else "${getString(R.string.there_was_an_error)}\n\n$message"
return AlertDialog.Builder(requireActivity())
.setTitle(R.string.error)
.setMessage(shownMessage)
.setPositiveButton(R.string.close, null)
.create()
}
companion object {
operator fun invoke(message: String?): ErrorDialog {
val dialog = ErrorDialog()
val args = Bundle()
args.putString("message", message)
dialog.arguments = args
return dialog
}
}
}
class SetupDoneDialog : DialogFragment() {
init {
isCancelable = false
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setTitle(R.string.successfully_logged_in)
.setMessage(R.string.setup_will_continue_in_background)
.setCancelable(false)
.setPositiveButton(R.string.close) { _, _ ->
requireActivity().run {
setResult(FragmentActivity.RESULT_OK)
requireActivity().finish()
}
}
.create()
}
}
}
|
agpl-3.0
|
f15c6a38433a70b7dfb77156c8bf20dc
| 33.891304 | 127 | 0.614458 | 5.266958 | false | false | false | false |
fabmax/kool
|
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/ShaderGeneratorImplVk.kt
|
1
|
11365
|
package de.fabmax.kool.platform.vk
import de.fabmax.kool.KoolContext
import de.fabmax.kool.modules.ksl.KslShader
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.shadermodel.CodeGenerator
import de.fabmax.kool.pipeline.shadermodel.ShaderGenerator
import de.fabmax.kool.pipeline.shadermodel.ShaderGraph
import de.fabmax.kool.pipeline.shadermodel.ShaderModel
import de.fabmax.kool.util.logE
class ShaderGeneratorImplVk : ShaderGenerator() {
private val shaderCodes = mutableMapOf<String, ShaderCode>()
private fun compile(vertexShaderSrc: String, fragmentShaderSrc: String): ShaderCode {
val codeKey = vertexShaderSrc + fragmentShaderSrc
var code = shaderCodes[codeKey]
if (code == null) {
try {
code = ShaderCode.vkCodeFromSource(vertexShaderSrc, fragmentShaderSrc)
shaderCodes[codeKey] = code
} catch (e: Exception) {
logE { "Compilation failed: $e" }
printCode(vertexShaderSrc, fragmentShaderSrc)
throw RuntimeException(e)
}
}
return code
}
fun generateKslShader(shader: KslShader, pipelineLayout: Pipeline.Layout): ShaderCode {
val src = KslGlslGeneratorVk(pipelineLayout).generateProgram(shader.program)
if (shader.program.dumpCode) {
src.dump()
}
return compile(src.vertexSrc, src.fragmentSrc)
}
override fun generateShader(model: ShaderModel, pipelineLayout: Pipeline.Layout, ctx: KoolContext): ShaderCode {
val (vertShader, fragShader) = generateCode(model, pipelineLayout)
if (model.dumpCode) {
printCode(vertShader, fragShader)
}
return compile(vertShader, fragShader)
}
private fun printCode(vertShader: String, fragShader: String) {
println("Vertex shader:\n\n")
vertShader.lines().forEachIndexed { i, l ->
println(String.format("%3d: %s", i+1, l))
}
println("Fragment shader:\n\n")
fragShader.lines().forEachIndexed { i, l ->
println(String.format("%3d: %s", i+1, l))
}
}
private fun generateCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): Pair<String, String> {
val vertShader = generateVertexShaderCode(model, pipelineLayout)
val fragShader = generateFragmentShaderCode(model, pipelineLayout)
return vertShader to fragShader
}
private fun generateVertexShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String {
val codeGen = CodeGen()
model.vertexStageGraph.generateCode(codeGen)
return """
#version 450
${model.infoStr()}
// descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.VERTEX_SHADER)}
// vertex attributes ${generateAttributeBindings(pipelineLayout)}
// outputs ${model.vertexStageGraph.generateStageOutputs()}
// functions
${codeGen.generateFunctions()}
void main() {
${codeGen.generateMain()}
gl_Position = ${model.vertexStageGraph.positionOutput.variable.ref4f()};
}
""".trimIndent()
}
private fun generateFragmentShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String {
val codeGen = CodeGen()
model.fragmentStageGraph.generateCode(codeGen)
return """
#version 450
precision highp float;
${model.infoStr()}
// descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.FRAGMENT_SHADER)}
// inputs ${model.fragmentStageGraph.generateStageInputs()}
// functions
${codeGen.generateFunctions()}
void main() {
${codeGen.generateMain()}
}
""".trimIndent()
}
private fun ShaderModel.infoStr(): String {
return modelName.lines().joinToString { "// $it\n"}
}
private fun generateDescriptorBindings(pipelineLayout: Pipeline.Layout, stage: ShaderStage): String {
val srcBuilder = StringBuilder("\n")
pipelineLayout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
if (desc.stages.contains(stage)) {
when (desc) {
is UniformBuffer -> srcBuilder.append(generateUniformBuffer(set, desc))
is TextureSampler1d -> srcBuilder.append(generateTextureSampler1d(set, desc))
is TextureSampler2d -> srcBuilder.append(generateTextureSampler2d(set, desc))
is TextureSampler3d -> srcBuilder.append(generateTextureSampler3d(set, desc))
is TextureSamplerCube -> srcBuilder.append(generateCubeMapSampler(set, desc))
}
}
}
}
var offset = 0
pipelineLayout.pushConstantRanges.forEach { pcr ->
if (pcr.stages.contains(stage)) {
srcBuilder.appendln(8, "layout(push_constant) uniform ${pcr.name} {")
pcr.pushConstants.forEach { u ->
srcBuilder.appendln(12, "${u.declare()};")
}
srcBuilder.appendln(8, "}${pcr.instanceName ?: ""};")
}
offset += pcr.size
}
return srcBuilder.toString()
}
private fun generateUniformBuffer(set: DescriptorSetLayout, desc: UniformBuffer): String {
val srcBuilder = StringBuilder()
.appendln(8, "layout(set=${set.set}, binding=${desc.binding}) uniform ${desc.name} {")
desc.uniforms.forEach { u ->
srcBuilder.appendln(12, "${u.declare()};")
}
srcBuilder.appendln(8, "}${desc.instanceName ?: ""};")
return srcBuilder.toString()
}
private fun generateTextureSampler1d(set: DescriptorSetLayout, desc: TextureSampler1d): String {
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "layout(set=${set.set}, binding=${desc.binding}) uniform sampler2D ${desc.name}$arraySuffix;\n"
}
private fun generateTextureSampler2d(set: DescriptorSetLayout, desc: TextureSampler2d): String {
val samplerType = if (desc.isDepthSampler) "sampler2DShadow" else "sampler2D"
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "layout(set=${set.set}, binding=${desc.binding}) uniform $samplerType ${desc.name}$arraySuffix;\n"
}
private fun generateTextureSampler3d(set: DescriptorSetLayout, desc: TextureSampler3d): String {
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "layout(set=${set.set}, binding=${desc.binding}) uniform sampler3D ${desc.name}$arraySuffix;\n"
}
private fun generateCubeMapSampler(set: DescriptorSetLayout, desc: TextureSamplerCube): String {
val samplerType = if (desc.isDepthSampler) "samplerCubeShadow" else "samplerCube"
val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" }
return "layout(set=${set.set}, binding=${desc.binding}) uniform $samplerType ${desc.name}$arraySuffix;\n"
}
private fun generateAttributeBindings(pipelineLayout: Pipeline.Layout): String {
val srcBuilder = StringBuilder("\n")
pipelineLayout.vertices.bindings.forEach { binding ->
binding.vertexAttributes.forEach { attr ->
srcBuilder.appendln(8, "layout(location=${attr.location}) in ${attr.type.glslType} ${attr.name};")
}
}
return srcBuilder.toString()
}
private fun ShaderGraph.generateStageInputs(): String {
val srcBuilder = StringBuilder("\n")
inputs.forEach {
val flat = if (it.isFlat) "flat" else ""
srcBuilder.appendln(8, "layout(location=${it.location}) $flat in ${it.variable.glslType()} ${it.variable.name};")
}
return srcBuilder.toString()
}
private fun ShaderGraph.generateStageOutputs(): String {
val srcBuilder = StringBuilder("\n")
outputs.forEach {
val flat = if (it.isFlat) "flat" else ""
srcBuilder.appendln(8, "layout(location=${it.location}) $flat out ${it.variable.glslType()} ${it.variable.name};")
}
return srcBuilder.toString()
}
private fun StringBuilder.appendln(indent: Int, line: String) = append(indent, "$line\n")
private fun StringBuilder.append(indent: Int, line: String) = append(String.format("%${indent}s%s", "", line))
private fun Uniform<*>.declare(): String {
return when (this) {
is Uniform1f -> "float $name"
is Uniform2f -> "vec2 $name"
is Uniform3f -> "vec3 $name"
is Uniform4f -> "vec4 $name"
is UniformColor -> "vec4 $name"
is Uniform1fv -> "float $name[$length]"
is Uniform2fv -> "vec2 $name[$length]"
is Uniform3fv -> "vec3 $name[$length]"
is Uniform4fv -> "vec4 $name[$length]"
is UniformMat3f -> "mat3 $name"
is UniformMat3fv -> "mat3 $name[$length"
is UniformMat4f -> "mat4 $name"
is UniformMat4fv -> "mat4 $name[$length]"
is Uniform1i -> "int $name"
is Uniform2i -> "ivec2 $name"
is Uniform3i -> "ivec3 $name"
is Uniform4i -> "ivec4 $name"
is Uniform1iv -> "int $name[$length]"
is Uniform2iv -> "ivec2 $name[$length]"
is Uniform3iv -> "ivec3 $name[$length]"
is Uniform4iv -> "ivec4 $name[$length]"
}
}
private class CodeGen : CodeGenerator {
val functions = mutableMapOf<String, String>()
val mainCode = mutableListOf<String>()
override fun appendFunction(name: String, glslCode: String) {
functions[name] = glslCode
}
override fun appendMain(glslCode: String) {
mainCode += glslCode
}
override fun sampleTexture1d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, "vec2($texCoords, 0.0)", lod)
override fun sampleTexture2d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
override fun sampleTexture2dDepth(texName: String, texCoords: String): String {
return "textureProj($texName, $texCoords).x"
}
override fun sampleTexture3d(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
override fun sampleTextureCube(texName: String, texCoords: String, lod: String?) =
sampleTexture(texName, texCoords, lod)
fun generateFunctions(): String = functions.values.joinToString("\n")
fun generateMain(): String = mainCode.joinToString("\n")
private fun sampleTexture(texName: String, texCoords: String, lod: String?): String {
return if (lod == null) {
"texture($texName, $texCoords)"
} else {
"textureLod($texName, $texCoords, $lod)"
}
}
}
}
|
apache-2.0
|
92f4c117f41ca2e338c2d4514d1de59f
| 40.940959 | 126 | 0.608183 | 4.337786 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/versions/UnsupportedAbiVersionNotificationPanelProvider.kt
|
1
|
16145
|
// 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.versions
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.compiler.CompilerManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.ui.EditorNotificationProvider.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NotNull
import org.jetbrains.kotlin.idea.*
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.util.application.invokeLater
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.isKotlinFileType
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.isJvm
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.util.function.Function
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.event.HyperlinkEvent
class UnsupportedAbiVersionNotificationPanelProvider : EditorNotificationProvider {
private fun doCreate(fileEditor: FileEditor, project: Project, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>): EditorNotificationPanel {
val answer = ErrorNotificationPanel(fileEditor)
val badRootFiles = badVersionedRoots.map { it.file }
val badRuntimeLibraries: List<Library> = ArrayList<Library>().also { list ->
project.forEachAllUsedLibraries { library ->
val runtimeJar = LibraryJarDescriptor.STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) }
val jsLibJar = LibraryJarDescriptor.JS_STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) }
if (badRootFiles.contains(runtimeJar) || badRootFiles.contains(jsLibJar)) {
list.add(library)
return@forEachAllUsedLibraries true
}
return@forEachAllUsedLibraries true
}
}
val isPluginOldForAllRoots = badVersionedRoots.all { it.supportedVersion < it.version }
val isPluginNewForAllRoots = badVersionedRoots.all { it.supportedVersion > it.version }
when {
badRuntimeLibraries.isNotEmpty() -> {
val badRootsInRuntimeLibraries = findBadRootsInRuntimeLibraries(badRuntimeLibraries, badVersionedRoots)
val otherBadRootsCount = badVersionedRoots.size - badRootsInRuntimeLibraries.size
val text = KotlinJvmBundle.htmlMessage(
"html.b.0.choice.0.1.1.some.kotlin.runtime.librar.0.choice.0.1.y.1.ies.b.1.choice.0.1.and.one.other.jar.1.and.1.other.jars.1.choice.0.has.0.have.an.unsupported.binary.format.html",
badRuntimeLibraries.size,
otherBadRootsCount
)
answer.text = text
if (isPluginOldForAllRoots) {
createUpdatePluginLink(answer)
}
val isPluginOldForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion < it.version }
val isPluginNewForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion > it.version }
val updateAction = when {
isPluginNewForAllRuntimeLibraries -> KotlinJvmBundle.message("button.text.update.library")
isPluginOldForAllRuntimeLibraries -> KotlinJvmBundle.message("button.text.downgrade.library")
else -> KotlinJvmBundle.message("button.text.replace.library")
}
val actionLabelText = "$updateAction " + KotlinJvmBundle.message(
"0.choice.0.1.1.all.kotlin.runtime.librar.0.choice.0.1.y.1.ies",
badRuntimeLibraries.size
)
answer.createActionLabel(actionLabelText) {
ApplicationManager.getApplication().invokeLater {
val newArtifactVersion = KotlinPluginLayout.instance.standaloneCompilerVersion.artifactVersion
updateLibraries(project, newArtifactVersion, badRuntimeLibraries)
}
}
}
badVersionedRoots.size == 1 -> {
val badVersionedRoot = badVersionedRoots.first()
val presentableName = badVersionedRoot.file.presentableName
when {
isPluginOldForAllRoots -> {
answer.text = KotlinJvmBundle.htmlMessage(
"html.kotlin.library.b.0.b.was.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin.html",
presentableName
)
createUpdatePluginLink(answer)
}
isPluginNewForAllRoots ->
answer.text = KotlinJvmBundle.htmlMessage(
"html.kotlin.library.b.0.b.has.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.the.library.html",
presentableName
)
else -> {
throw IllegalStateException("Bad root with compatible version found: $badVersionedRoot")
}
}
answer.createActionLabel(KotlinJvmBundle.message("button.text.go.to.0", presentableName)) {
navigateToLibraryRoot(
project,
badVersionedRoot.file
)
}
}
isPluginOldForAllRoots -> {
answer.text =
KotlinJvmBundle.message("some.kotlin.libraries.attached.to.this.project.were.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin")
createUpdatePluginLink(answer)
}
isPluginNewForAllRoots ->
answer.setText(
KotlinJvmBundle.message("some.kotlin.libraries.attached.to.this.project.have.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.found.libraries")
)
else ->
answer.setText(KotlinJvmBundle.message("some.kotlin.libraries.attached.to.this.project.have.unsupported.binary.format.please.update.the.libraries.or.the.plugin"))
}
createShowPathsActionLabel(project, badVersionedRoots, answer, KotlinJvmBundle.message("button.text.details"))
return answer
}
private fun createShowPathsActionLabel(
project: Project,
badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>,
answer: EditorNotificationPanel,
@NlsContexts.LinkLabel labelText: String
) {
answer.createComponentActionLabel(labelText) { label ->
val task = {
assert(!badVersionedRoots.isEmpty()) { "This action should only be called when bad roots are present" }
val listPopupModel = LibraryRootsPopupModel(
KotlinJvmBundle.message("unsupported.format.plugin.version.0", KotlinIdePlugin.version),
project,
badVersionedRoots
)
val popup = JBPopupFactory.getInstance().createListPopup(listPopupModel)
popup.showUnderneathOf(label)
null
}
DumbService.getInstance(project).tryRunReadActionInSmartMode(
task,
KotlinJvmBundle.message("can.t.show.all.paths.during.index.update")
)
}
}
private fun createUpdatePluginLink(answer: ErrorNotificationPanel) {
answer.createProgressAction(
KotlinJvmBundle.message("progress.action.text.check"),
KotlinJvmBundle.message("progress.action.text.update.plugin")
) { link, updateLink ->
KotlinPluginUpdater.getInstance().runCachedUpdate { pluginUpdateStatus ->
when (pluginUpdateStatus) {
is PluginUpdateStatus.Update -> {
link.isVisible = false
updateLink.isVisible = true
updateLink.addHyperlinkListener(object : HyperlinkAdapter() {
override fun hyperlinkActivated(e: HyperlinkEvent) {
KotlinPluginUpdater.getInstance().installPluginUpdate(pluginUpdateStatus)
}
})
}
is PluginUpdateStatus.LatestVersionInstalled -> {
link.text = KotlinJvmBundle.message("no.updates.found")
}
}
false // do not auto-retry update check
}
}
}
override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> {
if (!file.isKotlinFileType()) {
return CONST_NULL
}
try {
if (DumbService.isDumb(project) || isUnitTestMode()) return CONST_NULL
if (CompilerManager.getInstance(project).isExcludedFromCompilation(file)) return CONST_NULL
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return CONST_NULL
project.service<SuppressNotificationState>().state.takeUnless(SuppressNotificationState::isSuppressed) ?: return CONST_NULL
val badRoots: Collection<BinaryVersionedFile<BinaryVersion>> =
collectBadRoots(module).takeUnless(Collection<BinaryVersionedFile<BinaryVersion>>::isEmpty) ?: return CONST_NULL
return Function { doCreate(it, project, badRoots) }
} catch (e: ProcessCanceledException) {
// Ignore
} catch (e: IndexNotReadyException) {
DumbService.getInstance(project).runWhenSmart { updateNotifications(project) }
}
return CONST_NULL
}
private fun findBadRootsInRuntimeLibraries(
badRuntimeLibraries: List<Library>,
badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>
): ArrayList<BinaryVersionedFile<BinaryVersion>> {
val badRootsInLibraries = ArrayList<BinaryVersionedFile<BinaryVersion>>()
fun addToBadRoots(file: VirtualFile?) {
if (file != null) {
val runtimeJarBadRoot = badVersionedRoots.firstOrNull { it.file == file }
if (runtimeJarBadRoot != null) {
badRootsInLibraries.add(runtimeJarBadRoot)
}
}
}
badRuntimeLibraries.forEach { library ->
for (descriptor in LibraryJarDescriptor.values()) {
addToBadRoots(descriptor.findExistingJar(library)?.let<VirtualFile, @NotNull VirtualFile> { VfsUtil.getLocalFile(it) })
}
}
return badRootsInLibraries
}
private class LibraryRootsPopupModel(
@NlsContexts.PopupTitle title: String,
private val project: Project,
roots: Collection<BinaryVersionedFile<BinaryVersion>>
) : BaseListPopupStep<BinaryVersionedFile<BinaryVersion>>(title, *roots.toTypedArray()) {
override fun getTextFor(root: BinaryVersionedFile<BinaryVersion>): String {
val relativePath = VfsUtilCore.getRelativePath(root.file, project.baseDir, '/')
return KotlinJvmBundle.message("0.1.expected.2", relativePath ?: root.file.path, root.version, root.supportedVersion)
}
override fun getIconFor(aValue: BinaryVersionedFile<BinaryVersion>): Icon = if (aValue.file.isDirectory) {
AllIcons.Nodes.Folder
} else {
AllIcons.FileTypes.Archive
}
override fun onChosen(selectedValue: BinaryVersionedFile<BinaryVersion>, finalChoice: Boolean): PopupStep<*>? {
navigateToLibraryRoot(project, selectedValue.file)
return PopupStep.FINAL_CHOICE
}
override fun isSpeedSearchEnabled(): Boolean = true
}
private class ErrorNotificationPanel(fileEditor: FileEditor) : EditorNotificationPanel(fileEditor) {
init {
myLabel.icon = AllIcons.General.Error
}
fun createProgressAction(@Nls text: String, @Nls successLinkText: String, updater: (JLabel, HyperlinkLabel) -> Unit) {
val label = JLabel(text)
myLinksPanel.add(label)
val successLink = createActionLabel(successLinkText) { }
successLink.isVisible = false
// Several notification panels can be created almost instantly but we want to postpone deferred checks until
// panels are actually visible on screen.
myLinksPanel.addComponentListener(object : ComponentAdapter() {
var isUpdaterCalled = false
override fun componentResized(p0: ComponentEvent?) {
if (!isUpdaterCalled) {
isUpdaterCalled = true
updater(label, successLink)
}
}
})
}
}
private fun updateNotifications(project: Project) {
invokeLater {
if (!project.isDisposed) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
}
companion object {
private fun navigateToLibraryRoot(project: Project, root: VirtualFile) {
OpenFileDescriptor(project, root).navigate(true)
}
fun collectBadRoots(module: Module): Collection<BinaryVersionedFile<BinaryVersion>> {
val platform = TargetPlatformDetector.getPlatform(module)
val badRoots = when {
platform.isJvm() -> getLibraryRootsWithAbiIncompatibleKotlinClasses(module)
platform.isJs() -> getLibraryRootsWithAbiIncompatibleForKotlinJs(module)
// TODO: also check it for Native KT-34525
else -> return emptyList()
}
return if (badRoots.isEmpty()) emptyList() else badRoots.toHashSet()
}
}
}
fun EditorNotificationPanel.createComponentActionLabel(@NlsContexts.LinkLabel labelText: String, callback: (HyperlinkLabel) -> Unit) {
val label: Ref<HyperlinkLabel> = Ref.create()
val action = Runnable {
callback(label.get())
}
label.set(createActionLabel(labelText, action))
}
private operator fun BinaryVersion.compareTo(other: BinaryVersion): Int {
val first = this.toArray()
val second = other.toArray()
for (i in 0 until maxOf(first.size, second.size)) {
val thisPart = first.getOrNull(i) ?: -1
val otherPart = second.getOrNull(i) ?: -1
if (thisPart != otherPart) {
return thisPart - otherPart
}
}
return 0
}
|
apache-2.0
|
b38bade47c5a206b7bab9790671bf704
| 43.354396 | 200 | 0.644348 | 5.186315 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/FirWhenWithSubjectConditionContributor.kt
|
1
|
13950
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.contributors
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.util.parentOfType
import gnu.trove.THashSet
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.completion.InsertionHandlerBase
import org.jetbrains.kotlin.idea.completion.KotlinFirIconProvider.getIconFor
import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirWithSubjectEntryPositionContext
import org.jetbrains.kotlin.idea.completion.createKeywordElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirClassifierProvider.getAvailableClassifiersCurrentScope
import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirClassifierProvider.getAvailableClassifiersFromIndex
import org.jetbrains.kotlin.idea.completion.contributors.helpers.addTypeArguments
import org.jetbrains.kotlin.idea.completion.contributors.helpers.createStarTypeArgumentsList
import org.jetbrains.kotlin.idea.completion.contributors.helpers.insertSymbol
import org.jetbrains.kotlin.idea.completion.createKeywordElement
import org.jetbrains.kotlin.idea.completion.lookups.KotlinLookupObject
import org.jetbrains.kotlin.idea.completion.lookups.shortenReferencesForFirCompletion
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters
import org.jetbrains.kotlin.analysis.api.types.*
import org.jetbrains.kotlin.base.util.letIf
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
internal class FirWhenWithSubjectConditionContributor(
basicContext: FirBasicCompletionContext,
priority: Int,
) : FirCompletionContributorBase<FirWithSubjectEntryPositionContext>(basicContext, priority) {
override fun KtAnalysisSession.complete(positionContext: FirWithSubjectEntryPositionContext) {
val whenCondition = positionContext.whenCondition
val whenExpression = whenCondition.parentOfType<KtWhenExpression>() ?: return
val subject = whenExpression.subjectExpression ?: return
val allConditionsExceptCurrent = whenExpression.entries.flatMap { entry -> entry.conditions.filter { it != whenCondition } }
val subjectType = subject.getKtType() ?: return
val classSymbol = getClassSymbol(subjectType)
val visibilityChecker = CompletionVisibilityChecker.create(basicContext, positionContext)
val isSingleCondition = whenCondition.isSingleConditionInEntry()
when {
classSymbol?.classKind == KtClassKind.ENUM_CLASS -> {
completeEnumEntries(classSymbol, allConditionsExceptCurrent, visibilityChecker, isSingleCondition)
}
classSymbol?.modality == Modality.SEALED -> {
completeSubClassesOfSealedClass(
classSymbol,
allConditionsExceptCurrent,
whenCondition,
visibilityChecker,
isSingleCondition
)
}
else -> {
completeAllTypes(whenCondition, visibilityChecker, isSingleCondition)
}
}
addNullIfWhenExpressionCanReturnNull(subjectType)
addElseBranchIfSingleConditionInEntry(whenCondition)
}
private fun KtAnalysisSession.getClassSymbol(subjectType: KtType): KtNamedClassOrObjectSymbol? {
val classType = subjectType as? KtNonErrorClassType
return classType?.classSymbol as? KtNamedClassOrObjectSymbol
}
private fun KtAnalysisSession.addNullIfWhenExpressionCanReturnNull(type: KtType?) {
if (type?.canBeNull == true) {
val lookupElement = createKeywordElement(keyword = KtTokens.NULL_KEYWORD.value)
sink.addElement(lookupElement)
}
}
private fun KtAnalysisSession.completeAllTypes(
whenCondition: KtWhenCondition,
visibilityChecker: CompletionVisibilityChecker,
isSingleCondition: Boolean,
) {
val availableFromScope = mutableSetOf<KtClassifierSymbol>()
getAvailableClassifiersCurrentScope(originalKtFile, whenCondition, scopeNameFilter, visibilityChecker)
.forEach { classifier ->
if (classifier !is KtNamedSymbol) return@forEach
availableFromScope += classifier
addLookupElement(
classifier.name.asString(),
classifier,
(classifier as? KtNamedClassOrObjectSymbol)?.classIdIfNonLocal?.asSingleFqName(),
isPrefixNeeded(classifier),
isSingleCondition,
)
}
getAvailableClassifiersFromIndex(indexHelper, scopeNameFilter, visibilityChecker)
.forEach { classifier ->
if (classifier !is KtNamedSymbol || classifier in availableFromScope) return@forEach
addLookupElement(
classifier.name.asString(),
classifier,
(classifier as? KtNamedClassOrObjectSymbol)?.classIdIfNonLocal?.asSingleFqName(),
isPrefixNeeded(classifier),
isSingleCondition,
availableWithoutImport = false,
)
}
}
private fun KtAnalysisSession.isPrefixNeeded(classifier: KtClassifierSymbol): Boolean {
return when (classifier) {
is KtAnonymousObjectSymbol -> return false
is KtNamedClassOrObjectSymbol -> !classifier.classKind.isObject
is KtTypeAliasSymbol -> (classifier.expandedType as? KtNonErrorClassType)?.classSymbol?.let { isPrefixNeeded(it) } == true
is KtTypeParameterSymbol -> true
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.completeSubClassesOfSealedClass(
classSymbol: KtNamedClassOrObjectSymbol,
conditions: List<KtWhenCondition>,
whenCondition: KtWhenCondition,
visibilityChecker: CompletionVisibilityChecker,
isSingleCondition: Boolean,
) {
require(classSymbol.modality == Modality.SEALED)
val handledCasesClassIds = getHandledClassIds(conditions)
val allInheritors = getAllSealedInheritors(classSymbol)
allInheritors
.asSequence()
.filter { it.classIdIfNonLocal !in handledCasesClassIds }
.filter { with(visibilityChecker) { isVisible(it as KtClassifierSymbol) } }
.forEach { inheritor ->
val classId = inheritor.classIdIfNonLocal ?: return@forEach
addLookupElement(
classId.relativeClassName.asString(),
inheritor,
classId.asSingleFqName(),
isPrefixNeeded(inheritor),
isSingleCondition
)
}
if (allInheritors.any { it.modality == Modality.ABSTRACT }) {
completeAllTypes(whenCondition, visibilityChecker, isSingleCondition)
}
}
private fun KtAnalysisSession.getHandledClassIds(conditions: List<KtWhenCondition>): Set<ClassId> =
conditions.mapNotNullTo(hashSetOf()) { condition ->
val reference = when (condition) {
is KtWhenConditionWithExpression -> condition.expression?.reference()
is KtWhenConditionIsPattern -> (condition.typeReference?.typeElement as? KtUserType)?.referenceExpression?.reference()
else -> null
}
val resolvesTo = reference?.resolveToSymbol() as? KtNamedClassOrObjectSymbol
resolvesTo?.classIdIfNonLocal
}
private fun KtAnalysisSession.getAllSealedInheritors(classSymbol: KtNamedClassOrObjectSymbol): Collection<KtNamedClassOrObjectSymbol> {
fun KtAnalysisSession.getAllSealedInheritorsTo(
classSymbol: KtNamedClassOrObjectSymbol,
destination: MutableSet<KtNamedClassOrObjectSymbol>
) {
classSymbol.getSealedClassInheritors().forEach { inheritor ->
destination += inheritor
if (inheritor.modality == Modality.SEALED) {
getAllSealedInheritorsTo(inheritor, destination)
}
}
}
return THashSet(KtNamedClassOrObjectSymbolTObjectHashingStrategy)
.apply { getAllSealedInheritorsTo(classSymbol, this) }
}
private fun addElseBranchIfSingleConditionInEntry(whenCondition: KtWhenCondition) {
val whenEntry = whenCondition.parent as? KtWhenEntry ?: return
if (whenEntry.conditions.size > 1) return
val lookupElement = createKeywordElement(keyword = KtTokens.ELSE_KEYWORD.value, tail = " -> ")
sink.addElement(lookupElement)
}
private fun KtAnalysisSession.completeEnumEntries(
classSymbol: KtNamedClassOrObjectSymbol,
conditions: List<KtWhenCondition>,
visibilityChecker: CompletionVisibilityChecker,
isSingleCondition: Boolean,
) {
require(classSymbol.classKind == KtClassKind.ENUM_CLASS)
val handledCasesNames = conditions.mapNotNullTo(hashSetOf()) { condition ->
val conditionWithExpression = condition as? KtWhenConditionWithExpression
val resolvesTo = conditionWithExpression?.expression?.reference()?.resolveToSymbol() as? KtEnumEntrySymbol
resolvesTo?.name
}
val allEnumEntrySymbols = classSymbol.getEnumEntries()
allEnumEntrySymbols
.filter { it.name !in handledCasesNames }
.filter { with(visibilityChecker) { isVisible(it) } }
.forEach { entry ->
addLookupElement(
"${classSymbol.name.asString()}.${entry.name.asString()}",
entry,
entry.callableIdIfNonLocal?.asSingleFqName(),
isPrefixNeeded = false,
isSingleCondition,
)
}
}
private fun KtWhenCondition.isSingleConditionInEntry(): Boolean {
val entry = parent as KtWhenEntry
return entry.conditions.size == 1
}
private fun KtAnalysisSession.addLookupElement(
lookupString: String,
symbol: KtNamedSymbol,
fqName: FqName?,
isPrefixNeeded: Boolean,
isSingleCondition: Boolean,
availableWithoutImport: Boolean = true,
) {
val typeArgumentsCount = (symbol as? KtSymbolWithTypeParameters)?.typeParameters?.size ?: 0
val lookupObject = WhenConditionLookupObject(symbol.name, fqName, isPrefixNeeded, isSingleCondition, typeArgumentsCount)
LookupElementBuilder.create(lookupObject, getIsPrefix(isPrefixNeeded) + lookupString)
.withIcon(getIconFor(symbol))
.withPsiElement(symbol.psi)
.withInsertHandler(WhenConditionInsertionHandler)
.withTailText(createStarTypeArgumentsList(typeArgumentsCount), /*grayed*/true)
.letIf(isSingleCondition) { it.appendTailText(" -> ", /*grayed*/true) }
.also { it.availableWithoutImport = availableWithoutImport }
.let(sink::addElement)
}
}
private data class WhenConditionLookupObject(
override val shortName: Name,
val fqName: FqName?,
val needIsPrefix: Boolean,
val isSingleCondition: Boolean,
val typeArgumentsCount: Int,
) : KotlinLookupObject
private object WhenConditionInsertionHandler : InsertionHandlerBase<WhenConditionLookupObject>(WhenConditionLookupObject::class) {
override fun handleInsert(context: InsertionContext, item: LookupElement, ktFile: KtFile, lookupObject: WhenConditionLookupObject) {
context.insertName(lookupObject, ktFile)
context.addTypeArguments(lookupObject.typeArgumentsCount)
context.addArrow(lookupObject)
}
private fun InsertionContext.addArrow(
lookupObject: WhenConditionLookupObject
) {
if (lookupObject.isSingleCondition && completionChar != ',') {
insertSymbol(" -> ")
commitDocument()
}
}
private fun InsertionContext.insertName(
lookupObject: WhenConditionLookupObject,
ktFile: KtFile
) {
if (lookupObject.fqName != null) {
val fqName = lookupObject.fqName
document.replaceString(
startOffset,
tailOffset,
getIsPrefix(lookupObject.needIsPrefix) + fqName.render()
)
commitDocument()
shortenReferencesForFirCompletion(ktFile, TextRange(startOffset, tailOffset))
}
}
}
private fun getIsPrefix(prefixNeeded: Boolean): String {
return if (prefixNeeded) "is " else ""
}
private object KtNamedClassOrObjectSymbolTObjectHashingStrategy : TObjectHashingStrategy<KtNamedClassOrObjectSymbol> {
override fun equals(p0: KtNamedClassOrObjectSymbol, p1: KtNamedClassOrObjectSymbol): Boolean =
p0.classIdIfNonLocal == p1.classIdIfNonLocal
override fun computeHashCode(p0: KtNamedClassOrObjectSymbol): Int =
p0.classIdIfNonLocal.hashCode()
}
|
apache-2.0
|
2f3b34308f8a8c47c498f0a3ffc959e7
| 44.439739 | 158 | 0.694982 | 5.548926 | false | false | false | false |
DmytroTroynikov/aemtools
|
aem-intellij-core/src/main/kotlin/com/aemtools/reference/common/reference/HtlPropertyAccessReference.kt
|
1
|
2924
|
package com.aemtools.reference.common.reference
import com.aemtools.analysis.htl.callchain.elements.CallChainElement
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.java.JavaPsiClassTypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.java.JavaPsiUnresolvedTypeDescriptor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiReferenceBase
/**
* @author Dmytro Troynikov
*/
class HtlPropertyAccessReference(
val propertyAccess: com.aemtools.lang.htl.psi.mixin.PropertyAccessMixin,
val callChainElement: CallChainElement,
textRange: TextRange,
val referencedElement: PsiElement,
soft: Boolean = true
) : PsiReferenceBase<com.aemtools.lang.htl.psi.mixin.PropertyAccessMixin>(propertyAccess, textRange, soft) {
override fun resolve(): PsiElement? = referencedElement
override fun isReferenceTo(element: PsiElement): Boolean {
return referencedElement == element
}
override fun getVariants(): Array<Any> = emptyArray()
override fun getValue(): String {
return if (referencedElement.text.startsWith("get")) {
referencedElement.text.substringAfter("get")
.decapitalize()
} else {
referencedElement.text
}
}
override fun handleElementRename(newElementName: String): PsiElement {
val actualElement = callChainElement.element as? com.aemtools.lang.htl.psi.mixin.AccessIdentifierMixin
?: return propertyAccess
val typeDescriptor = callChainElement.type
actualElement.setName(preprocessName(newElementName, actualElement, typeDescriptor))
return propertyAccess
}
private fun preprocessName(newName: String,
actualElement: com.aemtools.lang.htl.psi.mixin.AccessIdentifierMixin,
typeDescriptor: TypeDescriptor): String {
if (typeDescriptor is JavaPsiClassTypeDescriptor) {
val psiMember = typeDescriptor.psiMember
if (psiMember is PsiMethod) {
return persistNameConventionForMethod(actualElement.variableName(), newName)
}
}
if (typeDescriptor is JavaPsiUnresolvedTypeDescriptor) {
val psiMember = typeDescriptor.psiMember
if (psiMember is PsiMethod) {
return persistNameConventionForMethod(actualElement.variableName(), newName)
}
}
return newName
}
private fun persistNameConventionForMethod(oldName: String, newName: String): String =
when {
oldName.startsWith("is") && newName.startsWith("is") -> newName
oldName.startsWith("get") && newName.startsWith("get") -> newName
newName.startsWith("is") -> newName.substringAfter("is").decapitalize()
newName.startsWith("get") -> newName.substringAfter("get").decapitalize()
else -> newName
}
}
|
gpl-3.0
|
de6cc9f44be5f56e1aae18d37386048a
| 35.55 | 108 | 0.735978 | 4.889632 | false | false | false | false |
androidx/androidx
|
compose/runtime/runtime-livedata/src/main/java/androidx/compose/runtime/livedata/LiveDataAdapter.kt
|
3
|
2537
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime.livedata
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
/**
* Starts observing this [LiveData] and represents its values via [State]. Every time there would
* be new value posted into the [LiveData] the returned [State] will be updated causing
* recomposition of every [State.value] usage.
*
* The inner observer will automatically be removed when this composable disposes or the current
* [LifecycleOwner] moves to the [Lifecycle.State.DESTROYED] state.
*
* @sample androidx.compose.runtime.livedata.samples.LiveDataSample
*/
@Composable
fun <T> LiveData<T>.observeAsState(): State<T?> = observeAsState(value)
/**
* Starts observing this [LiveData] and represents its values via [State]. Every time there would
* be new value posted into the [LiveData] the returned [State] will be updated causing
* recomposition of every [State.value] usage.
*
* The inner observer will automatically be removed when this composable disposes or the current
* [LifecycleOwner] moves to the [Lifecycle.State.DESTROYED] state.
*
* @sample androidx.compose.runtime.livedata.samples.LiveDataWithInitialSample
*/
@Composable
fun <R, T : R> LiveData<T>.observeAsState(initial: R): State<R> {
val lifecycleOwner = LocalLifecycleOwner.current
val state = remember { mutableStateOf(initial) }
DisposableEffect(this, lifecycleOwner) {
val observer = Observer<T> { state.value = it }
observe(lifecycleOwner, observer)
onDispose { removeObserver(observer) }
}
return state
}
|
apache-2.0
|
450e1fe8945b99108c26d0a1138188bf
| 39.269841 | 97 | 0.766259 | 4.389273 | false | false | false | false |
androidx/androidx
|
room/room-compiler/src/main/kotlin/androidx/room/parser/expansion/ExpandableParsedQuery.kt
|
3
|
6294
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.parser.expansion
import androidx.room.parser.ParserErrors
import androidx.room.parser.QueryType
import androidx.room.parser.Table
import androidx.room.verifier.QueryResultInfo
/**
* ExpandableSqlParser parses the query in more detail such that we know when an ALL projection is
* used (select *). This is information is only ever used if `room.expandProjection` is set to
* true and that feature will be deprecated.
*
* This file stays for backwards compatibility purposes.
*/
sealed class ExpandableSection {
abstract val text: String
data class Text(val content: String) : ExpandableSection() {
override val text: String
get() = content
}
object Newline : ExpandableSection() {
override val text: String
get() = "\n"
}
data class BindVar(val symbol: String) : ExpandableSection() {
override val text: String
get() = symbol
}
sealed class Projection : ExpandableSection() {
object All : Projection() {
override val text: String
get() = "*"
}
data class Table(
val tableAlias: String,
override val text: String
) : Projection()
}
}
data class Position(val line: Int, val charInLine: Int) : Comparable<Position> {
override fun compareTo(other: Position): Int {
return if (line == other.line) {
charInLine - other.charInLine
} else {
line - other.line
}
}
}
data class SectionInfo(
val start: Position,
val end: Position,
val section: ExpandableSection
)
data class ExpandableParsedQuery(
// original query as written by user, code writers should use transformed query that has been
// processed and optimized.
val original: String,
val type: QueryType,
val inputs: List<SectionInfo>,
val projections: List<SectionInfo>,
val explicitColumns: List<String>,
val tables: Set<Table>,
val syntaxErrors: List<String>,
val runtimeQueryPlaceholder: Boolean
) {
companion object {
val STARTS_WITH_NUMBER = "^\\?[0-9]".toRegex()
val MISSING = ExpandableParsedQuery(
original = "missing query",
type = QueryType.UNKNOWN,
projections = emptyList(),
explicitColumns = emptyList(),
inputs = emptyList(),
tables = emptySet(),
syntaxErrors = emptyList(),
runtimeQueryPlaceholder = false
)
}
/**
* Optional data that might be assigned when the query is parsed inside an annotation processor.
* User may turn this off or it might be disabled for any reason so generated code should
* always handle not having it.
*/
var resultInfo: QueryResultInfo? = null
/**
* The transformed query when it is interpreted and rewritten by QueryInterpreter.
*/
var transformed: String = original
private set
val sections by lazy {
val specialSections: List<SectionInfo> = (inputs + projections).sortedBy { it.start }
val lines = original.lines()
val sections = arrayListOf<ExpandableSection>()
var index = 0
var charInLine = 0
while (index < lines.size) {
val line = lines[index]
var multipleLineSection = false
specialSections
.filter { it.start.line == index }
.forEach { (start, end, section) ->
if (charInLine < start.charInLine) {
sections.add(
ExpandableSection.Text(
line.substring(
charInLine,
start.charInLine
)
)
)
}
sections.add(section)
charInLine = end.charInLine
if (index < end.line) {
index = end.line
multipleLineSection = true
}
}
if (!multipleLineSection) {
if (charInLine < line.length) {
sections.add(ExpandableSection.Text(line.substring(charInLine)))
}
if (index + 1 < lines.size) {
sections.add(ExpandableSection.Newline)
}
index++
charInLine = 0
}
}
sections
}
val bindSections by lazy { sections.filterIsInstance<ExpandableSection.BindVar>() }
private fun unnamedVariableErrors(): List<String> {
val anonymousBindError = if (inputs.any { it.section.text == "?" }) {
arrayListOf(ParserErrors.ANONYMOUS_BIND_ARGUMENT)
} else {
emptyList<String>()
}
return anonymousBindError + inputs.filter {
it.section.text.matches(STARTS_WITH_NUMBER)
}.map {
ParserErrors.cannotUseVariableIndices(it.section.text, it.start.charInLine)
}
}
private fun unknownQueryTypeErrors(): List<String> {
return if (QueryType.SUPPORTED.contains(type)) {
emptyList()
} else {
listOf(ParserErrors.invalidQueryType(type))
}
}
val errors by lazy {
if (syntaxErrors.isNotEmpty()) {
// if there is a syntax error, don't report others since they might be misleading.
syntaxErrors
} else {
unnamedVariableErrors() + unknownQueryTypeErrors()
}
}
}
|
apache-2.0
|
2a4378fea966474eb1ee6979fa798f30
| 30.949239 | 100 | 0.581347 | 4.936471 | false | false | false | false |
matt-richardson/TeamCity.Node
|
common/src/com/jonnyzzz/teamcity/plugins/node/common/NPMBean.kt
|
2
|
1367
|
/*
* Copyright 2013-2013 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.common
/**
* Created by Eugene Petrenko ([email protected])
* Date: 14.01.13 22:02
*/
public class NPMBean {
public val nodeJSNPMConfigurationParameter: String = "node.js.npm"
public val runTypeName: String = "jonnyzzz.npm"
public val commandLineParameterKey: String = "npm_execution_args"
public val npmCommandsKey: String = "npm_commands"
public val npmCommandsDefault: String = "install\r\ntest"
public val toolPathKey : String = "npm_toolPath"
public fun parseCommands(text: String?): Collection<String> {
if (text == null)
return listOf()
else
return text
.split("[\r\n]+")
.map { it.trim() }
.filterNot { it.isEmpty() }
}
}
|
apache-2.0
|
ac6a11d835d7dd6c4a229e01546e4bc7
| 31.547619 | 75 | 0.697879 | 3.905714 | false | false | false | false |
GunoH/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/checkout/JBProtocolCheckoutCommand.kt
|
2
|
1609
|
// 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.checkout
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.JBProtocolCommand
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.CheckoutProvider
import com.intellij.openapi.vcs.CheckoutProviderEx
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.ui.AppIcon
import com.intellij.util.ui.cloneDialog.VcsCloneDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* @author Konstantin Bulenkov
*/
internal class JBProtocolCheckoutCommand : JBProtocolCommand("checkout") {
override suspend fun execute(target: String?, parameters: Map<String, String>, fragment: String?): String? {
val repository = parameter(parameters, "checkout.repo")
val providerClass =
CheckoutProvider.EXTENSION_POINT_NAME.findFirstSafe { it is CheckoutProviderEx && it.vcsId == target }?.javaClass
?: return VcsBundle.message("jb.protocol.no.provider", target)
withContext(Dispatchers.EDT) {
val project = ProjectManager.getInstance().defaultProject
val listener = ProjectLevelVcsManager.getInstance(project).compositeCheckoutListener
AppIcon.getInstance().requestAttention(null, true)
val dialog = VcsCloneDialog.Builder(project).forVcs(providerClass, repository)
if (dialog.showAndGet()) {
dialog.doClone(listener)
}
}
return null
}
}
|
apache-2.0
|
a4f0e312297ed42b0314bc48008799d8
| 42.513514 | 120 | 0.779366 | 4.545198 | false | false | false | false |
GunoH/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/project/importing/MavenImportContext.kt
|
2
|
5683
|
// 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.idea.maven.project.importing
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.concurrency.Promise
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenExplicitProfiles
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.model.MavenProjectProblem
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder
import org.jetbrains.idea.maven.utils.MavenProgressIndicator
data class MavenImportingResult(
val finishPromise: Promise<MavenImportFinishedContext>,
val vfsRefreshPromise: Promise<Any?>?,
val previewModulesCreated: Module?
)
abstract sealed class MavenImportContext(val project: Project) {
abstract val indicator: MavenProgressIndicator
}
class MavenStartedImport(project: Project) : MavenImportContext(project) {
override val indicator = MavenProgressIndicator(project, null)
}
class MavenInitialImportContext internal constructor(project: Project,
val paths: ImportPaths,
val profiles: MavenExplicitProfiles,
val generalSettings: MavenGeneralSettings,
val importingSettings: MavenImportingSettings,
val ignorePaths: List<String>,
val ignorePatterns: List<String>,
val importDisposable: Disposable,
val previewModule: Module?,
val startImportStackTrace: Exception
) : MavenImportContext(project) {
override val indicator = MavenProgressIndicator(project, null)
}
data class WrapperData(val distributionUrl: String, val baseDir: VirtualFile)
class MavenReadContext internal constructor(project: Project,
val projectsTree: MavenProjectsTree,
val toResolve: Collection<MavenProject>,
private val withSyntaxErrors: Collection<MavenProject>,
val initialContext: MavenInitialImportContext,
val wrapperData: WrapperData?,
override val indicator: MavenProgressIndicator) : MavenImportContext(project) {
fun hasReadingProblems() = !withSyntaxErrors.isEmpty()
fun collectProblems(): Collection<MavenProjectProblem> = withSyntaxErrors.flatMap { it.problems }
}
class MavenResolvedContext internal constructor(project: Project,
val unresolvedArtifacts: Collection<MavenArtifact>,
val projectsToImport: List<MavenProject>,
val nativeProjectHolder: List<Pair<MavenProject, NativeMavenProjectHolder>>,
val readContext: MavenReadContext) : MavenImportContext(project) {
val initialContext = readContext.initialContext
override val indicator = readContext.indicator
}
class MavenPluginResolvedContext internal constructor(project: Project,
val unresolvedPlugins: Set<MavenPlugin>,
private val resolvedContext: MavenResolvedContext) : MavenImportContext(project) {
override val indicator = resolvedContext.indicator
}
class MavenSourcesGeneratedContext internal constructor(private val resolvedContext: MavenResolvedContext,
val projectsFoldersResolved: List<MavenProject>) : MavenImportContext(
resolvedContext.project) {
override val indicator = resolvedContext.indicator
}
class MavenImportedContext internal constructor(project: Project,
val modulesCreated: List<Module>,
val postImportTasks: List<MavenProjectsProcessorTask>?,
val readContext: MavenReadContext,
val resolvedContext: MavenResolvedContext) : MavenImportContext(project) {
override val indicator = resolvedContext.indicator
}
class MavenImportFinishedContext internal constructor(val context: MavenImportedContext?,
val error: Throwable?,
project: Project) : MavenImportContext(project) {
override val indicator = context?.indicator ?: MavenProgressIndicator(project, null)
constructor(e: Throwable, project: Project) : this(null, e, project)
constructor(context: MavenImportedContext) : this(context, null, context.project)
}
sealed class ImportPaths
class FilesList(val poms: List<VirtualFile>) : ImportPaths() {
constructor(poms: Array<VirtualFile>) : this(poms.asList())
constructor(pom: VirtualFile) : this(listOf(pom))
}
class RootPath(val path: VirtualFile) : ImportPaths()
|
apache-2.0
|
f3585b67306692ab325db2953ef8043d
| 51.146789 | 158 | 0.622559 | 6.065101 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/j2k/new/tests/testData/newJ2k/field/valOrVar.kt
|
4
|
455
|
internal class A(private val field6: Int, private val field8: Int, a: A) {
private val field1 = 0
private val field2 = 0
private var field3 = 0
val field4 = 0
var field5 = 0
private val field7 = 10
private val field9 = 10
private var field10 = 0
private var field11 = 0
fun foo() {
field3 = field2
}
init {
if (field6 > 0) {
field10 = 10
}
a.field11 = 10
}
}
|
apache-2.0
|
c4eaa643394b9b6274e739cfef339089
| 20.714286 | 74 | 0.542857 | 3.582677 | false | false | false | false |
JetBrains/kotlin-native
|
performance/ring/src/main/kotlin/org/jetbrains/ring/DefaultArgumentBenchmark.kt
|
4
|
1947
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
import org.jetbrains.benchmarksLauncher.Random
/**
* Created by Mikhail.Glukhikh on 10/03/2015.
*
* Tests performance for function calls with default parameters
*/
open class DefaultArgumentBenchmark {
private var arg = 0
init {
arg = Random.nextInt()
}
fun sumTwo(first: Int, second: Int = 0): Int {
return first + second
}
fun sumFour(first: Int, second: Int = 0, third: Int = 1, fourth: Int = third): Int {
return first + second + third + fourth
}
fun sumEight(first: Int, second: Int = 0, third: Int = 1, fourth: Int = third,
fifth: Int = fourth, sixth: Int = fifth, seventh: Int = second, eighth: Int = seventh): Int {
return first + second + third + fourth + fifth + sixth + seventh + eighth
}
//Benchmark
fun testOneOfTwo() {
sumTwo(arg)
}
//Benchmark
fun testTwoOfTwo() {
sumTwo(arg, arg)
}
//Benchmark
fun testOneOfFour() {
sumFour(arg)
}
//Benchmark
fun testFourOfFour() {
sumFour(arg, arg, arg, arg)
}
//Benchmark
fun testOneOfEight() {
sumEight(arg)
}
//Benchmark
fun testEightOfEight() {
sumEight(arg, arg, arg, arg, arg, arg, arg, arg)
}
}
|
apache-2.0
|
74b779a8e68ff197b8e3a01ba728ec2f
| 22.743902 | 110 | 0.618387 | 3.917505 | false | true | false | false |
hellenxu/TipsProject
|
DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/dialog/BottomSheetDialogSampleActivity.kt
|
1
|
7942
|
package six.ca.droiddailyproject.dialog
import android.annotation.TargetApi
import android.content.*
import android.graphics.*
import android.graphics.pdf.PdfDocument
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.print.PrintAttributes
import android.provider.MediaStore
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import six.ca.droiddailyproject.BuildConfig
import six.ca.droiddailyproject.R
import six.ca.droiddailyproject.databinding.ActBottomSheetBinding
import six.ca.droiddailyproject.recyclerview.RVSampleAdapter
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
/**
* @author hellenxu
* @date 2021-04-14
* Copyright 2021 Six. All rights reserved.
*/
class BottomSheetDialogSampleActivity : AppCompatActivity(R.layout.act_bottom_sheet),
View.OnClickListener {
private lateinit var binding: ActBottomSheetBinding
private lateinit var bottomSheetDialog: BottomSheetDialog
private val data = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActBottomSheetBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnShowDialog.setOnClickListener {
showDialog()
}
binding.rvData.layoutManager = LinearLayoutManager(this)
binding.rvData.adapter = RVSampleAdapter(this, createMockData())
}
private fun createMockData(): List<String> {
for (i in 0..5) {
data.add("string $i")
}
return data
}
private fun showDialog() {
if (!this::bottomSheetDialog.isInitialized) {
bottomSheetDialog = BottomSheetDialog(this)
bottomSheetDialog.setCanceledOnTouchOutside(true)
val view = layoutInflater.inflate(R.layout.dialog_multiple_actions, binding.root, false)
view.findViewById<TextView>(R.id.cta_screen_shot).setOnClickListener(this)
view.findViewById<TextView>(R.id.cta_pdf).setOnClickListener(this)
view.findViewById<TextView>(R.id.cta_copy).setOnClickListener(this)
bottomSheetDialog.setContentView(view)
}
bottomSheetDialog.show()
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.cta_screen_shot -> {
takeScreenShot(binding.rvData)
bottomSheetDialog.dismiss()
}
R.id.cta_pdf -> {
saveAsPdf(binding.rvData)
bottomSheetDialog.dismiss()
}
R.id.cta_copy -> {
copyToClipboard()
bottomSheetDialog.dismiss()
}
}
}
// screenshot view
private fun takeScreenShot(view: View) {
println("xxl-snapshot")
// new way to capture screenshots
// val viewWidth = view.width
// val viewHeight = view.height
// val bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565)
// val canvas = Canvas(bitmap)
// val bgDrawable = view.background
// if (bgDrawable != null) {
// bgDrawable.draw(canvas)
// } else {
// canvas.drawColor(Color.WHITE)
// }
// view.draw(canvas)
// old way to capture screenshots
// view.isDrawingCacheEnabled = true
// view.drawingCacheBackgroundColor = Color.WHITE
// val bitmap = Bitmap.createBitmap(view.drawingCache)
// view.isDrawingCacheEnabled = false
saveToGallery(getScreenShot(view))
}
private fun getScreenShot(view: View): Bitmap {
val viewWidth = view.width
val viewHeight = view.height
val bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565)
val canvas = Canvas(bitmap)
val bgDrawable = view.background
if (bgDrawable != null) {
bgDrawable.draw(canvas)
} else {
canvas.drawColor(Color.WHITE)
}
view.draw(canvas)
return bitmap
}
private fun saveToGallery(bitmap: Bitmap) {
println("xxl-save00: ${bitmap.byteCount}")
val fileName = "backup_${System.currentTimeMillis()}.jpg"
val uri =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
saveToGalleryForQandAbove(bitmap, fileName)
} else {
saveToGalleryForBelowQ(bitmap, fileName)
}
println("xxl-uri: ${uri.toString()}")
showPreview(uri, "image/JPEG")
}
@TargetApi(29)
private fun saveToGalleryForQandAbove(bitmap: Bitmap, fileName: String): Uri? {
val path = "${Environment.DIRECTORY_PICTURES}/Screenshots"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "image/JPEG")
put(MediaStore.MediaColumns.RELATIVE_PATH, path)
}
val insertUri =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
?: return null
contentResolver.openOutputStream(insertUri)?.use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
it.flush()
it.close()
}
return insertUri
}
private fun saveToGalleryForBelowQ(bitmap: Bitmap, fileName: String): Uri? {
val parentFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Screenshots")
println("xxl-path: ${parentFile.path}")
val imageFile = File(parentFile, fileName)
imageFile.outputStream().use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
it.flush()
it.close()
MediaStore.Images.Media.insertImage(contentResolver, imageFile.absolutePath, fileName, "")
return FileProvider.getUriForFile(this, BuildConfig.FILE_AUTHORITY,imageFile)
}
}
private fun showPreview(uri: Uri?, type: String) {
if (uri == null) {
return
}
val previewIntent = Intent(Intent.ACTION_VIEW).apply {
flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
setDataAndType(uri, type)
}
startActivity(previewIntent)
}
private fun saveAsPdf(view: View) {
println("xxl-pdf")
val fileName = "backup_${System.currentTimeMillis()}.pdf"
val pdfDoc = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(view.width, view.height, 1).create()
val page = pdfDoc.startPage(pageInfo)
view.draw(page.canvas)
pdfDoc.finishPage(page)
val path =
getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
val file = File(path, fileName)
pdfDoc.writeTo(FileOutputStream(file))
pdfDoc.close()
showPreview(FileProvider.getUriForFile(this, BuildConfig.FILE_AUTHORITY, file), "application/pdf")
}
private fun copyToClipboard() {
println("xxl-copy")
val cbManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cbManager.setPrimaryClip(
ClipData.newPlainText(
"backup",
getFormatCode()
)
)
}
private fun getFormatCode(): String {
val result = StringBuilder()
data.forEachIndexed { index, s ->
result.append(s)
if (index % 2 == 0) {
result.append("\t")
} else {
result.append("\n")
}
}
return result.toString()
}
}
|
apache-2.0
|
a4574420d16a485d2e55e75d524305ec
| 32.095833 | 106 | 0.634475 | 4.633606 | false | false | false | false |
OnyxDevTools/onyx-database-parent
|
onyx-database-tests/src/main/kotlin/entities/recreate/UserTmp.kt
|
1
|
1180
|
package entities.recreate
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.*
import com.onyx.persistence.annotations.values.CascadePolicy
import com.onyx.persistence.annotations.values.FetchPolicy
import com.onyx.persistence.annotations.values.IdentifierGenerator
import com.onyx.persistence.annotations.values.RelationshipType
import java.util.ArrayList
import java.util.Date
/**
* Created by Tim Osborn on 8/30/14.
*/
@Entity
@Suppress("unused")
class UserTmp : IManagedEntity {
@Attribute
@Identifier(generator = IdentifierGenerator.SEQUENCE)
var id: Long? = null
@Attribute(size = 100)
var firstName: String? = null
@Relationship(fetchPolicy = FetchPolicy.EAGER, cascadePolicy = CascadePolicy.NONE, type = RelationshipType.MANY_TO_MANY, inverse = "users", inverseClass = AccountTmp::class)
var accounts: MutableList<AccountTmp> = ArrayList()
@Relationship(type = RelationshipType.ONE_TO_MANY, fetchPolicy = FetchPolicy.EAGER, cascadePolicy = CascadePolicy.SAVE, inverseClass = UserRoleTmp::class)
var roles: MutableList<UserRoleTmp> = ArrayList()
@Attribute
var dateValue: Date? = null
}
|
agpl-3.0
|
da3f977d06bf6b67f1f61a30dd844d10
| 32.714286 | 177 | 0.771186 | 4.15493 | false | false | false | false |
smmribeiro/intellij-community
|
java/idea-ui/src/com/intellij/ide/starters/shared/FormUiUtil.kt
|
1
|
7266
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.shared
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Experiments
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.CheckboxTreeBase
import com.intellij.ui.CheckedTreeNode
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBInsets
import java.awt.GridBagConstraints
import java.awt.event.ActionEvent
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.util.function.Supplier
import javax.swing.AbstractAction
import javax.swing.JComponent
import javax.swing.JTextField
import javax.swing.KeyStroke
import javax.swing.event.DocumentEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreeNode
fun DialogPanel.withVisualPadding(topField: Boolean = false): DialogPanel {
if (Experiments.getInstance().isFeatureEnabled("new.project.wizard")) {
val top = if (topField) 20 else 15
border = IdeBorderFactory.createEmptyBorder(JBInsets(top, 20, 20, 20))
} else {
val top = if (topField) 15 else 5
border = IdeBorderFactory.createEmptyBorder(JBInsets(top, 5, 0, 5))
}
return this
}
internal fun gridConstraint(col: Int, row: Int): GridBagConstraints {
return GridBagConstraints().apply {
fill = GridBagConstraints.BOTH
gridx = col
gridy = row
weightx = 1.0
weighty = 1.0
}
}
fun <T : JComponent> withValidation(
builder: CellBuilder<T>,
errorChecks: List<TextValidationFunction>,
warningChecks: TextValidationFunction?,
validatedTextComponents: MutableList<JTextField>,
parentDisposable: Disposable
): CellBuilder<T> {
if (errorChecks.isEmpty()) return builder
val textField = getJTextField(builder.component)
val validationFunc = Supplier<ValidationInfo?> {
val text = textField.text
for (validationUnit in errorChecks) {
val errorMessage = validationUnit.checkText(text)
if (errorMessage != null) {
return@Supplier ValidationInfo(errorMessage, textField)
}
}
if (warningChecks != null) {
val warningMessage = warningChecks.checkText(text)
if (warningMessage != null) {
return@Supplier ValidationInfo(warningMessage, textField).asWarning().withOKEnabled()
}
}
null
}
ComponentValidator(parentDisposable)
.withValidator(validationFunc)
.installOn(textField)
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
ComponentValidator.getInstance(textField).ifPresent { v: ComponentValidator -> v.updateInfo(null) }
}
})
// use FocusListener instead of Validator.andStartOnFocusLost(), because the second one can disable validation, that can cause
// not validating unfocused fields, that are depends on some other fields
textField.addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent) {
// ignore
}
override fun focusLost(e: FocusEvent) {
revalidateAllAndHighlight(validatedTextComponents)
}
})
validatedTextComponents.add(textField)
return builder
}
fun validateFormFields(formParent: JComponent,
contentPanel: DialogPanel,
validatedComponents: List<JComponent>): Boolean {
// look for errors
var firstInvalidComponent: JComponent? = null
for (component in validatedComponents) {
ComponentValidator.getInstance(component).ifPresent { validator: ComponentValidator ->
validator.revalidate()
val validationInfo = validator.validationInfo
if (validationInfo != null && !validationInfo.warning) {
if (firstInvalidComponent == null) {
firstInvalidComponent = component
}
}
}
}
if (firstInvalidComponent != null) {
contentPanel.preferredFocusedComponent = firstInvalidComponent
return false
}
// look for warnings
val warnings = mutableListOf<ValidationInfo>()
for (component in validatedComponents) {
ComponentValidator.getInstance(component).ifPresent { validator: ComponentValidator ->
val validationInfo = validator.validationInfo
if (validationInfo != null && validationInfo.warning) {
warnings.add(validationInfo)
}
}
}
if (warnings.isNotEmpty()) {
val message = getWarningsMessage(warnings)
val answer = Messages.showOkCancelDialog(formParent, message,
IdeBundle.message("title.warning"),
Messages.getYesButton(),
Messages.getCancelButton(),
Messages.getWarningIcon())
if (answer != Messages.OK) {
return false
}
}
return true
}
private fun revalidateAllAndHighlight(validatedComponents: List<JComponent>) {
for (component in validatedComponents) {
ComponentValidator.getInstance(component).ifPresent { validator: ComponentValidator ->
validator.revalidate()
}
}
}
private fun getJTextField(component: JComponent): JTextField {
return when (component) {
is TextFieldWithBrowseButton -> component.textField
is JTextField -> component
else -> throw IllegalArgumentException()
}
}
@NlsSafe
private fun getWarningsMessage(warnings: MutableList<ValidationInfo>): String {
val message = StringBuilder()
if (warnings.size > 1) {
message.append(JavaStartersBundle.message("project.settings.warnings.group"))
for (warning in warnings) {
message.append("\n- ").append(warning.message)
}
}
else if (warnings.isNotEmpty()) {
message.append(warnings.first().message)
}
message.append("\n\n").append(JavaStartersBundle.message("project.settings.warnings.ignore"))
return message.toString()
}
internal fun walkCheckedTree(root: CheckedTreeNode?, visitor: (CheckedTreeNode) -> Unit) {
if (root == null) return
fun walkTreeNode(root: TreeNode, visitor: (CheckedTreeNode) -> Unit) {
if (root is CheckedTreeNode) {
visitor.invoke(root)
}
for (child in root.children()) {
walkTreeNode(child, visitor)
}
}
walkTreeNode(root, visitor)
}
internal fun enableEnterKeyHandling(list: CheckboxTreeBase) {
list.inputMap.put(KeyStroke.getKeyStroke("ENTER"), "pick-node")
list.actionMap.put("pick-node", object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
val selection = list.selectionPath
if (selection != null) {
if (selection.lastPathComponent is CheckedTreeNode) {
val node = selection.lastPathComponent as CheckedTreeNode
list.setNodeState(node, !node.isChecked)
}
else if (selection.lastPathComponent is DefaultMutableTreeNode) {
if (list.isExpanded(selection)) {
list.collapsePath(selection)
}
else {
list.expandPath(selection)
}
}
}
}
})
}
|
apache-2.0
|
8311c119883efb5ecb9963967a051182
| 31.441964 | 140 | 0.703413 | 4.66068 | false | false | false | false |
cy6erGn0m/kotlin-frontend-plugin
|
kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/ktor/KtorLauncher.kt
|
1
|
1144
|
package org.jetbrains.kotlin.gradle.frontend.ktor
import org.gradle.api.*
import org.jetbrains.kotlin.gradle.frontend.*
object KtorLauncher : Launcher {
override fun apply(packageManager: PackageManager, project: Project,
packagesTask: Task, startTask: Task, stopTask: Task) {
val ktor = project.extensions.create("ktor", KtorExtension::class.java)
project.afterEvaluate {
if (ktor.port != null) {
val ktorRun = project.tasks.create("ktor-run", KtorStartStopTask::class.java) { t ->
t.description = "Run ktor server"
t.group = KtorGroup
}
val ktorStop = project.tasks.create("ktor-stop", KtorStartStopTask::class.java) { t ->
t.start = false
t.description = "Stop ktor server"
t.group = KtorGroup
}
ktorRun.dependsOn(project.tasks.getByName("assemble"))
startTask.dependsOn(ktorRun)
stopTask.dependsOn(ktorStop)
}
}
}
val KtorGroup = "KTor"
}
|
apache-2.0
|
ee560a923df73864e24442157b4d34f6
| 33.69697 | 102 | 0.562063 | 4.576 | false | false | false | false |
shalupov/idea-cloudformation
|
metadata-crawler/src/main/kotlin/OfficialExamplesSaver.kt
|
1
|
2501
|
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import org.jsoup.Jsoup
import java.io.File
import java.net.URL
import java.nio.file.Files
import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.SimpleFileVisitor
import java.nio.file.FileSystems
import java.nio.file.FileVisitResult
import java.nio.file.Path
object OfficialExamplesSaver {
fun save() {
val url = URL("https://s3.amazonaws.com/cloudformation-templates-us-east-1/")
val doc = Jsoup.parse(url, 2000)
for (key in doc.getElementsByTag("Key")) {
val name = key.text()
val size = Integer.parseInt(key.parent().getElementsByTag("Size").first().text())
val fileUrl = URL(url, name.replace(" ", "%20"))
val localName = StringUtils.removeEnd(name.toLowerCase(), ".template") + "-" + DigestUtils.md5Hex(name).substring(0, 4) + ".template"
val localFile = File("testData/officialExamples/src", localName)
if (localFile.exists() && localFile.length() == size.toLong()) {
continue
}
println("Downloading $fileUrl")
FileUtils.copyURLToFile(fileUrl, localFile)
}
}
fun saveServerless() {
val targetRoot = File("testData/serverless-application-model/src")
val tempFile = Files.createTempFile("serverless-application-model-master", ".zip")
tempFile.toFile().deleteOnExit()
val url = URL("https://github.com/awslabs/serverless-application-model/archive/master.zip")
FileUtils.copyURLToFile(url, tempFile.toFile())
val zipFs = FileSystems.newFileSystem(tempFile, null)
val rootPath = zipFs.rootDirectories.toList().single()
if (targetRoot.exists()) {
FileUtils.deleteDirectory(targetRoot)
}
val pathInZip = rootPath.resolve("serverless-application-model-master").resolve("examples")
Files.walkFileTree(pathInZip, object : SimpleFileVisitor<Path>() {
@Throws(IOException::class)
override fun visitFile(filePath: Path, attrs: BasicFileAttributes): FileVisitResult {
val fileName = pathInZip.relativize(filePath).toString().replace("/", "_")
if (!fileName.endsWith(".yaml")) return FileVisitResult.CONTINUE
val targetPath = targetRoot.toPath().resolve(fileName)
println(targetPath)
Files.createDirectories(targetPath.parent)
Files.copy(filePath, targetPath)
return FileVisitResult.CONTINUE
}
})
}
}
|
apache-2.0
|
f6d423bc2e5af670d61be69679cd2b21
| 33.260274 | 139 | 0.707717 | 4.210438 | false | false | false | false |
like5188/Common
|
common/src/main/java/com/like/common/util/ClickTextViewSpanUtils.kt
|
1
|
4691
|
package com.like.common.util
import android.graphics.Color
import android.support.annotation.ColorInt
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import android.widget.TextView
/**
* 一个TextView空间内设置不同颜色的文字,并使得该部分的文字有着单独的点击事件
*/
object ClickTextViewSpanUtils {
fun setSpan(textView: TextView, content: String, clickTextViewModelList: List<ClickTextViewModel>, maxLines: Int = 0) {
if (clickTextViewModelList.isEmpty()) {
textView.text = content
return
}
textView.text = content
textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
textView.viewTreeObserver.removeOnGlobalLayoutListener(this)
val realText = if (maxLines != 0 && textView.lineCount > maxLines) {
val lineEndIndex = textView.layout.getLineEnd(maxLines - 1)// 设置第maxLines行打省略号
"${textView.text.subSequence(0, lineEndIndex - 1)}..."
} else {
content
}
val ss = SpannableString(realText)
clickTextViewModelList.forEach {
if (it.start < realText.length) {
val start = it.start
val end = if (it.end > realText.length) realText.length else it.end
ss.setSpan(ClickTextViewSpan(it.color, it.clickListener), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
textView.text = ss
textView.movementMethod = LinkMovementMethod.getInstance() // 不设置就没有点击事件
textView.highlightColor = Color.TRANSPARENT // 设置点击后的颜色为透明
textView.setOnTouchListener(LinkMovementMethodOverride())// 固定 TextView 行数的时候,点击 ClickableSpan 文本会出现滚动现象
}
})
}
data class ClickTextViewModel(val start: Int, val end: Int, @ColorInt val color: Int, val clickListener: (() -> Unit)? = null)
class LinkMovementMethodOverride : View.OnTouchListener {
override fun onTouch(v: View, event: MotionEvent): Boolean {
val widget = v as TextView
val text = widget.text
if (text is Spanned) {
val action = event.action
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
var x = event.x.toInt()
var y = event.y.toInt()
x -= widget.totalPaddingLeft
y -= widget.totalPaddingTop
x += widget.scrollX
y += widget.scrollY
val layout = widget.layout
val line = layout.getLineForVertical(y)
val off = layout.getOffsetForHorizontal(line, x.toFloat())
val link = text.getSpans(off, off,
ClickableSpan::class.java)
if (link.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget)
} else if (action == MotionEvent.ACTION_DOWN) {
// Selection only works on Spannable text. In our case setSelection doesn't work on spanned text
//Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
}
return true
}
}
}
return false
}
}
/**
* 一个TextView空间内设置不同颜色的文字,并使得该部分的文字有着单独的点击事件
*/
class ClickTextViewSpan(@ColorInt val textColor: Int, private val clickListener: (() -> Unit)? = null) : ClickableSpan() {
override fun onClick(widget: View?) {
clickListener?.invoke()
}
override fun updateDrawState(ds: TextPaint?) {
super.updateDrawState(ds)
ds?.color = textColor// 设置可以点击文本部分的颜色
ds?.isUnderlineText = false // 设置该文本部分是否显示超链接形式的下划线
}
}
}
|
apache-2.0
|
5589ad04b6a63006a09e30bd8c1784d8
| 36.581197 | 130 | 0.575165 | 4.940449 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/AddBookmarkFolderDialog.kt
|
1
|
4044
|
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.bookmark.view
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Toast
import jp.hazuki.bookmark.R
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkFolder
import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager
import jp.hazuki.yuzubrowser.bookmark.util.BookmarkIdGenerator
class AddBookmarkFolderDialog @JvmOverloads constructor(context: Context, private var mManager: BookmarkManager?, title: String?, private var mParent: BookmarkFolder?, private val item: BookmarkFolder? = null) {
private val mDialog: AlertDialog
private val titleEditText: EditText
private val addToTopCheckBox: CheckBox
private var mOnClickListener: DialogInterface.OnClickListener? = null
constructor(context: Context, manager: BookmarkManager, item: BookmarkFolder) : this(context, manager, item.title, item.parent, item)
init {
val view = LayoutInflater.from(context).inflate(R.layout.add_bookmark_folder_dialog, null)
titleEditText = view.findViewById(R.id.titleEditText)
addToTopCheckBox = view.findViewById(R.id.addToTopCheckBox)
if (item != null) {
addToTopCheckBox.visibility = View.GONE
}
titleEditText.setText(title)
mDialog = AlertDialog.Builder(context)
.setTitle(if (item == null) R.string.add_folder else R.string.edit_bookmark)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel, null)
.create()
}
fun show() {
mDialog.show()
mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { _ ->
val title = titleEditText.text
if (TextUtils.isEmpty(title)) {
Toast.makeText(mDialog.context, R.string.title_empty_mes, Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (mManager == null)
mManager = BookmarkManager.getInstance(mDialog.context)
if (mParent == null)
mParent = mManager!!.root
if (item == null) {
val item = BookmarkFolder(title.toString(), mParent, BookmarkIdGenerator.getNewId())
if (addToTopCheckBox.isChecked)
mParent!!.addFirst(item)
else
mParent!!.add(item)
} else {
if (item.parent == null) {
item.parent = mParent
mParent!!.add(item)
}
item.title = title.toString()
}
if (mManager!!.save()) {
Toast.makeText(mDialog.context, R.string.succeed, Toast.LENGTH_SHORT).show()
if (mOnClickListener != null)
mOnClickListener!!.onClick(mDialog, DialogInterface.BUTTON_POSITIVE)
mDialog.dismiss()
} else {
Toast.makeText(mDialog.context, R.string.failed, Toast.LENGTH_LONG).show()
}
}
}
fun setOnClickListener(l: DialogInterface.OnClickListener): AddBookmarkFolderDialog {
mOnClickListener = l
return this
}
}
|
apache-2.0
|
8a5a62fff5fc0ea2ecffaee7bd87a2fc
| 37.514286 | 211 | 0.650841 | 4.696864 | false | false | false | false |
kpspemu/kpspemu
|
src/commonMain/kotlin/com/soywiz/kpspemu/util/Struct.kt
|
1
|
6754
|
package com.soywiz.kpspemu.util
import com.soywiz.korio.lang.*
import com.soywiz.korio.stream.*
import com.soywiz.korio.util.*
import kotlin.reflect.*
open class Struct<T>(val create: () -> T, vararg val items: Item<T, *>) : StructType<T> {
override val size: Int = items.map { it.type.size }.sum()
data class Item<T1, V>(val type: StructType<V>, val property: KMutableProperty1<T1, V>)
override fun write(s: SyncStream, value: T) {
for (item in items) {
@Suppress("UNCHECKED_CAST")
val i = item as Item<T, Any>
i.type.write(s, i.property.get(value))
}
}
override fun read(s: SyncStream): T = read(s, create())
fun read(s: SyncStream, value: T): T {
for (item in items) {
@Suppress("UNCHECKED_CAST")
val i = item as Item<T, Any>
i.property.set(value, i.type.read(s))
}
return value
}
fun toByteArray(value: T): ByteArray = MemorySyncStream().apply { write(this, value) }.toByteArray()
}
infix fun <T1, V> KMutableProperty1<T1, V>.AS(type: StructType<V>) = Struct.Item(type, this)
/*
class Header(
var magic: Int = 0,
var size: Int = 0
) {
companion object : Struct<Header>({ Header() },
Item(INT32, Header::magic),
Item(INT32, Header::size)
)
}
fun test() {
Header.write()
}
*/
interface StructType<T> {
val size: Int
fun write(s: SyncStream, value: T)
fun read(s: SyncStream): T
}
fun <T> SyncStream.write(s: StructType<T>, value: T) = s.write(this, value)
fun <T> SyncStream.read(s: StructType<T>): T = s.read(this)
object UINT8 : StructType<Int> {
override val size = 1
override fun write(s: SyncStream, value: Int) = s.write8(value)
override fun read(s: SyncStream): Int = s.readU8()
}
object UINT16 : StructType<Int> {
override val size = 2
override fun write(s: SyncStream, value: Int) = s.write16_le(value)
override fun read(s: SyncStream): Int = s.readU16_le()
}
object INT32 : StructType<Int> {
override val size = 4
override fun write(s: SyncStream, value: Int) = s.write32_le(value)
override fun read(s: SyncStream): Int = s.readS32_le()
}
object INT32_be : StructType<Int> {
override val size = 4
override fun write(s: SyncStream, value: Int) = s.write32_be(value)
override fun read(s: SyncStream): Int = s.readS32_be()
}
fun <T, TR> StructType<T>.map(map: (T) -> TR, invMap: (TR) -> T): StructType<TR> = object : StructType<TR> {
override val size: Int = [email protected]
override fun write(s: SyncStream, value: TR) = [email protected](s, invMap(value))
override fun read(s: SyncStream): TR = map([email protected](s))
}
fun <TR : IdEnum> StructType<Int>.asEnum(e: BaseEnum<TR>): StructType<TR> = this.map({ e(it) }, { it.id })
object INT64 : StructType<Long> {
override val size = 8
override fun write(s: SyncStream, value: Long) = s.write64_le(value)
override fun read(s: SyncStream): Long = s.readS64_le()
}
object FLOAT32 : StructType<Float> {
override val size = 4
override fun write(s: SyncStream, value: Float) = s.writeF32_le(value)
override fun read(s: SyncStream): Float = s.readF32_le()
}
class STRINGZ(val charset: Charset, val len: Int? = null) : StructType<String> {
override val size = len ?: 0
constructor(size: Int? = null) : this(UTF8, size)
override fun write(s: SyncStream, value: String) = when {
len == null -> s.writeStringz(value, charset)
else -> s.writeStringz(value, len, charset)
}
override fun read(s: SyncStream): String = when {
len == null -> s.readStringz(charset)
else -> s.readStringz(len, charset)
}
}
class ARRAY<T>(val etype: StructType<T>, val len: Int) : StructType<ArrayList<T>> {
override val size: Int = len * etype.size
override fun write(s: SyncStream, value: ArrayList<T>) {
for (v in value) s.write(etype, v)
}
override fun read(s: SyncStream): ArrayList<T> {
val out = arrayListOf<T>()
for (n in 0 until len) out += s.read(etype)
return out
}
}
class INTLIKEARRAY(val etype: StructType<Int>, val len: Int) : StructType<IntArray> {
override val size: Int = len * etype.size
override fun write(s: SyncStream, value: IntArray) {
for (v in value) s.write(etype, v)
}
override fun read(s: SyncStream): IntArray {
val out = IntArray(len)
for (n in 0 until len) out[n] = s.read(etype)
return out
}
}
class BYTEARRAY(val len: Int) : StructType<ByteArray> {
override val size: Int = len
override fun write(s: SyncStream, value: ByteArray) = s.writeBytes(value)
override fun read(s: SyncStream): ByteArray = s.readBytes(len)
}
class SHORTARRAY(val len: Int) : StructType<ShortArray> {
override val size: Int = 2 * len
override fun write(s: SyncStream, value: ShortArray) = s.writeShortArray_le(value)
override fun read(s: SyncStream): ShortArray = s.readShortArray_le(len)
}
class CHARARRAY(val len: Int) : StructType<CharArray> {
override val size: Int = 2 * len
override fun write(s: SyncStream, value: CharArray) = s.writeCharArray_le(value)
override fun read(s: SyncStream): CharArray = s.readCharArray_le(len)
}
class INTARRAY(val len: Int) : StructType<IntArray> {
override val size: Int = 4 * len
override fun write(s: SyncStream, value: IntArray) = s.writeIntArray_le(value)
override fun read(s: SyncStream): IntArray = s.readIntArray_le(len)
}
interface BaseEnum<T : IdEnum> {
operator fun invoke(id: Int): T
}
open class INT32_ENUM<T : IdEnum>(val values: Array<T>) : StructType<T>, BaseEnum<T> {
override val size: Int = 4
override fun write(s: SyncStream, value: T) = s.write32_le(value.id)
override fun read(s: SyncStream): T = invoke(s.readS32_le())
private val defaultValue: T = values.first()
private val MAX_ID = values.map { it.id }.maxOrNull() ?: 0
private val valuesById = Array<Any>(MAX_ID + 1) { defaultValue }
init {
for (v in values) valuesById[v.id] = v
}
operator override fun invoke(id: Int): T = valuesById.getOrElse(id) { defaultValue } as T
}
open class UINT8_ENUM<T : IdEnum>(val values: Array<T>) : StructType<T>, BaseEnum<T> {
override val size: Int = 1
override fun write(s: SyncStream, value: T) = s.write8(value.id)
override fun read(s: SyncStream): T = invoke(s.readU8())
private val defaultValue: T = values.first()
private val MAX_ID = values.map { it.id }.maxOrNull() ?: 0
private val valuesById = Array<Any>(MAX_ID + 1) { defaultValue }
init {
for (v in values) valuesById[v.id] = v
}
operator override fun invoke(id: Int): T = valuesById.getOrElse(id) { defaultValue } as T
}
|
mit
|
e817cf5a7afed55e18e9f05c83d873eb
| 31.014218 | 108 | 0.643619 | 3.242439 | false | false | false | false |
Zubnix/westmalle
|
compositor/src/main/kotlin/org/westford/nativ/glibc/cmsghdr.kt
|
3
|
501
|
package org.westford.nativ.glibc
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(Field(name = "cmsg_len",
type = CType.UNSIGNED_LONG),
Field(name = "cmsg_level",
type = CType.INT),
Field(name = "cmsg_type",
type = CType.INT),
Field(name = "__cmsg_data",
cardinality = 0,
type = CType.UNSIGNED_CHAR)) class cmsghdr : Struct_cmsghdr()
|
apache-2.0
|
9670f352a14a116f364cf5fc474e5d21
| 32.4 | 75 | 0.602794 | 3.738806 | false | false | false | false |
zitmen/thunderstorm-algorithms
|
src/main/kotlin/cz/cuni/lf1/thunderstorm/datastructures/extensions/Array.kt
|
1
|
5451
|
package cz.cuni.lf1.thunderstorm.datastructures.extensions
import cz.cuni.lf1.thunderstorm.datastructures.GrayScaleImage
internal fun create2DDoubleArray(rows: Int, columns: Int, initValue: Double)
= Array(rows) { Array(columns) { initValue } }
internal fun create2DDoubleArray(rows: Int, columns: Int, initFun: (row: Int, col: Int) -> Double)
= Array(rows) { row -> Array(columns) { col -> initFun(row, col) } }
internal fun Array<Array<Double>>.copyDataToPosition(data: GrayScaleImage, row: Int, column: Int) {
for ((dataY, y) in (row..min(row + data.getHeight() - 1, this.size - 1)).withIndex()) {
for ((dataX, x) in (column..min(column + data.getWidth() - 1, this[y].size - 1)).withIndex()) {
this[y][x] = data.getValue(dataY, dataX)
}
}
}
internal fun Array<Array<Double>>.fillRectangle(top: Int, left: Int, bottom: Int, right: Int, value: Double) {
for (y in top..bottom) {
for (x in left..right) {
this[y][x] = value
}
}
}
internal operator fun Array<Double>.plus(add: Double)
= this.map { it + add }.toTypedArray()
internal operator fun Double.plus(add: Array<Double>)
= add + this
internal operator fun Array<Double>.plus(add: Array<Double>): Array<Double> {
if (size != add.size) {
throw IllegalArgumentException("Both arrays must be of the same size!")
}
return (0 until size).map { this[it] + add[it] }.toTypedArray()
}
internal operator fun Array<Double>.minus(sub: Double)
= this.map { it - sub }.toTypedArray()
internal operator fun Double.minus(sub: Array<Double>)
= sub.map { this - it }.toTypedArray()
internal operator fun Array<Double>.minus(sub: Array<Double>): Array<Double> {
if (size != sub.size) {
throw IllegalArgumentException("Both arrays must be of the same size!")
}
return (0 until size).map { this[it] - sub[it] }.toTypedArray()
}
internal operator fun Array<Double>.times(mul: Double)
= this.map { it * mul }.toTypedArray()
internal operator fun Double.times(mul: Array<Double>)
= mul * this
internal operator fun Array<Double>.times(mul: Array<Double>): Array<Double> {
if (size != mul.size) {
throw IllegalArgumentException("Both arrays must be of the same size!")
}
return (0 until size).map { this[it] * mul[it] }.toTypedArray()
}
internal operator fun Array<Double>.div(by: Double)
= this.map { it / by }.toTypedArray()
internal operator fun Double.div(by: Array<Double>)
= by.map { this / it }.toTypedArray()
internal operator fun Array<Double>.div(by: Array<Double>): Array<Double> {
if (size != by.size) {
throw IllegalArgumentException("Both arrays must be of the same size!")
}
return (0 until size).map { this[it] / by[it] }.toTypedArray()
}
internal operator fun Array<Double>.rem(by: Double)
= this.map { it % by }.toTypedArray()
internal operator fun Double.rem(by: Array<Double>)
= by.map { this % it }.toTypedArray()
internal operator fun Array<Double>.rem(by: Array<Double>): Array<Double> {
if (size != by.size) {
throw IllegalArgumentException("Both arrays must be of the same size!")
}
return (0 until size).map { this[it] % by[it] }.toTypedArray()
}
internal fun Array<Double>.pow(to: Double)
= this.map { it.pow(to) }.toTypedArray()
internal fun Array<Double>.and(arg: Array<Double>)
= (0 until size).map { this[it].and(arg[it]) }.toTypedArray()
internal fun Array<Double>.or(arg: Array<Double>)
= (0 until size).map { this[it].or(arg[it]) }.toTypedArray()
internal fun Array<Double>.eq(arg: Array<Double>)
= (0 until size).map { this[it].eq(arg[it]) }.toTypedArray()
internal fun Array<Double>.eq(arg: Double)
= this.map { it.eq(arg) }.toTypedArray()
internal fun Double.eq(arg: Array<Double>)
= arg.eq(this)
internal fun Array<Double>.neq(arg: Array<Double>)
= (0 until size).map { this[it].neq(arg[it]) }.toTypedArray()
internal fun Array<Double>.neq(arg: Double)
= this.map { it.neq(arg) }.toTypedArray()
internal fun Double.neq(arg: Array<Double>)
= arg.neq(this)
internal fun Array<Double>.lt(arg: Array<Double>)
= (0 until size).map { this[it].lt(arg[it]) }.toTypedArray()
internal fun Array<Double>.lt(arg: Double)
= this.map { it.lt(arg) }.toTypedArray()
internal fun Double.lt(arg: Array<Double>)
= arg.lt(this)
internal fun Array<Double>.gt(arg: Array<Double>)
= (0 until size).map { this[it].gt(arg[it]) }.toTypedArray()
internal fun Array<Double>.gt(arg: Double)
= this.map { it.gt(arg) }.toTypedArray()
internal fun Double.gt(arg: Array<Double>)
= arg.gt(this)
internal fun Array<Double>.median()
= sortedArray().let {
if (size % 2 == 1) {
it[it.size / 2]
} else {
(it[it.size / 2] + it[(it.size - 1) / 2]) / 2.0
}
}
/**
* Normalize sum to 1
*/
internal fun Array<Double>.normalize()
= div(sum())
internal fun Array<Double>.mean()
= this.sum() / this.size
internal fun Array<Double>.variance(): Double {
val avg = this.mean()
return this.map { (it - avg).sqr() }.toTypedArray().mean()
}
internal fun Array<Double>.stddev(): Double
= this.variance().sqrt()
internal fun Array<Double>.abs()
= this.map { it.abs() }.toTypedArray()
|
gpl-3.0
|
927309cdf75c0ecf7ad816d53d92b059
| 32.243902 | 110 | 0.627591 | 3.469764 | false | false | false | false |
Esri/arcgis-runtime-samples-android
|
kotlin/display-layer-view-state/src/main/java/com/esri/arcgisruntime/sample/displaylayerviewstate/MainActivity.kt
|
1
|
6777
|
/*
* 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.displaylayerviewstate
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.LayerViewStatus
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.portal.Portal
import com.esri.arcgisruntime.portal.PortalItem
import com.esri.arcgisruntime.sample.displaylayerviewstate.databinding.ActivityMainBinding
import java.util.EnumSet
class MainActivity : AppCompatActivity() {
private var featureLayer: FeatureLayer? = null
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val loadButton: Button by lazy {
activityMainBinding.loadButton
}
private val hideButton: Button by lazy {
activityMainBinding.hideButton
}
private val statesContainer: ConstraintLayout by lazy {
activityMainBinding.statesContainer
}
private val activeStateTextView: TextView by lazy {
activityMainBinding.activeStateTextView
}
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)
mapView.apply {
// create a map with a topographic basemap
map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// zoom to custom viewpoint
setViewpoint(
Viewpoint(
Point(-11e6, 45e5, SpatialReferences.getWebMercator()),
40_000_000.0
)
)
}
mapView.addLayerViewStateChangedListener { layerViewStateChangedEvent ->
// get the layer which changed its state
val layer = layerViewStateChangedEvent.layer
// we only want to check the view state of the image layer
if (layer != featureLayer) {
return@addLayerViewStateChangedListener
}
val layerViewStatus = layerViewStateChangedEvent.layerViewStatus
// if there is an error or warning, display it in a toast
layerViewStateChangedEvent.error?.let { error ->
val message = error.cause?.toString() ?: error.message
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
displayViewStateText(layerViewStatus)
}
loadButton.setOnClickListener {
if (featureLayer != null) {
return@setOnClickListener
}
// load a feature layer from a portal item
val portalItem = PortalItem(
Portal("https://runtime.maps.arcgis.com/"),
"b8f4033069f141729ffb298b7418b653"
)
featureLayer = FeatureLayer(portalItem, 0).apply {
// set the scales at which this layer can be viewed
minScale = 400_000_000.0
maxScale = minScale / 10
}
// add the layer on the map to load it
mapView.map.operationalLayers.add(featureLayer)
// hide the button
loadButton.apply {
isEnabled = false
visibility = View.GONE
}
// show the view state UI and the hide layer button
statesContainer.visibility = View.VISIBLE
hideButton.visibility = View.VISIBLE
}
hideButton.setOnClickListener {
featureLayer?.apply {
// toggle visibility
isVisible = !isVisible
// update button text
hideButton.text = when {
isVisible -> getString(R.string.show_layer)
else -> getString(R.string.hide_layer)
}
}
}
}
/**
* Formats and displays the layer view status flags in a text view.
*
* @param layerViewStatus to display
*/
private fun displayViewStateText(layerViewStatus: EnumSet<LayerViewStatus>) {
// for each view state property that's active,
// add it to a list and display the states as a comma-separated string
val stringList = mutableListOf<String>()
if (layerViewStatus.contains(LayerViewStatus.ACTIVE)) {
stringList.add(getString(R.string.active_state))
}
if (layerViewStatus.contains(LayerViewStatus.ERROR)) {
stringList.add(getString(R.string.error_state))
}
if (layerViewStatus.contains(LayerViewStatus.LOADING)) {
stringList.add(getString(R.string.loading_state))
}
if (layerViewStatus.contains(LayerViewStatus.NOT_VISIBLE)) {
stringList.add(getString(R.string.not_visible_state))
}
if (layerViewStatus.contains(LayerViewStatus.OUT_OF_SCALE)) {
stringList.add(getString(R.string.out_of_scale_state))
}
if (layerViewStatus.contains(LayerViewStatus.WARNING)) {
stringList.add(getString(R.string.warning_state))
}
activeStateTextView.text = stringList.joinToString(", ")
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
|
apache-2.0
|
c45d68222c2982d57a437ee5306e8d6e
| 34.857143 | 96 | 0.649255 | 4.844174 | false | false | false | false |
google/private-compute-libraries
|
javatests/com/google/android/libraries/pcc/chronicle/codegen/backend/ConnectionsPropertyProviderTest.kt
|
1
|
2453
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.backend
import com.google.android.libraries.pcc.chronicle.api.ReadConnection
import com.google.android.libraries.pcc.chronicle.api.WriteConnection
import com.google.android.libraries.pcc.chronicle.codegen.backend.api.PropertyProvider
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.asTypeName
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ConnectionsPropertyProviderTest {
@Test
fun emptyConnectionTypeNames_providesEmptySet() {
val provider =
ConnectionsPropertyProvider(
entityClassSimpleName = "MyEntity",
connectionTypeNames = emptySet()
)
val fileContents = provider.getGeneratedSource()
assertThat(fileContents)
.contains("public val MY_ENTITY_GENERATED_CONNECTIONS: Set<Class<out Connection>> = setOf()")
}
@Test
fun nonEmptyConnectionTypeNames() {
val provider =
ConnectionsPropertyProvider(
entityClassSimpleName = "MyEntity",
connectionTypeNames =
listOf(MyEntityReader::class.asTypeName(), MyEntityWriter::class.asTypeName())
)
val fileContents = provider.getGeneratedSource()
assertThat(fileContents)
.contains(
"public val MY_ENTITY_GENERATED_CONNECTIONS: Set<Class<out Connection>> =\n" +
" setOf(MyEntityReader::class.java, MyEntityWriter::class.java)"
)
}
private fun PropertyProvider.getGeneratedSource(): String {
val fileSpec =
FileSpec.builder("com.google", "FileName").apply { provideContentsInto(this) }.build()
return StringBuilder().also { fileSpec.writeTo(it) }.toString()
}
}
interface MyEntityReader : ReadConnection
interface MyEntityWriter : WriteConnection
|
apache-2.0
|
0ed1ea861ef58d7cf15e02086b286030
| 32.60274 | 99 | 0.742356 | 4.411871 | false | true | false | false |
Stargamers/FastHub
|
app/src/main/java/com/fastaccess/provider/timeline/handler/HeaderHandler.kt
|
7
|
1143
|
package com.fastaccess.provider.timeline.handler
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import net.nightwhistler.htmlspanner.TagNodeHandler
import net.nightwhistler.htmlspanner.spans.FontFamilySpan
import org.htmlcleaner.TagNode
/**
* Created by Kosh on 29.09.17.
*/
class HeaderHandler(val size: Float) : TagNodeHandler() {
override fun beforeChildren(node: TagNode?, builder: SpannableStringBuilder?) {
appendNewLine(builder)
}
override fun handleTagNode(node: TagNode, builder: SpannableStringBuilder, start: Int, end: Int) {
builder.setSpan(RelativeSizeSpan(this.size), start, end, 33)
val originalSpan = this.getFontFamilySpan(builder, start, end)
val boldSpan: FontFamilySpan
if (originalSpan == null) {
boldSpan = FontFamilySpan(this.spanner.defaultFont)
} else {
boldSpan = FontFamilySpan(originalSpan.fontFamily)
boldSpan.isItalic = originalSpan.isItalic
}
boldSpan.isBold = true
builder.setSpan(boldSpan, start, end, 33)
appendNewLine(builder)
}
}
|
gpl-3.0
|
487fe197f3fd46021f5b312aeeb01b8e
| 33.666667 | 102 | 0.712161 | 4.217712 | false | false | false | false |
guyca/react-native-navigation
|
lib/android/app/src/test/java/com/reactnativenavigation/mocks/ImageLoaderMock.kt
|
2
|
1697
|
package com.reactnativenavigation.mocks
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.drawable.Drawable
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.whenever
import com.reactnativenavigation.utils.ImageLoader
import com.reactnativenavigation.utils.ImageLoader.ImagesLoadingListener
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.mockito.invocation.InvocationOnMock
import java.util.*
object ImageLoaderMock {
private val mockDrawable: Drawable = object : Drawable() {
override fun draw(canvas: Canvas) {}
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(colorFilter: ColorFilter?) {}
override fun getOpacity(): Int {
return 0
}
}
private val backIcon: Drawable = BackDrawable()
@JvmStatic
fun mock(): ImageLoader {
val imageLoader = Mockito.mock(ImageLoader::class.java)
Mockito.doAnswer { invocation: InvocationOnMock ->
val urlCount = (invocation.arguments[1] as Collection<*>).size
val drawables = Collections.nCopies(urlCount, mockDrawable)
(invocation.arguments[2] as ImagesLoadingListener).onComplete(drawables)
null
}.`when`(imageLoader).loadIcons(any(), ArgumentMatchers.anyList(), any())
Mockito.doAnswer { invocation: InvocationOnMock ->
(invocation.arguments[2] as ImagesLoadingListener).onComplete(mockDrawable)
null
}.`when`(imageLoader).loadIcon(any(), any(), any())
whenever(imageLoader.getBackButtonIcon(any())).thenReturn(backIcon)
return imageLoader
}
}
|
mit
|
448011117eb027a182b7eef960b6e3a1
| 37.590909 | 87 | 0.712434 | 5.035608 | false | false | false | false |
elect86/modern-jogl-examples
|
src/main/kotlin/glNext/tut08/interpolation.kt
|
2
|
6524
|
package glNext.tut08
import com.jogamp.newt.event.KeyEvent
import glm.mat.Mat4
import com.jogamp.opengl.GL3
import glNext.*
import glm.*
import glm.quat.Quat
import main.framework.Framework
import main.framework.component.Mesh
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.time.Timer
/**
* Created by GBarbieri on 17.03.2017.
*/
fun main(args: Array<String>) {
Interpolation_Next().setup("Tutorial 08 - Interpolation")
}
class Interpolation_Next : Framework() {
lateinit var ship: Mesh
var theProgram = 0
var modelToCameraMatrixUnif = 0
var cameraToClipMatrixUnif = 0
var baseColorUnif = 0
val frustumScale = calcFrustumScale(20f)
fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f)
val cameraToClipMatrix = Mat4(0.0f)
val orient = Orientation()
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
ship = Mesh(gl, javaClass, "tut08/Ship.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut08", "pos-color-local-transform.vert", "color-mult-uniform.frag")
withProgram(theProgram) {
modelToCameraMatrixUnif = "modelToCameraMatrix".location
cameraToClipMatrixUnif = "cameraToClipMatrix".location
baseColorUnif = "baseColor".location
val zNear = 1.0f
val zFar = 600.0f
cameraToClipMatrix[0].x = frustumScale
cameraToClipMatrix[1].y = frustumScale
cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar)
cameraToClipMatrix[2].w = -1.0f
cameraToClipMatrix[3].z = (2 * zFar * zNear) / (zNear - zFar)
use { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix }
}
}
override fun display(gl: GL3) = with(gl) {
orient.updateTime()
clear {
color(0)
depth()
}
val matrixStack = MatrixStack()
.translate(0.0f, 0.0f, -200.0f)
.applyMatrix(orient.getOrient().toMat4())
usingProgram(theProgram) {
matrixStack
.scale(3.0f, 3.0f, 3.0f)
.rotateX(-90.0f)
//Set the base color for this object.
glUniform4f(baseColorUnif, 1.0f)
modelToCameraMatrixUnif.mat4 = matrixStack.top()
ship.render(gl, "tint")
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
cameraToClipMatrix[0].x = frustumScale * (h / w.f)
cameraToClipMatrix[1].y = frustumScale
usingProgram(theProgram) { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix }
glViewport(w, h)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> {
val slerp = orient.toggleSlerp()
println(if (slerp) "Slerp" else "Lerp")
}
}
orientKeys.indices.filter { e.keyCode == orientKeys[it] }.forEach { applyOrientation(it) }
}
fun applyOrientation(index: Int) {
if (!orient.isAnimating)
orient.animateToOrient(index)
}
val orientKeys = shortArrayOf(
KeyEvent.VK_Q,
KeyEvent.VK_W,
KeyEvent.VK_E,
KeyEvent.VK_R,
KeyEvent.VK_T,
KeyEvent.VK_Y,
KeyEvent.VK_U)
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
ship.dispose(gl)
}
inner class Orientation {
var isAnimating = false
var currentOrient = 0
var slerp = false
val anim = Animation()
fun toggleSlerp(): Boolean {
slerp = !slerp
return slerp
}
fun getOrient() =
if (isAnimating)
anim.getOrient(orients[currentOrient], slerp)
else
orients[currentOrient]
fun updateTime() {
if (isAnimating) {
val isFinished = anim.updateTime()
if (isFinished) {
isAnimating = false
currentOrient = anim.finalX
}
}
}
fun animateToOrient(destination: Int) {
if (currentOrient == destination) {
return
}
anim.startAnimation(destination, 1.0f)
isAnimating = true
}
inner class Animation {
var finalX = 0
private set
lateinit var currTimer: Timer
fun updateTime() = currTimer.update()
fun getOrient(initial: Quat, slerp: Boolean) =
if (slerp)
slerp(initial, orients[finalX], currTimer.getAlpha())
else
lerp(initial, orients[finalX], currTimer.getAlpha())
fun startAnimation(destination: Int, duration: Float) {
finalX = destination
currTimer = Timer(Timer.Type.Single, duration)
}
}
}
fun slerp(v0: Quat, v1: Quat, alpha: Float): Quat {
var dot = v0 dot v1
val DOT_THRESHOLD = 0.9995f
if (dot > DOT_THRESHOLD)
return lerp(v0, v1, alpha)
dot = glm.clamp(dot, -1.0f, 1.0f)
val theta0 = glm.acos(dot)
val theta = theta0 * alpha
val v2 = v1 - v0 * dot
v2.normalize_()
return v0 * theta.cos + v2 * theta.sin
}
// TODO check lerp thinkness
fun lerp(v0: Quat, v1: Quat, alpha: Float): Quat {
val start = v0.vectorize()
val end = v1.vectorize()
val interp = glm.mix(start, end, alpha)
println("alpha: $alpha, $interp")
interp.normalize_()
return Quat(interp)
}
val orients = arrayOf(
Quat(0.7071f, 0.7071f, 0.0f, 0.0f),
Quat(0.5f, 0.5f, -0.5f, 0.5f),
Quat(-0.4895f, -0.7892f, -0.3700f, -0.02514f),
Quat(0.4895f, 0.7892f, 0.3700f, 0.02514f),
Quat(0.3840f, -0.1591f, -0.7991f, -0.4344f),
Quat(0.5537f, 0.5208f, 0.6483f, 0.0410f),
Quat(0.0f, 0.0f, 1.0f, 0.0f))
}
|
mit
|
3a858979925f1fcfe8322aaa96e13e8a
| 24.888889 | 115 | 0.536941 | 3.939614 | false | false | false | false |
t-yoshi/peca-android
|
ui/src/main/java/org/peercast/core/ui/view/NestedWebView.kt
|
1
|
4708
|
package org.peercast.core.ui.view
/*
* Copyright (C) 2015 takahirom
*
* 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.
*/
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.webkit.WebView
import androidx.core.view.MotionEventCompat
import androidx.core.view.NestedScrollingChild
import androidx.core.view.NestedScrollingChildHelper
import androidx.core.view.ViewCompat
class NestedWebView : WebView, NestedScrollingChild {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
private var mLastY = 0
private val mScrollOffset = IntArray(2)
private val mScrollConsumed = IntArray(2)
private var mNestedOffsetY = 0
private val mChildHelper = NestedScrollingChildHelper(this)
override fun onTouchEvent(ev: MotionEvent): Boolean {
var returnValue = false
val event = MotionEvent.obtain(ev)
val action = MotionEventCompat.getActionMasked(event)
if (action == MotionEvent.ACTION_DOWN) {
mNestedOffsetY = 0
}
val eventY = event.y.toInt()
event.offsetLocation(0f, mNestedOffsetY.toFloat())
when (action) {
MotionEvent.ACTION_MOVE -> {
var deltaY = mLastY - eventY
// NestedPreScroll
if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
deltaY -= mScrollConsumed[1]
mLastY = eventY - mScrollOffset[1]
event.offsetLocation(0f, (-mScrollOffset[1]).toFloat())
mNestedOffsetY += mScrollOffset[1]
}
returnValue = super.onTouchEvent(event)
// NestedScroll
if (dispatchNestedScroll(0, mScrollOffset[1], 0, deltaY, mScrollOffset)) {
event.offsetLocation(0f, mScrollOffset[1].toFloat())
mNestedOffsetY += mScrollOffset[1]
mLastY -= mScrollOffset[1]
}
}
MotionEvent.ACTION_DOWN -> {
returnValue = super.onTouchEvent(event)
mLastY = eventY
// start NestedScroll
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL)
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
returnValue = super.onTouchEvent(event)
// end NestedScroll
stopNestedScroll()
}
}
return returnValue
}
init {
isNestedScrollingEnabled = true
}
// Nested Scroll implements
override fun setNestedScrollingEnabled(enabled: Boolean) {
mChildHelper.isNestedScrollingEnabled = enabled
}
override fun isNestedScrollingEnabled(): Boolean {
return mChildHelper.isNestedScrollingEnabled
}
override fun startNestedScroll(axes: Int): Boolean {
return mChildHelper.startNestedScroll(axes)
}
override fun stopNestedScroll() {
mChildHelper.stopNestedScroll()
}
override fun hasNestedScrollingParent(): Boolean {
return mChildHelper.hasNestedScrollingParent()
}
override fun dispatchNestedScroll(dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, offsetInWindow: IntArray?): Boolean {
return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow)
}
override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean {
return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow)
}
override fun dispatchNestedFling(velocityX: Float, velocityY: Float, consumed: Boolean): Boolean {
return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed)
}
override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean {
return mChildHelper.dispatchNestedPreFling(velocityX, velocityY)
}
}
|
gpl-3.0
|
c1b81f87d8fb615ebf715e62d4986db1
| 36.07874 | 147 | 0.665675 | 4.971489 | false | false | false | false |
appnexus/mobile-sdk-android
|
tests/AppNexusSDKTestApp/app/src/main/java/appnexus/com/appnexussdktestapp/utility/Utils.kt
|
1
|
2077
|
package appnexus.com.appnexussdktestapp.utility
import com.appnexus.opensdk.BannerAdView
import com.appnexus.opensdk.InterstitialAdView
import com.appnexus.opensdk.MediaType
import com.appnexus.opensdk.NativeAdRequest
import com.appnexus.opensdk.instreamvideo.VideoAd
import com.appnexus.opensdk.ut.UTRequestParameters
import com.appnexus.opensdk.utils.Clog
import java.lang.reflect.InvocationTargetException
class Utils {
fun setForceCreativeId(
creative_id: Int,
banner: BannerAdView? = null,
interstitial: InterstitialAdView? = null,
nativeAdRequest: NativeAdRequest? = null,
video: VideoAd? = null
) {
try {
var requestParameters: UTRequestParameters? = null
if (video != null) {
val videoAd = VideoAd::class.java
val met = videoAd.getDeclaredMethod("getRequestParameters")
met.isAccessible = true
requestParameters = met.invoke(video) as UTRequestParameters
} else if (banner != null) {
requestParameters = banner?.getRequestParameters()
} else if (interstitial != null) {
requestParameters = interstitial?.getRequestParameters()
} else if (nativeAdRequest != null) {
requestParameters = nativeAdRequest?.getRequestParameters()
}
Clog.e("REQ_PARAMS", requestParameters.toString())
val utParams = UTRequestParameters::class.java
val met = utParams.getDeclaredMethod("setForceCreativeId", Int::class.javaPrimitiveType)
met.isAccessible = true
met.invoke(requestParameters, creative_id)
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
}
}
fun method(): Int {
return 0
}
}
|
apache-2.0
|
c9d103a936ff8b9a04ce834fdbe9199d
| 33.633333 | 100 | 0.638421 | 5.041262 | false | false | false | false |
kotlintest/kotlintest
|
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/channels/ChannelTest.kt
|
1
|
4383
|
package com.sksamuel.kotest.matchers.channels
import io.kotest.assertions.shouldFail
import io.kotest.matchers.channels.*
import io.kotest.matchers.ints.shouldBeExactly
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.time.Duration
class ChannelTest : StringSpec() {
init {
"shouldBeClosed should not fail on closed channels" {
val channel: Channel<Int> = Channel()
channel.close()
channel.shouldBeClosed()
}
"shouldBeClosed should fail on open channels" {
val channel: Channel<Int> = Channel()
shouldFail {
channel.shouldBeClosed()
}
}
"shouldBeEmpty should not fail on empty channels" {
val channel: Channel<Int> = Channel()
channel.shouldBeEmpty()
}
"shouldBeEmpty should not fail on channels that have received all elements" {
val channel: Channel<Int> = Channel()
launch {
channel.send(1)
}
channel.receive() shouldBeExactly 1
channel.shouldBeEmpty()
}
"shouldBeEmpty should fail on non-empty channels" {
val channel: Channel<Int> = Channel(1)
channel.send(1)
shouldFail {
channel.shouldBeEmpty()
}
channel.receive() shouldBe 1
}
"shouldReceiveWithin should not fail on non-empty channels" {
val channel: Channel<Int> = Channel(1)
channel.send(1)
channel.shouldReceiveWithin(Duration.ofSeconds(1))
}
"shouldReceiveWithin should not fail when elements are received later" {
val channel: Channel<Int> = Channel()
launch {
delay(1000)
channel.send(1)
}
channel.shouldReceiveWithin(Duration.ofSeconds(3))
}
"shouldReceiveWithin should fail when no elements are sent" {
val channel: Channel<Int> = Channel()
shouldFail {
channel.shouldReceiveWithin(Duration.ofSeconds(1))
}
}
"shouldReceiveNoElementsWithin should not fail when no elements are sent" {
val channel: Channel<Int> = Channel()
channel.shouldReceiveNoElementsWithin(Duration.ofSeconds(1))
}
"shouldReceiveNoElementsWithin should fail when elements are sent" {
val channel: Channel<Int> = Channel()
launch {
channel.send(1)
}
shouldFail {
channel.shouldReceiveNoElementsWithin(Duration.ofSeconds(1))
}
}
"!shouldHaveSize should not fail when n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(10) { channel.send(1) }
channel.close()
}
channel.shouldHaveSize(10)
}
"shouldHaveSize should fail when greater than n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(12) { channel.send(1) }
channel.close()
}
shouldFail {
channel.shouldHaveSize(10)
}
repeat(2) { channel.receive() }
}
"shouldReceiveAtLeast should not fail when n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(10) { channel.send(1) }
channel.close()
}
channel.shouldReceiveAtLeast(10)
}
"shouldReceiveAtLeast should not fail when greater than n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(12) { channel.send(1) }
channel.close()
}
channel.shouldReceiveAtLeast(10)
repeat(2) { channel.receive() }
}
"shouldReceiveAtMost should not fail when n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(10) { channel.send(1) }
channel.close()
}
channel.shouldReceiveAtMost(10)
}
"shouldReceiveAtMost should not fail when less than n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(9) { channel.send(1) }
channel.close()
}
channel.shouldReceiveAtMost(10)
}
"shouldReceiveAtMost should fail when more than n elements are sent" {
val channel: Channel<Int> = Channel()
launch {
repeat(11) { channel.send(1) }
channel.close()
}
shouldFail {
channel.shouldReceiveAtMost(10)
}
channel.receive()
}
}
}
|
apache-2.0
|
ddbaf00918850402fcff50203f9a51cf
| 29.866197 | 82 | 0.633812 | 4.352532 | false | false | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/feed/item/FeedItemViewModel.kt
|
1
|
1512
|
package mil.nga.giat.mage.feed.item
import android.app.Application
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import mil.nga.giat.mage.R
import mil.nga.giat.mage.data.feed.FeedItemDao
import mil.nga.giat.mage.feed.FeedItemState
import javax.inject.Inject
class SnackbarState(val message: String = "")
@HiltViewModel
class FeedItemViewModel @Inject constructor(
val application: Application,
private val feedItemDao: FeedItemDao
): ViewModel() {
private val _snackbar = MutableStateFlow(SnackbarState())
val snackbar: StateFlow<SnackbarState>
get() = _snackbar.asStateFlow()
fun getFeedItem(feedId: String, feedItemId: String): LiveData<FeedItemState> {
return feedItemDao.item(feedId, feedItemId).map {
FeedItemState.fromItem(it, application)
}.asLiveData()
}
fun copyToClipBoard(text: String) {
val clipboard = application.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
val clip = ClipData.newPlainText("Feed Item Location", text)
if (clipboard != null && clip != null) {
clipboard.setPrimaryClip(clip)
_snackbar.value = SnackbarState(application.getString(R.string.location_text_copy_message))
}
}
}
|
apache-2.0
|
c9b52ed32d5930d7da20ab30091da21e
| 33.386364 | 100 | 0.763889 | 4.369942 | false | false | false | false |
dgrlucky/Awesome
|
app/src/main/java/com/dgrlucky/extend/kotlin/LazyThreadSafeDoubleCheck.kt
|
1
|
654
|
package net.println.kt10.kotlin
/**
* Created by benny on 11/13/16.
*/
class LazyThreadSafeDoubleCheck private constructor(){
companion object{
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
LazyThreadSafeDoubleCheck()
}
private @Volatile var instance2: LazyThreadSafeDoubleCheck? = null
fun get(): LazyThreadSafeDoubleCheck {
if(instance2 == null){
synchronized(this){
if(instance2 == null)
instance2 = LazyThreadSafeDoubleCheck()
}
}
return instance2!!
}
}
}
|
apache-2.0
|
573b6007842e636b90dffadd84ec8039
| 26.291667 | 74 | 0.568807 | 5.109375 | false | false | false | false |
robinverduijn/gradle
|
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/RepositoryHandlerExtensionsTest.kt
|
1
|
2674
|
package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.*
import org.gradle.api.Action
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import org.junit.Test
import org.mockito.invocation.InvocationOnMock
class RepositoryHandlerExtensionsTest {
@Test
fun `#maven(String)`() {
val repository = mock<MavenArtifactRepository>()
val repositories = mavenRepositoryHandlerMockFor(repository)
val url = Any()
repositories {
maven(url = url)
}
verify(repository, only()).setUrl(url)
}
@Test
fun `#maven(String, Action) sets url before invoking configuration action`() {
val repository = mock<MavenArtifactRepository>()
val repositories = mavenRepositoryHandlerMockFor(repository)
val url = Any()
repositories {
maven(url = url) {
verify(repository).setUrl(url)
name = "repo name"
}
}
verify(repository).name = "repo name"
}
@Test
fun `#ivy(String)`() {
val repository = mock<IvyArtifactRepository>()
val repositories = ivyRepositoryHandlerMockFor(repository)
val url = Any()
repositories {
ivy(url = url)
}
verify(repository, only()).setUrl(url)
}
@Test
fun `#ivy(String, Action) sets url before invoking configuration action`() {
val repository = mock<IvyArtifactRepository>()
val repositories = ivyRepositoryHandlerMockFor(repository)
val url = Any()
repositories {
ivy(url = url) {
verify(repository).setUrl(url)
name = "repo name"
}
}
verify(repository).name = "repo name"
}
private
inline operator fun RepositoryHandler.invoke(action: RepositoryHandler.() -> Unit) = apply(action)
private
fun mavenRepositoryHandlerMockFor(repository: MavenArtifactRepository) = mock<RepositoryHandler> {
on { maven(any<Action<MavenArtifactRepository>>()) }.then {
it.configureWithAction(repository)
}
}
private
fun ivyRepositoryHandlerMockFor(repository: IvyArtifactRepository) = mock<RepositoryHandler> {
on { ivy(any<Action<IvyArtifactRepository>>()) }.then {
it.configureWithAction(repository)
}
}
private
fun <T> InvocationOnMock.configureWithAction(repository: T): T = repository.also {
getArgument<Action<T>>(0).execute(it)
}
}
|
apache-2.0
|
cab08f5606316874b1195a6c1debb6c6
| 26.010101 | 102 | 0.633882 | 4.60241 | false | true | false | false |
google/horologist
|
media-data/src/main/java/com/google/android/horologist/media/data/mapper/PlayerStateMapper.kt
|
1
|
1822
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.data.mapper
import androidx.media3.common.Player
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
import com.google.android.horologist.media.model.PlayerState
/**
* Maps a [Media3 player][Player] into a [PlayerState].
*/
@ExperimentalHorologistMediaDataApi
public object PlayerStateMapper {
public fun map(player: Player): PlayerState {
return if ((
player.playbackState == Player.STATE_BUFFERING ||
player.playbackState == Player.STATE_READY
) &&
player.playWhenReady
) {
PlayerState.Playing
} else if (player.isLoading) {
PlayerState.Loading
} else {
map(player.playbackState)
}
}
private fun map(@Player.State media3PlayerState: Int): PlayerState = when (media3PlayerState) {
Player.STATE_IDLE -> PlayerState.Idle
Player.STATE_BUFFERING -> PlayerState.Loading
Player.STATE_READY -> PlayerState.Ready
Player.STATE_ENDED -> PlayerState.Ended
else -> throw IllegalArgumentException("Invalid media3 player state: $media3PlayerState")
}
}
|
apache-2.0
|
27650168e0755d31f2ee998809cec73c
| 35.44 | 99 | 0.695939 | 4.624365 | false | false | false | false |
Kotlin/dokka
|
plugins/base/src/main/kotlin/resolvers/local/DokkaLocationProviderFactory.kt
|
1
|
774
|
package org.jetbrains.dokka.base.resolvers.local
import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext
import java.util.concurrent.ConcurrentHashMap
class DokkaLocationProviderFactory(private val context: DokkaContext) : LocationProviderFactory {
private val cache = ConcurrentHashMap<CacheWrapper, LocationProvider>()
override fun getLocationProvider(pageNode: RootPageNode) = cache.computeIfAbsent(CacheWrapper(pageNode)) {
DokkaLocationProvider(pageNode, context)
}
private class CacheWrapper(val pageNode: RootPageNode) {
override fun equals(other: Any?) = other is CacheWrapper && other.pageNode == this.pageNode
override fun hashCode() = System.identityHashCode(pageNode)
}
}
|
apache-2.0
|
a664c27236cac99c4bb14b9e865906d8
| 42 | 110 | 0.781654 | 4.777778 | false | false | false | false |
vase4kin/TeamCityApp
|
app/src/main/java/com/github/vase4kin/teamcityapp/account/create/data/CreateAccountDataManagerImpl.kt
|
1
|
8042
|
/*
* Copyright 2020 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.account.create.data
import android.content.Context
import android.net.Uri
import android.os.Handler
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.TeamCityApplication
import com.github.vase4kin.teamcityapp.account.create.helper.UrlFormatter
import com.github.vase4kin.teamcityapp.api.AUTHORIZATION
import com.github.vase4kin.teamcityapp.storage.SharedUserStorage
import com.google.firebase.crashlytics.FirebaseCrashlytics
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.UnknownHostException
private const val AUTH_URL = "httpAuth/app/rest/server"
private const val AUTH_GUEST_URL = "guestAuth/app/rest/server"
private const val SCHEME_HTTP = "http"
/**
* Default error code
*/
private const val DEFAULT_ERROR_CODE = 0
/**
* Impl of [CreateAccountDataManager]
*/
class CreateAccountDataManagerImpl(
private val context: Context,
private val baseOkHttpClient: OkHttpClient,
private val unsafeBaseOkHttpClient: OkHttpClient,
private val sharedUserStorage: SharedUserStorage,
private val urlFormatter: UrlFormatter
) : CreateAccountDataManager {
/**
* {@inheritDoc}
*/
override fun authUser(
listener: CustomOnLoadingListener<String>,
url: String,
userName: String,
password: String,
isSslDisabled: Boolean,
checkSecureConnection: Boolean
) {
// Creating okHttpClient with authenticator
val okHttpClient = createClientWithAuthenticator(userName, password, isSslDisabled)
// Handling request
handleAuthRequest(url, AUTH_URL, okHttpClient, listener, checkSecureConnection)
}
private fun createClientWithAuthenticator(
userName: String,
password: String,
isSslDisabled: Boolean
): OkHttpClient {
return getClient(isSslDisabled).newBuilder().authenticator { _, response ->
val credential = Credentials.basic(userName, password)
if (credential == response.request().header(AUTHORIZATION)) {
return@authenticator null // If we already failed with these credentials, don't retry.
}
response.request().newBuilder()
.header(AUTHORIZATION, credential)
.build()
}.build()
}
/**
* {@inheritDoc}
*/
override fun authGuestUser(
listener: CustomOnLoadingListener<String>,
url: String,
isSslDisabled: Boolean,
checkSecureConnection: Boolean
) {
handleAuthRequest(
url,
AUTH_GUEST_URL,
getClient(isSslDisabled),
listener,
checkSecureConnection
)
}
/**
* @return [OkHttpClient] depending on ssl enabled state
*/
private fun getClient(isSslEnabled: Boolean): OkHttpClient {
return if (isSslEnabled) unsafeBaseOkHttpClient else baseOkHttpClient
}
/**
* Handle auth request
*
* @param serverUrl - Server url
* @param authUrl - Appended auth url
* @param okHttpClient - Client to make an auth
* @param listener - Listener to receive callbacks
*/
private fun handleAuthRequest(
serverUrl: String,
authUrl: String,
okHttpClient: OkHttpClient,
listener: CustomOnLoadingListener<String>,
checkSecureConnection: Boolean
) {
val serverAuthUri = Uri.parse(serverUrl).buildUpon()
.appendEncodedPath(authUrl).build()
if (checkSecureConnection && SCHEME_HTTP == serverAuthUri.scheme) {
listener.onFail(
CreateAccountDataManager.ERROR_CODE_HTTP_NOT_SECURE,
context.getString(R.string.server_not_secure_http)
)
return
}
val handler = Handler(context.mainLooper)
try {
val request = Request.Builder()
.url(serverAuthUri.toString())
.build()
okHttpClient
.newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
handler.post {
if (e is UnknownHostException) {
listener.onFail(
DEFAULT_ERROR_CODE,
context.getString(R.string.server_no_such_server)
)
} else {
listener.onFail(DEFAULT_ERROR_CODE, e.message ?: "")
}
}
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val formattedServerUrl = urlFormatter.formatServerUrl(serverUrl)
handler.post { listener.onSuccess(formattedServerUrl) }
} else {
var message: String
if (response.body() != null && response.body()!!.source() != null) {
try {
message = response.body()!!.source().readUtf8()
} catch (exception: IOException) {
FirebaseCrashlytics.getInstance().recordException(exception)
message = response.message()
}
} else {
message = response.message()
}
handler.post { listener.onFail(response.code(), message) }
}
}
})
} catch (e: IllegalArgumentException) {
listener.onFail(DEFAULT_ERROR_CODE, context.getString(R.string.server_correct_url))
} catch (e: Exception) {
listener.onFail(DEFAULT_ERROR_CODE, context.getString(R.string.server_check_url))
}
}
/**
* {@inheritDoc}
*/
override fun saveNewUserAccount(
serverUrl: String,
userName: String,
password: String,
isSslDisabled: Boolean,
listener: OnLoadingListener<String>
) {
sharedUserStorage.saveUserAccountAndSetItAsActive(
serverUrl,
userName,
password,
isSslDisabled,
object : SharedUserStorage.OnStorageListener {
override fun onSuccess() {
// On data save success
listener.onSuccess(serverUrl)
}
override fun onFail() {
// On data save fail
listener.onFail("")
}
}
)
}
/**
* {@inheritDoc}
*/
override fun saveGuestUserAccount(url: String, isSslDisabled: Boolean) {
sharedUserStorage.saveGuestUserAccountAndSetItAsActive(url, isSslDisabled)
}
/**
* {@inheritDoc}
*/
override fun initTeamCityService(url: String) {
(context.applicationContext as TeamCityApplication).buildRestApiInjectorWithBaseUrl(url)
}
}
|
apache-2.0
|
b9cfd01d8085a559c9dc2742e21410ef
| 32.789916 | 102 | 0.58294 | 5.256209 | false | false | false | false |
techlung/wearfaceutils
|
wearfaceutils-sample/src/main/java/com/techlung/wearfaceutils/sample/modules/face/BackgroundPainter.kt
|
1
|
1196
|
package com.techlung.wearfaceutils.sample.modules.face
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.support.v4.content.ContextCompat
import com.techlung.wearfaceutils.sample.R
import com.techlung.wearfaceutils.sample.generic.GenericPainter
class BackgroundPainter : GenericPainter {
private var initialized: Boolean = false
private var backgroundPaint: Paint = Paint()
private var isAmbient: Boolean = false;
override fun setAmbientMode(isAmbient: Boolean) {
this.isAmbient = isAmbient
}
fun onDraw(context: Context, canvas: Canvas, bounds: Rect): Boolean {
if (!initialized) {
initialize(context, bounds)
}
if (isAmbient) {
canvas.drawColor(Color.BLACK)
} else {
canvas.drawRect(0f, 0f, bounds.width().toFloat(), bounds.height().toFloat(), backgroundPaint)
}
return false
}
fun initialize(context: Context, bounds: Rect) {
initialized = true
backgroundPaint.color = ContextCompat.getColor(context, R.color.background)
}
}
|
apache-2.0
|
3dbfd310d87e998624441c191f347c76
| 28.195122 | 105 | 0.700669 | 4.226148 | false | false | false | false |
mrkirby153/KirBot
|
src/main/kotlin/me/mrkirby153/KirBot/command/executors/admin/CommandStats.kt
|
1
|
3921
|
package me.mrkirby153.KirBot.command.executors.admin
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.globalAdmin
import me.mrkirby153.kcutils.Time
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.sharding.ShardManager
import java.awt.Color
import javax.inject.Inject
class CommandStats @Inject constructor(private val shardManager: ShardManager){
@Command(name = "stats", category = CommandCategory.UTILITY, permissions = [Permission.MESSAGE_EMBED_LINKS])
@CommandDescription("Displays statistics about the bot")
fun execute(context: Context, cmdContext: CommandContext) {
var guilds = 0
val users = mutableSetOf<String>()
for (shard in shardManager.shards) {
guilds += shard.guilds.size
users.addAll(shard.users.map { it.id })
}
context.send().embed("Bot Statistics") {
color = Color.BLUE
fields {
field {
title = "Servers"
inline = true
description = guilds.toString()
}
field {
title = "Shard"
inline = true
description = context.jda.shardInfo.shardId.toString()
}
field {
title = "Users"
inline = true
description = users.size.toString()
}
field {
title = "Messages"
inline = true
description = "${messages.values.sum()} total. ${messages[context.guild.id]} in this server"
}
field {
title = "Uptime"
inline = true
description = Time.formatLong(System.currentTimeMillis() - Bot.startTime)
}
field {
title = "Version"
inline = !context.author.globalAdmin
description = buildString {
val gitProperties = Bot.gitProperties
if (gitProperties == null) {
append("_Build information currently unavailable_")
} else {
if (!context.author.globalAdmin) {
append(gitProperties.getProperty("git.build.version", "Unknown"))
} else {
appendln("__Branch__: ${gitProperties["git.branch"]}")
append("__Commit__: ${gitProperties["git.commit.id"]}")
if (gitProperties.getProperty("git.dirty", "false")!!.toBoolean()) {
append("*\n")
} else {
append("\n")
}
appendln(
"__Message__: `${gitProperties["git.commit.message.short"]}`")
}
}
}
}
field {
title = "URL"
inline = true
description = Bot.constants.getProperty("bot-base-url")
}
}
}.rest().queue()
}
companion object {
var messages = mutableMapOf<String, Long>()
fun incMessage(guild: Guild) {
messages[guild.id] = (messages[guild.id] ?: 0) + 1
}
}
}
|
mit
|
16fe8ced7cc04c69ad16572793da5b3e
| 38.616162 | 112 | 0.487376 | 5.423237 | false | false | false | false |
ThanosFisherman/WifiUtils
|
buildSrc/src/main/kotlin/GradleDependency.kt
|
1
|
679
|
object GradlePluginVersion {
const val ANDROID_GRADLE = "7.0.2"
const val KOTLIN = CoreVersion.KOTLIN
const val DOKKA_VERSION = "1.5.30"
const val DEPENDENCY_UPDATE_VERSION = "0.39.0"
}
object GradlePluginId {
const val ANDROID_GRADLE_PLUGIN = "com.android.tools.build:gradle:${GradlePluginVersion.ANDROID_GRADLE}"
const val KOTLIN_GRADLE_PLUGIN = "org.jetbrains.kotlin:kotlin-gradle-plugin:${GradlePluginVersion.KOTLIN}"
const val ANDROID_APPLICATION = "com.android.application"
const val ANDROID_LIBRARY = "com.android.library"
const val DOKKA = "org.jetbrains.dokka"
const val DEPENDENCY_UPDATE = "com.github.ben-manes.versions"
}
|
apache-2.0
|
57f92e5c49a0df7768fef9eda48c55a5
| 34.736842 | 110 | 0.730486 | 3.67027 | false | false | false | false |
charlesmadere/smash-ranks-android
|
smash-ranks-android/app/src/main/java/com/garpr/android/features/player/PlayerProfileManagerImpl.kt
|
1
|
3654
|
package com.garpr.android.features.player
import android.content.Context
import android.text.TextUtils
import com.garpr.android.R
import com.garpr.android.data.models.AbsPlayer
import com.garpr.android.data.models.AbsRegion
import com.garpr.android.data.models.FullPlayer
import com.garpr.android.data.models.SmashCompetitor
import com.garpr.android.extensions.truncate
import com.garpr.android.features.player.PlayerProfileManager.Presentation
import com.garpr.android.misc.Constants
class PlayerProfileManagerImpl(
private val context: Context,
private val smashRosterAvatarUrlHelper: SmashRosterAvatarUrlHelper
) : PlayerProfileManager {
override fun getPresentation(identity: AbsPlayer?, region: AbsRegion, isFavorited: Boolean,
player: FullPlayer, smashCompetitor: SmashCompetitor?): Presentation {
var presentation = Presentation(
isAddToFavoritesVisible = !isFavorited,
isCompareVisible = identity != null && identity != player
)
player.ratings?.get(region.id)?.let { rating ->
presentation = presentation.copy(
rating = context.getString(R.string.rating_x, rating.rating.truncate()),
unadjustedRating = context.getString(
R.string.unadjusted_x_y,
rating.mu.truncate(),
rating.sigma.truncate()
)
)
}
val uniqueAliases = player.uniqueAliases
if (!uniqueAliases.isNullOrEmpty()) {
presentation = presentation.copy(
aliases = context.resources.getQuantityString(
R.plurals.aliases_x,
uniqueAliases.size,
TextUtils.join(context.getText(R.string.delimiter), uniqueAliases)
)
)
}
if (smashCompetitor == null) {
presentation = presentation.copy(tag = player.name)
return presentation
}
presentation = presentation.copy(
name = smashCompetitor.name,
tag = smashCompetitor.tag
)
val avatar = smashRosterAvatarUrlHelper.getAvatarUrl(
avatarPath = smashCompetitor.avatar?.largeButFallbackToMediumThenOriginalThenSmall
)
if (!avatar.isNullOrBlank()) {
presentation = presentation.copy(avatar = avatar)
}
val filteredMains = smashCompetitor.filteredMains
if (!filteredMains.isNullOrEmpty()) {
val mainsStrings = filteredMains.map { main ->
context.getString(main.textResId)
}
presentation = presentation.copy(
mains = context.resources.getQuantityString(
R.plurals.mains_x,
filteredMains.size,
TextUtils.join(context.getText(R.string.delimiter), mainsStrings)
)
)
}
val twitch = smashCompetitor.websites?.get(Constants.TWITCH)
if (!twitch.isNullOrBlank()) {
presentation = presentation.copy(twitch = twitch)
}
val twitter = smashCompetitor.websites?.get(Constants.TWITTER)
if (!twitter.isNullOrBlank()) {
presentation = presentation.copy(twitter = twitter)
}
val youTube = smashCompetitor.websites?.get(Constants.YOUTUBE)
if (!youTube.isNullOrBlank()) {
presentation = presentation.copy(youTube = youTube)
}
return presentation
}
}
|
unlicense
|
4eec9fb4432c0938ae4a05b8843148d2
| 35.909091 | 95 | 0.601533 | 5.146479 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox
|
profile_cgms/src/main/java/no/nordicsemi/android/cgms/view/CGMScreen.kt
|
1
|
4235
|
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.cgms.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import no.nordicsemi.android.cgms.R
import no.nordicsemi.android.cgms.viewmodel.CGMViewModel
import no.nordicsemi.android.service.*
import no.nordicsemi.android.ui.view.BackIconAppBar
import no.nordicsemi.android.ui.view.LoggerIconAppBar
import no.nordicsemi.android.utils.exhaustive
import no.nordicsemi.ui.scanner.ui.DeviceConnectingView
import no.nordicsemi.ui.scanner.ui.DeviceDisconnectedView
import no.nordicsemi.ui.scanner.ui.NoDeviceView
import no.nordicsemi.ui.scanner.ui.Reason
@Composable
fun CGMScreen() {
val viewModel: CGMViewModel = hiltViewModel()
val state = viewModel.state.collectAsState().value
Column {
val navigateUp = { viewModel.onEvent(NavigateUp) }
AppBar(state, navigateUp, viewModel)
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
when (state) {
NoDeviceState -> NoDeviceView()
is WorkingState -> when (state.result) {
is IdleResult,
is ConnectingResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) }
is ConnectedResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) }
is DisconnectedResult -> DeviceDisconnectedView(Reason.USER, navigateUp)
is LinkLossResult -> DeviceDisconnectedView(Reason.LINK_LOSS, navigateUp)
is MissingServiceResult -> DeviceDisconnectedView(Reason.MISSING_SERVICE, navigateUp)
is UnknownErrorResult -> DeviceDisconnectedView(Reason.UNKNOWN, navigateUp)
is SuccessResult -> CGMContentView(state.result.data) { viewModel.onEvent(it) }
}
}.exhaustive
}
}
}
@Composable
private fun AppBar(state: CGMViewState, navigateUp: () -> Unit, viewModel: CGMViewModel) {
val toolbarName = (state as? WorkingState)?.let {
(it.result as? DeviceHolder)?.deviceName()
}
if (toolbarName == null) {
BackIconAppBar(stringResource(id = R.string.cgms_title), navigateUp)
} else {
LoggerIconAppBar(toolbarName, navigateUp, { viewModel.onEvent(DisconnectEvent) }) {
viewModel.onEvent(OpenLoggerEvent)
}
}
}
|
bsd-3-clause
|
dfb8623a9c1666b4a7f83fd8f1ef5a4c
| 44.053191 | 105 | 0.734357 | 4.633479 | false | false | false | false |
hidroh/materialistic
|
app/src/main/java/io/github/hidroh/materialistic/AboutActivity.kt
|
1
|
2403
|
/*
* Copyright (c) 2015 Ha Duy Trung
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.hidroh.materialistic
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.appcompat.app.ActionBar
import android.view.MenuItem
class AboutActivity : InjectableActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
setSupportActionBar(findViewById(R.id.toolbar))
supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_HOME or
ActionBar.DISPLAY_HOME_AS_UP or ActionBar.DISPLAY_SHOW_TITLE
var versionName = ""
var versionCode = 0
try {
versionName = packageManager.getPackageInfo(packageName, 0).versionName
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode
} catch (e: PackageManager.NameNotFoundException) {
// do nothing
}
setTextWithLinks(R.id.text_application_info, getString(R.string.application_info_text, versionName, versionCode))
setTextWithLinks(R.id.text_developer_info, getString(R.string.developer_info_text))
setTextWithLinks(R.id.text_libraries, getString(R.string.libraries_text))
setTextWithLinks(R.id.text_license, getString(R.string.license_text))
setTextWithLinks(R.id.text_3rd_party_licenses, getString(R.string.third_party_licenses_text))
setTextWithLinks(R.id.text_privacy_policy, getString(R.string.privacy_policy_text))
}
private fun setTextWithLinks(@IdRes textViewResId: Int, htmlText: String) {
AppUtils.setTextWithLinks(findViewById(textViewResId), AppUtils.fromHtml(htmlText))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
}
|
apache-2.0
|
36d4e354424825441df313fa4749cd3f
| 37.758065 | 117 | 0.752809 | 4.100683 | false | false | false | false |
sangcomz/FishBun
|
FishBunDemo/src/main/java/com/sangcomz/fishbundemo/WithActivityActivity.kt
|
1
|
6559
|
package com.sangcomz.fishbundemo
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.sangcomz.fishbun.FishBun
import com.sangcomz.fishbun.MimeType
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter
import com.sangcomz.fishbun.adapter.image.impl.CoilAdapter
import com.sangcomz.fishbundemo.databinding.ActivityWithactivityBinding
import java.util.*
class WithActivityActivity : AppCompatActivity() {
var path = ArrayList<Uri>()
private lateinit var imageAdapter: ImageAdapter
private var mode: Int = 0
private lateinit var binding: ActivityWithactivityBinding
private val startForResultCallback = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
path = it.data?.getParcelableArrayListExtra(FishBun.INTENT_PATH) ?: arrayListOf()
imageAdapter.changePath(path)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityWithactivityBinding.inflate(layoutInflater)
setContentView(binding.root)
mode = intent.getIntExtra("mode", -1)
with(binding.recyclerview) {
layoutManager = LinearLayoutManager(
this@WithActivityActivity,
LinearLayoutManager.HORIZONTAL,
false
)
imageAdapter = ImageAdapter(context, ImageController(binding.imgMain), path)
adapter = imageAdapter
}
}
override fun onActivityResult(
requestCode: Int, resultCode: Int,
imageData: Intent?
) {
super.onActivityResult(requestCode, resultCode, imageData)
if (requestCode == FishBun.FISHBUN_REQUEST_CODE && resultCode == RESULT_OK) {
path = imageData?.getParcelableArrayListExtra(FishBun.INTENT_PATH) ?: arrayListOf()
imageAdapter.changePath(path)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_plus) {
when (mode) {
//basic
0 -> {
FishBun.with(this@WithActivityActivity)
.setImageAdapter(GlideAdapter())
.setSelectedImages(path)
.startAlbumWithActivityResultCallback(startForResultCallback)
}
//dark
1 -> {
FishBun.with(this@WithActivityActivity)
.setImageAdapter(GlideAdapter())
.setMaxCount(5)
.setMinCount(3)
.setPickerSpanCount(5)
.setActionBarColor(
Color.parseColor("#795548"),
Color.parseColor("#5D4037"),
false
)
.setActionBarTitleColor(Color.parseColor("#ffffff"))
.setSelectedImages(path)
.setAlbumSpanCount(2, 3)
.setButtonInAlbumActivity(false)
.hasCameraInPickerPage(true)
.exceptMimeType(arrayListOf(MimeType.GIF))
.setReachLimitAutomaticClose(true)
.setHomeAsUpIndicatorDrawable(
ContextCompat.getDrawable(
this,
R.drawable.ic_custom_back_white
)
)
.setDoneButtonDrawable(
ContextCompat.getDrawable(
this,
R.drawable.ic_custom_ok
)
)
.setAllViewTitle("All")
.setActionBarTitle("FishBun Dark")
.textOnNothingSelected("Please select three or more!")
.startAlbum()
}
//Light
2 -> {
FishBun.with(this@WithActivityActivity)
.setImageAdapter(CoilAdapter())
.setMaxCount(50)
.setPickerSpanCount(4)
.setActionBarColor(
Color.parseColor("#ffffff"),
Color.parseColor("#ffffff"),
true
)
.setActionBarTitleColor(Color.parseColor("#000000"))
.setSelectedImages(path)
.setAlbumSpanCount(1, 2)
.setButtonInAlbumActivity(true)
.hasCameraInPickerPage(false)
.exceptMimeType(arrayListOf(MimeType.GIF))
.setReachLimitAutomaticClose(false)
.setHomeAsUpIndicatorDrawable(
ContextCompat.getDrawable(
this,
R.drawable.ic_arrow_back_black_24dp
)
)
.setIsUseAllDoneButton(true)
.setMenuDoneText("Choose")
.setMenuAllDoneText("Choose All")
.setIsUseAllDoneButton(true)
.setAllViewTitle("All of your photos")
.setActionBarTitle("FishBun Light")
.textOnImagesSelectionLimitReached("You can't select any more.")
.textOnNothingSelected("I need a photo!")
.startAlbum()
}
else -> {
finish()
}
}
return true
}
return super.onOptionsItemSelected(item)
}
}
|
apache-2.0
|
5473b2f10c6a62085cf26c7c9948e77f
| 39.487654 | 118 | 0.52569 | 6.00641 | false | false | false | false |
msebire/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.kt
|
1
|
5436
|
// 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.openapi.vcs.ex
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.ide.GeneralSettings
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.editor.markup.MarkupEditorFilter
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import java.awt.Graphics
import java.awt.Point
import java.awt.event.MouseEvent
import java.util.*
interface LineStatusTracker<out R : Range> : LineStatusTrackerI<R> {
val project: Project
override val virtualFile: VirtualFile
fun isAvailableAt(editor: Editor): Boolean
fun scrollAndShowHint(range: Range, editor: Editor)
fun showHint(range: Range, editor: Editor)
}
abstract class LocalLineStatusTracker<R : Range> constructor(override val project: Project,
document: Document,
override val virtualFile: VirtualFile,
mode: Mode
) : LineStatusTrackerBase<R>(project, document), LineStatusTracker<R> {
enum class Mode {
DEFAULT, SMART, SILENT
}
private val vcsDirtyScopeManager: VcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project)
abstract override val renderer: LocalLineStatusMarkerRenderer
var mode: Mode = mode
set(value) {
if (value == mode) return
field = value
updateInnerRanges()
}
@CalledInAwt
override fun isAvailableAt(editor: Editor): Boolean {
return mode != Mode.SILENT && editor.settings.isLineMarkerAreaShown && !DiffUtil.isDiffEditor(editor)
}
@CalledInAwt
override fun isDetectWhitespaceChangedLines(): Boolean = mode == Mode.SMART
@CalledInAwt
override fun fireFileUnchanged() {
if (GeneralSettings.getInstance().isSaveOnFrameDeactivation) {
// later to avoid saving inside document change event processing and deadlock with CLM.
TransactionGuard.getInstance().submitTransactionLater(project, Runnable {
FileDocumentManager.getInstance().saveDocument(document)
val isEmpty = documentTracker.readLock { blocks.isEmpty() }
if (isEmpty) {
// file was modified, and now it's not -> dirty local change
vcsDirtyScopeManager.fileDirty(virtualFile)
}
})
}
}
override fun fireLinesUnchanged(startLine: Int, endLine: Int) {
if (document.textLength == 0) return // empty document has no lines
if (startLine == endLine) return
(document as DocumentImpl).clearLineModificationFlags(startLine, endLine)
}
override fun scrollAndShowHint(range: Range, editor: Editor) {
renderer.scrollAndShow(editor, range)
}
override fun showHint(range: Range, editor: Editor) {
renderer.showAfterScroll(editor, range)
}
protected open class LocalLineStatusMarkerRenderer(open val tracker: LocalLineStatusTracker<*>)
: LineStatusMarkerPopupRenderer(tracker) {
override fun getEditorFilter(): MarkupEditorFilter? = MarkupEditorFilterFactory.createIsNotDiffFilter()
override fun canDoAction(editor: Editor, ranges: List<Range>, e: MouseEvent): Boolean {
if (tracker.mode == Mode.SILENT) return false
return super.canDoAction(editor, ranges, e)
}
override fun paint(editor: Editor, g: Graphics) {
if (tracker.mode == Mode.SILENT) return
super.paint(editor, g)
}
override fun createToolbarActions(editor: Editor, range: Range, mousePosition: Point?): List<AnAction> {
val actions = ArrayList<AnAction>()
actions.add(ShowPrevChangeMarkerAction(editor, range))
actions.add(ShowNextChangeMarkerAction(editor, range))
actions.add(RollbackLineStatusRangeAction(editor, range))
actions.add(ShowLineStatusRangeDiffAction(editor, range))
actions.add(CopyLineStatusRangeAction(editor, range))
actions.add(ToggleByWordDiffAction(editor, range, mousePosition))
return actions
}
override fun getFileType(): FileType = tracker.virtualFile.fileType
private inner class RollbackLineStatusRangeAction(editor: Editor, range: Range)
: RangeMarkerAction(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK) {
override fun isEnabled(editor: Editor, range: Range): Boolean = true
override fun actionPerformed(editor: Editor, range: Range) {
RollbackLineStatusAction.rollback(tracker, range, editor)
}
}
}
@CalledInAny
internal fun freeze() {
documentTracker.freeze(Side.LEFT)
documentTracker.freeze(Side.RIGHT)
}
@CalledInAwt
internal fun unfreeze() {
documentTracker.unfreeze(Side.LEFT)
documentTracker.unfreeze(Side.RIGHT)
}
}
|
apache-2.0
|
f1360fc6686fcf11ae63123d417e8437
| 36.75 | 140 | 0.730684 | 4.682171 | false | false | false | false |
samiuelson/Hipstore
|
hipstore/src/test/java/tech/lab23/hipstore/EntitiesStorageTest.kt
|
1
|
2771
|
package tech.lab23.hipstore
import android.content.SharedPreferences
import android.preference.PreferenceManager
import junit.framework.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class)
class EntitiesStorageTest {
var prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application)
@Before
fun init() {
prefs.edit().clear().apply()
}
@Test
fun contains() {
// given empty storage
val storage = entitiesStorage<TestMocks.Person>(prefs)
org.junit.Assert.assertTrue(storage.all.isEmpty())
// when Bob is added to storage
val bob = TestMocks.MocksProvider.provideBob()
storage.add(bob)
// then
org.junit.Assert.assertTrue(storage.contains(bob))
org.junit.Assert.assertTrue(storage.all.size == 1)
}
@Test
fun remove() {
// given storage with Bob inside
val storage = entitiesStorage<TestMocks.Person>(prefs)
org.junit.Assert.assertTrue(storage.all.isEmpty())
val bob = TestMocks.MocksProvider.provideBob()
storage.add(bob)
Assert.assertTrue(storage.contains(bob))
// when
storage.remove(bob)
// then
Assert.assertFalse(storage.contains(bob))
Assert.assertTrue(storage.all.isEmpty())
}
@Test
fun getAll() {
// given storage
val storage = entitiesStorage<TestMocks.Person>(prefs)
org.junit.Assert.assertTrue(storage.all.isEmpty())
// when
val bob = TestMocks.MocksProvider.provideBob()
val ala = TestMocks.MocksProvider.provideAlice()
storage.add(bob)
storage.add(ala)
// then
Assert.assertFalse(storage.contains(bob))
Assert.assertFalse(storage.contains(ala))
Assert.assertTrue(storage.all.contains(bob))
Assert.assertTrue(storage.all.contains(ala))
Assert.assertTrue(storage.all.size == 2)
}
@Test
@Throws(Exception::class)
fun clear() {
// given storage with Bob and Ala inside
val storage = entitiesStorage<TestMocks.Person>(prefs)
org.junit.Assert.assertTrue(storage.all.isEmpty())
val bob = TestMocks.MocksProvider.provideBob()
val ala = TestMocks.MocksProvider.provideAlice()
storage.add(bob)
storage.add(ala)
// when
storage.clear()
// then
Assert.assertTrue(storage.all.size == 0)
Assert.assertTrue(storage.all.isEmpty())
}
}
|
apache-2.0
|
ac38833311209fd3db8b6111215b1fd3
| 28.178947 | 112 | 0.663298 | 4.336463 | false | true | false | false |
valich/intellij-markdown
|
src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/impl/BacktickParser.kt
|
1
|
2353
|
package org.intellij.markdown.parser.sequentialparsers.impl
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.sequentialparsers.RangesListBuilder
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil
import org.intellij.markdown.parser.sequentialparsers.TokensCache
class BacktickParser : SequentialParser {
override fun parse(tokens: TokensCache, rangesToGlue: List<IntRange>): SequentialParser.ParsingResult {
val result = SequentialParser.ParsingResultBuilder()
val delegateIndices = RangesListBuilder()
var iterator: TokensCache.Iterator = tokens.RangesListIterator(rangesToGlue)
while (iterator.type != null) {
if (iterator.type == MarkdownTokenTypes.BACKTICK || iterator.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) {
val endIterator = findOfSize(iterator.advance(), getLength(iterator, true))
if (endIterator != null) {
result.withNode(SequentialParser.Node(iterator.index..endIterator.index + 1, MarkdownElementTypes.CODE_SPAN))
iterator = endIterator.advance()
continue
}
}
delegateIndices.put(iterator.index)
iterator = iterator.advance()
}
return result.withFurtherProcessing(delegateIndices.get())
}
private fun findOfSize(it: TokensCache.Iterator, length: Int): TokensCache.Iterator? {
var iterator = it
while (iterator.type != null) {
if (iterator.type == MarkdownTokenTypes.BACKTICK || iterator.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) {
if (getLength(iterator, false) == length) {
return iterator
}
}
iterator = iterator.advance()
}
return null
}
private fun getLength(info: TokensCache.Iterator, canEscape: Boolean): Int {
var toSubtract = 0
if (info.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) {
if (canEscape) {
toSubtract = 2
} else {
toSubtract = 1
}
}
return info.length - toSubtract
}
}
|
apache-2.0
|
32380d5d8fa0daeebaf08fab14bfb252
| 37.57377 | 129 | 0.648959 | 5.093074 | false | false | false | false |
icanit/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt
|
1
|
9763
|
package eu.kanade.tachiyomi.ui.catalogue
import android.os.Bundle
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.source.SourceManager
import eu.kanade.tachiyomi.data.source.base.Source
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.RxPager
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import timber.log.Timber
import javax.inject.Inject
/**
* Presenter of [CatalogueFragment].
*/
class CataloguePresenter : BasePresenter<CatalogueFragment>() {
/**
* Source manager.
*/
@Inject lateinit var sourceManager: SourceManager
/**
* Database.
*/
@Inject lateinit var db: DatabaseHelper
/**
* Preferences.
*/
@Inject lateinit var prefs: PreferencesHelper
/**
* Enabled sources.
*/
val sources by lazy { getEnabledSources() }
/**
* Active source.
*/
lateinit var source: Source
private set
/**
* Query from the view.
*/
private var query: String? = null
/**
* Pager containing a list of manga results.
*/
private lateinit var pager: RxPager<Manga>
/**
* Last fetched page from network.
*/
private var lastMangasPage: MangasPage? = null
/**
* Subject that initializes a list of manga.
*/
private val mangaDetailSubject = PublishSubject.create<List<Manga>>()
/**
* Whether the view is in list mode or not.
*/
var isListMode: Boolean = false
private set
companion object {
/**
* Id of the restartable that delivers a list of manga from network.
*/
const val GET_MANGA_LIST = 1
/**
* Id of the restartable that requests the list of manga from network.
*/
const val GET_MANGA_PAGE = 2
/**
* Id of the restartable that initializes the details of a manga.
*/
const val GET_MANGA_DETAIL = 3
/**
* Key to save and restore [source] from a [Bundle].
*/
const val ACTIVE_SOURCE_KEY = "active_source"
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
if (savedState != null) {
source = sourceManager.get(savedState.getInt(ACTIVE_SOURCE_KEY))!!
}
pager = RxPager()
startableReplay(GET_MANGA_LIST,
{ pager.results() },
{ view, pair -> view.onAddPage(pair.first, pair.second) })
startableFirst(GET_MANGA_PAGE,
{ pager.request { page -> getMangasPageObservable(page + 1) } },
{ view, next -> },
{ view, error -> view.onAddPageError(error) })
startableLatestCache(GET_MANGA_DETAIL,
{ mangaDetailSubject.observeOn(Schedulers.io())
.flatMap { Observable.from(it) }
.filter { !it.initialized }
.concatMap { getMangaDetailsObservable(it) }
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread()) },
{ view, manga -> view.onMangaInitialized(manga) },
{ view, error -> Timber.e(error.message) })
add(prefs.catalogueAsList().asObservable()
.subscribe { setDisplayMode(it) })
}
override fun onSave(state: Bundle) {
state.putInt(ACTIVE_SOURCE_KEY, source.id)
super.onSave(state)
}
/**
* Sets the display mode.
*
* @param asList whether the current mode is in list or not.
*/
private fun setDisplayMode(asList: Boolean) {
isListMode = asList
if (asList) {
stop(GET_MANGA_DETAIL)
} else {
start(GET_MANGA_DETAIL)
}
}
/**
* Starts the request with the given source.
*
* @param source the active source.
*/
fun startRequesting(source: Source) {
this.source = source
restartRequest(null)
}
/**
* Restarts the request for the active source with a query.
*
* @param query a query, or null if searching popular manga.
*/
fun restartRequest(query: String?) {
this.query = query
stop(GET_MANGA_PAGE)
lastMangasPage = null
if (!isListMode) {
start(GET_MANGA_DETAIL)
}
start(GET_MANGA_LIST)
start(GET_MANGA_PAGE)
}
/**
* Requests the next page for the active pager.
*/
fun requestNext() {
if (hasNextPage()) {
start(GET_MANGA_PAGE)
}
}
/**
* Retry a failed request.
*/
fun retryRequest() {
start(GET_MANGA_PAGE)
}
/**
* Returns the observable of the network request for a page.
*
* @param page the page number to request.
* @return an observable of the network request.
*/
private fun getMangasPageObservable(page: Int): Observable<List<Manga>> {
val nextMangasPage = MangasPage(page)
if (page != 1) {
nextMangasPage.url = lastMangasPage!!.nextPageUrl
}
val obs = if (query.isNullOrEmpty())
source.pullPopularMangasFromNetwork(nextMangasPage)
else
source.searchMangasFromNetwork(nextMangasPage, query!!)
return obs.subscribeOn(Schedulers.io())
.doOnNext { lastMangasPage = it }
.flatMap { Observable.from(it.mangas) }
.map { networkToLocalManga(it) }
.toList()
.doOnNext { initializeMangas(it) }
.observeOn(AndroidSchedulers.mainThread())
}
/**
* Returns a manga from the database for the given manga from network. It creates a new entry
* if the manga is not yet in the database.
*
* @param networkManga the manga from network.
* @return a manga from the database.
*/
private fun networkToLocalManga(networkManga: Manga): Manga {
var localManga = db.getManga(networkManga.url, source.id).executeAsBlocking()
if (localManga == null) {
val result = db.insertManga(networkManga).executeAsBlocking()
networkManga.id = result.insertedId()
localManga = networkManga
}
return localManga
}
/**
* Initialize a list of manga.
*
* @param mangas the list of manga to initialize.
*/
fun initializeMangas(mangas: List<Manga>) {
mangaDetailSubject.onNext(mangas)
}
/**
* Returns an observable of manga that initializes the given manga.
*
* @param manga the manga to initialize.
* @return an observable of the manga to initialize
*/
private fun getMangaDetailsObservable(manga: Manga): Observable<Manga> {
return source.pullMangaFromNetwork(manga.url)
.flatMap { networkManga ->
manga.copyFrom(networkManga)
db.insertManga(manga).executeAsBlocking()
Observable.just(manga)
}
.onErrorResumeNext { Observable.just(manga) }
}
/**
* Returns true if the last fetched page has a next page.
*/
fun hasNextPage(): Boolean {
return lastMangasPage?.nextPageUrl != null
}
/**
* Gets the last used source from preferences, or the first valid source.
*
* @return the index of the last used source.
*/
fun getLastUsedSourceIndex(): Int {
val index = prefs.lastUsedCatalogueSource().get() ?: -1
if (index < 0 || index >= sources.size || !isValidSource(sources[index])) {
return findFirstValidSource()
}
return index
}
/**
* Checks if the given source is valid.
*
* @param source the source to check.
* @return true if the source is valid, false otherwise.
*/
fun isValidSource(source: Source): Boolean = with(source) {
if (!isLoginRequired || isLogged)
return true
prefs.sourceUsername(this) != "" && prefs.sourcePassword(this) != ""
}
/**
* Finds the first valid source.
*
* @return the index of the first valid source.
*/
fun findFirstValidSource(): Int {
return sources.indexOfFirst { isValidSource(it) }
}
/**
* Sets the enabled source.
*
* @param index the index of the source in [sources].
*/
fun setEnabledSource(index: Int) {
prefs.lastUsedCatalogueSource().set(index)
}
/**
* Returns a list of enabled sources ordered by language and name.
*/
private fun getEnabledSources(): List<Source> {
val languages = prefs.enabledLanguages().getOrDefault()
// Ensure at least one language
if (languages.isEmpty()) {
languages.add("EN")
}
return sourceManager.getSources()
.filter { it.lang.code in languages }
.sortedBy { "(${it.lang.code}) ${it.name}" }
}
/**
* Adds or removes a manga from the library.
*
* @param manga the manga to update.
*/
fun changeMangaFavorite(manga: Manga) {
manga.favorite = !manga.favorite
db.insertManga(manga).executeAsBlocking()
}
/**
* Changes the active display mode.
*/
fun swapDisplayMode() {
prefs.catalogueAsList().set(!isListMode)
}
}
|
apache-2.0
|
2069a178ab18b48aec1f387031cd1649
| 27.298551 | 97 | 0.58947 | 4.572834 | false | false | false | false |
Gu3pardo/PasswordSafe-AndroidClient
|
mobile/src/main/java/guepardoapps/passwordsafe/repositories/AccountGroupRepository.kt
|
1
|
5868
|
package guepardoapps.passwordsafe.repositories
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.github.guepardoapps.kulid.ULID
import guepardoapps.encryption.decryptHash
import guepardoapps.encryption.encryptObject
import guepardoapps.passwordsafe.enums.ModelState
import guepardoapps.passwordsafe.models.accountgroups.AccountGroup
// Helpful
// https://developer.android.com/training/data-storage/sqlite
// https://www.techotopia.com/index.php/A_Kotlin_Android_SQLite_Database_Tutorial
internal class AccountGroupRepository(
context: Context,
private val argumentOne: Array<Int>,
private val argumentTwo: Array<Int>,
private val passphrase: String)
: SQLiteOpenHelper(context, DatabaseName, null, DatabaseVersion) {
override fun onCreate(database: SQLiteDatabase) {
val createTable = (
"CREATE TABLE IF NOT EXISTS $DatabaseTable"
+ "("
+ "$ColumnId TEXT,"
+ "$ColumnTitle TEXT,"
+ "$ColumnDescription TEXT,"
+ "$ColumnUserId TEXT,"
+ "$ColumnModelState INT"
+ ")")
database.execSQL(createTable)
}
override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
database.execSQL("DROP TABLE IF EXISTS $DatabaseTable")
onCreate(database)
}
override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
onUpgrade(database, oldVersion, newVersion)
}
fun getList(decrypt: Boolean = true): MutableList<AccountGroup> {
val database = this.readableDatabase
val projection = arrayOf(ColumnId, ColumnTitle, ColumnDescription, ColumnUserId, ColumnModelState)
val sortOrder = "$ColumnTitle ASC"
val cursor = database.query(
DatabaseTable, projection, null, null,
null, null, sortOrder)
val list = mutableListOf<AccountGroup>()
with(cursor) {
while (moveToNext()) {
val accountGroup = AccountGroup()
val idString = getString(getColumnIndexOrThrow(ColumnId))
accountGroup.id = ULID.fromString(idString)
accountGroup.title = if (decrypt) decryptHash(argumentOne, argumentTwo, passphrase, getString(getColumnIndexOrThrow(ColumnTitle))) else getString(getColumnIndexOrThrow(ColumnTitle))
accountGroup.description = if (decrypt) decryptHash(argumentOne, argumentTwo, passphrase, getString(getColumnIndexOrThrow(ColumnDescription))) else getString(getColumnIndexOrThrow(ColumnDescription))
val userIdString = decryptHash(argumentOne, argumentTwo, passphrase, getString(getColumnIndexOrThrow(ColumnUserId)))
accountGroup.userId = ULID.fromString(userIdString)
val modelStateString = decryptHash(argumentOne, argumentTwo, passphrase, getString(getColumnIndexOrThrow(ColumnModelState)))
accountGroup.modelState = ModelState.values()[Integer.parseInt(modelStateString)]
list.add(accountGroup)
}
}
return list
}
fun add(accountGroup: AccountGroup): Long {
val values = ContentValues().apply {
put(ColumnId, accountGroup.id)
put(ColumnTitle, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.title))
put(ColumnDescription, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.description))
put(ColumnUserId, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.userId))
put(ColumnModelState, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.modelState.ordinal))
}
val database = this.writableDatabase
return database.insert(DatabaseTable, null, values)
}
fun update(accountGroup: AccountGroup): Int {
val values = ContentValues().apply {
put(ColumnId, accountGroup.id)
put(ColumnTitle, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.title))
put(ColumnDescription, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.description))
put(ColumnUserId, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.userId))
put(ColumnModelState, encryptObject(argumentOne, argumentTwo, passphrase, accountGroup.modelState.ordinal))
}
val selection = "$ColumnId LIKE ?"
val selectionArgs = arrayOf(accountGroup.id)
val database = this.writableDatabase
return database.update(DatabaseTable, values, selection, selectionArgs)
}
fun delete(accountGroup: AccountGroup): Int {
val database = this.writableDatabase
val selection = "$ColumnId LIKE ?"
val selectionArgs = arrayOf(accountGroup.id)
return database.delete(DatabaseTable, selection, selectionArgs)
}
fun sync(accountGroupList: List<AccountGroup>): Boolean {
erase()
accountGroupList.forEach { accountGroup -> add(accountGroup) }
return true
}
fun erase() {
getList().forEach { x -> delete(x) }
}
companion object {
private const val DatabaseVersion = 1
private const val DatabaseName = "guepardoapps-passwordsafe-accountgroups.db"
private const val DatabaseTable = "accountGroupTable"
private const val ColumnId = "id"
private const val ColumnTitle = "title"
private const val ColumnDescription = "description"
private const val ColumnUserId = "userId"
private const val ColumnModelState = "modelState"
}
}
|
mit
|
35eaeec69f297804324eee4ed27df0f3
| 41.528986 | 215 | 0.679277 | 5.09375 | false | false | false | false |
cemrich/zapp
|
app/src/main/java/de/christinecoenen/code/zapp/persistence/MediathekShowDao.kt
|
1
|
3234
|
package de.christinecoenen.code.zapp.persistence
import androidx.paging.PagingSource
import androidx.room.*
import de.christinecoenen.code.zapp.models.shows.DownloadStatus
import de.christinecoenen.code.zapp.models.shows.MediathekShow
import de.christinecoenen.code.zapp.models.shows.PersistedMediathekShow
import kotlinx.coroutines.flow.Flow
import org.joda.time.DateTime
@Dao
interface MediathekShowDao {
@Query("SELECT * FROM PersistedMediathekShow")
fun getAll(): Flow<List<PersistedMediathekShow>>
@Query("SELECT * FROM PersistedMediathekShow WHERE downloadStatus!=0 AND downloadStatus!=7 AND downloadStatus!=8 ORDER BY downloadedAt DESC")
fun getAllDownloads(): PagingSource<Int, PersistedMediathekShow>
@Query("SELECT * FROM PersistedMediathekShow WHERE id=:id")
fun getFromId(id: Int): Flow<PersistedMediathekShow>
@Query("SELECT * FROM PersistedMediathekShow WHERE apiId=:apiId")
fun getFromApiId(apiId: String): Flow<PersistedMediathekShow>
@Query("SELECT * FROM PersistedMediathekShow WHERE apiId=:apiId")
fun getFromApiIdSync(apiId: String): PersistedMediathekShow?
@Query("SELECT * FROM PersistedMediathekShow WHERE downloadId=:downloadId")
fun getFromDownloadId(downloadId: Int): Flow<PersistedMediathekShow>
@Query("SELECT downloadStatus FROM PersistedMediathekShow WHERE id=:id")
fun getDownloadStatus(id: Int): Flow<DownloadStatus>
@Query("SELECT downloadProgress FROM PersistedMediathekShow WHERE id=:id")
fun getDownloadProgress(id: Int): Flow<Int>
@Insert
suspend fun insert(vararg show: PersistedMediathekShow)
@Update
suspend fun update(vararg show: PersistedMediathekShow)
@Transaction
suspend fun insertOrUpdate(show: MediathekShow) {
val existingPersistedShow = getFromApiIdSync(show.apiId)
if (existingPersistedShow == null) {
// insert new show
val newPersistedShow = PersistedMediathekShow(
mediathekShow = show
)
insert(newPersistedShow)
} else {
// update existing show
existingPersistedShow.mediathekShow = show
update(existingPersistedShow)
}
}
@Query("UPDATE PersistedMediathekShow SET downloadStatus=:downloadStatus WHERE downloadId=:downloadId")
suspend fun updateDownloadStatus(downloadId: Int, downloadStatus: DownloadStatus)
@Query("UPDATE PersistedMediathekShow SET downloadProgress=:progress WHERE downloadId=:downloadId")
suspend fun updateDownloadProgress(downloadId: Int, progress: Int)
@Query("UPDATE PersistedMediathekShow SET downloadedVideoPath=:videoPath WHERE downloadId=:downloadId")
suspend fun updateDownloadedVideoPath(downloadId: Int, videoPath: String)
@Query("UPDATE PersistedMediathekShow SET playbackPosition=:positionMillis, videoDuration=:durationMillis, lastPlayedBackAt=:lastPlayedBackAt WHERE id=:id")
suspend fun setPlaybackPosition(
id: Int,
positionMillis: Long,
durationMillis: Long,
lastPlayedBackAt: DateTime
)
@Query("SELECT playbackPosition FROM PersistedMediathekShow WHERE id=:id")
suspend fun getPlaybackPosition(id: Int): Long
@Query("SELECT (CAST(playbackPosition AS FLOAT) / videoDuration) FROM PersistedMediathekShow WHERE apiId=:apiId")
fun getPlaybackPositionPercent(apiId: String): Flow<Float>
@Delete
suspend fun delete(show: PersistedMediathekShow)
}
|
mit
|
f218dee1b7396799444053a0c734396b
| 36.604651 | 157 | 0.804576 | 4.244094 | false | false | false | false |
pagecloud/fitcloud-bot
|
src/main/kotlin/com/pagecloud/slack/Slack.kt
|
1
|
6185
|
package com.pagecloud.slack
import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.cache.annotation.Cacheable
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.server.ServerResponse
import reactor.core.publisher.Mono
import java.math.BigDecimal
/**
* @author Edward Smith
*/
@Service
class Slack(slackProperties: SlackProperties) {
val webClient: WebClient = WebClient.create()
val token = slackProperties.botToken
// TODO - replace with actual @Cacheable / ttl
val users by lazy { fetchUsers() }
val channels by lazy { fetchChannels() }
fun getUser(username: String): User? = users[username]
fun getChannel(name: String): Channel? = channels[name]
fun fetchUsers(): Map<String, User> {
return webClient.get()
.uri("$BASE_URL/users.list?token=$token")
.accept(MediaType.APPLICATION_JSON)
.exchange().flatMap { resp ->
if (resp.statusCode().is2xxSuccessful) {
resp.bodyToMono(UserListResponse::class.java).flatMap { response ->
when {
response.ok -> Mono.just(response.users.associateBy(User::name, { it }))
else -> {
log.error("Could not fetch Users. Error: ${response.error}; Warning: ${response.warning}")
Mono.just(emptyMap())
}
}
}
} else {
log.error("Could not fetch Users, HTTP status ${resp.statusCode()}")
Mono.just(emptyMap())
}
}.block()!! // Sadness - should be Mono return type but whatever
}
fun fetchChannels(): Map<String, Channel> {
return webClient.get()
.uri("$BASE_URL/channels.list?token=$token")
.accept(MediaType.APPLICATION_JSON)
.exchange().flatMap { resp ->
if (resp.statusCode().is2xxSuccessful) {
resp.bodyToMono(ChannelListResponse::class.java).flatMap { response ->
when {
response.ok -> Mono.just(response.channels.associateBy({ it.name }, { it }))
else -> {
log.error("Could not fetch Channels. Error: ${response.error}; Warning: ${response.warning}")
Mono.just(emptyMap())
}
}
}
} else {
log.error("Could not fetch Users, HTTP status ${resp.statusCode()}")
Mono.just(emptyMap())
}
}.block()!!
}
companion object {
val log = logger()
const val BASE_URL = "https://slack.com/api"
}
}
data class User(val id: String,
@JsonProperty("team_id") val teamId: String,
val name: String,
val status: String?,
val deleted: Boolean,
val color: String?,
val profile: Profile,
@JsonProperty("is_admin") val admin: Boolean,
@JsonProperty("is_owner") val owner: Boolean,
@JsonProperty("is_primary_owner") val primaryOwner: Boolean?,
@JsonProperty("is_restricted") val restricted: Boolean?,
@JsonProperty("is_ultra_restricted") val ultraRestricted: Boolean?,
@JsonProperty("has_2fa") val has2FactorAuth: Boolean,
@JsonProperty("two_factor_type") val twoFactorType: String?)
data class Profile(@JsonProperty("first_name")
val firstName: String?,
@JsonProperty("last_name")
val lastName: String?,
@JsonProperty("real_name")
val realName: String,
val skype: String?,
val email: String?,
val phone: String?,
val image_24: String,
val image_32: String,
val image_48: String,
val image_72: String,
val image_192: String,
val image_512: String?)
data class Channel(val id: String,
val name: String,
@JsonProperty("is_channel") val channel: Boolean?,
val created: Long,
val creator: String,
val numMembers: Int?,
@JsonProperty("is_archived") val archived: Boolean,
@JsonProperty("is_general") val general: Boolean?,
val members: List<String>?,
val topic: Topic?,
val purpose: Purpose,
@JsonProperty("is_member") val member: Boolean? = false,
@JsonProperty("last_read") val lastRead: BigDecimal?,
val unreadCount: Int?,
val unreadCountDisplay: Int?)
data class Topic(val value: String,
val creator: String,
val lastSet: Long)
data class Purpose(val value: String,
val creator: String,
val lastSet: Long)
class UserListResponse(ok: Boolean,
error: String?,
warning: String?,
@JsonProperty("members") val users: List<User>) : BaseResponse(ok, error, warning)
class ChannelListResponse(ok: Boolean,
error: String?,
warning: String?,
val channels: List<Channel>) : BaseResponse(ok, error, warning)
abstract class BaseResponse(val ok: Boolean,
val error: String?,
val warning: String?)
|
unlicense
|
a54255da9c2324d8b1b0a47c3361e8d9
| 40.24 | 122 | 0.535974 | 5.098928 | false | false | false | false |
googlecodelabs/watchnext-for-movie-tv-episodes
|
step_4_completed/src/main/java/com/android/tv/reference/auth/SignInFragment.kt
|
8
|
6720
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.reference.auth
import android.app.PendingIntent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.android.tv.reference.R
import com.android.tv.reference.auth.SignInViewModel.SignInStatus
import com.android.tv.reference.databinding.FragmentSignInBinding
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.Identity
// import com.google.android.gms.auth.api.identity.SavePasswordRequest
// import com.google.android.gms.auth.api.identity.SignInPassword
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.ApiException
/**
* Fragment that allows the user to sign in using an email and password.
*/
class SignInFragment : Fragment() {
private val viewModel: SignInViewModel by viewModels {
SignInViewModelFactory(
UserManager.getInstance(
requireContext()
)
)
}
private val signInClient by lazy { Identity.getSignInClient(requireContext()) }
// private val credentialSavingClient by lazy { Identity.getCredentialSavingClient(requireContext()) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentSignInBinding.inflate(inflater, container, false)
viewModel.signInStatus.observe(
viewLifecycleOwner,
Observer { status ->
when (status) {
is SignInStatus.Success -> findNavController().popBackStack()
is SignInStatus.ShouldSavePassword -> startSavePasswordWithGoogle(
status.username,
status.password
)
is SignInStatus.Error -> {
val errorText = when (status) {
is SignInStatus.Error.InputError ->
getString(R.string.empty_username_or_password)
is SignInStatus.Error.InvalidPassword ->
getString(R.string.invalid_credentials)
is SignInStatus.Error.ServerError -> getString(R.string.server_error)
is SignInStatus.Error.OneTapInvalid ->
getString(R.string.invalid_credentials)
is SignInStatus.Error.OneTapError -> getString(R.string.onetap_error)
else -> getString(R.string.unknown_error)
}
binding.signInError.text = getString(R.string.sign_in_error, errorText)
}
}
}
)
binding.signInIntro.text = getString(R.string.sign_in_intro, MockAuthClient.MOCK_USER_EMAIL)
binding.signInButton.setOnClickListener {
val username = binding.usernameEdit.text.toString()
val password = binding.passwordEdit.text.toString()
viewModel.signInWithPassword(username, password)
}
startGoogleOneTapRequest()
return binding.root
}
/*
Initiates Google's One Tap flow.
*/
private fun startGoogleOneTapRequest() {
val request = BeginSignInRequest.Builder()
.setPasswordRequestOptions(
BeginSignInRequest.PasswordRequestOptions.Builder().setSupported(true).build()
).build()
signInClient.beginSignIn(request)
.addOnSuccessListener { launchGoogleOneTapUi(it.pendingIntent) }
.addOnFailureListener { viewModel.processOneTapError(it) }
}
/*
Launches the UI overlay associated with Google's One Tap flow. The user is prompted to use
existing saved credentials. On success, attempt to immediately use these to sign in.
*/
private fun launchGoogleOneTapUi(pendingIntent: PendingIntent) {
val request = IntentSenderRequest.Builder(pendingIntent.intentSender).build()
registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
try {
viewModel.signInWithOneTap(signInClient.getSignInCredentialFromIntent(it.data))
} catch (e: ApiException) {
viewModel.processOneTapError(e)
}
}.launch(request)
}
/*
Initiates Google's password saving flow.
*/
private fun startSavePasswordWithGoogle(email: String, password: String) {
if (isPlayServicesUnavailable()) {
viewModel.finishSavePassword()
return
}
viewModel.finishSavePassword()
/*
val request = SavePasswordRequest.builder()
.setSignInPassword(SignInPassword(email, password))
.build()
credentialSavingClient.savePassword(request)
.addOnSuccessListener { launchSavePasswordUi(it.pendingIntent) }
.addOnFailureListener { viewModel.finishSavePassword() }
*/
}
/*
Launches the UI overlay associated with Google's password saving flow. Regardless of success
result, the sign in fragment is dismissed afterwards.
*/
private fun launchSavePasswordUi(pendingIntent: PendingIntent) {
val request = IntentSenderRequest.Builder(pendingIntent.intentSender).build()
registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult()
) { viewModel.finishSavePassword() }.launch(request)
}
private fun isPlayServicesUnavailable() = GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(requireContext()) != ConnectionResult.SUCCESS
}
|
apache-2.0
|
d6fd1fc5d440ab3bec26031da13998aa
| 41.802548 | 106 | 0.66756 | 5.110266 | false | false | false | false |
PaulWoitaschek/Voice
|
bookOverview/src/test/kotlin/voice/bookOverview/BookFactory.kt
|
1
|
1174
|
package voice.bookOverview
import voice.common.BookId
import voice.data.Book
import voice.data.BookContent
import voice.data.Chapter
import java.time.Instant
import java.util.UUID
fun book(
chapters: List<Chapter> = listOf(chapter(), chapter()),
time: Long = 42,
currentChapter: Chapter.Id = chapters.first().id,
name: String = UUID.randomUUID().toString(),
author: String? = UUID.randomUUID().toString(),
): Book {
return Book(
content = BookContent(
author = author,
name = name,
positionInChapter = time,
playbackSpeed = 1F,
addedAt = Instant.EPOCH,
chapters = chapters.map { it.id },
cover = null,
currentChapter = currentChapter,
isActive = true,
lastPlayedAt = Instant.EPOCH,
skipSilence = false,
id = BookId(UUID.randomUUID().toString()),
gain = 0F,
),
chapters = chapters,
)
}
fun chapter(
duration: Long = 10000,
id: Chapter.Id = Chapter.Id(UUID.randomUUID().toString()),
): Chapter {
return Chapter(
id = id,
name = UUID.randomUUID().toString(),
duration = duration,
fileLastModified = Instant.EPOCH,
markData = emptyList(),
)
}
|
gpl-3.0
|
9150470b7eeac4973e2924a5b98c333f
| 23.458333 | 60 | 0.650767 | 3.993197 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies
|
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/compoundmaker/CompoundRecipeButtonPiece.kt
|
1
|
2245
|
package net.ndrei.teslapoweredthingies.machines.compoundmaker
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import net.ndrei.teslacorelib.gui.ButtonPiece
import net.ndrei.teslacorelib.inventory.BoundingRectangle
import net.ndrei.teslapoweredthingies.client.ThingiesTexture
class CompoundRecipeButtonPiece(private val entity: CompoundMakerEntity, private val direction: Direction, left: Int = 151, top: Int = 25)
: ButtonPiece(left, top, 14, 7) {
enum class Direction { UP, DOWN }
override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) {
super.drawBackgroundLayer(container, guiX, guiY, partialTicks, mouseX, mouseY)
CompoundMakerIcon.BUTTON_BACKGROUND.drawCentered(container, this)
if (this.isInside(container, mouseX, mouseY) && this.isEnabled) {
ButtonPiece.drawHoverArea(container, this, 1)
}
}
override val isEnabled : Boolean
get() {
if (this.entity.hasCurrentRecipe) {
return false
}
val index = this.entity.selectedRecipeIndex
val recipes = this.entity.availableRecipes
return !when (this.direction) {
Direction.UP -> ((index == 0) || recipes.isEmpty())
Direction.DOWN -> (recipes.isEmpty() || (index >= (recipes.size - 1)))
}
}
override fun renderState(container: BasicTeslaGuiContainer<*>, over: Boolean, box: BoundingRectangle) {
stateMap[this.direction to this.isEnabled]?.drawCentered(container, this, true)
}
override fun clicked() {
when (this.direction) {
Direction.UP -> this.entity.selectedRecipeIndex--
Direction.DOWN -> this.entity.selectedRecipeIndex++
}
}
companion object {
private val stateMap = mapOf(
(Direction.UP to true) to CompoundMakerIcon.RECIPE_BUTTON_UP,
(Direction.UP to false) to CompoundMakerIcon.RECIPE_BUTTON_UP_GRAYED,
(Direction.DOWN to true) to CompoundMakerIcon.RECIPE_BUTTON_DOWN,
(Direction.DOWN to false) to CompoundMakerIcon.RECIPE_BUTTON_DOWN_GRAYED
)
}
}
|
mit
|
d2d6561b85b057d8bb6e43d6a227d447
| 39.818182 | 145 | 0.665924 | 4.609856 | false | false | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/playstats/factory/GivenVersion22OrGreaterOfMediaCenter/WhenGettingThePlaystatsUpdater.kt
|
2
|
2884
|
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.GivenVersion22OrGreaterOfMediaCenter
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FakeFilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedFilePropertiesProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.IPlaystatsUpdate
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.PlaystatsUpdateSelector
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.playedfile.PlayedFilePlayStatsUpdater
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.storage.ScopedFilePropertiesStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeScopedRevisionProvider
import com.lasthopesoftware.bluewater.client.connection.FakeConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.authentication.CheckIfScopedConnectionIsReadOnly
import com.lasthopesoftware.bluewater.client.servers.version.IProgramVersionProvider
import com.lasthopesoftware.bluewater.client.servers.version.SemanticVersion
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenGettingThePlaystatsUpdater {
companion object {
private var updater: IPlaystatsUpdate? = null
@BeforeClass
@JvmStatic
fun before() {
val fakeConnectionProvider = FakeConnectionProvider()
val programVersionProvider = mockk<IProgramVersionProvider>()
every { programVersionProvider.promiseServerVersion() } returns Promise(SemanticVersion(22, 0, 0))
val fakeScopedRevisionProvider = FakeScopedRevisionProvider(19)
val fakeFilePropertiesContainer = FakeFilePropertiesContainer()
val checkConnection = mockk<CheckIfScopedConnectionIsReadOnly>()
every { checkConnection.promiseIsReadOnly() } returns false.toPromise()
val playstatsUpdateSelector = PlaystatsUpdateSelector(
fakeConnectionProvider,
ScopedFilePropertiesProvider(fakeConnectionProvider, fakeScopedRevisionProvider, fakeFilePropertiesContainer),
ScopedFilePropertiesStorage(fakeConnectionProvider, checkConnection, fakeScopedRevisionProvider, fakeFilePropertiesContainer),
programVersionProvider
)
updater = playstatsUpdateSelector.promisePlaystatsUpdater().toFuture().get()
}
}
@Test
fun thenThePlayedFilePlaystatsUpdaterIsGiven() {
assertThat(updater).isInstanceOf(PlayedFilePlayStatsUpdater::class.java)
}
}
|
lgpl-3.0
|
b975ac3badb77636867dc08e7f69e640
| 52.407407 | 138 | 0.859223 | 4.621795 | false | false | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/preparation/FakeDeferredPlayableFilePreparationSourceProvider.kt
|
1
|
1632
|
package com.lasthopesoftware.bluewater.client.playback.file.preparation
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.IPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.fakes.FakePreparedPlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.fakes.ResolvablePlaybackHandler
import com.namehillsoftware.handoff.Messenger
import com.namehillsoftware.handoff.promises.MessengerOperator
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
class FakeDeferredPlayableFilePreparationSourceProvider : IPlayableFilePreparationSourceProvider {
val deferredResolution = DeferredResolution()
override fun providePlayableFilePreparationSource(): PlayableFilePreparationSource {
return PlayableFilePreparationSource { _, preparedAt ->
deferredResolution.preparedAt = preparedAt
Promise(deferredResolution)
}
}
override fun getMaxQueueSize(): Int {
return 1
}
class DeferredResolution : MessengerOperator<PreparedPlayableFile> {
private var resolve: Messenger<PreparedPlayableFile>? = null
var preparedAt: Duration = Duration.ZERO
fun resolve(): ResolvablePlaybackHandler {
val playbackHandler = ResolvablePlaybackHandler()
playbackHandler.setCurrentPosition(preparedAt.millis.toInt())
resolve?.sendResolution(FakePreparedPlayableFile(playbackHandler))
return playbackHandler
}
override fun send(resolve: Messenger<PreparedPlayableFile>) {
this.resolve = resolve
}
}
}
|
lgpl-3.0
|
7510f325464b6fcb0c36d0d546466af7
| 38.804878 | 111 | 0.781863 | 5.494949 | false | false | false | false |
gotev/android-upload-service
|
uploadservice/src/main/java/net/gotev/uploadservice/data/NameValue.kt
|
2
|
1142
|
package net.gotev.uploadservice.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import net.gotev.uploadservice.extensions.isASCII
import net.gotev.uploadservice.persistence.Persistable
import net.gotev.uploadservice.persistence.PersistableData
@Parcelize
data class NameValue(val name: String, val value: String) : Parcelable, Persistable {
fun validateAsHeader(): NameValue {
require(name.isASCII() && value.isASCII()) {
"Header $name and its value $value must be ASCII only! Read http://stackoverflow.com/a/4410331"
}
return this
}
override fun toPersistableData() = PersistableData().apply {
putString(CodingKeys.name, name)
putString(CodingKeys.value, value)
}
companion object : Persistable.Creator<NameValue> {
private object CodingKeys {
const val name = "name"
const val value = "value"
}
override fun createFromPersistableData(data: PersistableData) = NameValue(
name = data.getString(CodingKeys.name),
value = data.getString(CodingKeys.value)
)
}
}
|
apache-2.0
|
722f6f0ff6de72465ce1a87ba764c35b
| 31.628571 | 107 | 0.683888 | 4.513834 | false | false | false | false |
gumil/basamto
|
app/src/main/kotlin/io/github/gumil/basamto/reddit/comments/CommentViewItem.kt
|
1
|
3432
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* 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 io.github.gumil.basamto.reddit.comments
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import io.github.gumil.basamto.R
import io.github.gumil.basamto.common.adapter.ItemAdapter
import io.github.gumil.basamto.common.adapter.ViewItem
import io.github.gumil.basamto.extensions.getColorRes
import io.github.gumil.basamto.extensions.setVisible
import io.github.gumil.basamto.widget.html.getBlocks
import kotlinx.android.synthetic.main.item_comment.view.author
import kotlinx.android.synthetic.main.item_comment.view.body
import kotlinx.android.synthetic.main.item_comment.view.depth
import kotlinx.android.synthetic.main.item_comment.view.divider
import kotlinx.android.synthetic.main.item_comment.view.replies
internal class CommentViewItem : ViewItem<CommentItem> {
private var depthColors = arrayOf(
R.color.md_blue_500,
R.color.md_green_500,
R.color.md_yellow_500,
R.color.md_orange_500,
R.color.md_red_500
)
override var onItemClick: ((CommentItem) -> Unit)? = null
override val layout: Int get() = R.layout.item_comment
override fun bind(view: View, item: CommentItem) {
when (item) {
is CommentBodyItem -> renderComment(view, item)
is MoreItem -> renderMore(view, item)
}
}
private fun renderComment(view: View, item: CommentBodyItem) {
val blocks = item.body.getBlocks()
view.author.text = item.user
view.body.setViews(blocks)
view.replies.run {
layoutManager = LinearLayoutManager(view.context)
adapter = ItemAdapter(CommentViewItem()).apply {
list = item.replies
}
}
view.divider.setVisible(item.replies.isNotEmpty())
if (item.depth > 0) {
view.depth.run {
setVisible(item.depth > 0)
setBackgroundColor(context.getColorRes(depthColors[item.depth - 1]))
}
}
}
private fun renderMore(view: View, item: MoreItem) {
view.author.text = view.context.getString(R.string.load_more)
view.depth.run {
setVisible(true)
setBackgroundColor(context.getColorRes(R.color.md_grey_700))
}
}
}
|
mit
|
e2be2771755587df22e2df0b2cb545ca
| 37.144444 | 84 | 0.697552 | 4.04717 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/activities/FilterSettingsActivity.kt
|
1
|
15817
|
package org.tasks.activities
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButtonToggleGroup
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.todoroo.andlib.sql.Field
import com.todoroo.andlib.sql.Query
import com.todoroo.andlib.sql.UnaryCriterion
import com.todoroo.andlib.utility.AndroidUtilities
import com.todoroo.astrid.activity.MainActivity
import com.todoroo.astrid.activity.TaskListFragment
import com.todoroo.astrid.api.*
import com.todoroo.astrid.core.CriterionInstance
import com.todoroo.astrid.core.CustomFilterAdapter
import com.todoroo.astrid.core.CustomFilterItemTouchHelper
import com.todoroo.astrid.dao.Database
import com.todoroo.astrid.data.Task
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.tasks.R
import org.tasks.Strings
import org.tasks.data.Filter
import org.tasks.data.FilterDao
import org.tasks.data.TaskDao.TaskCriteria.activeAndVisible
import org.tasks.databinding.FilterSettingsActivityBinding
import org.tasks.db.QueryUtils
import org.tasks.extensions.Context.openUri
import org.tasks.filters.FilterCriteriaProvider
import java.util.*
import javax.inject.Inject
import kotlin.math.max
@AndroidEntryPoint
class FilterSettingsActivity : BaseListSettingsActivity() {
@Inject lateinit var filterDao: FilterDao
@Inject lateinit var locale: Locale
@Inject lateinit var database: Database
@Inject lateinit var filterCriteriaProvider: FilterCriteriaProvider
private lateinit var name: TextInputEditText
private lateinit var nameLayout: TextInputLayout
private lateinit var recyclerView: RecyclerView
private lateinit var fab: ExtendedFloatingActionButton
private var filter: CustomFilter? = null
private lateinit var adapter: CustomFilterAdapter
private var criteria: MutableList<CriterionInstance> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
filter = intent.getParcelableExtra(TOKEN_FILTER)
super.onCreate(savedInstanceState)
if (savedInstanceState == null && filter != null) {
selectedColor = filter!!.tint
selectedIcon = filter!!.icon
name.setText(filter!!.listingTitle)
}
when {
savedInstanceState != null -> lifecycleScope.launch {
setCriteria(CriterionInstance.fromString(
filterCriteriaProvider, savedInstanceState.getString(EXTRA_CRITERIA)!!))
}
filter != null -> lifecycleScope.launch {
setCriteria(CriterionInstance.fromString(
filterCriteriaProvider, filter!!.criterion))
}
intent.hasExtra(EXTRA_CRITERIA) -> lifecycleScope.launch {
name.setText(intent.getStringExtra(EXTRA_TITLE))
setCriteria(CriterionInstance.fromString(
filterCriteriaProvider, intent.getStringExtra(EXTRA_CRITERIA)!!))
}
else -> setCriteria(universe())
}
recyclerView.layoutManager = LinearLayoutManager(this)
ItemTouchHelper(
CustomFilterItemTouchHelper(this, this::onMove, this::onDelete, this::updateList))
.attachToRecyclerView(recyclerView)
if (isNew) {
toolbar.inflateMenu(R.menu.menu_help)
}
updateTheme()
}
private fun universe() = listOf(CriterionInstance().apply {
criterion = filterCriteriaProvider.startingUniverse
type = CriterionInstance.TYPE_UNIVERSE
})
private fun setCriteria(criteria: List<CriterionInstance>) {
this.criteria = criteria
.ifEmpty { universe() }
.toMutableList()
adapter = CustomFilterAdapter(criteria, locale) { replaceId: String -> onClick(replaceId) }
recyclerView.adapter = adapter
fab.isExtended = isNew || adapter.itemCount <= 1
updateList()
}
private fun onDelete(index: Int) {
criteria.removeAt(index)
updateList()
}
private fun onMove(from: Int, to: Int) {
val criterion = criteria.removeAt(from)
criteria.add(to, criterion)
adapter.notifyItemMoved(from, to)
}
private fun onClick(replaceId: String) {
val criterionInstance = criteria.find { it.id == replaceId }!!
val view = layoutInflater.inflate(R.layout.dialog_custom_filter_row_edit, recyclerView, false)
val group: MaterialButtonToggleGroup = view.findViewById(R.id.button_toggle)
val selected = getSelected(criterionInstance)
group.check(selected)
dialogBuilder
.newDialog(criterionInstance.titleFromCriterion)
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
criterionInstance.type = getType(group.checkedButtonId)
updateList()
}
.setNeutralButton(R.string.help) { _, _ -> help() }
.show()
}
private fun getSelected(instance: CriterionInstance): Int =
when (instance.type) {
CriterionInstance.TYPE_ADD -> R.id.button_or
CriterionInstance.TYPE_SUBTRACT -> R.id.button_not
else -> R.id.button_and
}
private fun getType(selected: Int): Int =
when (selected) {
R.id.button_or -> CriterionInstance.TYPE_ADD
R.id.button_not -> CriterionInstance.TYPE_SUBTRACT
else -> CriterionInstance.TYPE_INTERSECT
}
private fun addCriteria() {
AndroidUtilities.hideKeyboard(this)
fab.shrink()
lifecycleScope.launch {
val all = filterCriteriaProvider.all()
val names = all.map(CustomFilterCriterion::getName)
dialogBuilder.newDialog()
.setItems(names) { dialog: DialogInterface, which: Int ->
val instance = CriterionInstance()
instance.criterion = all[which]
showOptionsFor(instance) {
criteria.add(instance)
updateList()
}
dialog.dismiss()
}
.show()
}
}
/** Show options menu for the given criterioninstance */
private fun showOptionsFor(item: CriterionInstance, onComplete: Runnable?) {
if (item.criterion is BooleanCriterion) {
onComplete?.run()
return
}
val dialog = dialogBuilder.newDialog(item.criterion.name)
if (item.criterion is MultipleSelectCriterion) {
val multiSelectCriterion = item.criterion as MultipleSelectCriterion
val titles = multiSelectCriterion.entryTitles
val listener = DialogInterface.OnClickListener { _: DialogInterface?, which: Int ->
item.selectedIndex = which
onComplete?.run()
}
dialog.setItems(titles, listener)
} else if (item.criterion is TextInputCriterion) {
val textInCriterion = item.criterion as TextInputCriterion
val frameLayout = FrameLayout(this)
frameLayout.setPadding(10, 0, 10, 0)
val editText = EditText(this)
editText.setText(item.selectedText)
editText.hint = textInCriterion.hint
frameLayout.addView(
editText,
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT))
dialog
.setView(frameLayout)
.setPositiveButton(R.string.ok) { _, _ ->
item.selectedText = editText.text.toString()
onComplete?.run()
}
}
dialog.show()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(EXTRA_CRITERIA, CriterionInstance.serialize(criteria))
}
override val isNew: Boolean
get() = filter == null
override val toolbarTitle: String?
get() = if (isNew) getString(R.string.FLA_new_filter) else filter!!.listingTitle
override suspend fun save() {
val newName = newName
if (Strings.isNullOrEmpty(newName)) {
nameLayout.error = getString(R.string.name_cannot_be_empty)
return
}
if (hasChanges()) {
val f = Filter()
f.title = newName
f.setColor(selectedColor)
f.setIcon(selectedIcon)
f.values = AndroidUtilities.mapToSerializedString(values)
f.criterion = CriterionInstance.serialize(criteria)
if (f.criterion.isNullOrBlank()) {
throw RuntimeException("Criterion cannot be empty")
}
f.setSql(sql)
if (isNew) {
f.id = filterDao.insert(f)
} else {
filter?.let {
f.id = it.id
f.order = it.order
filterDao.update(f)
}
}
setResult(
Activity.RESULT_OK,
Intent(TaskListFragment.ACTION_RELOAD)
.putExtra(MainActivity.OPEN_FILTER, CustomFilter(f)))
}
finish()
}
private val newName: String
get() = name.text.toString().trim { it <= ' ' }
override fun hasChanges(): Boolean {
return if (isNew) {
(!Strings.isNullOrEmpty(newName)
|| selectedColor != 0 || selectedIcon != -1 || criteria.size > 1)
} else newName != filter!!.listingTitle
|| selectedColor != filter!!.tint
|| selectedIcon != filter!!.icon
|| CriterionInstance.serialize(criteria) != filter!!.criterion.trim()
|| values != filter!!.valuesForNewTasks
|| sql != filter!!.originalSqlQuery
}
override fun finish() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(name.windowToken, 0)
super.finish()
}
override fun bind() = FilterSettingsActivityBinding.inflate(layoutInflater).let {
name = it.name.apply {
addTextChangedListener(
onTextChanged = { _, _, _, _ -> nameLayout.error = null }
)
}
nameLayout = it.nameLayout
recyclerView = it.recyclerView
fab = it.fab.apply {
setOnClickListener { addCriteria() }
}
it.root
}
override suspend fun delete() {
filterDao.delete(filter!!.id)
setResult(
Activity.RESULT_OK, Intent(TaskListFragment.ACTION_DELETED).putExtra(TOKEN_FILTER, filter))
finish()
}
override fun onMenuItemClick(item: MenuItem): Boolean =
if (item.itemId == R.id.menu_help) {
help()
true
} else {
super.onMenuItemClick(item)
}
private fun help() = openUri(R.string.url_filters)
private fun updateList() {
var max = 0
var last = -1
val sql = StringBuilder(Query.select(Field.COUNT).from(Task.TABLE).toString())
.append(" WHERE ")
for (instance in criteria) {
var value = instance.valueFromCriterion
if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) {
value = ""
}
when (instance.type) {
CriterionInstance.TYPE_ADD -> sql.append("OR ")
CriterionInstance.TYPE_SUBTRACT -> sql.append("AND NOT ")
CriterionInstance.TYPE_INTERSECT -> sql.append("AND ")
}
// special code for all tasks universe
if (instance.type == CriterionInstance.TYPE_UNIVERSE || instance.criterion.sql == null) {
sql.append(activeAndVisible()).append(' ')
} else {
var subSql: String? = instance.criterion.sql.replace("?", UnaryCriterion.sanitize(value!!))
subSql = PermaSql.replacePlaceholdersForQuery(subSql)
sql.append(Task.ID).append(" IN (").append(subSql).append(")")
}
val sqlString = QueryUtils.showHiddenAndCompleted(sql.toString())
database.query(sqlString, null).use { cursor ->
cursor.moveToNext()
instance.start = if (last == -1) cursor.getInt(0) else last
instance.end = cursor.getInt(0)
last = instance.end
max = max(max, last)
}
}
for (instance in criteria) {
instance.max = max
}
adapter.submitList(criteria)
}
private fun getValue(instance: CriterionInstance): String? {
var value = instance.valueFromCriterion
if (value == null && instance.criterion.sql != null && instance.criterion.sql.contains("?")) {
value = ""
}
return value
}
// special code for all tasks universe
private val sql: String
get() {
val sql = StringBuilder(" WHERE ")
for (instance in criteria) {
val value = getValue(instance)
when (instance.type) {
CriterionInstance.TYPE_ADD -> sql.append(" OR ")
CriterionInstance.TYPE_SUBTRACT -> sql.append(" AND NOT ")
CriterionInstance.TYPE_INTERSECT -> sql.append(" AND ")
}
// special code for all tasks universe
if (instance.type == CriterionInstance.TYPE_UNIVERSE || instance.criterion.sql == null) {
sql.append(activeAndVisible())
} else {
val subSql = instance.criterion.sql
.replace("?", UnaryCriterion.sanitize(value!!))
.trim()
sql.append(Task.ID).append(" IN (").append(subSql).append(")")
}
}
return sql.toString()
}
private val values: Map<String, Any>
get() {
val values: MutableMap<String, Any> = HashMap()
for (instance in criteria) {
val value = getValue(instance)
if (instance.criterion.valuesForNewTasks != null
&& instance.type == CriterionInstance.TYPE_INTERSECT) {
for ((key, value1) in instance.criterion.valuesForNewTasks) {
values[key.replace("?", value!!)] = value1.toString().replace("?", value)
}
}
}
return values
}
companion object {
const val TOKEN_FILTER = "token_filter"
const val EXTRA_TITLE = "extra_title"
const val EXTRA_CRITERIA = "extra_criteria"
}
}
|
gpl-3.0
|
fc947d23146ae73f1a9c89041828d920
| 38.446384 | 107 | 0.599039 | 5.048516 | false | false | false | false |
UnknownJoe796/kotlin-components-starter
|
app/src/androidTest/java/com/ivieleague/kotlin_components_starter/ExampleLoginVCFullTest.kt
|
1
|
6464
|
package com.ivieleague.kotlin_components_starter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.support.test.InstrumentationRegistry
import android.view.ContextThemeWrapper
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import com.lightningkite.kotlin.anko.FullInputType
import com.lightningkite.kotlin.anko.forThisAndAllChildrenRecursive
import com.lightningkite.kotlin.anko.lifecycle
import com.lightningkite.kotlin.anko.viewcontrollers.VCContext
import com.lightningkite.kotlin.async.Async
import com.lightningkite.kotlin.async.AsyncInterface
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.childrenSequence
import org.junit.Assert
import org.junit.Test
/**
*
* Created by joseph on 11/3/17.
*/
class ExampleLoginVCFullTest {
@Test
fun testLogins() {
// Mocking
val appContext = InstrumentationRegistry.getTargetContext()
val mockVCContext = object : VCContext {
override val activity: Activity? get() = null
override val context: Context = appContext
override val onResume: MutableCollection<() -> Unit> = ArrayList()
override val onPause: MutableCollection<() -> Unit> = ArrayList()
override val onSaveInstanceState: MutableCollection<(outState: Bundle) -> Unit> = ArrayList()
override val onLowMemory: MutableCollection<() -> Unit> = ArrayList()
override val onDestroy: MutableCollection<() -> Unit> = ArrayList()
override val onActivityResult: MutableCollection<(request: Int, result: Int, data: Intent?) -> Unit> = ArrayList()
override fun prepareOnResult(presetCode: Int, onResult: (Int, Intent?) -> Unit): Int = 0
override fun requestPermissions(permission: Array<String>, onResult: (Map<String, Int>) -> Unit) {
onResult.invoke(permission.associate { it to 0 })
}
override fun requestPermission(permission: String, onResult: (Boolean) -> Unit) {
onResult.invoke(true)
}
}
val fakeUIThread = HandlerThread("FakeUIThread")
fakeUIThread.start()
val handler = Handler(fakeUIThread.looper)
Async.uiThreadInterface = object : AsyncInterface {
override fun sendToThread(action: () -> Unit) {
handler.post(action)
}
}
//Make the VC
var loginData: LoginData? = null
val vc = ExampleLoginVC({
loginData = it
})
//Pull components out of the view
val view = vc.createView(AnkoContext.Companion.create(ContextThemeWrapper(appContext, R.style.AppTheme), mockVCContext))
view.forThisAndAllChildrenRecursive {
it.lifecycle.onViewAttachedToWindow(it)
}
val emailEditText = view.childrenRecursive()
.findOfType { it: EditText -> it.inputType == FullInputType.EMAIL } ?: throw IllegalStateException("Email view not found!")
val passwordEditText = view.childrenRecursive()
.findOfType { it: EditText -> it.inputType == FullInputType.PASSWORD } ?: throw IllegalStateException("Password view not found!")
val loginButton = view.childrenRecursive()
.findOfType { it: Button -> it.text.contains("log", ignoreCase = true) } ?: throw IllegalStateException("Login view not found!")
//Email empty
handler.post {
emailEditText.setText("")
passwordEditText.setText("testpass")
}
handler.post {
loginButton.performClick()
}
Thread.sleep(50)
Assert.assertEquals(appContext.getString(R.string.validation_email_blank), emailEditText.error)
//Email invalid
handler.post {
emailEditText.setText("invalid")
passwordEditText.setText("testpass")
}
handler.post {
loginButton.performClick()
}
Thread.sleep(50)
Assert.assertTrue(emailEditText.error?.contains(appContext.getString(R.string.validation_email_invalid, "invalid")) ?: false)
//Password empty
handler.post {
emailEditText.setText("[email protected]")
passwordEditText.setText("")
}
handler.post {
loginButton.performClick()
}
Thread.sleep(50)
Assert.assertEquals(appContext.getString(R.string.validation_password_empty), passwordEditText.error)
//Password short
handler.post {
emailEditText.setText("[email protected]")
passwordEditText.setText("wrong")
}
handler.post {
loginButton.performClick()
}
Thread.sleep(50)
Assert.assertEquals(appContext.getString(R.string.validation_password_short), passwordEditText.error)
//Success
handler.post {
emailEditText.setText("[email protected]")
passwordEditText.setText("testpass")
}
handler.post {
loginButton.performClick()
}
Thread.sleep(500)
assert(loginData != null)
fakeUIThread.quitSafely()
}
fun View.childrenRecursive(): Sequence<View> = object : Sequence<View> {
override fun iterator(): Iterator<View> = object : Iterator<View> {
val parentQueue = ArrayList<ViewGroup>()
var currentIterator = [email protected]().iterator()
override fun hasNext(): Boolean {
while (!currentIterator.hasNext() && parentQueue.isNotEmpty()) {
currentIterator = parentQueue.removeAt(0).childrenSequence().iterator()
}
return currentIterator.hasNext()
}
override fun next(): View {
if (!hasNext()) throw NoSuchElementException()
val new = currentIterator.next()
if (new is ViewGroup) {
parentQueue.add(new)
}
return new
}
}
}
inline fun <A, reified B : A> Sequence<A>.findOfType(predicate: (B) -> Boolean): B? {
return firstOrNull {
if (it is B) predicate(it)
else false
} as? B
}
}
|
mit
|
d5f6aeaef1fefd07fec3b0aa56ace026
| 34.916667 | 145 | 0.629177 | 4.976135 | false | true | false | false |
nemerosa/ontrack
|
ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/measures/SonarQubeMetrics.kt
|
1
|
687
|
package net.nemerosa.ontrack.extension.sonarqube.measures
object SonarQubeMetrics {
const val METRIC_ONTRACK_SONARQUBE_COLLECTION_STARTED_COUNT = "ontrack_sonarqube_collection_started_count"
const val METRIC_ONTRACK_SONARQUBE_COLLECTION_SUCCESS_COUNT = "ontrack_sonarqube_collection_success_count"
const val METRIC_ONTRACK_SONARQUBE_COLLECTION_ERROR_COUNT = "ontrack_sonarqube_collection_error_count"
const val METRIC_ONTRACK_SONARQUBE_COLLECTION_TIME = "ontrack_sonarqube_collection_time"
const val METRIC_ONTRACK_SONARQUBE_COLLECTION_NONE_COUNT = "ontrack_sonarqube_collection_none"
const val METRIC_ONTRACK_SONARQUBE_MEASURE = "ontrack_sonarqube_measure"
}
|
mit
|
296ce2390a0e85b75f5c6836df6d6844
| 51.923077 | 110 | 0.803493 | 3.654255 | false | false | false | false |
dykstrom/jcc
|
src/test/kotlin/se/dykstrom/jcc/basic/compiler/BasicSyntaxVisitorFunctionTests.kt
|
1
|
2640
|
/*
* Copyright (C) 2017 Johan Dykstrom
*
* 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 se.dykstrom.jcc.basic.compiler
import org.junit.Test
import se.dykstrom.jcc.basic.ast.PrintStatement
import se.dykstrom.jcc.common.ast.Expression
import se.dykstrom.jcc.common.ast.FunctionCallExpression
import java.util.Collections.emptyList
/**
* Tests class `BasicSyntaxVisitor`, especially functionality related to function calls.
*
* @author Johan Dykstrom
* @see BasicSyntaxVisitor
*/
class BasicSyntaxVisitorFunctionTests : AbstractBasicSyntaxVisitorTest() {
@Test
fun shouldParseCall() {
val fe = FunctionCallExpression(0, 0, IDENT_FLOAT_FOO, emptyList())
val ps = PrintStatement(0, 0, listOf(fe))
parseAndAssert("print foo()", listOf(ps))
}
@Test
fun shouldParseCallWithTypedFunc() {
val fe = FunctionCallExpression(0, 0, IDENT_STR_COMMAND, emptyList())
val ps = PrintStatement(0, 0, listOf(fe))
parseAndAssert("print command$()", listOf(ps))
}
@Test
fun shouldParseCallWithArg() {
val fe = FunctionCallExpression(0, 0, IDENT_FLOAT_FOO, listOf(IL_1))
val ps = PrintStatement(0, 0, listOf(fe))
parseAndAssert("print foo(1)", listOf(ps))
}
@Test
fun shouldParseCallWithSeveralArgs() {
val expressions = listOf<Expression>(IL_1, SL_A, BL_FALSE)
val fe = FunctionCallExpression(0, 0, IDENT_FLOAT_FOO, expressions)
val ps = PrintStatement(0, 0, listOf(fe))
parseAndAssert("print foo(1, \"A\", false)", listOf(ps))
}
@Test
fun shouldParseCallWithFunCallArgs() {
val feBar12 = FunctionCallExpression(0, 0, IDENT_INT_BAR, listOf(IL_1, IL_2))
val feBar34 = FunctionCallExpression(0, 0, IDENT_INT_BAR, listOf(IL_3, IL_4))
val feFoo = FunctionCallExpression(0, 0, IDENT_FLOAT_FOO, listOf(feBar12, feBar34))
val ps = PrintStatement(0, 0, listOf(feFoo))
parseAndAssert("print foo(bar%(1, 2), bar%(3, 4))", listOf(ps))
}
}
|
gpl-3.0
|
a05c907f08459d55ccd171fed885b40d
| 33.736842 | 91 | 0.687879 | 3.882353 | false | true | false | false |
goodwinnk/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GithubPullRequestsDetailsLoader.kt
|
1
|
2973
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import git4idea.commands.Git
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.CalledInBackground
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.GithubPullRequest
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.pullrequest.ui.GithubPullRequestsListComponent
import java.util.concurrent.Future
class GithubPullRequestsDetailsLoader(progressManager: ProgressManager,
private val requestExecutorHolder: GithubApiRequestExecutorManager.ManagedHolder,
private val git: Git,
private val repository: GitRepository,
private val remote: GitRemote)
: SingleWorkerProcessExecutor(progressManager,
"GitHub PR info loading breaker"), GithubPullRequestsListComponent.PullRequestSelectionListener {
@set:CalledInAwt
var detailsFuture: Future<GithubPullRequest>? = null
private set
override fun selectionChanged(selection: GithubSearchedIssue?) {
cancelCurrentTasks()
if (selection == null) {
detailsFuture = null
}
else {
val requestExecutor = requestExecutorHolder.executor
detailsFuture = submit { indicator -> loadInformationAndFetchBranch(indicator, requestExecutor, selection) }
}
}
@CalledInBackground
private fun loadInformationAndFetchBranch(indicator: ProgressIndicator,
requestExecutor: GithubApiRequestExecutor,
searchedIssue: GithubSearchedIssue): GithubPullRequest {
val links = searchedIssue.pullRequestLinks ?: throw IllegalStateException("Missing pull request links")
val pullRequest = requestExecutor.execute(indicator, GithubApiRequests.Repos.PullRequests.get(links.url))
if (!isCommitFetched(pullRequest.head.sha)) {
git.fetch(repository, remote, emptyList(), "refs/pull/${pullRequest.number}/head:").throwOnError()
}
if (!isCommitFetched(pullRequest.head.sha)) throw IllegalStateException("Pull request head is not available after fetch")
return pullRequest
}
private fun isCommitFetched(commitHash: String): Boolean {
val result = git.getObjectType(repository, commitHash)
return result.success() && result.outputAsJoinedString == "commit"
}
}
|
apache-2.0
|
3d5cd9b75bab33d012e0f0d88be945a4
| 47.737705 | 140 | 0.734612 | 5.425182 | false | false | false | false |
d9n/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/DemorgansLawIntention.kt
|
1
|
4906
|
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psi.ext.LogicOp.*
import org.rust.lang.utils.isNegation
import org.rust.lang.utils.negateToString
class DemorgansLawIntention : RsElementBaseIntentionAction<DemorgansLawIntention.Context>() {
override fun getFamilyName() = "DeMorgan's Law"
private fun setTextForElement(element: RsBinaryExpr) {
val binaryExpression = element
text = when (binaryExpression.operatorType) {
AND -> "DeMorgan's Law, Replace '&&' with '||'"
OR -> "DeMorgan's Law, Replace '||' with '&&'"
else -> ""
}
}
data class Context(
val binaryExpr: RsBinaryExpr,
val binaryOpType: BinaryOperator
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val binExpr = element.parentOfType<RsBinaryExpr>() ?: return null
val opType = binExpr.operatorType
if (opType is LogicOp) {
setTextForElement(binExpr)
return Context(binExpr, opType)
}
return null
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (binExpr, opType) = ctx
var topBinExpr = binExpr
var isAllSameOpType = true
while (topBinExpr.parent is RsBinaryExpr
|| (topBinExpr.parent is RsParenExpr
&& topBinExpr.parent.parent.isNegation()
&& topBinExpr.parent.parent.parent is RsBinaryExpr)) {
topBinExpr = if (topBinExpr.parent is RsBinaryExpr) topBinExpr.parent as RsBinaryExpr else topBinExpr.parent.parent.parent as RsBinaryExpr
isAllSameOpType = topBinExpr.parent is RsBinaryExpr && topBinExpr.operatorType == opType
}
if (isAllSameOpType) {
applyDemorgan(project, topBinExpr, opType)
} else {
val binaryExprs = topBinExpr.descendantsOfType<RsBinaryExpr>().filter { e ->
!(e.operatorType != opType || e.parent is RsBinaryExpr && (e.parent as RsBinaryExpr).operatorType == opType)
}
binaryExprs.forEach {
applyDemorgan(project, it, opType)
}
}
}
private fun applyDemorgan(project: Project, topBinExpr: RsBinaryExpr, opType: BinaryOperator) {
val converted = convertConjunctionExpression(topBinExpr, opType) ?: return
var expressionToReplace: RsExpr = topBinExpr
var expString = "!($converted)"
val parent = topBinExpr.parent.parent
if (parent.isNegation()) {
expressionToReplace = parent as RsExpr
expString = converted
}
val newExpr = RsPsiFactory(project).createExpression(expString)
expressionToReplace.replace(newExpr)
}
private fun isConjunctionExpression(expression: RsExpr, opType: BinaryOperator): Boolean {
return expression is RsBinaryExpr && expression.operatorType == opType
}
private fun convertLeafExpression(condition: RsExpr): String {
if (condition.isNegation()) {
val negated = (condition as RsUnaryExpr).expr ?: return ""
return negated.text
} else {
if (condition is RsParenExpr) {
var c = condition.expr
var level = 1
while (c is RsParenExpr) {
level += 1
c = c.expr
}
return if (c is RsBinaryExpr && c.operatorType !is LogicOp) {
"${"(".repeat(level)}${c.negateToString()}${")".repeat(level)}"
} else {
"!" + condition.text
}
} else if (condition is RsBinaryExpr) {
return condition.negateToString()
} else {
return "!" + condition.text
}
}
}
private fun convertConjunctionExpression(exp: RsBinaryExpr, opType: BinaryOperator): String? {
val lhs = exp.left
val lhsText = if (isConjunctionExpression(lhs, opType)) {
convertConjunctionExpression(lhs as RsBinaryExpr, opType)
} else {
convertLeafExpression(lhs)
}
exp.right ?: return null
val rhs = exp.right ?: return null
val rhsText = if (isConjunctionExpression(rhs, opType)) {
convertConjunctionExpression(rhs as RsBinaryExpr, opType)
} else {
convertLeafExpression(rhs)
}
val flippedConjunction = if (exp.operatorType == opType) {
if (opType == AND) "||" else "&&"
} else {
exp.operator.text
}
return "$lhsText $flippedConjunction $rhsText"
}
}
|
mit
|
5d1ae80c017683bb38bdec5d3dcef2ce
| 35.340741 | 150 | 0.605789 | 4.641438 | false | false | false | false |
hewking/HUILibrary
|
app/src/main/java/com/hewking/base/recyclerview/LoadView.kt
|
1
|
2008
|
package com.livestar.flowchat.wallet.ui.tron
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.hewking.base.recyclerview.LoadState
import com.hewking.custom.util.dp2px
/**
* 项目名称:FlowChat
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/10/30 0030
* 修改人员:hewking
* 修改时间:2018/10/30 0030
* 修改备注:
* Version: 1.0.0
*/
class LoadView(val ctx : Context) : LinearLayout(ctx) {
var state : LoadState = LoadState.LOAD
set(value) {
field = value
initStateUI(value)
}
init {
setUpView()
}
private fun setUpView() {
orientation = HORIZONTAL
gravity = Gravity.CENTER
addView(TextView(ctx).apply {
setPadding(dp2px(10f),dp2px(10f),dp2px(10f),dp2px(10f))
text = "Loading"
setTextColor(Color.parseColor("#666666"))
})
addView(ProgressBar(ctx).apply {
setPadding(dp2px(10f),dp2px(10f),dp2px(10f),dp2px(10f))
})
layoutParams = androidx.recyclerview.widget.RecyclerView.LayoutParams(-1,-2)
}
private fun initStateUI(value: LoadState) {
when(value) {
LoadState.NOMORE -> {
getChildAt(1).visibility = View.GONE
(getChildAt(0) as TextView).text = "-- end --"
}
LoadState.NONET -> {
getChildAt(1).visibility = View.GONE
(getChildAt(0) as TextView).text = " no net please waitting ,then load"
}
LoadState.LOAD -> {
getChildAt(1).visibility = View.VISIBLE
(getChildAt(0) as TextView).text = " Loading"
}
else -> {
}
}
}
}
|
mit
|
5912f425637048ab3e5d9c20d1f3bdab
| 24.575342 | 87 | 0.562951 | 4.0375 | false | false | false | false |
doerfli/hacked
|
app/src/main/kotlin/li/doerf/hacked/ui/fragments/AccountsFragment.kt
|
1
|
7223
|
package li.doerf.hacked.ui.fragments
import android.content.Context
import android.os.Bundle
import android.text.Html
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.constraintlayout.widget.Group
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.google.android.material.snackbar.Snackbar
import io.reactivex.processors.PublishProcessor
import kotlinx.coroutines.*
import li.doerf.hacked.HackedApplication
import li.doerf.hacked.R
import li.doerf.hacked.db.AppDatabase
import li.doerf.hacked.db.daos.AccountDao
import li.doerf.hacked.db.entities.Account
import li.doerf.hacked.remote.hibp.HIBPAccountCheckerWorker
import li.doerf.hacked.services.AccountService
import li.doerf.hacked.ui.adapters.AccountsAdapter
import li.doerf.hacked.ui.viewmodels.AccountViewModel
import li.doerf.hacked.util.NavEvent
import org.joda.time.format.DateTimeFormat
import java.util.*
class AccountsFragment : Fragment() {
private lateinit var hibpInfo: TextView
private lateinit var fragmentRootView: View
private lateinit var accountEditText: EditText
private lateinit var groupAddAccount: Group
private lateinit var accountDao: AccountDao
private lateinit var accountsAdapter: AccountsAdapter
private lateinit var navEvents: PublishProcessor<NavEvent>
private var isFullView: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
accountDao = AppDatabase.get(context).accountDao
if (arguments != null) {
val args: AccountsFragmentArgs by navArgs()
if (args.fullView) {
isFullView = true
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
fragmentRootView = inflater.inflate(R.layout.fragment_accounts, container, false)
val accountsList: RecyclerView = fragmentRootView.findViewById(R.id.accounts_list)
accountsList.setHasFixedSize(true)
val lm = LinearLayoutManager(context)
accountsList.layoutManager = lm
accountsList.adapter = accountsAdapter
val lastChecked = fragmentRootView.findViewById<TextView>(R.id.last_checked)
val viewModel: AccountViewModel by viewModels()
viewModel.lastChecked.observe(viewLifecycleOwner, Observer { lastCheckedAccount: Account? ->
if (lastCheckedAccount?.lastChecked != null) {
val dtfOut = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm")
Log.d("AccountsFragment", dtfOut.print(lastCheckedAccount.lastChecked))
lastChecked.text = dtfOut.print(lastCheckedAccount.lastChecked)
lastChecked.visibility = View.VISIBLE
} else {
lastChecked.visibility = View.INVISIBLE
}
})
if (!isFullView) {
val title = fragmentRootView.findViewById<TextView>(R.id.title_accounts)
title.setOnClickListener {
navEvents.onNext(NavEvent(NavEvent.Destination.ACCOUNTS_LIST, null, null))
}
}
accountEditText = fragmentRootView.findViewById(R.id.account)
val addButton = fragmentRootView.findViewById<Button>(R.id.add)
addButton.setOnClickListener {
val accountName = accountEditText.text
AccountService(requireActivity().application).addAccount(accountName.toString())
hideSectionAndKeyboard(fragmentRootView)
hibpInfo.visibility = View.VISIBLE
}
val cancelButton = fragmentRootView.findViewById<Button>(R.id.cancel)
cancelButton.setOnClickListener {
hideSectionAndKeyboard(fragmentRootView)
hibpInfo.visibility = View.VISIBLE
}
groupAddAccount = fragmentRootView.findViewById(R.id.group_add_account)
hibpInfo = fragmentRootView.findViewById(R.id.hibp_info)
hibpInfo.movementMethod = LinkMovementMethod.getInstance()
hibpInfo.text = Html.fromHtml("${getString(R.string.data_provided_by)} <a href=\"https://haveibeenpwned.com\">Have i been pwned?</a>")
return fragmentRootView
}
private fun hideSectionAndKeyboard(fragmentRootView: View) {
groupAddAccount.visibility = View.GONE
val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(fragmentRootView.windowToken, 0)
}
override fun onAttach(context: Context) {
super.onAttach(context)
accountsAdapter = AccountsAdapter(requireActivity().applicationContext, ArrayList())
val accountsViewModel: AccountViewModel by viewModels()
accountsViewModel.accountList.observe(this, Observer { accounts: List<Account> -> accountsAdapter.addItems(accounts) })
navEvents = (requireActivity().applicationContext as HackedApplication).navEvents
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu_fragment_accounts, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
R.id.action_add -> {
showAddAcountView()
true
}
R.id.action_refresh -> {
val checker = OneTimeWorkRequest.Builder(HIBPAccountCheckerWorker::class.java)
.build()
WorkManager.getInstance(requireContext()).enqueue(checker)
Snackbar.make(fragmentRootView, getString(R.string.snackbar_checking_account), Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun showAddAcountView() {
CoroutineScope(Job()).launch {
val accounts = accountDao.all
withContext(Dispatchers.Main) {
if (accounts.size > MAX_ACCOUNTS) {
Log.w(LOGTAG, "maximum number of accounts reached")
Snackbar.make(fragmentRootView, getString(R.string.snackbar_max_accounts), Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
} else {
accountEditText.text.clear()
groupAddAccount.visibility = View.VISIBLE
hibpInfo.visibility = View.GONE
}
}
}
}
companion object {
const val LOGTAG = "AccountsFragmentBase"
const val MAX_ACCOUNTS = 50
}
}
|
apache-2.0
|
665bf314f1a84441ff024c67d9f5a414
| 39.80791 | 142 | 0.685588 | 4.83791 | false | false | false | false |
UnsignedInt8/d.Wallet-Core
|
android/lib/src/main/java/dWallet/core/bitcoin/protocol/structures/NetworkAddress.kt
|
1
|
1457
|
package dwallet.core.bitcoin.protocol.structures
/**
* Created by unsignedint8 on 8/15/17.
*/
import dwallet.core.extensions.*
import java.net.InetAddress
import kotlin.*
class NetworkAddress(val ip: String, val port: Short, val services: ByteArray = ByteArray(8), val time: Int = (System.currentTimeMillis() / 1000).toInt(), val addTimestamp: Boolean = true) {
companion object {
fun fromBytes(bytes: ByteArray, hasTimestamp: Boolean = true): NetworkAddress {
val time = if (hasTimestamp) bytes.readInt32LE(0) else 0
var offset = if (hasTimestamp) 4 else 0
val services = bytes.sliceArray(offset, offset + 8)
offset += 8
val ip = InetAddress.getByAddress(bytes.sliceArray(offset, offset + 16))
offset += 16
val port = bytes.readInt16BE(offset)
return NetworkAddress(ip.hostAddress, port, services, time)
}
fun fromBytes2(bytes: ByteArray): Pair<NetworkAddress, Int> {
return Pair(fromBytes(bytes), standardSize)
}
const val standardSize = 30
}
fun toBytes(): ByteArray {
val inetAddr = InetAddress.getByName(ip)
val addr = if (inetAddr.address.size == 4) "00000000000000000000FFFF".hexToByteArray() + inetAddr.address else inetAddr.address
return (if (addTimestamp) time.toInt32LEBytes() else ByteArray(0)) + services + addr + port.toInt16BEBytes()
}
}
|
gpl-3.0
|
2047d7308eb2ae3b1077821fba8be88b
| 32.136364 | 190 | 0.65477 | 4.223188 | false | false | false | false |
AromaTech/banana-data-operations
|
src/test/java/tech/aroma/data/sql/SQLReactionRepositoryTest.kt
|
3
|
6709
|
package tech.aroma.data.sql
/*
* Copyright 2017 RedRoma, 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.
*/
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Captor
import org.mockito.Mock
import org.springframework.jdbc.core.JdbcOperations
import org.springframework.jdbc.core.PreparedStatementSetter
import tech.aroma.data.invalidArg
import tech.aroma.data.operationError
import tech.aroma.data.sql.SQLStatements.Inserts
import tech.aroma.data.sql.SQLStatements.Queries
import tech.aroma.thrift.generators.ReactionGenerators
import tech.aroma.thrift.reactions.Reaction
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.DontRepeat
import tech.sirwellington.alchemy.test.junit.runners.GenerateString
import tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.ALPHABETIC
import tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.UUID
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import tech.sirwellington.alchemy.thrift.ThriftObjects
import java.sql.Connection
import java.sql.PreparedStatement
@RunWith(AlchemyTestRunner::class)
@Repeat
class SQLReactionRepositoryTest
{
@Mock
private lateinit var database: JdbcOperations
@Mock
private lateinit var serializer: DatabaseSerializer<MutableList<Reaction>>
@Mock
private lateinit var preparedStatement: PreparedStatement
@Mock
private lateinit var connection: Connection
@Mock
private lateinit var sqlArray: java.sql.Array
@Captor
private lateinit var statementCaptor: ArgumentCaptor<PreparedStatementSetter>
@GenerateString(UUID)
private lateinit var ownerId: String
@GenerateString(ALPHABETIC)
private lateinit var invalidId: String
private lateinit var reactions: List<Reaction>
private val serializedReactions get() = reactions.map(ThriftObjects::toJson)
private lateinit var instance: SQLReactionRepository
@Before
fun setUp()
{
setupData()
setupMocks()
instance = SQLReactionRepository(database, serializer)
}
@Test
fun testSaveReactionsForUser()
{
instance.saveReactionsForUser(ownerId, reactions)
verifyInsertOccurred()
}
@DontRepeat
@Test
fun testSaveReactionsForUserWithBadArgs()
{
assertThrows {
instance.saveReactionsForApplication("", reactions)
}.invalidArg()
assertThrows { instance.saveReactionsForUser(invalidId, reactions) }.invalidArg()
instance.saveReactionsForUser(ownerId, emptyList())
}
@DontRepeat
@Test
fun testSaveReactionsForUserWhenDatabaseFails()
{
setupForFailure()
assertThrows { instance.saveReactionsForUser(ownerId, reactions) }.operationError()
}
@Test
fun testGetReactionsForUser()
{
val result = instance.getReactionsForUser(ownerId)
assertThat(result, equalTo(reactions))
}
@DontRepeat
@Test
fun testGetReactionsForUserWithBadArgs()
{
assertThrows { instance.getReactionsForUser("") }.invalidArg()
assertThrows { instance.getReactionsForUser(invalidId) }.invalidArg()
}
@DontRepeat
@Test
fun testGetReactionsForUserWhenDatabaseFails()
{
setupForFailure()
assertThrows { instance.getReactionsForUser(ownerId) }.operationError()
}
@Test
fun testSaveReactionsForApplication()
{
instance.saveReactionsForApplication(ownerId, reactions)
verifyInsertOccurred()
}
@DontRepeat
@Test
fun testSaveReactionsForApplicationWithBadArgs()
{
assertThrows { instance.saveReactionsForApplication("", reactions) }.invalidArg()
assertThrows { instance.saveReactionsForApplication(invalidId, reactions) }.invalidArg()
instance.saveReactionsForApplication(ownerId, emptyList())
}
@DontRepeat
@Test
fun testSaveReactionsForApplicationWhenDatabaseFails()
{
setupForFailure()
assertThrows { instance.saveReactionsForApplication(ownerId, reactions) }.operationError()
}
@Test
fun testGetReactionsForApplication()
{
val result = instance.getReactionsForApplication(ownerId)
assertThat(result, equalTo(reactions))
}
@DontRepeat
@Test
fun testGetReactionsForApplicationWithBadArgs()
{
assertThrows { instance.getReactionsForApplication("") }.invalidArg()
assertThrows { instance.getReactionsForApplication(invalidId) }.invalidArg()
}
@DontRepeat
@Test
fun testGetReactionsForApplicationWhenDatabaseFails()
{
setupForFailure()
assertThrows { instance.getReactionsForApplication(ownerId) }.operationError()
}
private fun verifyInsertOccurred()
{
val sql = Inserts.REACTION
verify(database).update(eq(sql), statementCaptor.capture())
val statement = statementCaptor.value
statement.setValues(preparedStatement)
verify(preparedStatement).setObject(1, ownerId.toUUID())
verify(preparedStatement).setArray(2, sqlArray)
}
private fun setupForFailure()
{
database.setupForFailure()
}
private fun setupData()
{
reactions = CollectionGenerators.listOf(ReactionGenerators.reactions(), 5)
}
private fun setupMocks()
{
whenever(preparedStatement.connection).thenReturn(connection)
whenever(connection.createArrayOf("text", serializedReactions.toTypedArray()))
.thenReturn(sqlArray)
whenever(database.queryForObject(Queries.SELECT_REACTION, serializer, ownerId.toUUID()))
.thenReturn(reactions.toMutableList())
}
}
|
apache-2.0
|
6e7b80c492dad708ec4d83d77a278e9e
| 27.798283 | 98 | 0.732896 | 5.010456 | false | true | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/view/AddPaymentMethodCardView.kt
|
1
|
4387
|
package com.stripe.android.view
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.stripe.android.databinding.AddPaymentMethodCardViewBinding
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCreateParams
/**
* View for adding a payment method of type [PaymentMethod.Type.Card].
*
* See [AddPaymentMethodActivity] for usage.
*/
internal class AddPaymentMethodCardView @JvmOverloads internal constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
private val billingAddressFields: BillingAddressFields = BillingAddressFields.PostalCode
) : AddPaymentMethodView(context, attrs, defStyleAttr) {
private val cardMultilineWidget: CardMultilineWidget
private val billingAddressWidget: ShippingInfoWidget
override val createParams: PaymentMethodCreateParams?
get() {
return when (billingAddressFields) {
BillingAddressFields.Full -> {
val paymentMethodCard = cardMultilineWidget.paymentMethodCard
val billingDetails = this.billingDetails
if (paymentMethodCard != null && billingDetails != null) {
PaymentMethodCreateParams.create(
paymentMethodCard,
billingDetails
)
} else {
null
}
}
BillingAddressFields.None -> {
cardMultilineWidget.paymentMethodCreateParams
}
BillingAddressFields.PostalCode -> {
cardMultilineWidget.paymentMethodCreateParams
}
}
}
private val billingDetails: PaymentMethod.BillingDetails?
get() {
return if (billingAddressFields == BillingAddressFields.Full) {
billingAddressWidget.shippingInformation?.let {
PaymentMethod.BillingDetails.create(it)
}
} else {
null
}
}
init {
val viewBinding = AddPaymentMethodCardViewBinding.inflate(
LayoutInflater.from(context),
this,
true
)
cardMultilineWidget = viewBinding.cardMultilineWidget
cardMultilineWidget.setShouldShowPostalCode(
billingAddressFields == BillingAddressFields.PostalCode
)
billingAddressWidget = viewBinding.billingAddressWidget
if (billingAddressFields == BillingAddressFields.Full) {
billingAddressWidget.visibility = View.VISIBLE
}
(context as? AddPaymentMethodActivity?)?.let {
initEnterListeners(it)
}
}
private fun initEnterListeners(activity: AddPaymentMethodActivity) {
val listener = OnEditorActionListenerImpl(
activity,
this,
KeyboardController(activity)
)
cardMultilineWidget.cardNumberEditText
.setOnEditorActionListener(listener)
cardMultilineWidget.expiryDateEditText
.setOnEditorActionListener(listener)
cardMultilineWidget.cvcEditText
.setOnEditorActionListener(listener)
cardMultilineWidget.postalCodeEditText
.setOnEditorActionListener(listener)
}
override fun setCommunicatingProgress(communicating: Boolean) {
cardMultilineWidget.isEnabled = !communicating
}
internal class OnEditorActionListenerImpl(
private val activity: AddPaymentMethodActivity,
private val addPaymentMethodCardView: AddPaymentMethodCardView,
private val keyboardController: KeyboardController
) : TextView.OnEditorActionListener {
override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
if (actionId == EditorInfo.IME_ACTION_DONE) {
if (addPaymentMethodCardView.createParams != null) {
keyboardController.hide()
}
activity.onActionSave()
return true
}
return false
}
}
}
|
mit
|
f0ab5cf55997d279a11aa26ff0ebb7d9
| 34.959016 | 93 | 0.63711 | 6.034388 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.