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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/tlv/Tag.kt | 1 | 4445 | package io.github.binaryfoo.tlv
import io.github.binaryfoo.TagInfo
import io.github.binaryfoo.TagMetaData
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
/**
* The tag in T-L-V. Sometimes called Type but EMV 4.3 Book 3 - B3 Coding of the Value Field of Data Objects uses the term.
*/
data class Tag constructor(val bytes: List<Byte>, val compliant: Boolean = true) {
constructor(bytes: ByteArray, compliant: Boolean = true) : this(bytes.toMutableList(), compliant)
init {
if (compliant) {
validate(bytes)
}
}
private fun validate(b: List<Byte>) {
if (b.size == 0) {
throw IllegalArgumentException("Tag must be constructed with a non-empty byte array")
}
if (b.size == 1) {
if ((b[0].toInt() and 0x1F) == 0x1F) {
throw IllegalArgumentException("If bit 6 to bit 1 are set tag must not be only one byte long")
}
} else {
if ((b[b.size - 1].toInt() and 0x80) != 0) {
throw IllegalArgumentException("For multibyte tag bit 8 of the final byte must be 0: " + Integer.toHexString(b[b.size - 1].toInt()))
}
if (b.size > 2) {
for (i in 1..b.size - 2) {
if ((b[i].toInt() and 0x80) != 0x80) {
throw IllegalArgumentException("For multibyte tag bit 8 of the internal bytes must be 1: " + Integer.toHexString(b[i].toInt()))
}
}
}
}
}
val hexString: String
get() = ISOUtil.hexString(bytes)
val constructed: Boolean
get() = (bytes[0].toInt() and 0x20) == 0x20
val byteArray: ByteArray
get() = bytes.toByteArray()
fun isConstructed(): Boolean = constructed
override fun toString(): String {
return ISOUtil.hexString(bytes)
}
fun toString(tagMetaData: TagMetaData): String {
return toString(tagMetaData.get(this))
}
fun toString(tagInfo: TagInfo): String {
return "${ISOUtil.hexString(bytes)} (${tagInfo.fullName})"
}
companion object {
@JvmStatic
fun fromHex(hexString: String): Tag {
return Tag(ISOUtil.hex2byte(hexString))
}
@JvmStatic
fun parse(buffer: ByteBuffer): Tag = parse(buffer, CompliantTagMode)
@JvmStatic
fun parse(buffer: ByteBuffer, recognitionMode: TagRecognitionMode): Tag {
val out = ByteArrayOutputStream()
var b = buffer.get()
out.write(b.toInt())
if ((b.toInt() and 0x1F) == 0x1F) {
do {
b = buffer.get()
out.write(b.toInt())
} while (recognitionMode.keepReading(b, out))
}
return Tag(out.toByteArray(), recognitionMode == CompliantTagMode)
}
}
}
interface TagRecognitionMode {
fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean
}
/**
* Follows EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects to the letter.
*/
object CompliantTagMode : TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean = (current.toInt() and 0x80) == 0x80
}
/**
* EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects unless it's in a list of special cases.
*/
class QuirkListTagMode(val nonStandard: Set<String>) : TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean {
return CompliantTagMode.keepReading(current, all) && !nonStandard.contains(all.toByteArray().toHexString())
}
}
/**
* Seems at least one vendor read the following and thought I'll pick 9F80 as the start of my private tag range.
* According to Book 3 anything greater than 7F in byte two means the tag is at least 3 three bytes long, not two.
*
* <blockquote>
* The coding of primitive context-specific class data objects in the range '9F50' to '9F7F' is reserved for the payment systems.
* <footer>
* <cite>EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects</cite>
* </footer>
* </blockquote>
*/
object CommonVendorErrorMode : TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean {
return CompliantTagMode.keepReading(current, all) && (all.size() != 2 || !isCommonError(all.toByteArray()))
}
fun isCommonError(tag: ByteArray): Boolean {
return isCommonError(tag.toMutableList())
}
fun isCommonError(tag: List<Byte>): Boolean {
return tag.size > 1 && (tag[0] == 0x9F.toByte() && (tag[1].toInt() and 0xF0) == 0x80)
}
}
fun hasCommonVendorErrorTag(tlv: BerTlv): Boolean = CommonVendorErrorMode.isCommonError(tlv.tag.bytes)
| mit | 9b8016cd6d08311816f1f8dd70fcfb98 | 31.445255 | 140 | 0.668841 | 3.652424 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/permission/FixedParentMemorySubjectData.kt | 1 | 1596 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.permission
import org.lanternpowered.api.util.collections.immutableListBuilderOf
import org.spongepowered.api.service.context.Context
import org.spongepowered.api.service.permission.Subject
import org.spongepowered.api.service.permission.SubjectReference
import java.util.concurrent.CompletableFuture
/**
* Implementation that forces a single parent to always be part of the parents.
*/
class FixedParentMemorySubjectData(
subject: Subject, private val forcedParent: SubjectReference
) : GlobalMemorySubjectData(subject) {
override fun getParents(contexts: Set<Context>): List<SubjectReference> =
immutableListBuilderOf<SubjectReference>().add(this.forcedParent).addAll(super.getParents(contexts)).build()
override fun addParent(contexts: Set<Context>, parent: SubjectReference): CompletableFuture<Boolean> =
if (this.forcedParent == parent && contexts.isEmpty()) CompletableFuture.completedFuture(true) else super.addParent(contexts, parent)
override fun removeParent(contexts: Set<Context>, parent: SubjectReference): CompletableFuture<Boolean> =
if (this.forcedParent == parent) CompletableFuture.completedFuture(false) else super.removeParent(contexts, parent)
}
| mit | ad0a6ab4b0993e0c38e7c90bd499b64c | 45.941176 | 145 | 0.77193 | 4.421053 | false | false | false | false |
jcam3ron/cassandra-migration | src/main/java/com/builtamont/cassandra/migration/internal/command/Baseline.kt | 1 | 3425 | /**
* File : Baseline.kt
* License :
* Original - Copyright (c) 2015 - 2016 Contrast Security
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* 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.builtamont.cassandra.migration.internal.command
import com.builtamont.cassandra.migration.api.CassandraMigrationException
import com.builtamont.cassandra.migration.api.MigrationVersion
import com.builtamont.cassandra.migration.api.resolver.MigrationResolver
import com.builtamont.cassandra.migration.internal.dbsupport.SchemaVersionDAO
/**
* Handles the baseline command.
*
* @param migrationResolver The Cassandra migration resolver.
* @param baselineVersion The baseline version of the migration.
* @param schemaVersionDAO The Cassandra migration schema version DAO.
* @param baselineDescription The baseline version description / comments.
* @param user The user to execute the migration as.
*/
class Baseline(
private val migrationResolver: MigrationResolver,
private val baselineVersion: MigrationVersion,
private val schemaVersionDAO: SchemaVersionDAO,
private val baselineDescription: String,
private val user: String
) {
/**
* Runs the migration baselining.
*
* @return The number of successfully applied migration baselining.
* @throws CassandraMigrationException when migration baselining failed for any reason.
*/
@Throws(CassandraMigrationException::class)
fun run() {
val baselineMigration = schemaVersionDAO.baselineMarker
if (schemaVersionDAO.hasAppliedMigrations()) {
val msg = "Unable to baseline metadata table ${schemaVersionDAO.tableName} as it already contains migrations"
throw CassandraMigrationException(msg)
}
if (schemaVersionDAO.hasBaselineMarker()) {
val isNotBaselineByVersion = !(baselineMigration.version?.equals(baselineVersion) ?: false)
val isNotBaselineByDescription = !baselineMigration.description.equals(baselineDescription)
if (isNotBaselineByVersion || isNotBaselineByDescription) {
val msg = "Unable to baseline metadata table ${schemaVersionDAO.tableName} with ($baselineVersion, $baselineDescription)" +
" as it has already been initialized with (${baselineMigration.version}, ${baselineMigration.description})"
throw CassandraMigrationException(msg)
}
} else {
if (baselineVersion.equals(MigrationVersion.fromVersion("0"))) {
val msg = "Unable to baseline metadata table ${schemaVersionDAO.tableName} with version 0 as this version was used for schema creation"
throw CassandraMigrationException(msg)
}
schemaVersionDAO.addBaselineMarker(baselineVersion, baselineDescription, user)
}
}
} | apache-2.0 | 91d754922dabcf407c16d4a3be2804d0 | 45.297297 | 151 | 0.720584 | 4.94228 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/ApiKeyAuthenticationServerInterceptor.kt | 1 | 3884 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.Context
import io.grpc.Contexts
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.ServerInterceptors
import io.grpc.ServerServiceDefinition
import io.grpc.Status
import io.grpc.StatusException
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import org.wfanet.measurement.api.ApiKeyConstants
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.withPrincipal
import org.wfanet.measurement.common.crypto.hashSha256
import org.wfanet.measurement.common.grpc.SuspendableServerInterceptor
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.kingdom.ApiKey
import org.wfanet.measurement.internal.kingdom.ApiKeysGrpcKt.ApiKeysCoroutineStub
import org.wfanet.measurement.internal.kingdom.MeasurementConsumer
import org.wfanet.measurement.internal.kingdom.authenticateApiKeyRequest
/** gRPC [ServerInterceptor] to check [ApiKey] credentials coming in from a request. */
class ApiKeyAuthenticationServerInterceptor(
private val internalApiKeysClient: ApiKeysCoroutineStub,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) : SuspendableServerInterceptor(coroutineContext) {
override suspend fun <ReqT : Any, RespT : Any> interceptCallSuspending(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
val authenticationKey =
headers.get(ApiKeyConstants.API_AUTHENTICATION_KEY_METADATA_KEY)
?: return Contexts.interceptCall(Context.current(), call, headers, next)
var context = Context.current()
try {
val measurementConsumer = authenticateAuthenticationKey(authenticationKey)
context =
context.withPrincipal(
MeasurementConsumerPrincipal(
MeasurementConsumerKey(
externalIdToApiId(measurementConsumer.externalMeasurementConsumerId)
)
)
)
} catch (e: StatusException) {
val status =
when (e.status.code) {
Status.Code.NOT_FOUND -> Status.UNAUTHENTICATED.withDescription("API key is invalid")
Status.Code.CANCELLED -> Status.CANCELLED
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
else -> Status.UNKNOWN
}
call.close(status.withCause(e), headers)
}
return Contexts.interceptCall(context, call, headers, next)
}
private suspend fun authenticateAuthenticationKey(
authenticationKey: String
): MeasurementConsumer =
internalApiKeysClient.authenticateApiKey(
authenticateApiKeyRequest {
authenticationKeyHash = hashSha256(apiIdToExternalId(authenticationKey))
}
)
}
fun ServerServiceDefinition.withApiKeyAuthenticationServerInterceptor(
internalApiKeysStub: ApiKeysCoroutineStub
): ServerServiceDefinition =
ServerInterceptors.intercept(this, ApiKeyAuthenticationServerInterceptor(internalApiKeysStub))
| apache-2.0 | c26d56170e07fcefb06ad9c7e580667f | 39.884211 | 96 | 0.779094 | 4.783251 | false | false | false | false |
orhanobut/dialogplus | dialogplus/src/test/java/com/orhanobut/android/dialogplus/DialogPlusBuilderTest.kt | 2 | 10063 | package com.orhanobut.android.dialogplus
import android.app.Activity
import android.view.Gravity
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.orhanobut.dialogplus.*
import junit.framework.Assert.fail
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DialogPlusBuilderTest {
private val context = Robolectric.setupActivity(Activity::class.java)
@Test fun testAdapter() {
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1, arrayOf("234")
)
val builder = DialogPlus.newDialog(context).setAdapter(adapter)
assertThat(builder.adapter).isEqualTo(adapter)
}
@Test fun testFooter() {
val builder = DialogPlus.newDialog(context)
builder.setFooter(android.R.layout.simple_list_item_1)
assertThat(builder.footerView).isNotNull()
val footerView = LinearLayout(context)
builder.setFooter(footerView)
assertThat(builder.footerView).isEqualTo(footerView)
}
@Test fun testHeader() {
val builder = DialogPlus.newDialog(context)
builder.setHeader(android.R.layout.simple_list_item_1)
assertThat(builder.headerView).isNotNull()
val headerView = LinearLayout(context)
builder.setHeader(headerView)
assertThat(builder.headerView).isEqualTo(headerView)
}
@Test fun getHolder_shouldBeListHolderAsDefault() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.holder).isNotNull()
assertThat(builder.holder).isInstanceOf(ListHolder::class.java)
}
@Test fun testSetContentHolder() {
val builder = DialogPlus.newDialog(context)
//Test ListHolder
val listHolder = ListHolder()
builder.setContentHolder(listHolder)
assertThat(builder.holder).isEqualTo(listHolder)
//test GridHolder
val gridHolder = GridHolder(3)
builder.setContentHolder(gridHolder)
assertThat(builder.holder).isEqualTo(gridHolder)
//test ViewHolder
val viewHolder = ViewHolder(LinearLayout(context))
builder.setContentHolder(viewHolder)
assertThat(builder.holder).isEqualTo(viewHolder)
}
@Test fun testSetCancelable() {
val builder = DialogPlus.newDialog(context)
//default should be true
assertThat(builder.isCancelable).isTrue()
builder.isCancelable = false
assertThat(builder.isCancelable).isFalse()
}
@Test fun testBackgroundColorResId() {
//TODO fill it
}
@Test fun testGravity() {
val builder = DialogPlus.newDialog(context)
//default should be bottom
val params = builder.contentParams
assertThat(params.gravity).isEqualTo(Gravity.BOTTOM)
// set different gravity
builder.setGravity(Gravity.TOP)
assertThat(params.gravity).isEqualTo(Gravity.TOP)
//set combination
builder.setGravity(Gravity.TOP or Gravity.CENTER)
assertThat(params.gravity).isEqualTo(Gravity.TOP or Gravity.CENTER)
}
@Test fun testInAnimation() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.inAnimation).isNotNull()
//TODO
}
@Test fun testOutAnimation() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.outAnimation).isNotNull()
//TODO
}
@Test fun testContentLayoutParams_whenExpandedFalseAndNotSet() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.contentParams).isInstanceOf(FrameLayout.LayoutParams::class.java)
//when not expanded
val params = builder.contentParams
assertThat(builder.isExpanded).isFalse()
assertThat(params.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
assertThat(params.height).isEqualTo(ViewGroup.LayoutParams.WRAP_CONTENT)
assertThat(params.gravity).isEqualTo(Gravity.BOTTOM)
}
@Test fun testContentLayoutParams_whenExpandedTrueAndNotSet() {
val builder = DialogPlus.newDialog(context)
builder.isExpanded = true
assertThat(builder.contentParams).isInstanceOf(FrameLayout.LayoutParams::class.java)
//when not expanded
val params = builder.contentParams
assertThat(builder.isExpanded).isTrue()
assertThat(params.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
assertThat(params.height).isEqualTo(builder.defaultContentHeight)
assertThat(params.gravity).isEqualTo(Gravity.BOTTOM)
}
@Test fun testContentLayoutParams_whenExpandedTrueWithHeightAndNotSet() {
val builder = DialogPlus.newDialog(context)
builder.setExpanded(true, 100)
assertThat(builder.contentParams).isInstanceOf(FrameLayout.LayoutParams::class.java)
//when not expanded
val params = builder.contentParams
assertThat(builder.isExpanded).isTrue()
assertThat(params.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
assertThat(params.height).isEqualTo(100)
assertThat(params.gravity).isEqualTo(Gravity.BOTTOM)
}
@Test fun testExpanded() {
val builder = DialogPlus.newDialog(context)
//default should be false
assertThat(builder.isExpanded).isFalse()
builder.isExpanded = true
assertThat(builder.isExpanded).isTrue()
}
@Test fun testOutMostParams() {
val builder = DialogPlus.newDialog(context)
var params = builder.outmostLayoutParams
assertThat(params.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
assertThat(params.height).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
// default should be 0 for all
assertThat(params.leftMargin).isEqualTo(0)
assertThat(params.rightMargin).isEqualTo(0)
assertThat(params.topMargin).isEqualTo(0)
assertThat(params.bottomMargin).isEqualTo(0)
//set new margin
builder.setOutMostMargin(1, 2, 3, 4)
params = builder.outmostLayoutParams
assertThat(params.leftMargin).isEqualTo(1)
assertThat(params.topMargin).isEqualTo(2)
assertThat(params.rightMargin).isEqualTo(3)
assertThat(params.bottomMargin).isEqualTo(4)
}
@Test fun testDefaultContentMarginWhenGravityCenter() {
val builder = DialogPlus.newDialog(context)
builder.setGravity(Gravity.CENTER)
val minimumMargin = context.resources.getDimensionPixelSize(R.dimen.dialogplus_default_center_margin)
val margin = builder.contentMargin
assertThat(margin[0]).isEqualTo(minimumMargin)
assertThat(margin[1]).isEqualTo(minimumMargin)
assertThat(margin[2]).isEqualTo(minimumMargin)
assertThat(margin[3]).isEqualTo(minimumMargin)
}
@Test fun testDefaultContentMarginWhenGravityIsNotCenter() {
val builder = DialogPlus.newDialog(context)
val margin = builder.contentMargin
assertThat(margin[0]).isEqualTo(0)
assertThat(margin[1]).isEqualTo(0)
assertThat(margin[2]).isEqualTo(0)
assertThat(margin[3]).isEqualTo(0)
}
@Test fun testContentMarginWhenSet() {
val builder = DialogPlus.newDialog(context)
builder.setMargin(1, 2, 3, 4)
val margin = builder.contentMargin
assertThat(margin[0]).isEqualTo(1)
assertThat(margin[1]).isEqualTo(2)
assertThat(margin[2]).isEqualTo(3)
assertThat(margin[3]).isEqualTo(4)
}
@Test fun testPadding() {
val builder = DialogPlus.newDialog(context)
//default 0
var padding = builder.contentPadding
assertThat(padding[0]).isEqualTo(0)
assertThat(padding[1]).isEqualTo(0)
assertThat(padding[2]).isEqualTo(0)
assertThat(padding[3]).isEqualTo(0)
builder.setPadding(1, 2, 3, 4)
padding = builder.contentPadding
assertThat(padding[0]).isEqualTo(1)
assertThat(padding[1]).isEqualTo(2)
assertThat(padding[2]).isEqualTo(3)
assertThat(padding[3]).isEqualTo(4)
}
@Test fun testSetContentWidth() {
val builder = DialogPlus.newDialog(context)
builder.setContentWidth(100)
val params = builder.contentParams
assertThat(params.width).isEqualTo(100)
}
@Test fun testSetContentHeight() {
val builder = DialogPlus.newDialog(context)
builder.setContentHeight(100)
val params = builder.contentParams
assertThat(params.height).isEqualTo(100)
}
@Test fun testSetOnClickListener() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.onClickListener).isNull()
val clickListener = OnClickListener { dialog, view -> }
builder.onClickListener = clickListener
assertThat(builder.onClickListener).isNotNull()
assertThat(builder.onClickListener).isEqualTo(clickListener)
}
@Test fun testSetOnItemClickListener() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.onItemClickListener).isNull()
val listener = OnItemClickListener { dialog, item, view, position -> }
builder.onItemClickListener = listener
assertThat(builder.onItemClickListener).isNotNull()
assertThat(builder.onItemClickListener).isEqualTo(listener)
}
@Test fun testSetOnDismissListener() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.onDismissListener).isNull()
val listener = OnDismissListener { }
builder.onDismissListener = listener
assertThat(builder.onDismissListener).isNotNull()
assertThat(builder.onDismissListener).isEqualTo(listener)
}
@Test fun testSetOnCancelListener() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.onCancelListener).isNull()
val listener = OnCancelListener { }
builder.setOnCancelListener(listener)
assertThat(builder.onCancelListener).isNotNull()
assertThat(builder.onCancelListener).isEqualTo(listener)
}
@Test fun testSetOnBackPressListener() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.onBackPressListener).isNull()
val listener = OnBackPressListener { }
builder.onBackPressListener = listener
assertThat(builder.onBackPressListener).isNotNull()
assertThat(builder.onBackPressListener).isEqualTo(listener)
}
@Test fun create_shouldNotReturnNull() {
val builder = DialogPlus.newDialog(context)
assertThat(builder.create()).isNotNull()
}
}
| apache-2.0 | 953d0cd079976dee1e0cba0e425ae1ac | 31.46129 | 105 | 0.748683 | 4.512556 | false | true | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/SpannerMeasurementsService.kt | 1 | 8166 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner
import io.grpc.Status
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.common.identity.IdGenerator
import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient
import org.wfanet.measurement.internal.kingdom.CancelMeasurementRequest
import org.wfanet.measurement.internal.kingdom.GetMeasurementByComputationIdRequest
import org.wfanet.measurement.internal.kingdom.GetMeasurementRequest
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.MeasurementsGrpcKt.MeasurementsCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.SetMeasurementResultRequest
import org.wfanet.measurement.internal.kingdom.StreamMeasurementsRequest
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertificateIsInvalidException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertificateNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DataProviderNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyCertificateNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementConsumerNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementStateIllegalException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries.StreamMeasurements
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.CancelMeasurement
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.CreateMeasurement
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.SetMeasurementResult
class SpannerMeasurementsService(
private val idGenerator: IdGenerator,
private val client: AsyncDatabaseClient
) : MeasurementsCoroutineImplBase() {
override suspend fun createMeasurement(request: Measurement): Measurement {
validateCreateMeasurementRequest(request)
try {
return CreateMeasurement(request).execute(client, idGenerator)
} catch (e: CertificateIsInvalidException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Certificate is invalid." }
} catch (e: MeasurementConsumerNotFoundException) {
e.throwStatusRuntimeException(Status.NOT_FOUND) { "MeasurementConsumer not found." }
} catch (e: DataProviderNotFoundException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "DataProvider not found." }
} catch (e: DuchyNotFoundException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Duchy not found." }
} catch (e: CertificateNotFoundException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Certificate not found." }
} catch (e: KingdomInternalException) {
e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error." }
}
}
private fun validateCreateMeasurementRequest(request: Measurement) {
grpcRequire(request.externalMeasurementConsumerCertificateId != 0L) {
"external_measurement_consumer_certificate_id unspecified"
}
grpcRequire(request.details.apiVersion.isNotEmpty()) { "api_version unspecified" }
grpcRequire(!request.details.measurementSpec.isEmpty) { "measurement_spec unspecified" }
grpcRequire(!request.details.measurementSpecSignature.isEmpty) {
"measurement_spec_signature unspecified"
}
for ((externalDataProviderId, dataProvider) in request.dataProvidersMap) {
grpcRequire(!dataProvider.dataProviderPublicKey.isEmpty) {
"data_provider_public_key unspecified for ${ExternalId(externalDataProviderId)}"
}
grpcRequire(!dataProvider.dataProviderPublicKeySignature.isEmpty) {
"data_provider_public_key_signature unspecified for ${ExternalId(externalDataProviderId)}"
}
grpcRequire(!dataProvider.encryptedRequisitionSpec.isEmpty) {
"encrypted_requisition_spec unspecified for ${ExternalId(externalDataProviderId)}"
}
grpcRequire(!dataProvider.nonceHash.isEmpty) {
"nonce_hash unspecified for ${ExternalId(externalDataProviderId)}"
}
}
}
override suspend fun getMeasurement(request: GetMeasurementRequest): Measurement {
return MeasurementReader(Measurement.View.DEFAULT)
.readByExternalIds(
client.singleUse(),
ExternalId(request.externalMeasurementConsumerId),
ExternalId(request.externalMeasurementId)
)
?.measurement
?: failGrpc(Status.NOT_FOUND) { "Measurement not found" }
}
override suspend fun getMeasurementByComputationId(
request: GetMeasurementByComputationIdRequest
): Measurement {
return MeasurementReader(Measurement.View.COMPUTATION)
.readByExternalComputationId(client.singleUse(), ExternalId(request.externalComputationId))
?.measurement
?: failGrpc(Status.NOT_FOUND) { "Measurement not found" }
}
override fun streamMeasurements(request: StreamMeasurementsRequest): Flow<Measurement> {
return StreamMeasurements(request.measurementView, request.filter, request.limit)
.execute(client.singleUse())
.map { it.measurement }
}
override suspend fun setMeasurementResult(request: SetMeasurementResultRequest): Measurement {
try {
return SetMeasurementResult(request).execute(client, idGenerator)
} catch (e: MeasurementNotFoundException) {
e.throwStatusRuntimeException(Status.NOT_FOUND) { "Measurement not found." }
} catch (e: DuchyNotFoundException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Duchy not found." }
} catch (e: DuchyCertificateNotFoundException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) {
"Aggregator's Certificate not found."
}
} catch (e: KingdomInternalException) {
e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error." }
}
}
override suspend fun cancelMeasurement(request: CancelMeasurementRequest): Measurement {
with(request) {
grpcRequire(externalMeasurementConsumerId != 0L) {
"external_measurement_consumer_id not specified"
}
grpcRequire(externalMeasurementId != 0L) { "external_measurement_id not specified" }
}
val externalMeasurementConsumerId = ExternalId(request.externalMeasurementConsumerId)
val externalMeasurementId = ExternalId(request.externalMeasurementId)
try {
return CancelMeasurement(externalMeasurementConsumerId, externalMeasurementId)
.execute(client, idGenerator)
} catch (e: MeasurementNotFoundException) {
e.throwStatusRuntimeException(Status.NOT_FOUND) { "Measurement not found." }
} catch (e: MeasurementStateIllegalException) {
e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Measurement state illegal." }
} catch (e: KingdomInternalException) {
e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error." }
}
}
}
| apache-2.0 | 52f9afe9dc03a1cdeab27c169ad28081 | 50.0375 | 103 | 0.784472 | 4.74216 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/probablebugs/LatexMultipleGraphicsPathInspection.kt | 1 | 2048 | package nl.hannahsten.texifyidea.inspections.latex.probablebugs
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.inspections.InsightGroup
import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase
import nl.hannahsten.texifyidea.util.files.commandsInFile
/**
* @author Lukas Heiligenbrunner
*/
class LatexMultipleGraphicsPathInspection : TexifyInspectionBase() {
override val inspectionGroup = InsightGroup.LATEX
override val inspectionId = "MultipleGraphicsPath"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> {
val descriptors = descriptorList()
val commands = file.commandsInFile()
// Check if a graphicspath is defined
val paths = commands.filter { it.name == "\\graphicspath" }
// Throw error on multiple definition of \graphicspath.
if (paths.size > 1) {
for (i in paths) {
descriptors.add(
manager.createProblemDescriptor(
i,
TextRange(0, i.text.length),
"\\graphicspath is already used elsewhere",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly,
RemoveFix()
)
)
}
}
return descriptors
}
/**
* Remove the command line.
*/
class RemoveFix : LocalQuickFix {
override fun getFamilyName(): String {
return "Remove this Line"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
descriptor.psiElement.delete()
}
}
} | mit | 13b82a8578b345f3915d114f407f2cba | 31.52381 | 119 | 0.649902 | 5.237852 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/ui/video/VideoActivity.kt | 1 | 1482 | package com.andreapivetta.blu.ui.video
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.MediaController
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.utils.visible
import kotlinx.android.synthetic.main.activity_video.*
class VideoActivity : AppCompatActivity() {
companion object {
private const val TAG_URL = "video"
private const val TAG_TYPE = "type"
fun launch(context: Context, videoUrl: String, videoType: String) {
val intent = Intent(context, VideoActivity::class.java)
intent.putExtra(TAG_URL, videoUrl)
intent.putExtra(TAG_TYPE, videoType)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video)
val mc = MediaController(this)
mc.setAnchorView(videoView)
mc.setMediaPlayer(videoView)
videoView.setOnPreparedListener { loadingProgressBar.visible(false) }
if ("animated_gif" == intent.getStringExtra(TAG_TYPE))
videoView.setOnCompletionListener { videoView.start() }
videoView.setMediaController(mc)
videoView.setVideoURI(Uri.parse(intent.getStringExtra(TAG_URL)))
videoView.requestFocus()
videoView.start()
}
}
| apache-2.0 | 02a80235f029ffc35f13c2ef8809ac6c | 31.933333 | 77 | 0.704453 | 4.588235 | false | false | false | false |
chandilsachin/DietTracker | app/src/main/java/com/chandilsachin/diettracker/repository/FoodRepository.kt | 1 | 2133 | package com.chandilsachin.diettracker.repository
import android.arch.lifecycle.LiveData
import android.content.Context
import com.chandilsachin.diettracker.database.DietFood
import com.chandilsachin.diettracker.database.Food
import com.chandilsachin.diettracker.database.FoodDatabase
import com.chandilsachin.diettracker.database.PersonalizedFood
import com.chandilsachin.diettracker.model.Date
import com.chandilsachin.diettracker.other.AddFoodPresenter
/**
* Created by sachin on 27/5/17.
*/
class FoodRepository {
fun getAllFodList(context: Context):LiveData<List<Food>>{
return FoodDatabase.getInstance(context).getAllFoodList()
}
fun getFoodDetails(context: Context, foodId:Long):Food{
return FoodDatabase.getInstance(context).getFoodDetails(foodId)
}
fun saveFood(context: Context, food: PersonalizedFood){
FoodDatabase.getInstance(context).saveFood(food)
}
fun updateFood(context: Context, food: PersonalizedFood){
val tempFood = FoodDatabase.getInstance(context).getFood(food.foodId, Date())
if(tempFood != null)
food.quantity += tempFood.quantity
FoodDatabase.getInstance(context).saveFood(food)
}
fun setUpFoodDatabase(context:Context){
val list = AddFoodPresenter().readFoodItemsFile(context)
FoodDatabase.getInstance(context).addFoodList(list)
}
fun getTodaysFoodList(context: Context):List<DietFood>{
return FoodDatabase.getInstance(context).getFood(Date())
}
fun getFoodListOn(date: Date, context: Context):List<DietFood>{
return FoodDatabase.getInstance(context).getFood(date)
}
fun getFoodOn(date: Date, foodId:Long, context: Context):PersonalizedFood?{
return FoodDatabase.getInstance(context).getFood(foodId, date)
}
fun deleteDietFood(food:PersonalizedFood, context: Context){
FoodDatabase.getInstance(context).deleteDietFood(food)
}
fun getLastDateOfListing(context: Context):Date{
val date = FoodDatabase.getInstance(context).getLastDateOfListing()
return if(date == null) Date() else date
}
} | gpl-3.0 | d7189bdf3185a782e0a1b54378084caf | 33.419355 | 85 | 0.739334 | 4.166016 | false | false | false | false |
PaulWoitaschek/Voice | scanner/src/main/kotlin/voice/app/scanner/MediaScanTrigger.kt | 1 | 1702 | package voice.app.scanner
import androidx.documentfile.provider.DocumentFile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import voice.data.folders.AudiobookFolders
import voice.data.folders.FolderType
import voice.data.repo.BookRepository
import voice.logging.core.Logger
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MediaScanTrigger
@Inject constructor(
private val audiobookFolders: AudiobookFolders,
private val scanner: MediaScanner,
private val coverScanner: CoverScanner,
private val bookRepo: BookRepository,
) {
private val _scannerActive = MutableStateFlow(false)
val scannerActive: Flow<Boolean> = _scannerActive
private val scope = CoroutineScope(Dispatchers.IO)
private var scanningJob: Job? = null
fun scan(restartIfScanning: Boolean = false) {
Logger.i("scanForFiles with restartIfScanning=$restartIfScanning")
if (scanningJob?.isActive == true && !restartIfScanning) {
return
}
val oldJob = scanningJob
scanningJob = scope.launch {
_scannerActive.value = true
oldJob?.cancelAndJoin()
val folders: Map<FolderType, List<DocumentFile>> = audiobookFolders.all()
.first()
.mapValues { (_, documentFilesWithUri) ->
documentFilesWithUri.map { it.documentFile }
}
scanner.scan(folders)
val books = bookRepo.all()
coverScanner.scan(books)
_scannerActive.value = false
}
}
}
| gpl-3.0 | 66b6e72138423e3a858c44f1308ec434 | 28.859649 | 79 | 0.756757 | 4.352941 | false | false | false | false |
FHannes/intellij-community | platform/credential-store/src/macOsKeychainLibrary.kt | 6 | 10085 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.credentialStore
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ArrayUtilRt
import com.sun.jna.*
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.PointerByReference
import gnu.trove.TIntObjectHashMap
val isMacOsCredentialStoreSupported: Boolean
get() = SystemInfo.isMacIntel64 && SystemInfo.isMacOSLeopard
private val LIBRARY by lazy {
Native.loadLibrary("Security", MacOsKeychainLibrary::class.java) as MacOsKeychainLibrary
}
private const val errSecSuccess = 0
private const val errSecItemNotFound = -25300
private const val errSecInvalidRecord = -67701
// or if Deny clicked on access dialog
private const val errUserNameNotCorrect = -25293
private const val kSecFormatUnknown = 0
private const val kSecAccountItemAttr = (('a'.toInt() shl 8 or 'c'.toInt()) shl 8 or 'c'.toInt()) shl 8 or 't'.toInt()
internal class KeyChainCredentialStore() : CredentialStore {
override fun get(attributes: CredentialAttributes): Credentials? {
return findGenericPassword(attributes.serviceName.toByteArray(), attributes.userName)
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceName = attributes.serviceName.toByteArray()
if (credentials.isEmpty()) {
val itemRef = PointerByReference()
val userName = attributes.userName?.toByteArray()
val code = LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, null, null, itemRef)
if (code == errSecItemNotFound || code == errSecInvalidRecord) {
return
}
checkForError("find (for delete)", code)
itemRef.value?.let {
checkForError("delete", LIBRARY.SecKeychainItemDelete(it))
LIBRARY.CFRelease(it)
}
return
}
val userName = (attributes.userName ?: credentials!!.userName)?.toByteArray()
val searchUserName = if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null
val itemRef = PointerByReference()
val library = LIBRARY
checkForError("find (for save)", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, searchUserName?.size ?: 0, searchUserName, null, null, itemRef))
val password = if (attributes.isPasswordMemoryOnly || credentials!!.password == null) null else credentials.password!!.toByteArray(false)
val pointer = itemRef.value
if (pointer == null) {
checkForError("save (new)", library.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, password?.size ?: 0, password))
}
else {
val attribute = SecKeychainAttribute()
attribute.tag = kSecAccountItemAttr
attribute.length = userName?.size ?: 0
if (userName != null) {
val userNamePointer = Memory(userName.size.toLong())
userNamePointer.write(0, userName, 0, userName.size)
attribute.data = userNamePointer
}
val attributeList = SecKeychainAttributeList()
attributeList.count = 1
attribute.write()
attributeList.attr = attribute.pointer
checkForError("save (update)", library.SecKeychainItemModifyContent(pointer, attributeList, password?.size ?: 0, password ?: ArrayUtilRt.EMPTY_BYTE_ARRAY))
library.CFRelease(pointer)
}
password?.fill(0)
}
}
fun findGenericPassword(serviceName: ByteArray, accountName: String?): Credentials? {
val accountNameBytes = accountName?.toByteArray()
val passwordSize = IntArray(1)
val passwordRef = PointerByReference()
val itemRef = PointerByReference()
checkForError("find", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes?.size ?: 0, accountNameBytes, passwordSize, passwordRef, itemRef))
val pointer = passwordRef.value ?: return null
val password = OneTimeString(pointer.getByteArray(0, passwordSize.get(0)))
LIBRARY.SecKeychainItemFreeContent(null, pointer)
var effectiveAccountName = accountName
if (effectiveAccountName == null) {
val attributes = PointerByReference()
checkForError("SecKeychainItemCopyAttributesAndData", LIBRARY.SecKeychainItemCopyAttributesAndData(itemRef.value!!, SecKeychainAttributeInfo(kSecAccountItemAttr), null, attributes, null, null))
val attributeList = SecKeychainAttributeList(attributes.value)
try {
attributeList.read()
effectiveAccountName = readAttributes(attributeList).get(kSecAccountItemAttr)
}
finally {
LIBRARY.SecKeychainItemFreeAttributesAndData(attributeList, null)
}
}
return Credentials(effectiveAccountName, password)
}
// https://developer.apple.com/library/mac/documentation/Security/Reference/keychainservices/index.html
// It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered."
private interface MacOsKeychainLibrary : Library {
fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: Int, passwordData: ByteArray?, itemRef: Pointer? = null): Int
fun SecKeychainItemModifyContent(itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Any?, length: Int, data: ByteArray?): Int
fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?,
serviceNameLength: Int,
serviceName: ByteArray,
accountNameLength: Int,
accountName: ByteArray?,
passwordLength: IntArray?,
passwordData: PointerByReference?,
itemRef: PointerByReference?): Int
fun SecKeychainItemCopyAttributesAndData(itemRef: Pointer,
info: SecKeychainAttributeInfo,
itemClass: IntByReference?,
attrList: PointerByReference,
length: IntByReference?,
outData: PointerByReference?): Int
fun SecKeychainItemFreeAttributesAndData(attrList: SecKeychainAttributeList, data: Pointer?): Int
fun SecKeychainItemDelete(itemRef: Pointer): Int
fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer?
// http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long
fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char
fun CFRelease(/*CFTypeRef*/ cf: Pointer)
fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?)
}
internal class SecKeychainAttributeInfo : Structure() {
@JvmField
var count: Int = 0
@JvmField
var tag: Pointer? = null
@JvmField
var format: Pointer? = null
override fun getFieldOrder() = listOf("count", "tag", "format")
}
private fun checkForError(message: String, code: Int) {
if (code == errSecSuccess || code == errSecItemNotFound) {
return
}
val translated = LIBRARY.SecCopyErrorMessageString(code, null)
val builder = StringBuilder(message).append(": ")
if (translated == null) {
builder.append(code)
}
else {
val buf = CharArray(LIBRARY.CFStringGetLength(translated).toInt())
for (i in 0..buf.size - 1) {
buf[i] = LIBRARY.CFStringGetCharacterAtIndex(translated, i.toLong())
}
LIBRARY.CFRelease(translated)
builder.append(buf).append(" (").append(code).append(')')
}
if (code == errUserNameNotCorrect || code == -25299 /* The specified item already exists in the keychain */) {
LOG.warn(builder.toString())
}
else {
LOG.error(builder.toString())
}
}
internal fun SecKeychainAttributeInfo(vararg ids: Int): SecKeychainAttributeInfo {
val info = SecKeychainAttributeInfo()
val length = ids.size
info.count = length
val size = length shl 2
val tag = Memory((size shl 1).toLong())
val format = tag.share(size.toLong(), size.toLong())
info.tag = tag
info.format = format
var offset = 0
for (id in ids) {
tag.setInt(offset.toLong(), id)
format.setInt(offset.toLong(), kSecFormatUnknown)
offset += 4
}
return info
}
internal class SecKeychainAttributeList : Structure {
@JvmField
var count = 0
@JvmField
var attr: Pointer? = null
constructor(p: Pointer) : super(p) {
}
constructor() : super() {
}
override fun getFieldOrder() = listOf("count", "attr")
}
internal class SecKeychainAttribute : Structure, Structure.ByReference {
@JvmField
var tag = 0
@JvmField
var length = 0
@JvmField
var data: Pointer? = null
internal constructor(p: Pointer) : super(p) {
}
internal constructor() : super() {
}
override fun getFieldOrder() = listOf("tag", "length", "data")
}
private fun readAttributes(list: SecKeychainAttributeList): TIntObjectHashMap<String> {
val map = TIntObjectHashMap<String>()
val attrList = SecKeychainAttribute(list.attr!!)
attrList.read()
@Suppress("UNCHECKED_CAST")
for (attr in attrList.toArray(list.count) as Array<SecKeychainAttribute>) {
val data = attr.data ?: continue
map.put(attr.tag, String(data.getByteArray(0, attr.length)))
}
return map
} | apache-2.0 | 4b065451d52830c8bcada21ea85dbd46 | 37.643678 | 230 | 0.702826 | 4.375271 | false | false | false | false |
die-tageszeitung/tazapp-android | tazapp/src/main/java/de/thecode/android/tazreader/data/Paper.kt | 1 | 699 | package de.thecode.android.tazreader.data
class PaperWithDownloadState:Paper() {
var downloadState: DownloadState = DownloadState.NONE
var progress = 0
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PaperWithDownloadState) return false
if (!super.equals(other)) return false
if (downloadState != other.downloadState) return false
if (progress != other.progress) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + downloadState.hashCode()
result = 31 * result + progress
return result
}
} | agpl-3.0 | ff7d021131a2852918cc138f98388e4d | 28.166667 | 62 | 0.645207 | 4.66 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/ui/preferences/PreferencesAdvanced.kt | 1 | 7439 | /*
* *************************************************************************
* PreferencesAdvanced.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.television.ui.preferences
import android.annotation.TargetApi
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import kotlinx.coroutines.*
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.resources.AndroidDevices
import org.videolan.resources.VLCInstance
import org.videolan.tools.putSingle
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.gui.DebugLogActivity
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.helpers.hf.StoragePermissionsDelegate.Companion.getWritePermission
import org.videolan.vlc.util.FileUtils
import java.io.File
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class PreferencesAdvanced : BasePreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener, CoroutineScope by MainScope() {
override fun getXml(): Int {
return R.xml.preferences_adv
}
override fun getTitleId(): Int {
return R.string.advanced_prefs_category
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (BuildConfig.DEBUG) findPreference<Preference>("debug_logs")?.isVisible = false
}
override fun onStart() {
super.onStart()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onStop() {
super.onStop()
preferenceScreen.sharedPreferences
.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onPreferenceTreeClick(preference: Preference): Boolean {
val ctx = activity
if (preference.key == null || ctx == null) return false
when (preference.key) {
"debug_logs" -> {
val intent = Intent(ctx, DebugLogActivity::class.java)
startActivity(intent)
return true
}
"clear_history" -> {
AlertDialog.Builder(ctx)
.setTitle(R.string.clear_playback_history)
.setMessage(R.string.validation)
.setIcon(R.drawable.ic_warning)
.setPositiveButton(R.string.yes) { _, _ -> launch(Dispatchers.IO) {
Medialibrary.getInstance().clearHistory()
}}
.setNegativeButton(R.string.cancel, null)
.show()
return true
}
"clear_media_db" -> {
AlertDialog.Builder(ctx)
.setTitle(R.string.clear_media_db)
.setMessage(R.string.validation)
.setIcon(R.drawable.ic_warning)
.setPositiveButton(R.string.yes) { _, _ -> launch(Dispatchers.IO) { Medialibrary.getInstance().clearDatabase(true)
}}
.setNegativeButton(R.string.cancel, null)
.show()
return true
}
"quit_app" -> {
android.os.Process.killProcess(android.os.Process.myPid())
return true
}
"dump_media_db" -> {
if (Medialibrary.getInstance().isWorking)
activity?.let { Toast.makeText(it, R.string.settings_ml_block_scan, Toast.LENGTH_LONG).show() }
else {
val dst = File(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY + Medialibrary.VLC_MEDIA_DB_NAME)
launch {
if ((activity as FragmentActivity).getWritePermission(Uri.fromFile(dst))) {
val copied = withContext(Dispatchers.IO) {
val db = File(activity.getDir("db", Context.MODE_PRIVATE).toString() + Medialibrary.VLC_MEDIA_DB_NAME)
FileUtils.copyFile(db, dst)
}
Toast.makeText(activity, getString(if (copied) R.string.dump_db_succes else R.string.dump_db_failure), Toast.LENGTH_LONG).show()
}
}
}
return true
}
}
return super.onPreferenceTreeClick(preference)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
when (key) {
"network_caching" -> {
val editor = sharedPreferences.edit()
try {
editor.putInt("network_caching_value", Integer.parseInt(sharedPreferences.getString(key, "0")!!))
} catch (e: NumberFormatException) {
editor.putInt("network_caching_value", 0)
val networkCachingPref = findPreference<EditTextPreference>(key)
networkCachingPref?.text = ""
activity?.let { Toast.makeText(it, R.string.network_caching_popup, Toast.LENGTH_SHORT).show() }
}
editor.apply()
VLCInstance.restart()
(activity as? PreferencesActivity)?.restartMediaPlayer()
}
"custom_libvlc_options" -> {
try {
VLCInstance.restart()
} catch (e: IllegalStateException){
activity?.let { Toast.makeText(it, R.string.custom_libvlc_options_invalid, Toast.LENGTH_LONG).show() }
sharedPreferences.putSingle("custom_libvlc_options", "")
} finally {
(activity as? PreferencesActivity)?.restartMediaPlayer()
}
}
// No break because need VLCInstance.restart();
"opengl", "chroma_format", "deblocking", "enable_frame_skip", "enable_time_stretching_audio", "enable_verbose_mode" -> {
VLCInstance.restart()
(activity as? PreferencesActivity)?.restartMediaPlayer()
}
}
}
}
| gpl-2.0 | cba4faa98e675e38854c406595741a68 | 42.238372 | 156 | 0.584779 | 5.097327 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/util/Browserutils.kt | 1 | 2013 | /*****************************************************************************
* browserutils.kt
*****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.util
import android.net.Uri
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.vlc.mediadb.models.BrowserFav
import java.io.File
fun isSchemeSupported(scheme: String?) = when(scheme) {
"file", "smb", "ssh", "nfs", "ftp", "ftps", "content" -> true
else -> false
}
fun String?.isSchemeNetwork() = when(this) {
"smb", "ssh", "nfs", "ftp", "ftps" -> true
else -> false
}
fun convertFavorites(browserFavs: List<BrowserFav>?) = browserFavs?.filter {
it.uri.scheme != "file" || File(it.uri.path).exists()
}?.map { (uri, _, title, iconUrl) ->
MLServiceLocator.getAbstractMediaWrapper(uri).apply {
setDisplayTitle(Uri.decode(title))
type = MediaWrapper.TYPE_DIR
iconUrl?.let { artworkURL = Uri.decode(it) }
setStateFlags(MediaLibraryItem.FLAG_FAVORITE)
}
} ?: emptyList()
| gpl-2.0 | 92ddf957d4e491110767e9b423e645f5 | 40.916667 | 80 | 0.63668 | 4.393013 | false | false | false | false |
material-components/material-components-android-compose-theme-adapter | material3Lib/src/main/java/com/google/android/material/composethemeadapter3/Mdc3Theme.kt | 1 | 23377 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
@file:JvmName("Mdc3Theme")
package com.google.android.material.composethemeadapter3
import android.content.Context
import android.content.res.Resources
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Typography
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.core.content.res.getResourceIdOrThrow
import androidx.core.content.res.use
import com.google.android.material.composethemeadapter.core.FontFamilyWithWeight
import com.google.android.material.composethemeadapter.core.parseColor
import com.google.android.material.composethemeadapter.core.parseFontFamily
import com.google.android.material.composethemeadapter.core.parseShapeAppearance
import com.google.android.material.composethemeadapter.core.parseTextAppearance
import java.lang.reflect.Method
/**
* A [MaterialTheme] which reads the corresponding values from a Material Components for Android
* theme in the given [context].
*
* By default the text colors from any associated `TextAppearance`s from the theme are *not* read.
* This is because setting a fixed color in the resulting [TextStyle] breaks the usage of
* [androidx.compose.material.ContentAlpha] through [androidx.compose.material.LocalContentAlpha].
* You can customize this through the [setTextColors] parameter.
*
* @param context The context to read the theme from.
* @param readColorScheme whether the read the MDC color palette from the [context]'s theme.
* If `false`, the current value of [MaterialTheme.colorScheme] is preserved.
* @param readTypography whether the read the MDC text appearances from [context]'s theme.
* If `false`, the current value of [MaterialTheme.typography] is preserved.
* @param readShapes whether the read the MDC shape appearances from the [context]'s theme.
* If `false`, the current value of [MaterialTheme.shapes] is preserved.
* @param setTextColors whether to read the colors from the `TextAppearance`s associated from the
* theme. Defaults to `false`.
* @param setDefaultFontFamily whether to read and prioritize the `fontFamily` attributes from
* [context]'s theme, over any specified in the MDC text appearances. Defaults to `false`.
*/
@Composable
fun Mdc3Theme(
context: Context = LocalContext.current,
readColorScheme: Boolean = true,
readTypography: Boolean = true,
readShapes: Boolean = true,
setTextColors: Boolean = false,
setDefaultFontFamily: Boolean = false,
content: @Composable () -> Unit
) {
// We try and use the theme key value if available, which should be a perfect key for caching
// and avoid the expensive theme lookups in re-compositions.
//
// If the key is not available, we use the Theme itself as a rough approximation. Using the
// Theme instance as the key is not perfect, but it should work for 90% of cases.
// It falls down when the theme is manually mutated after a composition has happened
// (via `applyStyle()`, `rebase()`, `setTo()`), but the majority of apps do not use those.
val key = context.theme.key ?: context.theme
val layoutDirection = LocalLayoutDirection.current
val themeParams = remember(key) {
createMdc3Theme(
context = context,
layoutDirection = layoutDirection,
readColorScheme = readColorScheme,
readTypography = readTypography,
readShapes = readShapes,
setTextColors = setTextColors,
setDefaultFontFamily = setDefaultFontFamily
)
}
MaterialTheme(
colorScheme = themeParams.colorScheme ?: MaterialTheme.colorScheme,
typography = themeParams.typography ?: MaterialTheme.typography,
shapes = themeParams.shapes ?: MaterialTheme.shapes
) {
// We update the LocalContentColor to match our onBackground. This allows the default
// content color to be more appropriate to the theme background
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colorScheme.onBackground,
content = content
)
}
}
/**
* This class contains the individual components of a [MaterialTheme]: [ColorScheme] and
* [Typography].
*/
data class Theme3Parameters(
val colorScheme: ColorScheme?,
val typography: Typography?,
val shapes: Shapes?
)
/**
* This function creates the components of a [androidx.compose.material.MaterialTheme], reading the
* values from an Material Components for Android theme.
*
* By default the text colors from any associated `TextAppearance`s from the theme are *not* read.
* This is because setting a fixed color in the resulting [TextStyle] breaks the usage of
* [androidx.compose.material.ContentAlpha] through [androidx.compose.material.LocalContentAlpha].
* You can customize this through the [setTextColors] parameter.
*
* For [Shapes], the [layoutDirection] is taken into account when reading corner sizes of
* `ShapeAppearance`s from the theme. For example, [Shapes.medium.topStart] will be read from
* `cornerSizeTopLeft` for [LayoutDirection.Ltr] and `cornerSizeTopRight` for [LayoutDirection.Rtl].
*
* The individual components of the returned [Theme3Parameters] may be `null`, depending on the
* matching 'read' parameter. For example, if you set [readColorScheme] to `false`,
* [Theme3Parameters.colors] will be null.
*
* @param context The context to read the theme from.
* @param layoutDirection The layout direction to be used when reading shapes.
* @param density The current density.
* @param readColorScheme whether the read the MDC color palette from the [context]'s theme.
* @param readTypography whether the read the MDC text appearances from [context]'s theme.
* @param readShapes whether the read the MDC shape appearances from the [context]'s theme.
* @param setTextColors whether to read the colors from the `TextAppearance`s associated from the
* theme. Defaults to `false`.
* @param setDefaultFontFamily whether to read and prioritize the `fontFamily` attributes from
* [context]'s theme, over any specified in the MDC text appearances. Defaults to `false`.
* @return [Theme3Parameters] instance containing the resulting [ColorScheme] and [Typography].
*/
fun createMdc3Theme(
context: Context,
layoutDirection: LayoutDirection,
density: Density = Density(context),
readColorScheme: Boolean = true,
readTypography: Boolean = true,
readShapes: Boolean = true,
setTextColors: Boolean = false,
setDefaultFontFamily: Boolean = false
): Theme3Parameters {
return context.obtainStyledAttributes(R.styleable.ComposeThemeAdapterMaterial3Theme).use { ta ->
require(ta.hasValue(R.styleable.ComposeThemeAdapterMaterial3Theme_isMaterial3Theme)) {
"createMdc3Theme requires the host context's theme to extend Theme.Material3"
}
val colorScheme: ColorScheme? = if (readColorScheme) {
/* First we'll read the Material 3 color palette */
val primary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorPrimary)
val onPrimary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnPrimary)
val primaryInverse = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorPrimaryInverse)
val primaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorPrimaryContainer)
val onPrimaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnPrimaryContainer)
val secondary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorSecondary)
val onSecondary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnSecondary)
val secondaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorSecondaryContainer)
val onSecondaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnSecondaryContainer)
val tertiary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorTertiary)
val onTertiary = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnTertiary)
val tertiaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorTertiaryContainer)
val onTertiaryContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnTertiaryContainer)
val background = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_android_colorBackground)
val onBackground = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnBackground)
val surface = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorSurface)
val onSurface = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnSurface)
val surfaceVariant = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorSurfaceVariant)
val onSurfaceVariant = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnSurfaceVariant)
val elevationOverlay = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_elevationOverlayColor)
val surfaceInverse = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorSurfaceInverse)
val onSurfaceInverse = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnSurfaceInverse)
val outline = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOutline)
val error = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorError)
val onError = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnError)
val errorContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorErrorContainer)
val onErrorContainer = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_colorOnErrorContainer)
val scrimBackground = ta.parseColor(R.styleable.ComposeThemeAdapterMaterial3Theme_scrimBackground)
val isLightTheme = ta.getBoolean(R.styleable.ComposeThemeAdapterMaterial3Theme_isLightTheme, true)
if (isLightTheme) {
lightColorScheme(
primary = primary,
onPrimary = onPrimary,
inversePrimary = primaryInverse,
primaryContainer = primaryContainer,
onPrimaryContainer = onPrimaryContainer,
secondary = secondary,
onSecondary = onSecondary,
secondaryContainer = secondaryContainer,
onSecondaryContainer = onSecondaryContainer,
tertiary = tertiary,
onTertiary = onTertiary,
tertiaryContainer = tertiaryContainer,
onTertiaryContainer = onTertiaryContainer,
background = background,
onBackground = onBackground,
surface = surface,
onSurface = onSurface,
surfaceVariant = surfaceVariant,
onSurfaceVariant = onSurfaceVariant,
surfaceTint = elevationOverlay,
inverseSurface = surfaceInverse,
inverseOnSurface = onSurfaceInverse,
outline = outline,
// TODO: MDC-Android doesn't include outlineVariant yet, add when available
error = error,
onError = onError,
errorContainer = errorContainer,
onErrorContainer = onErrorContainer,
scrim = scrimBackground
)
} else {
darkColorScheme(
primary = primary,
onPrimary = onPrimary,
inversePrimary = primaryInverse,
primaryContainer = primaryContainer,
onPrimaryContainer = onPrimaryContainer,
secondary = secondary,
onSecondary = onSecondary,
secondaryContainer = secondaryContainer,
onSecondaryContainer = onSecondaryContainer,
tertiary = tertiary,
onTertiary = onTertiary,
tertiaryContainer = tertiaryContainer,
onTertiaryContainer = onTertiaryContainer,
background = background,
onBackground = onBackground,
surface = surface,
onSurface = onSurface,
surfaceVariant = surfaceVariant,
onSurfaceVariant = onSurfaceVariant,
surfaceTint = elevationOverlay,
inverseSurface = surfaceInverse,
inverseOnSurface = onSurfaceInverse,
outline = outline,
// TODO: MDC-Android doesn't include outlineVariant yet, add when available
error = error,
onError = onError,
errorContainer = errorContainer,
onErrorContainer = onErrorContainer,
scrim = scrimBackground
)
}
} else null
/**
* Next we'll create a typography instance, using the Material Theme text appearances
* for TextStyles.
*
* We create a normal 'empty' instance first to start from the defaults, then merge in our
* created text styles from the Android theme.
*/
val typography = if (readTypography) {
val defaultFontFamily = if (setDefaultFontFamily) {
val defaultFontFamilyWithWeight: FontFamilyWithWeight? = ta.parseFontFamily(
R.styleable.ComposeThemeAdapterMaterial3Theme_fontFamily
) ?: ta.parseFontFamily(R.styleable.ComposeThemeAdapterMaterial3Theme_android_fontFamily)
defaultFontFamilyWithWeight?.fontFamily
} else {
null
}
Typography(
displayLarge = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceDisplayLarge),
density,
setTextColors,
defaultFontFamily
),
displayMedium = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceDisplayMedium),
density,
setTextColors,
defaultFontFamily
),
displaySmall = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceDisplaySmall),
density,
setTextColors,
defaultFontFamily
),
headlineLarge = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceHeadlineLarge),
density,
setTextColors,
defaultFontFamily
),
headlineMedium = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceHeadlineMedium),
density,
setTextColors,
defaultFontFamily
),
headlineSmall = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceHeadlineSmall),
density,
setTextColors,
defaultFontFamily
),
titleLarge = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceTitleLarge),
density,
setTextColors,
defaultFontFamily
),
titleMedium = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceTitleMedium),
density,
setTextColors,
defaultFontFamily
),
titleSmall = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceTitleSmall),
density,
setTextColors,
defaultFontFamily
),
bodyLarge = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceBodyLarge),
density,
setTextColors,
defaultFontFamily
),
bodyMedium = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceBodyMedium),
density,
setTextColors,
defaultFontFamily
),
bodySmall = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceBodySmall),
density,
setTextColors,
defaultFontFamily
),
labelLarge = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceLabelLarge),
density,
setTextColors,
defaultFontFamily
),
labelMedium = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceLabelMedium),
density,
setTextColors,
defaultFontFamily
),
labelSmall = parseTextAppearance(
context,
ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_textAppearanceLabelSmall),
density,
setTextColors,
defaultFontFamily
),
)
} else null
/**
* Now read the shape appearances, taking into account the layout direction.
*/
val shapes = if (readShapes) {
Shapes(
extraSmall = parseShapeAppearance(
context = context,
id = ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_shapeAppearanceCornerExtraSmall),
layoutDirection = layoutDirection,
fallbackShape = emptyShapes.extraSmall
),
small = parseShapeAppearance(
context = context,
id = ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_shapeAppearanceCornerSmall),
layoutDirection = layoutDirection,
fallbackShape = emptyShapes.small
),
medium = parseShapeAppearance(
context = context,
id = ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_shapeAppearanceCornerMedium),
layoutDirection = layoutDirection,
fallbackShape = emptyShapes.medium
),
large = parseShapeAppearance(
context = context,
id = ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_shapeAppearanceCornerLarge),
layoutDirection = layoutDirection,
fallbackShape = emptyShapes.large
),
extraLarge = parseShapeAppearance(
context = context,
id = ta.getResourceIdOrThrow(R.styleable.ComposeThemeAdapterMaterial3Theme_shapeAppearanceCornerExtraLarge),
layoutDirection = layoutDirection,
fallbackShape = emptyShapes.extraLarge
)
)
} else null
Theme3Parameters(colorScheme, typography, shapes)
}
}
private val emptyShapes = Shapes()
/**
* This is gross, but we need a way to check for theme equality. Theme does not implement
* `equals()` or `hashCode()`, but it does have a hidden method called `getKey()`.
*
* The cost of this reflective invoke is a lot cheaper than the full theme read which can
* happen on each re-composition.
*/
private inline val Resources.Theme.key: Any?
get() {
if (!sThemeGetKeyMethodFetched) {
try {
@Suppress("PrivateApi")
sThemeGetKeyMethod = Resources.Theme::class.java.getDeclaredMethod("getKey")
.apply { isAccessible = true }
} catch (e: ReflectiveOperationException) {
// Failed to retrieve Theme.getKey method
}
sThemeGetKeyMethodFetched = true
}
if (sThemeGetKeyMethod != null) {
return try {
sThemeGetKeyMethod?.invoke(this)
} catch (e: ReflectiveOperationException) {
// Failed to invoke Theme.getKey()
}
}
return null
}
private var sThemeGetKeyMethodFetched = false
private var sThemeGetKeyMethod: Method? = null
| apache-2.0 | c3a9dee24274abe149deecff7fc082f1 | 48.950855 | 128 | 0.646405 | 5.63437 | false | false | false | false |
didi/DoraemonKit | Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/mock/http/HttpMockServer.kt | 1 | 6343 | package com.didichuxing.doraemonkit.kit.test.mock.http
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.didichuxing.doraemonkit.kit.core.DoKitManager
import com.didichuxing.doraemonkit.kit.test.mock.*
import com.didichuxing.doraemonkit.kit.test.mock.data.AppInfo
import com.didichuxing.doraemonkit.kit.test.mock.data.CaseInfo
import com.didichuxing.doraemonkit.kit.test.mock.data.HttpUploadInfo
import com.didichuxing.doraemonkit.kit.test.mock.data.McResInfo
import com.didichuxing.doraemonkit.util.GsonUtils
import com.didichuxing.doraemonkit.volley.VolleyManager
import org.json.JSONObject
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2021/6/21-17:16
* 描 述:
* 修订历史:
* ================================================
*/
object HttpMockServer {
const val RESPONSE_OK = 200
const val host = "https://www.dokit.cn"
const val host_test = "https://pre.dokit.cn"
var mExcludeKey: List<String> = mutableListOf()
suspend inline fun <reified T> getMcConfig(): McResInfo<T> = suspendCoroutine {
try {
val jsonObject = JSONObject()
jsonObject.put("pId", DoKitManager.PRODUCT_ID)
val request = JsonObjectRequest(
"$host/app/multiControl/getConfig",
jsonObject,
{ response ->
it.resume(convert2McResInfoWithObj(response))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
suspend inline fun <reified T> mockStart(): McResInfo<T> = suspendCoroutine {
try {
val request = JsonObjectRequest(
"$host/app/multiControl/startRecord",
JSONObject(GsonUtils.toJson(AppInfo())),
{ response ->
it.resume(convert2McResInfoWithObj(response))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
suspend inline fun <reified T> uploadHttpInfo(httpInfo: HttpUploadInfo): McResInfo<T> =
suspendCoroutine {
try {
val request = JsonObjectRequest(
"$host/app/multiControl/uploadApiInfo",
JSONObject(GsonUtils.toJson(httpInfo)),
{ response ->
it.resume(convert2McResInfoWithObj(response))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
suspend inline fun <reified T> mockStop(caseInfo: CaseInfo): McResInfo<T> =
suspendCoroutine {
try {
val request = JsonObjectRequest(
"$host/app/multiControl/endRecord",
JSONObject(GsonUtils.toJson(caseInfo)),
{ response ->
it.resume(convert2McResInfoWithObj(response))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
suspend inline fun <reified T> caseList(): McResInfo<List<T>> = suspendCoroutine {
try {
val request = StringRequest(
Request.Method.GET,
"$host/app/multiControl/caseList?pId=${DoKitManager.PRODUCT_ID}",
{ response ->
it.resume(convert2McResInfoWithList(JSONObject(response)))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
suspend inline fun <reified T> httpMatch(requestKey: String): McResInfo<T> = suspendCoroutine {
try {
val request = StringRequest(
"$host/app/multiControl/getCaseApiInfo?key=${requestKey}&pId=${DoKitManager.PRODUCT_ID}&caseId=${MockManager.MC_CASE_ID}",
{ response ->
it.resume(convert2McResInfoWithObj(JSONObject(response)))
}, { error ->
it.resumeWithException(error)
})
VolleyManager.add(request)
} catch (e: Exception) {
it.resumeWithException(e)
}
}
inline fun <reified T> convert2McResInfoWithObj(json: JSONObject): McResInfo<T> {
return try {
val mcInfo = McResInfo<T>(
json.optInt("code", 0),
json.optString("msg", "has no msg value")
)
val dataJson = json.optJSONObject("data")
val type = GsonUtils.getType(T::class.java)
if (dataJson != null) {
mcInfo.data = GsonUtils.fromJson(dataJson.toString(), type)
}
mcInfo
} catch (e: Exception) {
McResInfo(
0,
"Gson format error",
null
)
}
}
inline fun <reified T> convert2McResInfoWithList(json: JSONObject): McResInfo<List<T>> {
return try {
val mcInfo = McResInfo<List<T>>(
json.optInt("code", 0),
json.optString("msg", "has no msg value")
)
val dataJson = json.optJSONArray("data")
val type = GsonUtils.getListType(T::class.java)
mcInfo.data = GsonUtils.fromJson(dataJson.toString(), type)
mcInfo
} catch (e: Exception) {
McResInfo(
0,
"Gson format error",
null
)
}
}
}
| apache-2.0 | c88e2580411367fc8c2ae5d6c2ef3a0a | 32.31746 | 138 | 0.537875 | 4.654102 | false | false | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/MainStackView.kt | 1 | 5085 | package ch.bailu.aat_gtk.view
import ch.bailu.aat_gtk.app.GtkAppContext
import ch.bailu.aat_gtk.view.search.PoiStackView
import ch.bailu.aat_gtk.view.solid.PreferencesStackView
import ch.bailu.aat_gtk.view.stack.LazyStackView
import ch.bailu.aat_gtk.view.toplevel.CockpitView
import ch.bailu.aat_gtk.view.toplevel.DetailView
import ch.bailu.aat_gtk.view.toplevel.MapMainView
import ch.bailu.aat_gtk.view.toplevel.list.FileList
import ch.bailu.aat_lib.coordinates.BoundingBoxE6
import ch.bailu.aat_lib.description.*
import ch.bailu.aat_lib.dispatcher.CustomFileSource
import ch.bailu.aat_lib.dispatcher.Dispatcher
import ch.bailu.aat_lib.gpx.GpxInformation
import ch.bailu.aat_lib.gpx.InfoID
import ch.bailu.aat_lib.preferences.StorageInterface
import ch.bailu.gtk.GTK
import ch.bailu.gtk.gtk.*
import org.mapsforge.core.model.BoundingBox
class MainStackView (
app: Application,
dispatcher: Dispatcher,
window: Window,
storage: StorageInterface,
private val revealer: ToggleButton
) :
UiController {
companion object {
const val KEY = "main-stack"
const val INDEX_MAP = 0
const val INDEX_FILES = 1
const val INDEX_DETAIL = 2
const val INDEX_COCKPIT = 3
}
private val customFileSource = CustomFileSource(GtkAppContext)
private var preferencesStackView: PreferencesStackView? = null
private var mapView: MapMainView? = null
private val stack = LazyStackView(Stack().apply {
transitionType = StackTransitionType.SLIDE_LEFT
}, KEY, storage)
val widget
get() = stack.widget
private var revealerRestore = GTK.FALSE
private val preferences: LazyStackView.LazyPage
private val poi: LazyStackView.LazyPage
private var backTo = INDEX_MAP
init {
dispatcher.addSource(customFileSource)
stack.add("Map") {
val mapView = MapMainView(app, dispatcher, this, GtkAppContext, window)
this.mapView = mapView
mapView.onAttached()
dispatcher.requestUpdate()
mapView.overlay
}
stack.add("Files") {
FileList(app, GtkAppContext.storage, GtkAppContext, this).vbox
}
stack.add("Detail") {
val result = DetailView(dispatcher, GtkAppContext.storage).scrolled
dispatcher.requestUpdate()
result
}
stack.add("Cockpit") {
val result = CockpitView().apply {
add(dispatcher, CurrentSpeedDescription(GtkAppContext.storage), InfoID.LOCATION)
add(dispatcher, AltitudeDescription(GtkAppContext.storage), InfoID.LOCATION)
add(dispatcher, PredictiveTimeDescription(), InfoID.TRACKER_TIMER)
add(dispatcher, DistanceDescription(GtkAppContext.storage), InfoID.TRACKER)
add(dispatcher, AverageSpeedDescriptionAP(GtkAppContext.storage), InfoID.TRACKER)
}.flow
dispatcher.requestUpdate()
result
}
preferences = stack.add("Preferences") {
val stackView = PreferencesStackView(this, GtkAppContext.storage, app, window)
preferencesStackView = stackView
stackView.layout
}
poi = stack.add("POI") {
val stackView = PoiStackView(this, app, window)
stackView.layout
}
stack.restore()
}
override fun showCockpit() {
stack.show(INDEX_COCKPIT)
backTo = INDEX_COCKPIT
}
override fun showMap() {
stack.show(INDEX_MAP)
backTo = INDEX_MAP
}
fun showPreferences() {
revealerRestore = revealer.active
revealer.active = GTK.FALSE
preferences.show()
}
override fun showPoi() {
revealerRestore = revealer.active
revealer.active = GTK.FALSE
poi.show()
}
fun showFiles() {
stack.show(INDEX_FILES)
backTo = INDEX_FILES
}
override fun showInMap(info: GpxInformation) {
if (info.boundingBox.hasBounding()) {
showMap()
mapView?.map?.frameBounding(info.boundingBox)
}
}
override fun showDetail() {
stack.show(INDEX_DETAIL)
backTo = INDEX_DETAIL
}
override fun showInList() {
showFiles()
}
override fun showPreferencesMap() {
showPreferences()
preferencesStackView?.showMap()
}
override fun back() {
revealer.active = revealerRestore
stack.show(backTo)
}
override fun showContextBar() {
revealer.active = GTK.TRUE
}
override fun getMapBounding(): BoundingBoxE6 {
val bounding = mapView?.map?.boundingBox
if (bounding is BoundingBox) {
return BoundingBoxE6(bounding)
}
return BoundingBoxE6.NULL_BOX
}
override fun load(info: GpxInformation) {
customFileSource.setFileID(info.file.toString())
showContextBar()
}
fun onDestroy() {
// IMPORTANT this saves map position
mapView?.onDetached()
}
}
| gpl-3.0 | 83fceff690995b77c64665d5c01addc7 | 26.786885 | 97 | 0.643854 | 4.291139 | false | false | false | false |
dykstrom/jcc | src/test/kotlin/se/dykstrom/jcc/basic/compiler/BasicTypeManagerTests.kt | 1 | 17343 | /*
* Copyright (C) 2016 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.Assert.*
import org.junit.Before
import org.junit.Test
import se.dykstrom.jcc.basic.functions.BasicBuiltInFunctions.FUN_ABS
import se.dykstrom.jcc.basic.functions.BasicBuiltInFunctions.FUN_FMOD
import se.dykstrom.jcc.common.ast.*
import se.dykstrom.jcc.common.error.SemanticsException
import se.dykstrom.jcc.common.functions.ExternalFunction
import se.dykstrom.jcc.common.functions.LibraryFunction
import se.dykstrom.jcc.common.symbols.SymbolTable
import se.dykstrom.jcc.common.types.*
import java.util.Collections.emptyList
class BasicTypeManagerTests {
private val symbols = SymbolTable()
private val testee = BasicTypeManager()
@Before
fun setUp() {
// Define some functions for testing
symbols.addFunction(FUN_ABS)
symbols.addFunction(FUN_FMOD)
symbols.addFunction(FUN_COMMAND)
symbols.addFunction(FUN_SIN)
symbols.addFunction(FUN_THREE)
// Function 'sum' is overloaded with different number of (and types of) arguments
symbols.addFunction(FUN_SUM_F)
symbols.addFunction(FUN_SUM_1)
symbols.addFunction(FUN_SUM_2)
symbols.addFunction(FUN_SUM_3)
// Function 'foo' is overloaded with different types of arguments
symbols.addFunction(FUN_FOO_DI)
symbols.addFunction(FUN_FOO_ID)
}
@Test
fun shouldBeAssignableFrom() {
// You can assign any basic type to itself
assertTrue(testee.isAssignableFrom(F64.INSTANCE, F64.INSTANCE))
assertTrue(testee.isAssignableFrom(I64.INSTANCE, I64.INSTANCE))
assertTrue(testee.isAssignableFrom(Str.INSTANCE, Str.INSTANCE))
assertTrue(testee.isAssignableFrom(Bool.INSTANCE, Bool.INSTANCE))
// You can assign numeric values even if they are not exactly the same type
assertTrue(testee.isAssignableFrom(F64.INSTANCE, I64.INSTANCE))
assertTrue(testee.isAssignableFrom(I64.INSTANCE, F64.INSTANCE))
}
@Test
fun shouldNotBeAssignableFrom() {
assertFalse(testee.isAssignableFrom(Bool.INSTANCE, ID_FUN_BOOLEAN.type()))
assertFalse(testee.isAssignableFrom(Bool.INSTANCE, F64.INSTANCE))
assertFalse(testee.isAssignableFrom(Bool.INSTANCE, I64.INSTANCE))
assertFalse(testee.isAssignableFrom(Bool.INSTANCE, Str.INSTANCE))
assertFalse(testee.isAssignableFrom(F64.INSTANCE, Bool.INSTANCE))
assertFalse(testee.isAssignableFrom(F64.INSTANCE, ID_FUN_INTEGER.type()))
assertFalse(testee.isAssignableFrom(F64.INSTANCE, Str.INSTANCE))
assertFalse(testee.isAssignableFrom(I64.INSTANCE, Bool.INSTANCE))
assertFalse(testee.isAssignableFrom(I64.INSTANCE, ID_FUN_INTEGER.type()))
assertFalse(testee.isAssignableFrom(I64.INSTANCE, Str.INSTANCE))
assertFalse(testee.isAssignableFrom(Str.INSTANCE, Bool.INSTANCE))
assertFalse(testee.isAssignableFrom(Str.INSTANCE, F64.INSTANCE))
assertFalse(testee.isAssignableFrom(Str.INSTANCE, ID_FUN_STRING.type()))
assertFalse(testee.isAssignableFrom(Str.INSTANCE, I64.INSTANCE))
}
// Type names:
@Test
fun shouldGetTypeNameOfScalarTypes() {
assertEquals("boolean", testee.getTypeName(Bool.INSTANCE))
assertEquals("double", testee.getTypeName(F64.INSTANCE))
assertEquals("integer", testee.getTypeName(I64.INSTANCE))
assertEquals("string", testee.getTypeName(Str.INSTANCE))
}
@Test
fun shouldGetTypeNameOfFunctionTypes() {
assertEquals("function()->boolean", testee.getTypeName(ID_FUN_BOOLEAN.type()))
assertEquals("function(integer)->double", testee.getTypeName(ID_FUN_FLOAT.type()))
assertEquals("function(string)->integer", testee.getTypeName(ID_FUN_INTEGER.type()))
assertEquals("function(integer, boolean)->string", testee.getTypeName(ID_FUN_STRING.type()))
}
@Test
fun shouldGetTypeNameOfArrayTypes() {
assertEquals("boolean[]", testee.getTypeName(Arr.from(1, Bool.INSTANCE)))
assertEquals("double[]", testee.getTypeName(Arr.from(1, F64.INSTANCE)))
assertEquals("integer[]", testee.getTypeName(Arr.from(1, I64.INSTANCE)))
assertEquals("string[]", testee.getTypeName(Arr.from(1, Str.INSTANCE)))
assertEquals("string[][]", testee.getTypeName(Arr.from(2, Str.INSTANCE)))
assertEquals("integer[][][]", testee.getTypeName(Arr.from(3, I64.INSTANCE)))
}
// Literals:
@Test
fun shouldGetStringFromStringLiteral() {
assertEquals(Str.INSTANCE, testee.getType(STRING_LITERAL))
}
@Test
fun shouldGetFloatFromFloatLiteral() {
assertEquals(F64.INSTANCE, testee.getType(FLOAT_LITERAL))
}
@Test
fun shouldGetIntegerFromIntegerLiteral() {
assertEquals(I64.INSTANCE, testee.getType(INTEGER_LITERAL))
}
@Test
fun shouldGetBooleanFromBooleanLiteral() {
assertEquals(Bool.INSTANCE, testee.getType(BOOLEAN_LITERAL))
}
// Identifiers:
@Test
fun shouldGetStringFromStringIdentExpr() {
assertEquals(Str.INSTANCE, testee.getType(STRING_IDE))
}
@Test
fun shouldGetFloatFromFloatIdentExpr() {
assertEquals(F64.INSTANCE, testee.getType(FLOAT_IDE))
}
@Test
fun shouldGetIntegerFromIntegerIdentExpr() {
assertEquals(I64.INSTANCE, testee.getType(INTEGER_IDE))
}
@Test
fun shouldGetBooleanFromBooleanIdentExpr() {
assertEquals(Bool.INSTANCE, testee.getType(BOOLEAN_IDE))
}
// Expressions:
@Test
fun testAddStrings() {
assertEquals(Str.INSTANCE, testee.getType(ADD_STRINGS))
}
@Test
fun testAddFloats() {
assertEquals(F64.INSTANCE, testee.getType(ADD_FLOATS))
}
@Test
fun testAddIntegers() {
assertEquals(I64.INSTANCE, testee.getType(ADD_INTEGERS))
}
@Test
fun testAddIntegersComplex() {
assertEquals(I64.INSTANCE, testee.getType(ADD_INTEGERS_COMPLEX))
}
@Test
fun testSubIntegers() {
assertEquals(I64.INSTANCE, testee.getType(SUB_INTEGERS))
}
@Test
fun testSubIntegersComplex() {
assertEquals(I64.INSTANCE, testee.getType(SUB_INTEGERS_COMPLEX))
}
@Test
fun shouldGetFloatFromDivision() {
assertEquals(F64.INSTANCE, testee.getType(DIV_INTEGERS))
}
@Test
fun shouldGetIntegerFromIntegerDivision() {
assertEquals(I64.INSTANCE, testee.getType(IDIV_INTEGERS))
}
@Test
fun shouldGetIntegerFromModulo() {
assertEquals(I64.INSTANCE, testee.getType(MOD_INTEGERS))
}
@Test
fun shouldGetBooleanFromAnd() {
assertEquals(Bool.INSTANCE, testee.getType(AND_BOOLEANS))
}
@Test
fun shouldGetBooleanFromComplexAnd() {
assertEquals(Bool.INSTANCE, testee.getType(AND_BOOLEANS_COMPLEX))
}
@Test
fun shouldGetBooleanFromIntegerRelational() {
assertEquals(Bool.INSTANCE, testee.getType(REL_INTEGERS))
}
@Test
fun shouldGetBooleanFromStringRelational() {
assertEquals(Bool.INSTANCE, testee.getType(REL_STRINGS))
}
@Test
fun shouldGetBooleanFromComplexRelational() {
assertEquals(Bool.INSTANCE, testee.getType(REL_COMPLEX))
}
@Test
fun shouldGetBooleanFromBooleanFunction() {
assertEquals(Bool.INSTANCE, testee.getType(BOOLEAN_FCE))
}
@Test
fun shouldGetFloatFromFloatFunction() {
assertEquals(F64.INSTANCE, testee.getType(FLOAT_FCE))
}
@Test
fun shouldGetIntegerFromIntegerFunction() {
assertEquals(I64.INSTANCE, testee.getType(INTEGER_FCE))
}
@Test
fun shouldGetStringFromStringFunction() {
assertEquals(Str.INSTANCE, testee.getType(STRING_FCE))
}
@Test
fun shouldGetIntegerFromAddIntegerWithFunction() {
assertEquals(I64.INSTANCE, testee.getType(ADD_INTEGERS_FUNCTION))
}
// Type conversion integer -> float
@Test
fun shouldGetFloatFromAddIntegerFloat() {
assertEquals(F64.INSTANCE, testee.getType(ADD_INTEGER_FLOAT))
}
@Test
fun shouldGetFloatFromAddFloatInteger() {
assertEquals(F64.INSTANCE, testee.getType(ADD_FLOAT_INTEGER))
}
// Resolving functions
@Test
fun shouldResolveFunctionWithExactArgs() {
assertEquals(FUN_ABS, testee.resolveFunction(FUN_ABS.name, FUN_ABS.argTypes, symbols))
assertEquals(FUN_FMOD, testee.resolveFunction(FUN_FMOD.name, FUN_FMOD.argTypes, symbols))
assertEquals(FUN_COMMAND, testee.resolveFunction(FUN_COMMAND.name, FUN_COMMAND.argTypes, symbols))
assertEquals(FUN_SUM_F, testee.resolveFunction("sum", FUN_SUM_F.argTypes, symbols))
assertEquals(FUN_SUM_1, testee.resolveFunction("sum", FUN_SUM_1.argTypes, symbols))
assertEquals(FUN_SUM_2, testee.resolveFunction("sum", FUN_SUM_2.argTypes, symbols))
assertEquals(FUN_SUM_3, testee.resolveFunction("sum", FUN_SUM_3.argTypes, symbols))
assertEquals(FUN_FOO_DI, testee.resolveFunction("foo", FUN_FOO_DI.argTypes, symbols))
assertEquals(FUN_FOO_ID, testee.resolveFunction("foo", FUN_FOO_ID.argTypes, symbols))
}
@Test
fun shouldResolveFunctionWithOneCast() {
assertEquals(FUN_SIN, testee.resolveFunction(FUN_SIN.name, listOf(I64.INSTANCE), symbols))
assertEquals(FUN_ABS, testee.resolveFunction(FUN_ABS.name, listOf(F64.INSTANCE), symbols))
assertEquals(FUN_THREE, testee.resolveFunction(FUN_THREE.name, listOf(F64.INSTANCE, F64.INSTANCE, F64.INSTANCE), symbols))
}
@Test
fun shouldResolveFunctionWithTwoCasts() {
assertEquals(FUN_FMOD, testee.resolveFunction(FUN_FMOD.name, listOf(I64.INSTANCE, I64.INSTANCE), symbols))
assertEquals(FUN_THREE, testee.resolveFunction(FUN_THREE.name, listOf(I64.INSTANCE, I64.INSTANCE, I64.INSTANCE), symbols))
assertEquals(FUN_SUM_2, testee.resolveFunction(FUN_SUM_2.name, listOf(F64.INSTANCE, F64.INSTANCE), symbols))
}
// Negative tests:
@Test(expected = SemanticsException::class)
fun shouldNotResolveFloatFloatFunctionWithFloatString() {
testee.resolveFunction(FUN_FMOD.name, listOf(F64.INSTANCE, Str.INSTANCE), symbols)
}
@Test(expected = SemanticsException::class)
fun shouldNotResolveFunctionWithAmbiguousOverload() {
testee.resolveFunction("foo", listOf(I64.INSTANCE, I64.INSTANCE), symbols)
}
@Test(expected = SemanticsException::class)
fun testAddStringFloat() {
testee.getType(ADD_STRING_FLOAT)
}
@Test(expected = SemanticsException::class)
fun testAddStringInteger() {
testee.getType(ADD_STRING_INTEGER)
}
@Test(expected = SemanticsException::class)
fun testAddIntegerString() {
testee.getType(ADD_INTEGER_STRING)
}
@Test(expected = SemanticsException::class)
fun testSubString() {
testee.getType(SUB_STRINGS)
}
@Test(expected = SemanticsException::class)
fun testSubStringInteger() {
testee.getType(SUB_STRING_INTEGER)
}
@Test(expected = SemanticsException::class)
fun testSubBooleanInteger() {
testee.getType(SUB_BOOLEAN_INTEGER)
}
@Test(expected = SemanticsException::class)
fun shouldGetExceptionFromIDivStringInteger() {
testee.getType(IDIV_STRING_INTEGER)
}
@Test(expected = SemanticsException::class)
fun shouldGetExceptionFromModStringInteger() {
testee.getType(MOD_STRING_INTEGER)
}
companion object {
private val ID_BOOLEAN = Identifier("boolean", Bool.INSTANCE)
private val ID_INTEGER = Identifier("integer", I64.INSTANCE)
private val ID_FLOAT = Identifier("float", F64.INSTANCE)
private val ID_STRING = Identifier("string", Str.INSTANCE)
private val FUN_COMMAND = LibraryFunction("command$", emptyList(), Str.INSTANCE, "", ExternalFunction(""))
private val FUN_SIN = LibraryFunction("sin", listOf(F64.INSTANCE), F64.INSTANCE, "", ExternalFunction(""))
private val FUN_SUM_F = LibraryFunction("sum", listOf(F64.INSTANCE), F64.INSTANCE, "", ExternalFunction(""))
private val FUN_SUM_1 = LibraryFunction("sum", listOf(I64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val FUN_SUM_2 = LibraryFunction("sum", listOf(I64.INSTANCE, I64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val FUN_SUM_3 = LibraryFunction("sum", listOf(I64.INSTANCE, I64.INSTANCE, I64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val FUN_FOO_DI = LibraryFunction("foo", listOf(F64.INSTANCE, I64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val FUN_FOO_ID = LibraryFunction("foo", listOf(I64.INSTANCE, F64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val FUN_THREE = LibraryFunction("three", listOf(F64.INSTANCE, I64.INSTANCE, F64.INSTANCE), I64.INSTANCE, "", ExternalFunction(""))
private val ID_FUN_BOOLEAN = Identifier("booleanf", Fun.from(emptyList(), Bool.INSTANCE))
private val ID_FUN_FLOAT = Identifier("floatf", Fun.from(listOf(I64.INSTANCE), F64.INSTANCE))
private val ID_FUN_INTEGER = Identifier("integerf", Fun.from(listOf(Str.INSTANCE), I64.INSTANCE))
private val ID_FUN_STRING = Identifier("stringf", Fun.from(listOf(I64.INSTANCE, Bool.INSTANCE), Str.INSTANCE))
private val BOOLEAN_LITERAL = BooleanLiteral(0, 0, "true")
private val FLOAT_LITERAL = FloatLiteral(0, 0, "5.7")
private val INTEGER_LITERAL = IntegerLiteral(0, 0, "5")
private val STRING_LITERAL = StringLiteral(0, 0, "value")
private val BOOLEAN_IDE = IdentifierDerefExpression(0, 0, ID_BOOLEAN)
private val FLOAT_IDE = IdentifierDerefExpression(0, 0, ID_FLOAT)
private val INTEGER_IDE = IdentifierDerefExpression(0, 0, ID_INTEGER)
private val STRING_IDE = IdentifierDerefExpression(0, 0, ID_STRING)
private val BOOLEAN_FCE = FunctionCallExpression(0, 0, ID_FUN_BOOLEAN, emptyList())
private val FLOAT_FCE = FunctionCallExpression(0, 0, ID_FUN_FLOAT, emptyList())
private val INTEGER_FCE = FunctionCallExpression(0, 0, ID_FUN_INTEGER, emptyList())
private val STRING_FCE = FunctionCallExpression(0, 0, ID_FUN_STRING, emptyList())
private val ADD_FLOATS = AddExpression(0, 0, FLOAT_LITERAL, FLOAT_IDE)
private val ADD_INTEGERS = AddExpression(0, 0, INTEGER_LITERAL, INTEGER_IDE)
private val ADD_INTEGERS_COMPLEX = AddExpression(0, 0, INTEGER_LITERAL, AddExpression(0, 0, INTEGER_IDE, INTEGER_IDE))
private val ADD_INTEGERS_FUNCTION = AddExpression(0, 0, INTEGER_FCE, AddExpression(0, 0, INTEGER_IDE, INTEGER_FCE))
private val ADD_STRINGS = AddExpression(0, 0, STRING_LITERAL, STRING_IDE)
private val ADD_FLOAT_INTEGER = AddExpression(0, 0, FLOAT_LITERAL, INTEGER_LITERAL)
private val ADD_INTEGER_FLOAT = AddExpression(0, 0, INTEGER_LITERAL, FLOAT_LITERAL)
private val ADD_STRING_INTEGER = AddExpression(0, 0, STRING_LITERAL, INTEGER_LITERAL)
private val ADD_STRING_FLOAT = AddExpression(0, 0, STRING_LITERAL, FLOAT_LITERAL)
private val ADD_INTEGER_STRING = AddExpression(0, 0, INTEGER_LITERAL, STRING_LITERAL)
private val SUB_INTEGERS = SubExpression(0, 0, INTEGER_LITERAL, INTEGER_IDE)
private val SUB_INTEGERS_COMPLEX = SubExpression(0, 0, INTEGER_LITERAL, SubExpression(0, 0, INTEGER_IDE, INTEGER_IDE))
private val SUB_STRINGS = SubExpression(0, 0, STRING_IDE, STRING_LITERAL)
private val SUB_STRING_INTEGER = SubExpression(0, 0, STRING_IDE, INTEGER_IDE)
private val SUB_BOOLEAN_INTEGER = SubExpression(0, 0, BOOLEAN_IDE, INTEGER_IDE)
private val DIV_INTEGERS = DivExpression(0, 0, INTEGER_LITERAL, INTEGER_IDE)
private val IDIV_INTEGERS = IDivExpression(0, 0, INTEGER_LITERAL, INTEGER_IDE)
private val IDIV_STRING_INTEGER = IDivExpression(0, 0, STRING_IDE, INTEGER_IDE)
private val MOD_INTEGERS = ModExpression(0, 0, INTEGER_LITERAL, INTEGER_IDE)
private val MOD_STRING_INTEGER = ModExpression(0, 0, STRING_IDE, INTEGER_IDE)
private val AND_BOOLEANS = AndExpression(0, 0, BOOLEAN_LITERAL, BOOLEAN_IDE)
private val AND_BOOLEANS_COMPLEX = AndExpression(0, 0, BOOLEAN_LITERAL, AndExpression(0, 0, BOOLEAN_IDE, BOOLEAN_IDE))
private val REL_INTEGERS = EqualExpression(0, 0, INTEGER_IDE, INTEGER_LITERAL)
private val REL_STRINGS = NotEqualExpression(0, 0, STRING_IDE, STRING_LITERAL)
private val REL_COMPLEX = AndExpression(0, 0, EqualExpression(0, 0, INTEGER_IDE, INTEGER_LITERAL), BOOLEAN_IDE)
}
}
| gpl-3.0 | 7ac8d6a8e8f9702ec30dac3fba4dcf03 | 40 | 146 | 0.69936 | 3.938905 | false | true | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/device/PowerManagementServiceImpl.kt | 1 | 3311 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
*
* Copyright (C) 2020 Chris Narkiewicz <[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 <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.device
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.PowerManager
import com.nextcloud.client.preferences.AppPreferences
import com.nextcloud.client.preferences.AppPreferencesImpl
internal class PowerManagementServiceImpl(
private val context: Context,
private val platformPowerManager: PowerManager,
private val preferences: AppPreferences,
private val deviceInfo: DeviceInfo = DeviceInfo()
) : PowerManagementService {
companion object {
/**
* Vendors on this list use aggressive power saving methods that might
* break application experience.
*/
val OVERLY_AGGRESSIVE_POWER_SAVING_VENDORS = setOf("samsung", "huawei", "xiaomi")
@JvmStatic
fun fromContext(context: Context): PowerManagementServiceImpl {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val preferences = AppPreferencesImpl.fromContext(context)
return PowerManagementServiceImpl(context, powerManager, preferences, DeviceInfo())
}
}
override val isPowerSavingEnabled: Boolean
get() {
if (preferences.isPowerCheckDisabled) {
return false
}
return platformPowerManager.isPowerSaveMode
}
override val isPowerSavingExclusionAvailable: Boolean
get() = deviceInfo.vendor in OVERLY_AGGRESSIVE_POWER_SAVING_VENDORS
@Suppress("MagicNumber") // 100% is 100, we're not doing Cobol
override val battery: BatteryStatus
get() {
val intent: Intent? = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val isCharging = intent?.let {
when (it.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)) {
BatteryManager.BATTERY_PLUGGED_USB -> true
BatteryManager.BATTERY_PLUGGED_AC -> true
BatteryManager.BATTERY_PLUGGED_WIRELESS -> true
else -> false
}
} ?: false
val level = intent?.let { it ->
val level: Int = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = it.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
(level * 100 / scale.toFloat()).toInt()
} ?: 0
return BatteryStatus(isCharging, level)
}
}
| gpl-2.0 | 48b4c903c3a4cecc32a8fd9b334e2d39 | 37.5 | 109 | 0.674117 | 4.897929 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/UnionTypeDefinition.kt | 1 | 994 | package graphql.language
import java.util.ArrayList
class UnionTypeDefinition(override val name: String) : AbstractNode(), TypeDefinition {
val directives: MutableList<Directive> = ArrayList()
val memberTypes: MutableList<Type> = ArrayList()
override val children: List<Node>
get() {
val result = ArrayList<Node>()
result.addAll(directives)
result.addAll(memberTypes)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as UnionTypeDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "UnionTypeDefinition{" +
"name='" + name + '\'' +
"directives=" + directives +
", memberTypes=" + memberTypes +
'}'
}
}
| mit | 2292a2a496ed0f0e0274f204cec6cb92 | 25.157895 | 87 | 0.565392 | 5.020202 | false | false | false | false |
edvin/tornadofx-samples | itemviewmodel/withFXproperties/src/test/kotlin/no/tornadofx/fxsamples/withfxproperties/views/TestView.kt | 1 | 3424 | package no.tornadofx.fxsamples.withfxproperties.views
import javafx.collections.ObservableList
import javafx.scene.control.TableCell
import javafx.scene.input.KeyCode
import no.tornado.fxsample.TestBase
import no.tornadofx.fxsamples.withfxproperties.model.Person
import no.tornadofx.fxsamples.withfxproperties.WithFXPropertiesApp
import org.testfx.api.FxAssert.verifyThat
import org.testfx.matcher.control.TableViewMatchers
import org.testfx.matcher.control.TextInputControlMatchers
import tornadofx.FX.Companion.find
import kotlin.test.Test
class TestView : TestBase() {
private lateinit var persons: ObservableList<Person>
override fun initView() {
showView<ItemViewModelWithFxMainView, WithFXPropertiesApp>()
persons = find<PersonList>().controller.persons
}
@Test
fun testView() {
verifyThat("#personList", TableViewMatchers.hasNumRows(persons.size))
var idx = 0
persons.forEach {
verifyThat(
"#personList",
TableViewMatchers.containsRowAtIndex(idx++, it.idProperty.value, it.nameProperty.value)
)
}
clickOn(persons[0].nameProperty.value)
verifyThat("#phoneNumbers", TableViewMatchers.hasNumRows(2))
verifyThat("#infoName", TextInputControlMatchers.hasText(persons[0].nameProperty.value))
clickOn(persons[1].nameProperty.value)
verifyThat("#phoneNumbers", TableViewMatchers.hasNumRows(1))
verifyThat("#infoName", TextInputControlMatchers.hasText(persons[1].nameProperty.value))
}
@Test
fun testAddNumber() {
val newRegion = "2"
val newNumber = "624 426 42"
clickOn(persons[1].nameProperty.value)
clickOn("Add number")
write(newRegion).push(KeyCode.ENTER)
val phoneNumbersTable = lookup("#phoneNumbers").queryTableView<Person>()
clickOn(
from(phoneNumbersTable).lookup(".table-cell").nth(cellIndex(1, 1, 2)).query<TableCell<String, String>>()
).write(newNumber).push(KeyCode.ENTER)
clickOn("Save")
verifyThat("#phoneNumbers", TableViewMatchers.hasNumRows(2))
assert(
from(phoneNumbersTable).lookup(".table-cell").nth(cellIndex(1, 0, 2))
.query<TableCell<String, String>>().text.equals(newRegion)
)
assert(
from(phoneNumbersTable).lookup(".table-cell").nth(cellIndex(1, 1, 2))
.query<TableCell<String, String>>().text.equals(newNumber)
)
}
@Test
fun testChangeName() {
val newName = "James Smith"
val testedPerson = persons[0]
clickOn(testedPerson.nameProperty.value)
clickOn("#infoName").rightClickOn().clickOn("Select All")
write(newName).push(KeyCode.ENTER)
clickOn("Save")
verifyThat("#personList", TableViewMatchers.containsRowAtIndex(0, testedPerson.idProperty.value, newName))
}
@Test
fun testReset() {
val newName = "Jenny Newman"
val testedPerson = persons[1]
val currentName = testedPerson.nameProperty.value
clickOn(testedPerson.nameProperty.value)
clickOn("#infoName").rightClickOn().clickOn("Select All")
write(newName).push(KeyCode.ENTER)
clickOn("Reset")
verifyThat("#personList", TableViewMatchers.containsRowAtIndex(1, testedPerson.idProperty.value, currentName))
}
} | apache-2.0 | 000e7397e6cc822a9d4c7e4cb3051377 | 31.619048 | 118 | 0.67465 | 4.372925 | false | true | false | false |
langara/MyIntent | myviews/src/main/java/pl/mareklangiewicz/myviews/MyPie.kt | 1 | 5130 | package pl.mareklangiewicz.myviews
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.OvalShape
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import pl.mareklangiewicz.myutils.scale1d
class MyPie @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
: View(context, attrs, defStyle) {
private var _minimum: Float = 0f
private var _maximum: Float = 100f
private var _from: Float = 0f
private var _to: Float = 75f
var minimum: Float get() = _minimum; set(value) { _minimum = value; invalidate() }
var maximum: Float get() = _maximum; set(value) { _maximum = value; invalidate() }
var from: Float get() = _from; set(value) { _from = value; invalidate() }
var to: Float get() = _to; set(value) { _to = value; invalidate() }
private val mOvalDrawable = ShapeDrawable(OvalShape())
private val mPieDrawable = ShapeDrawable(object : OvalShape() {
override fun draw(canvas: Canvas, paint: Paint) {
canvas.drawArc(rect(),
_from.scale1d(_minimum, _maximum, 270f, (270 + 360).toFloat()),
(_to - _from).scale1d(_minimum, _maximum, 0f, 360f),
true, paint)
}
})
var pieColor: Int
get() = mPieDrawable.paint.color
set(value) {
mPieDrawable.paint.color = value
invalidate()
}
var ovalColor: Int
get() = mOvalDrawable.paint.color
set(value) {
mOvalDrawable.paint.color = value
invalidate()
}
init {
background = mOvalDrawable
// Load attributes
val a = context.theme.obtainStyledAttributes( attrs, R.styleable.mv_MyPie, defStyle, 0)
try {
_minimum = a.getFloat(R.styleable.mv_MyPie_mv_min, _minimum)
_maximum = a.getFloat(R.styleable.mv_MyPie_mv_max, _maximum)
_from = a.getFloat(R.styleable.mv_MyPie_mv_from, _from)
_to = a.getFloat(R.styleable.mv_MyPie_mv_to, _to)
pieColor = a.getColor(R.styleable.mv_MyPie_mv_pieColor, Color.BLACK)
ovalColor = a.getColor(R.styleable.mv_MyPie_mv_ovalColor, Color.TRANSPARENT)
} finally {
a.recycle()
}
invalidateData()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val left = paddingLeft
val top = paddingTop
val right = width - left - paddingRight
val bottom = height - top - paddingBottom
mPieDrawable.setBounds(left, top, right, bottom)
mOvalDrawable.setBounds(left, top, right, bottom)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
mPieDrawable.draw(canvas)
}
private fun invalidateData() {
_maximum = _maximum.coerceAtLeast(_minimum)
_from = _from.coerceIn(_minimum, _maximum)
_to = _to.coerceIn(_from, _maximum)
}
override fun invalidate() {
invalidateData()
super.invalidate()
}
public override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val ss = SavedState(superState)
ss.mMinimum = _minimum
ss.mMaximum = _maximum
ss.mFrom = _from
ss.mTo = _to
return ss
}
public override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
_minimum = state.mMinimum
_maximum = state.mMaximum
_from = state.mFrom
_to = state.mTo
invalidate()
}
internal class SavedState : View.BaseSavedState {
var mMinimum: Float = 0f
var mMaximum: Float = 0f
var mFrom: Float = 0f
var mTo: Float = 0f
constructor(superState: Parcelable?) : super(superState) {
}
private constructor(inp: Parcel) : super(inp) {
mMinimum = inp.readFloat()
mMaximum = inp.readFloat()
mFrom = inp.readFloat()
mTo = inp.readFloat()
}
override fun writeToParcel(outp: Parcel, flags: Int) {
super.writeToParcel(outp, flags)
outp.writeFloat(mMinimum)
outp.writeFloat(mMaximum)
outp.writeFloat(mFrom)
outp.writeFloat(mTo)
}
companion object {
//TODO SOMEDAY: we should save colors too
@JvmField val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(inp: Parcel): SavedState { return SavedState(inp) }
override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) }
}
}
}
}
| apache-2.0 | eb21af7d61d856aaed5f1869b116bc7e | 33.2 | 109 | 0.605068 | 4.113873 | false | false | false | false |
laomou/LogDog | src/main/kotlin/bean/FilterInfo.kt | 1 | 1400 | package bean
import utils.DefaultConfig
import utils.UID
import java.util.*
class FilterInfo(uuid: String? = null) {
var enabled = false
// 1 new 2 edit 3 delete 4 enable
var state = -1
// 1 contains 2 regex
var type = -1
var text = ""
var color = DefaultConfig.DEFAULT_BG_COLOR
var uuid = uuid ?: UID.getNewUID()
var lines = LinkedList<Int>()
override fun toString(): String {
return when (type) {
1 -> {
"C#$text (${lines.size})"
}
2 -> {
"M#$text (${lines.size})"
}
else -> {
"N#$text (${lines.size})"
}
}
}
override fun hashCode(): Int {
var result = text.hashCode()
result = 31 * result + enabled.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (other == null) {
return false
}
if (other === this) {
return true
}
if (other !is FilterInfo) {
return false
}
if (other.uuid == this.uuid) {
return true
}
return false
}
fun detail(): String {
return when (type) {
1 -> "C#$text"
2 -> "M#$text"
else -> text
}
}
fun toggle() {
enabled = !enabled
}
} | apache-2.0 | b1d81a7f99ae6bb8a15453050ebb09aa | 20.227273 | 49 | 0.454286 | 4.320988 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/networking/models/FaceUploadParam.kt | 1 | 1483 | package com.stripe.android.identity.networking.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
internal data class FaceUploadParam(
@SerialName("best_high_res_image")
val bestHighResImage: String,
@SerialName("best_low_res_image")
val bestLowResImage: String,
@SerialName("first_high_res_image")
val firstHighResImage: String,
@SerialName("first_low_res_image")
val firstLowResImage: String,
@SerialName("last_high_res_image")
val lastHighResImage: String,
@SerialName("last_low_res_image")
val lastLowResImage: String,
@SerialName("best_face_score")
val bestFaceScore: Float,
@SerialName("face_score_variance")
val faceScoreVariance: Float,
@SerialName("num_frames")
val numFrames: Int,
@SerialName("best_exposure_duration")
val bestExposureDuration: Int? = null,
@SerialName("best_brightness_value")
val bestBrightnessValue: Float? = null,
@SerialName("best_camera_lens_model")
val bestCameraLensModel: String? = null,
@SerialName("best_focal_length")
val bestFocalLength: Float? = null,
@SerialName("best_is_virtual_camera")
val bestIsVirtualCamera: Boolean? = null,
@SerialName("best_exposure_iso")
val bestExposureIso: Float? = null,
@SerialName("training_consent")
val trainingConsent: Boolean? = null
) : Parcelable
| mit | afde42a94d768b50ac36dea61447ae27 | 33.488372 | 53 | 0.724882 | 3.902632 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/EditSession.kt | 1 | 1195 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Information about the Vimeo Create session of a video.
*
* @param isMusicLicensed Whether the video has licensed music.
* @param isMaxResolution Whether the current version of clip is of max resolution.
* @param vsid Video session id.
* @param resultVideoHash The result video hash.
* @param hasWatermark Whether the video has watermark.
* @param isRated Whether the video is rated.
* @param minTierForMovie The minimum required Vimeo membership for the user to be able to share or download the video.
*/
@JsonClass(generateAdapter = true)
data class EditSession(
@Json(name = "is_music_licensed")
val isMusicLicensed: Boolean? = null,
@Json(name = "is_max_resolution")
val isMaxResolution: Boolean? = null,
@Json(name = "vsid")
val vsid: Int? = null,
@Json(name = "result_video_hash")
val resultVideoHash: String? = null,
@Json(name = "has_watermark")
val hasWatermark: Boolean? = null,
@Json(name = "is_rated")
val isRated: Boolean? = null,
@Json(name = "min_tier_for_movie")
val minTierForMovie: String? = null,
)
| mit | 36b522d6549e0a631262da872ec85245 | 28.875 | 119 | 0.705439 | 3.676923 | false | false | false | false |
AndroidX/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/config/ThreadConfigModule.kt | 3 | 6751 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.config
import android.os.Handler
import android.os.HandlerThread
import android.os.Process
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraPipe
import androidx.camera.camera2.pipe.core.AndroidThreads
import androidx.camera.camera2.pipe.core.AndroidThreads.asCachedThreadPool
import androidx.camera.camera2.pipe.core.AndroidThreads.asFixedSizeThreadPool
import androidx.camera.camera2.pipe.core.AndroidThreads.asScheduledThreadPool
import androidx.camera.camera2.pipe.core.AndroidThreads.withAndroidPriority
import androidx.camera.camera2.pipe.core.AndroidThreads.withPrefix
import androidx.camera.camera2.pipe.core.Threads
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.asExecutor
/**
* Configure and provide a single [Threads] object to other parts of the library.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@Module
internal class ThreadConfigModule(private val threadConfig: CameraPipe.ThreadConfig) {
// Lightweight executors are for CPU bound work that should take less than ~10ms to operate and
// do not block the calling thread.
private val lightweightThreadCount: Int =
maxOf(2, Runtime.getRuntime().availableProcessors() - 2)
// Background thread count is for operations that are not latency sensitive and may take more
// than a few milliseconds to run.
private val backgroundThreadCount: Int = 4
// High priority threads for interrupt and rendering sensitive operations. This is set to have
// slightly (1) lower priority than the display rendering thread should have.
private val cameraThreadPriority: Int =
Process.THREAD_PRIORITY_DISPLAY + Process.THREAD_PRIORITY_LESS_FAVORABLE
// Default thread priorities are slightly higher than the default priorities since most camera
// operations are latency sensitive and should take precedence over other background work.
private val defaultThreadPriority: Int =
Process.THREAD_PRIORITY_DEFAULT + Process.THREAD_PRIORITY_MORE_FAVORABLE
@Singleton
@Provides
fun provideThreads(): Threads {
val testOnlyDispatcher = threadConfig.testOnlyDispatcher
val testOnlyScope = threadConfig.testOnlyScope
if (testOnlyDispatcher != null && testOnlyScope != null) {
return provideTestOnlyThreads(testOnlyDispatcher, testOnlyScope)
}
check(testOnlyDispatcher == null || testOnlyScope == null) {
"testOnlyDispatcher and testOnlyScope must be specified together!"
}
val blockingExecutor =
threadConfig.defaultBlockingExecutor ?: AndroidThreads.factory
.withPrefix("CXCP-IO-")
.withAndroidPriority(defaultThreadPriority)
.asCachedThreadPool()
val blockingDispatcher = blockingExecutor.asCoroutineDispatcher()
val backgroundExecutor =
threadConfig.defaultBackgroundExecutor ?: AndroidThreads.factory
.withPrefix("CXCP-BG-")
.withAndroidPriority(defaultThreadPriority)
.asScheduledThreadPool(backgroundThreadCount)
val backgroundDispatcher = backgroundExecutor.asCoroutineDispatcher()
val lightweightExecutor =
threadConfig.defaultLightweightExecutor ?: AndroidThreads.factory
.withPrefix("CXCP-")
.withAndroidPriority(cameraThreadPriority)
.asScheduledThreadPool(lightweightThreadCount)
val lightweightDispatcher = lightweightExecutor.asCoroutineDispatcher()
val cameraHandlerFn =
{
val handlerThread = threadConfig.defaultCameraHandler ?: HandlerThread(
"CXCP-Camera-H",
cameraThreadPriority
).also {
it.start()
}
Handler(handlerThread.looper)
}
val cameraExecutorFn = {
threadConfig.defaultCameraExecutor ?: AndroidThreads.factory
.withPrefix("CXCP-Camera-E")
.withAndroidPriority(cameraThreadPriority)
.asFixedSizeThreadPool(1)
}
val globalScope = CoroutineScope(
SupervisorJob() + lightweightDispatcher + CoroutineName("CXCP")
)
return Threads(
globalScope = globalScope,
blockingExecutor = blockingExecutor,
blockingDispatcher = blockingDispatcher,
backgroundExecutor = backgroundExecutor,
backgroundDispatcher = backgroundDispatcher,
lightweightExecutor = lightweightExecutor,
lightweightDispatcher = lightweightDispatcher,
camera2Handler = cameraHandlerFn,
camera2Executor = cameraExecutorFn
)
}
private fun provideTestOnlyThreads(
testDispatcher: CoroutineDispatcher,
testScope: CoroutineScope
): Threads {
val testExecutor = testDispatcher.asExecutor()
// TODO: This should delegate to the testDispatcher instead of using a HandlerThread.
val cameraHandlerFn = {
val handlerThread = HandlerThread(
"CXCP-Camera-H",
cameraThreadPriority
).also {
it.start()
}
Handler(handlerThread.looper)
}
return Threads(
globalScope = testScope,
blockingExecutor = testExecutor,
blockingDispatcher = testDispatcher,
backgroundExecutor = testExecutor,
backgroundDispatcher = testDispatcher,
lightweightExecutor = testExecutor,
lightweightDispatcher = testDispatcher,
camera2Handler = cameraHandlerFn,
camera2Executor = { testExecutor }
)
}
} | apache-2.0 | f80ca14daf7bccdaf146c49bc6ce7342 | 40.679012 | 99 | 0.695304 | 5.439968 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/inlineTypeAlias/RsInlineTypeAliasHandler.kt | 2 | 1672 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.inlineTypeAlias
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.lang.Language
import com.intellij.lang.refactoring.InlineActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.RsLanguage
import org.rust.lang.core.macros.isExpandedFromMacro
import org.rust.lang.core.psi.RsBlock
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.openapiext.isUnitTestMode
class RsInlineTypeAliasHandler : InlineActionHandler() {
override fun isEnabledForLanguage(language: Language): Boolean = language == RsLanguage
override fun canInlineElement(element: PsiElement): Boolean =
element is RsTypeAlias
&& element.name != null
// `type Foo: X = ...;`
&& element.typeParamBounds == null
&& element.typeReference != null
&& element.parent.let { it is RsMod || it is RsBlock }
&& !element.isExpandedFromMacro
override fun inlineElement(project: Project, editor: Editor, element: PsiElement) {
val typeAlias = element as RsTypeAlias
val reference = TargetElementUtil.findReference(editor, editor.caretModel.offset) as? RsReference
val dialog = RsInlineTypeAliasDialog(typeAlias, reference)
if (!isUnitTestMode) {
dialog.show()
} else {
dialog.doAction()
}
}
}
| mit | ab9080f08f50bb51ce52514a87014738 | 36.155556 | 105 | 0.716507 | 4.470588 | false | false | false | false |
android/identity-samples | Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/ui/home/CredentialAdapter.kt | 1 | 2318 | /*
* Copyright 2021 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.gms.identity.sample.fido2.ui.home
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.identity.sample.fido2.api.Credential
import com.google.android.gms.identity.sample.fido2.databinding.CredentialItemBinding
class CredentialAdapter(
private val onDeleteClicked: (String) -> Unit
) : ListAdapter<Credential, CredentialViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CredentialViewHolder {
return CredentialViewHolder(
CredentialItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
onDeleteClicked
)
}
override fun onBindViewHolder(holder: CredentialViewHolder, position: Int) {
holder.binding.credential = getItem(position)
}
}
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Credential>() {
override fun areItemsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem == newItem
}
}
class CredentialViewHolder(
val binding: CredentialItemBinding,
onDeleteClicked: (String) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.delete.setOnClickListener {
binding.credential?.let { c ->
onDeleteClicked(c.id)
}
}
}
}
| apache-2.0 | 1f10a591a76a6e7c906ad1403696d247 | 33.088235 | 93 | 0.710958 | 4.654618 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/DTReportMgr.kt | 1 | 4060 | package com.exyui.android.debugbottle.components
import android.os.Environment
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by yuriel on 9/13/16.
*/
internal abstract class DTReportMgr {
open val TYPE: String = ".txt"
abstract val TAG: String
private val SAVE_DELETE_LOCK = Any()
open val FILE_NAME_FORMATTER = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS", Locale.getDefault())
open val TIME_FORMATTER = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
open val OBSOLETE_DURATION = 2 * 24 * 3600 * 1000L
abstract val logPath: String
abstract val filePrefix: String
val path: String
get() {
val state = Environment.getExternalStorageState()
if (Environment.MEDIA_MOUNTED == state && Environment.getExternalStorageDirectory().canWrite()) {
return Environment.getExternalStorageDirectory().path + logPath
}
return Environment.getDataDirectory().absolutePath + logPath
}
internal val logFiles: Array<File>?
get() {
val f = detectedFileDirectory()
if (f.exists() && f.isDirectory) {
return f.listFiles { dir, filename ->
filename.endsWith(TYPE)
}
}
return null
}
internal fun detectedFileDirectory(): File {
val directory = File(path)
if (!directory.exists()) {
directory.mkdirs()
}
return directory
}
fun deleteLogFiles() {
synchronized(SAVE_DELETE_LOCK) {
try {
val f = logFiles
for (aF in f?: return) {
aF.delete()
}
} catch (e: Throwable) {
Log.e(TAG, "deleteLogFiles: ", e)
}
}
}
fun cleanOldFiles() {
val handlerThread = HandlerThread("DT_file_cleaner")
handlerThread.start()
Handler(handlerThread.looper).post {
val now = System.currentTimeMillis()
val f = logFiles
synchronized(SAVE_DELETE_LOCK) {
for (aF in f?: return@synchronized) {
if (now - aF.lastModified() > OBSOLETE_DURATION) {
aF.delete()
}
}
}
}
}
internal fun saveLogToSDCard(logFileNamePrefix: String, str: String): String {
var path = ""
var writer: BufferedWriter? = null
try {
val file = detectedFileDirectory()
val time = System.currentTimeMillis()
path = "${file.absolutePath}/$logFileNamePrefix-${FILE_NAME_FORMATTER.format(time)}$TYPE"
val out = OutputStreamWriter(FileOutputStream(path, true), "UTF-8")
writer = BufferedWriter(out)
writer.write("\r\n**********************\r\n")
writer.write(TIME_FORMATTER.format(time) + "(write log time)")
writer.write("\r\n")
writer.write("\r\n")
writer.write(str)
writer.write("\r\n")
writer.flush()
writer.close()
writer = null
} catch (t: Throwable) {
Log.e(TAG, "saveLogToSDCard: ", t)
} finally {
try {
if (writer != null) {
writer.close()
}
} catch (e: Exception) {
Log.e(TAG, "saveLogToSDCard: ", e)
}
}
return path
}
/**
* Save log to file
* @param str block log string
* *
* @return log file path
*/
fun saveLog(str: String): String {
var path: String = ""
synchronized(SAVE_DELETE_LOCK) {
path = saveLogToSDCard(filePrefix, str)
}
return path
}
} | apache-2.0 | 081193995feed3672fffedb9386c2240 | 28.860294 | 109 | 0.539655 | 4.613636 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/models/GooglePayButton.kt | 2 | 1173 | package org.thoughtcrime.securesms.components.settings.app.subscription.models
import android.view.View
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
object GooglePayButton {
class Model(val onClick: () -> Unit, override val isEnabled: Boolean) : PreferenceModel<Model>(isEnabled = isEnabled) {
override fun areItemsTheSame(newItem: Model): Boolean = true
}
class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val googlePayButton: View = findViewById(R.id.googlepay_button)
override fun bind(model: Model) {
googlePayButton.isEnabled = model.isEnabled
googlePayButton.setOnClickListener {
googlePayButton.isEnabled = false
model.onClick()
}
}
}
fun register(adapter: MappingAdapter) {
adapter.registerFactory(Model::class.java, LayoutFactory({ ViewHolder(it) }, R.layout.google_pay_button_pref))
}
}
| gpl-3.0 | 6353a5d33afca2a7a4062d40218af79e | 35.65625 | 121 | 0.770673 | 4.460076 | false | false | false | false |
lvtanxi/Study | BootMybatis/src/main/kotlin/com/lv/controller/MyUserInfoController.kt | 1 | 902 | package com.lv.controller
import com.lv.dto.ResultDto
import com.lv.service.MyUserInfoService
import com.lv.util.ResultUtil
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
/**
* Date: 2017-03-21
* Time: 10:43
* Description:
*/
@RestController
@RequestMapping(value = "userInfo")
class MyUserInfoController(val myUserInfoService: MyUserInfoService) {
@GetMapping(value = "findAllUserInfo")
fun findAllUser(): ResultDto {
val findAllUser = myUserInfoService.findAllMyUserInfo()
return ResultUtil.success(findAllUser)
}
@GetMapping(value = "findAllMyUserInfoMap")
fun findAllMyUserInfoMap(): ResultDto {
val findAllUser = myUserInfoService.findAllMyUserInfoMap()
return ResultUtil.success(findAllUser)
}
} | apache-2.0 | 83cce19309692837fa1a87c243429bca | 27.21875 | 70 | 0.761641 | 4.063063 | false | false | false | false |
ealva-com/ealvalog | ealvalog-jdk/src/main/java/com/ealva/ealvalog/jul/JdkBridge.kt | 1 | 3636 | /*
* Copyright 2017 Eric A. Snell
*
* This file is part of eAlvaLog.
*
* 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.ealva.ealvalog.jul
import com.ealva.ealvalog.FilterResult
import com.ealva.ealvalog.FilterResult.DENY
import com.ealva.ealvalog.LogEntry
import com.ealva.ealvalog.LogLevel
import com.ealva.ealvalog.LoggerFilter
import com.ealva.ealvalog.Marker
import com.ealva.ealvalog.core.Bridge
import com.ealva.ealvalog.core.CoreLogger
import com.ealva.ealvalog.core.ExtLogRecord
import com.ealva.ealvalog.filter.AlwaysNeutralFilter
import java.util.logging.Handler
/**
* Bridge the [CoreLogger] to the underlying java.util.logging.Logger
*
*
* Created by Eric A. Snell on 3/7/17.
*/
class JdkBridge internal constructor(
name: String,
private var filter: LoggerFilter = AlwaysNeutralFilter,
handler: Handler? = null,
logLevel: LogLevel? = null
) : Bridge {
@field:Volatile var parent: JdkBridge? = null // root bridge will have a null parent
private val jdkLogger: java.util.logging.Logger =
java.util.logging.Logger.getLogger(name).apply {
handler?.let { addHandler(it) }
level = logLevel?.jdkLevel
}
override var logLevel: LogLevel
get() = LogLevel.fromLevel(jdkLogger.level)
set(logLevel) {
jdkLogger.level = logLevel.jdkLevel
}
override var includeLocation: Boolean = false
override var logToParent: Boolean
get() = jdkLogger.useParentHandlers
set(value) {
jdkLogger.useParentHandlers = value
}
override val name: String
get() = jdkLogger.name
override fun getFilter(): LoggerFilter {
return filter
}
override fun setFilter(filter: LoggerFilter?) {
this.filter = filter ?: AlwaysNeutralFilter
}
override fun shouldIncludeLocation(
level: LogLevel,
marker: Marker?,
throwable: Throwable?
): Boolean {
return includeLocation || parent?.shouldIncludeLocation(level, marker, throwable) == true
}
override fun willLogToParent(loggerName: String): Boolean {
return !bridgeIsLoggerPeer(loggerName) || jdkLogger.useParentHandlers
}
/**
* {@inheritDoc}
*
*
* If the level check passes and any contained filter does not deny, then accepted
*/
override fun isLoggable(
loggerName: String,
logLevel: LogLevel,
marker: Marker?,
throwable: Throwable?
): FilterResult {
if (!jdkLogger.isLoggable(logLevel.jdkLevel)) {
return DENY
}
return filter.isLoggable(loggerName, logLevel, marker, throwable).acceptIfNeutral()
}
override fun log(logEntry: LogEntry) {
ExtLogRecord.fromLogEntry(logEntry).use { record ->
jdkLogger.log(record)
}
}
override fun getLevelForLogger(logger: com.ealva.ealvalog.Logger): LogLevel? {
return if (bridgeIsLoggerPeer(logger.name)) {
LogLevel.fromLevel(jdkLogger.level)
} else null
}
override fun bridgeIsLoggerPeer(loggerName: String): Boolean {
return name == loggerName
}
fun addLoggerHandler(loggerHandler: Handler) {
jdkLogger.addHandler(loggerHandler)
}
fun setToDefault() {
jdkLogger.useParentHandlers = true
}
}
| apache-2.0 | 700a16a99828f73d245e91b90a496177 | 26.969231 | 93 | 0.720847 | 3.767876 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/forge/gradle/ForgeRunConfigDataService.kt | 1 | 7958 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.gradle
import com.demonwav.mcdev.platform.forge.ForgeModuleType
import com.demonwav.mcdev.platform.forge.creator.ForgeRunConfigsStep
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.invokeAndWait
import com.demonwav.mcdev.util.invokeLater
import com.demonwav.mcdev.util.localFile
import com.demonwav.mcdev.util.runGradleTaskAndWait
import com.intellij.execution.RunManager
import com.intellij.execution.RunManagerListener
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.application.ApplicationConfiguration
import com.intellij.execution.application.ApplicationConfigurationType
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.atomic.AtomicInteger
import org.jetbrains.plugins.gradle.util.GradleConstants
class ForgeRunConfigDataService : AbstractProjectDataService<ProjectData, Project>() {
override fun getTargetDataKey() = ProjectKeys.PROJECT
override fun postProcess(
toImport: Collection<DataNode<ProjectData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (projectData == null || projectData.owner != GradleConstants.SYSTEM_ID) {
return
}
val baseDir = project.guessProjectDir() ?: return
val baseDirPath = baseDir.localFile.toPath()
val hello = baseDirPath.resolve(Paths.get(".gradle", ForgeRunConfigsStep.HELLO))
if (!Files.isRegularFile(hello)) {
return
}
val lines = Files.readAllLines(hello, Charsets.UTF_8)
if (lines.size < 4) {
return
}
val (moduleName, mcVersion, forgeVersion, task) = lines
val mcVersionParsed = SemanticVersion.parse(mcVersion)
val forgeVersionParsed = SemanticVersion.parse(forgeVersion)
val moduleMap = modelsProvider.modules.associateBy { it.name }
val module = moduleMap[moduleName] ?: return
// We've found the module we were expecting, so we can assume the project imported correctly
Files.delete(hello)
val isPre113 = mcVersionParsed < ForgeModuleType.FG3_MC_VERSION
if (isPre113 && forgeVersionParsed < ForgeModuleType.FG3_FORGE_VERSION) {
manualCreate(project, moduleMap, module)
} else {
genIntellijRuns(project, moduleMap, module, task, hasData = !isPre113)
}
}
private fun manualCreate(
project: Project,
moduleMap: Map<String, Module>,
module: Module
) {
invokeLater {
val mainModule = findMainModule(moduleMap, module)
val runManager = RunManager.getInstance(project)
val factory = ApplicationConfigurationType.getInstance().configurationFactories.first()
// Client run config
val clientSettings = runManager.createConfiguration(module.name + " run client", factory)
val runClientConfig = clientSettings.configuration as ApplicationConfiguration
runClientConfig.isAllowRunningInParallel = false
val runningDir = File(project.basePath, "run")
if (!runningDir.exists()) {
runningDir.mkdir()
}
runClientConfig.workingDirectory = project.basePath + File.separator + "run"
runClientConfig.mainClassName = "GradleStart"
runClientConfig.setModule(mainModule)
clientSettings.isActivateToolWindowBeforeRun = true
clientSettings.storeInLocalWorkspace()
runManager.addConfiguration(clientSettings)
runManager.selectedConfiguration = clientSettings
// Server run config
val serverSettings = runManager.createConfiguration(module.name + " run server", factory)
val runServerConfig = serverSettings.configuration as ApplicationConfiguration
runServerConfig.isAllowRunningInParallel = false
runServerConfig.mainClassName = "GradleStartServer"
runServerConfig.programParameters = "nogui"
runServerConfig.workingDirectory = project.basePath + File.separator + "run"
runServerConfig.setModule(mainModule)
serverSettings.isActivateToolWindowBeforeRun = true
serverSettings.storeInLocalWorkspace()
runManager.addConfiguration(serverSettings)
}
}
private fun genIntellijRuns(
project: Project,
moduleMap: Map<String, Module>,
module: Module,
task: String,
hasData: Boolean
) {
val mainModule = findMainModule(moduleMap, module)
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, "genIntellijRuns", false) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val projectDir = project.guessProjectDir() ?: return
indicator.text = "Creating run configurations"
indicator.text2 = "Running Gradle task: '$task'"
runGradleTaskAndWait(project, projectDir.localFile.toPath()) { settings ->
settings.taskNames = listOf(task)
}
cleanupGeneratedRuns(project, mainModule, hasData)
}
}
)
}
private fun cleanupGeneratedRuns(project: Project, module: Module, hasData: Boolean) {
invokeAndWait {
if (!module.isDisposed) {
ForgeRunManagerListener(module, hasData)
}
}
project.guessProjectDir()?.let { dir ->
LocalFileSystem.getInstance().refreshFiles(listOf(dir), true, true, null)
}
}
private fun findMainModule(moduleMap: Map<String, Module>, module: Module): Module {
return moduleMap[module.name + ".main"] ?: module
}
}
class ForgeRunManagerListener(private val module: Module, hasData: Boolean) : RunManagerListener {
private val count = AtomicInteger(3)
private val disposable = Disposer.newDisposable()
init {
Disposer.register(module, disposable)
module.project.messageBus.connect(disposable).subscribe(RunManagerListener.TOPIC, this)
// If we don't have a data run, don't wait for it
if (!hasData) {
count.decrementAndGet()
}
}
override fun runConfigurationAdded(settings: RunnerAndConfigurationSettings) {
val config = settings.configuration as? ApplicationConfiguration ?: return
val postFixes = arrayOf("runClient", "runServer", "runData")
if (postFixes.none { settings.name.endsWith(it) }) {
return
}
config.isAllowRunningInParallel = false
config.setModule(module)
RunManager.getInstance(module.project).addConfiguration(settings)
if (count.decrementAndGet() == 0) {
Disposer.dispose(disposable)
}
}
}
| mit | 687bc32ba279d0b343d61ab475ee957a | 37.259615 | 101 | 0.685222 | 5.174252 | false | true | false | false |
0x1bad1d3a/Kaku | app/src/main/java/ca/fuwafuwa/kaku/Windows/InstantInfoWindow.kt | 2 | 12569 | package ca.fuwafuwa.kaku.Windows
import android.content.Context
import android.graphics.Color
import android.util.Log
import android.view.MotionEvent
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import ca.fuwafuwa.kaku.*
import ca.fuwafuwa.kaku.Database.JmDictDatabase.Models.EntryOptimized
import ca.fuwafuwa.kaku.Search.JmSearchResult
import ca.fuwafuwa.kaku.Search.SearchInfo
import ca.fuwafuwa.kaku.Search.Searcher
import ca.fuwafuwa.kaku.Windows.Data.DisplayDataOcr
import ca.fuwafuwa.kaku.Windows.Data.ISquareChar
import ca.fuwafuwa.kaku.Windows.Enums.LayoutPosition
import ca.fuwafuwa.kaku.Windows.Interfaces.IRecalculateKanjiViews
import ca.fuwafuwa.kaku.Windows.Interfaces.ISearchPerformer
class InstantInfoWindow(context: Context,
windowCoordinator: WindowCoordinator,
private val instantKanjiWindow: InstantKanjiWindow) : Window(context, windowCoordinator, R.layout.window_instant_info), Searcher.SearchDictDone, IRecalculateKanjiViews, ISearchPerformer
{
private val isBoxHorizontal: Boolean
get()
{
return displayData.boxParams.width > displayData.boxParams.height;
}
private val paddingSize = dpToPx(context, 5)
private lateinit var layoutPosition: LayoutPosition
private lateinit var displayData: DisplayDataOcr
private var searcher: Searcher = Searcher(context)
private var searchedChars: MutableList<ISquareChar> = mutableListOf()
private var textInfo = window.findViewById<TextView>(R.id.instant_window_text)
private var textFrame = window.findViewById<LinearLayout>(R.id.instant_window_text_frame)
private var updateView = false
init
{
searcher.registerCallback(this)
textFrame.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
run {
if (updateView)
{
val width = v.width + dpToPx(context, 10)
val height = v.height + dpToPx(context, 10)
if (isBoxHorizontal)
{
calcParamsForHorizontal(width, height)
} else
{
calcParamsForVertical(width, height)
}
window.visibility = VISIBLE
windowManager.updateViewLayout(window, params)
updateView = false
Log.d(TAG, "layoutChanged - InstantInfoWindow")
}
}
}
}
override fun onDown(e: MotionEvent?): Boolean
{
instantKanjiWindow.hide()
return super.onDown(e)
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean
{
return false
}
override fun onResize(e: MotionEvent?): Boolean
{
return false
}
override fun show()
{
synchronized(this)
{
if (!addedToWindowManager)
{
textInfo.text = displayData.text
textInfo.setTextColor(Color.BLACK)
if (isBoxHorizontal)
{
val topRectHeight = displayData.boxParams.y - statusBarHeight
val bottomRectHeight = realDisplaySize.y - displayData.boxParams.y - displayData.boxParams.height - (realDisplaySize.y - viewHeight - statusBarHeight)
val maxHeight = dpToPx(context, 600)
var height: Int
if (topRectHeight > bottomRectHeight){
layoutPosition = LayoutPosition.TOP
height = topRectHeight
}
else {
layoutPosition = LayoutPosition.BOTTOM
height = bottomRectHeight
}
height = minOf(height, maxHeight)
calcParamsForHorizontal(dpToPx(context, 400), height)
} else
{
val leftRectWidth = displayData.boxParams.x
val rightRectWidth = viewWidth - (displayData.boxParams.x + displayData.boxParams.width)
val maxWidth = dpToPx(context, 400)
var width: Int
if (leftRectWidth > rightRectWidth)
{
layoutPosition = LayoutPosition.LEFT
width = leftRectWidth
}
else {
layoutPosition = LayoutPosition.RIGHT
width = rightRectWidth
}
width = minOf(width, maxWidth)
calcParamsForVertical(width, dpToPx(context, 600))
}
window.visibility = INVISIBLE
windowManager.addView(window, params)
addedToWindowManager = true
}
}
}
override fun jmResultsCallback(results: MutableList<JmSearchResult>, search: SearchInfo)
{
show()
updateView = true
if (results.size > 0)
{
if (search.squareChar.userTouched && !searchedChars.contains(search.squareChar))
{
//windowCoordinator.getWindowOfType<HistoryWindow>(WINDOW_HISTORY).addResult(search.squareChar, results)
searchedChars.add(search.squareChar)
}
displayResults(results)
}
else
{
textInfo.text = "No dictionary entry found"
}
// Highlights words in the window as long as they match
val start = search.index - instantKanjiWindow.getKanjiView().offset
if (results.size > 0)
{
val kanji = results[0].word
for (i in start until start + kanji.codePointCount(0, kanji.length))
{
if (i >= instantKanjiWindow.getKanjiView().kanjiViewList.size)
{
break
}
instantKanjiWindow.getKanjiView().kanjiViewList[i].highlight()
}
} else
{
instantKanjiWindow.getKanjiView().kanjiViewList[start].highlight()
}
}
override fun recalculateKanjiViews()
{
instantKanjiWindow.recalculateKanjiViews()
}
override fun performSearch(squareChar: ISquareChar)
{
hide()
instantKanjiWindow.getKanjiView().unhighlightAll(squareChar)
searcher.search(SearchInfo(squareChar))
}
fun setResult(result: DisplayDataOcr)
{
displayData = result
searchedChars = mutableListOf()
}
private fun changeLayoutForKanjiWindow()
{
if (instantKanjiWindow.getLayoutPosition() != layoutPosition)
{
setPadding(paddingSize, paddingSize, paddingSize, paddingSize)
return
}
var kanjiWindowSize = if (isBoxHorizontal) instantKanjiWindow.getHeight() else instantKanjiWindow.getWidth()
when(layoutPosition)
{
LayoutPosition.TOP ->
{
kanjiWindowSize -= dpToPx(context, 5)
params.y -= kanjiWindowSize
if (params.y < 0)
{
params.height += params.y
params.y = 0
}
setPadding(paddingSize, paddingSize, paddingSize, 0)
}
LayoutPosition.BOTTOM ->
{
params.y += kanjiWindowSize
if (params.y + params.height > viewHeight)
{
val overflowHeight = params.y + params.height - viewHeight
params.height -= overflowHeight
}
setPadding(paddingSize, 0, paddingSize, paddingSize)
}
LayoutPosition.LEFT ->
{
kanjiWindowSize += dpToPx(context, 5)
params.x -= kanjiWindowSize
if (params.x < 0)
{
params.width += params.x
params.x = 0
}
setPadding(paddingSize, paddingSize, 0, paddingSize)
}
LayoutPosition.RIGHT ->
{
kanjiWindowSize += dpToPx(context, 5)
params.x += kanjiWindowSize
if (params.x + params.width > realDisplaySize.x)
{
val overflowWidth = params.x + params.width - realDisplaySize.x
params.width -= overflowWidth
}
setPadding(0, paddingSize, paddingSize, paddingSize)
}
}
}
private fun displayResults(jmResults: List<JmSearchResult>)
{
val sb = StringBuilder()
for ((entry, deinfInfo) in jmResults)
{
sb.append(entry.kanji)
if (!entry.readings.isEmpty())
{
if (DB_JMDICT_NAME == entry.dictionary)
{
sb.append(" (")
} else
{
sb.append(" ")
}
sb.append(entry.readings)
if (DB_JMDICT_NAME == entry.dictionary) sb.append(")")
}
val deinfReason = deinfInfo!!.reason
if (deinfReason != null && !deinfReason.isEmpty())
{
sb.append(String.format(" %s", deinfReason))
}
sb.append("\n")
sb.append(getMeaning(entry))
sb.append("\n\n")
}
if (sb.length > 2)
{
sb.setLength(sb.length - 2)
}
textInfo.text = sb.toString()
}
private fun getMeaning(entry: EntryOptimized): String
{
val meanings = entry.meanings.split("\ufffc".toRegex()).toTypedArray()
val pos = entry.pos.split("\ufffc".toRegex()).toTypedArray()
val sb = StringBuilder()
for (i in meanings.indices)
{
if (i > 2)
{
sb.append(" [......]")
break
}
if (i != 0)
{
sb.append(" ")
}
sb.append(LangUtils.ConvertIntToCircledNum(i + 1))
sb.append(" ")
if (DB_JMDICT_NAME == entry.dictionary && !pos[i].isEmpty())
{
sb.append(String.format("(%s) ", pos[i]))
}
sb.append(meanings[i])
}
return sb.toString()
}
private fun setPadding(l: Int, t: Int, r: Int, b: Int)
{
val frameLayout = window.findViewById<FrameLayout>(R.id.instant_info_window_layout)
frameLayout.setPadding(l, t, r, b)
}
private fun calcParamsForHorizontal(maxWidth: Int, maxHeight: Int)
{
var xPos = displayData.boxParams.x
if (xPos + maxWidth > realDisplaySize.x)
{
xPos = realDisplaySize.x - maxWidth
}
params.width = maxWidth
if (layoutPosition == LayoutPosition.TOP){
params.x = xPos
params.y = displayData.boxParams.y - maxHeight - statusBarHeight
params.height = maxHeight
}
else {
params.x = xPos
params.y = displayData.boxParams.y + displayData.boxParams.height - statusBarHeight
params.height = maxHeight
}
changeLayoutForKanjiWindow()
}
private fun calcParamsForVertical(maxWidth: Int, maxHeight: Int)
{
var yPos = displayData.boxParams.y - statusBarHeight
if (yPos + maxHeight > realDisplaySize.y){
yPos = viewHeight - maxHeight
}
params.height = maxHeight
if (layoutPosition == LayoutPosition.LEFT)
{
var xPos = displayData.boxParams.x - maxWidth
if (xPos < 0)
{
xPos = 0
}
params.x = xPos
params.y = yPos
params.width = maxWidth
}
else {
var xPos = displayData.boxParams.x + displayData.boxParams.width
params.x = xPos
params.y = yPos
params.width = maxWidth
}
changeLayoutForKanjiWindow()
}
companion object
{
val TAG = InstantInfoWindow::class.java.name
}
} | bsd-3-clause | d4e3ed93770e142f05895e2228140dbd | 29.658537 | 209 | 0.538945 | 5.031625 | false | false | false | false |
thomasvolk/worm | src/test/kotlin/net/t53k/worm/ModelTest.kt | 1 | 664 | package net.t53k.worm
import org.junit.Assert.*
import org.junit.Test
import java.nio.charset.Charset
class ModelTest {
@Test
fun stringRepresentations() {
val body = Body("text".toByteArray(Charset.forName("UTF-8")), ContentType(ContentType.DEFAULT_CONTENT_TYPE))
val bodyRepresentation = body.toString()
assertEquals("Body(contentType=ContentType(contentType=application/octet-stream), bytes=4)", bodyRepresentation)
val document = Document(Resource("http://example.com", body), listOf())
assertEquals("Document(resource='Resource(url=http://example.com, body=$body)', linkCount=0)", document.toString())
}
} | apache-2.0 | 1fcc8066c29c018eef6d3b42c9e89d3b | 40.5625 | 123 | 0.715361 | 4.04878 | false | true | false | false |
jeffgbutler/mybatis-dynamic-sql | src/test/kotlin/nullability/test/NotBetweenTest.kt | 1 | 5520 | /*
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nullability.test
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class NotBetweenTest {
@Test
fun `Test That First Null Causes Compile Error`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
fun testFunction() {
countFrom(person) {
where { id isNotBetween null and 4 }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(9, 33)))
}
@Test
fun `Test That Second Null Causes Compile Error`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
fun testFunction() {
countFrom(person) {
where { id isNotBetween 4 and null }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(9, 39)))
}
@Test
fun `Test That Both Null Causes Compile Errors`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
fun testFunction() {
countFrom(person) {
where { id isNotBetween null and null }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(
ErrorLocation(9, 33),
ErrorLocation(9, 42)
))
}
@Test
fun `Test That First Null In Elements Method Causes Compile Error`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
import org.mybatis.dynamic.sql.util.kotlin.elements.isNotBetween
fun testFunction() {
countFrom(person) {
where { id (isNotBetween<Int>(null).and(4)) }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(10, 39)))
}
@Test
fun `Test That Second Null In Elements Method Causes Compile Error`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
import org.mybatis.dynamic.sql.util.kotlin.elements.isNotBetween
fun testFunction() {
countFrom(person) {
where { id (isNotBetween(4).and(null)) }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(10, 41)))
}
@Test
fun `Test That Both Null In Elements Method Causes Compile Error`() {
val source = """
package temp.kotlin.test
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
import org.mybatis.dynamic.sql.util.kotlin.elements.isNotBetween
fun testFunction() {
countFrom(person) {
where { id (isNotBetween<Int>(null).and(null)) }
}
}
"""
val compilerMessageCollector = compile(source)
assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(
ErrorLocation(10, 39),
ErrorLocation(10, 49)
))
}
}
| apache-2.0 | 574f192bd35919dab536ae196b0b2db0 | 35.8 | 102 | 0.617935 | 5.031905 | false | true | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/DurationUnit.kt | 1 | 2135 | package wangdaye.com.geometricweather.common.basic.models.options.unit
import android.content.Context
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum
import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils
import wangdaye.com.geometricweather.common.utils.DisplayUtils
// actual duration = duration(h) * factor.
enum class DurationUnit(
override val id: String,
override val unitFactor: Float
): UnitEnum<Float> {
H("h", 1f);
override val valueArrayId = R.array.duration_unit_values
override val nameArrayId = R.array.duration_units
override val voiceArrayId = R.array.duration_unit_voices
override fun getName(context: Context) = Utils.getName(context, this)
override fun getVoice(context: Context) = Utils.getVoice(context, this)
override fun getValueWithoutUnit(valueInDefaultUnit: Float) = valueInDefaultUnit * unitFactor
override fun getValueInDefaultUnit(valueInCurrentUnit: Float) = valueInCurrentUnit / unitFactor
override fun getValueTextWithoutUnit(
valueInDefaultUnit: Float
) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit, 2)!!
override fun getValueText(
context: Context,
valueInDefaultUnit: Float
) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueText(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getValueText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float
) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getVoiceText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
} | lgpl-3.0 | 2c89746318e7a0492e7e59aeb6ab9e67 | 31.861538 | 99 | 0.712881 | 4.304435 | false | false | false | false |
mtransitapps/parser | src/main/java/org/mtransit/parser/mt/data/MRoute.kt | 1 | 3504 | package org.mtransit.parser.mt.data
import org.mtransit.parser.Constants
import org.mtransit.parser.db.SQLUtils
import kotlin.math.max
data class MRoute(
val id: Long,
val shortName: String?,
var longName: String,
private val color: String?
) : Comparable<MRoute> {
val shortNameOrDefault: String = shortName ?: Constants.EMPTY
fun toFile(): String {
return id.toString() + // ID
Constants.COLUMN_SEPARATOR + //
// (this.shortName == null ? Constants.EMPTY : CleanUtils.escape(this.shortName)) + // short name
SQLUtils.quotes(SQLUtils.escape(shortName ?: Constants.EMPTY)) + // short name
Constants.COLUMN_SEPARATOR + //
// (this.longName == null ? Constants.EMPTY : CleanUtils.escape(this.longName)) + // long name
SQLUtils.quotes(SQLUtils.escape(longName)) + // long name
Constants.COLUMN_SEPARATOR + //
SQLUtils.quotes(color ?: Constants.EMPTY) // color
}
override fun compareTo(other: MRoute): Int {
return id.compareTo(other.id)
}
fun equalsExceptLongName(obj: Any): Boolean {
val o = obj as MRoute
return when {
id != o.id -> false
shortName != o.shortName -> false // not equal
else -> true // mostly equal
}
}
fun mergeLongName(mRouteToMerge: MRoute?): Boolean {
if (mRouteToMerge == null || mRouteToMerge.longName.isEmpty()) {
return true
} else if (longName.isEmpty()) {
longName = mRouteToMerge.longName
return true
} else if (mRouteToMerge.longName.contains(longName)) {
longName = mRouteToMerge.longName
return true
} else if (longName.contains(mRouteToMerge.longName)) {
return true
}
val prefix = longName.commonPrefixWith(mRouteToMerge.longName)
val maxLength = max(longName.length, mRouteToMerge.longName.length)
if (prefix.length > maxLength / 2) {
longName = prefix +
longName.substring(prefix.length) +
SLASH +
mRouteToMerge.longName.substring(prefix.length)
return true
}
val suffix = longName.commonSuffixWith(mRouteToMerge.longName)
if (suffix.length > maxLength / 2) {
longName = longName.substring(0, longName.length - suffix.length) +
SLASH +
mRouteToMerge.longName.substring(0, mRouteToMerge.longName.length - suffix.length) +
suffix
return true
}
return if (longName > mRouteToMerge.longName) {
longName = mRouteToMerge.longName + SLASH + longName
true
} else {
longName = longName + SLASH + mRouteToMerge.longName
true
}
}
@Suppress("unused")
fun simpleMergeLongName(mRouteToMerge: MRoute?): Boolean {
@Suppress("RedundantIf")
return if (mRouteToMerge == null || mRouteToMerge.longName.isEmpty()) {
true
} else if (longName.isEmpty()) {
true
} else if (mRouteToMerge.longName.contains(longName)) {
true
} else if (longName.contains(mRouteToMerge.longName)) {
true
} else {
false // not simple
}
}
companion object {
private const val SLASH = " / "
}
} | apache-2.0 | 37b18776defefc3654f49c6816e16156 | 34.765306 | 113 | 0.574772 | 4.5625 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/activity/AttachActivity.kt | 2 | 4183 | package com.commit451.gitlab.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateDecelerateInterpolator
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.extension.toPart
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.model.api.Project
import kotlinx.android.synthetic.main.activity_attach.*
import pl.aprilapps.easyphotopicker.DefaultCallback
import pl.aprilapps.easyphotopicker.EasyImage
import timber.log.Timber
import java.io.File
/**
* Attaches files
*/
class AttachActivity : BaseActivity() {
companion object {
const val KEY_FILE_UPLOAD_RESPONSE = "response"
private const val KEY_PROJECT = "project"
fun newIntent(context: Context, project: Project): Intent {
val intent = Intent(context, AttachActivity::class.java)
intent.putExtra(KEY_PROJECT, project)
return intent
}
}
private var project: Project? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_attach)
root.setOnClickListener {
onBackPressed()
}
buttonTakePhoto.setOnClickListener {
EasyImage.openCameraForImage(this, 0)
}
buttonChoosePhoto.setOnClickListener {
EasyImage.openGallery(this, 0)
}
buttonChooseFile.setOnClickListener {
EasyImage.openChooserWithDocuments(this, "Choose file", 0)
}
reveal()
project = intent.getParcelableExtra(KEY_PROJECT)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
EasyImage.handleActivityResult(requestCode, resultCode, data, this, object : DefaultCallback() {
override fun onImagePickerError(e: Exception?, source: EasyImage.ImageSource?, type: Int) {
//Some error handling
}
override fun onImagesPicked(imageFiles: List<File>, source: EasyImage.ImageSource, type: Int) {
onPhotoReturned(imageFiles[0])
}
override fun onCanceled(source: EasyImage.ImageSource?, type: Int) {
//Cancel handling, you might wanna remove taken photo if it was canceled
if (source == EasyImage.ImageSource.CAMERA_IMAGE) {
val photoFile = EasyImage.lastlyTakenButCanceledPhoto(this@AttachActivity)
photoFile?.delete()
}
}
})
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.do_nothing, R.anim.fade_out)
}
private fun reveal() {
//Run the runnable after the view has been measured
card.post {
//we need the radius of the animation circle, which is the diagonal of the view
val finalRadius = Math.hypot(card.width.toDouble(), card.height.toDouble()).toFloat()
//it's using a 3rd-party ViewAnimationUtils class for compat reasons (up to API 14)
val animator = ViewAnimationUtils
.createCircularReveal(card, 0, card.height, 0f, finalRadius)
animator.duration = 500
animator.interpolator = AccelerateDecelerateInterpolator()
animator.start()
}
}
fun onPhotoReturned(photo: File) {
progress.visibility = View.VISIBLE
rootButtons.visibility = View.INVISIBLE
photo.toPart()
.flatMap { part -> App.get().gitLab.uploadFile(project!!.id, part) }
.with(this)
.subscribe({
val data = Intent()
data.putExtra(KEY_FILE_UPLOAD_RESPONSE, it)
setResult(Activity.RESULT_OK, data)
finish()
}, {
Timber.e(it)
finish()
})
}
}
| apache-2.0 | b5a2a847d97a43208fe3a9ea00a5d649 | 33.858333 | 107 | 0.631843 | 4.863953 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/MigrationFlags.kt | 1 | 1933 | package eu.kanade.tachiyomi.ui.browse.migration
import eu.kanade.domain.manga.model.Manga
import eu.kanade.domain.manga.model.hasCustomCover
import eu.kanade.domain.track.interactor.GetTracks
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.CoverCache
import kotlinx.coroutines.runBlocking
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
object MigrationFlags {
private const val CHAPTERS = 0b0001
private const val CATEGORIES = 0b0010
private const val TRACK = 0b0100
private const val CUSTOM_COVER = 0b1000
private val coverCache: CoverCache by injectLazy()
private val getTracks: GetTracks = Injekt.get()
val flags get() = arrayOf(CHAPTERS, CATEGORIES, TRACK, CUSTOM_COVER)
fun hasChapters(value: Int): Boolean {
return value and CHAPTERS != 0
}
fun hasCategories(value: Int): Boolean {
return value and CATEGORIES != 0
}
fun hasTracks(value: Int): Boolean {
return value and TRACK != 0
}
fun hasCustomCover(value: Int): Boolean {
return value and CUSTOM_COVER != 0
}
fun getEnabledFlagsPositions(value: Int): List<Int> {
return flags.mapIndexedNotNull { index, flag -> if (value and flag != 0) index else null }
}
fun getFlagsFromPositions(positions: Array<Int>): Int {
return positions.fold(0) { accumulated, position -> accumulated or (1 shl position) }
}
fun titles(manga: Manga?): Array<Int> {
val titles = arrayOf(R.string.chapters, R.string.categories).toMutableList()
if (manga != null) {
if (runBlocking { getTracks.await(manga.id) }.isNotEmpty()) {
titles.add(R.string.track)
}
if (manga.hasCustomCover(coverCache)) {
titles.add(R.string.custom_cover)
}
}
return titles.toTypedArray()
}
}
| apache-2.0 | c26caaaa403c68652dd11502302d0465 | 30.177419 | 98 | 0.669943 | 4.112766 | false | false | false | false |
FlightOfStairs/redesigned-potato | android/src/org/flightofstairs/redesignedPotato/StatBlockFragment.kt | 1 | 5048 | package org.flightofstairs.redesignedPotato
import android.app.Fragment
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.flightofstairs.redesignedPotato.model.AttributeType
import org.flightofstairs.redesignedPotato.model.Attributes
import org.flightofstairs.redesignedPotato.model.MonsterAction
import org.flightofstairs.redesignedPotato.model.MonsterTrait
import org.flightofstairs.redesignedPotato.view.Text
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.slf4j.LoggerFactory
private val MONSTER_NAME_ARGUMENT = "monsterName"
class StatBlockFragment: Fragment() {
companion object {
fun forMonster(monsterName: String) = StatBlockFragment().apply {
arguments = Bundle().apply {
putString(MONSTER_NAME_ARGUMENT, monsterName)
}
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val monsterName = arguments[MONSTER_NAME_ARGUMENT]
if (monsterName == null) {
LoggerFactory.getLogger(StatBlockFragment::class.java).warn("Empty $MONSTER_NAME_ARGUMENT")
return UI { }.view
}
val monster = monsters[monsterName]!! // todo failure handling
return UI {
scrollView {
verticalLayout {
textView(monster.name)
textView("${monster.size} ${monster.type}, ${monster.alignment}")
divider()
property("Armor Class", monster.armorClass.toString())
property("Hit Points", "${monster.hitPoints.average()} (${monster.hitPoints})")
divider()
attributes(monster.attributes)
divider()
property("Saving Throws", monster.saves.map { "${it.attributeType} ${it.modifier}" })
property("Skills", monster.skills.map { "${it.skill} ${it.modifier}" })
property("Damage Resistances", monster.resist)
property("Damage Immunities", monster.immune)
property("Condition Immunities", monster.conditionImmune)
property("Senses", monster.senses)
property("Languages", monster.languages)
property("Challenge", "${monster.challengeRating} (${monster.xp} XP)")
divider()
monster.traits.forEach { trait(it) }
if (monster.actions.isNotEmpty()) {
divider()
textView("Actions")
monster.actions.forEach { action(it, context) }
}
if (monster.legendaries.isNotEmpty()) {
divider()
textView("Legendary Actions")
monster.legendaries.forEach { trait(it) }
}
}
}
}.view
}
private fun ViewGroup.divider() {
linearLayout {
view {
backgroundColor = Color.LTGRAY
}.lparams {
width = matchParent
height = dip(5)
}
}
}
private fun ViewGroup.property(title: String, value: String?) {
if (value == null) return
htmlTextView("<b>$title</b> $value")
}
private fun <X> ViewGroup.property(title: String, values: Collection<X>) {
if (values.isEmpty()) return
property(title, values.joinToString())
}
private fun ViewGroup.attributes(attributes: Attributes) {
linearLayout {
AttributeType.values().forEach {
verticalLayout {
textView(it.name.toUpperCase())
val attribute = attributes.getAttributeOfType(it)
textView("${attribute.score} (${attribute.modifier.number})")
}
}
}
}
private fun ViewGroup.trait(trait: MonsterTrait) {
htmlTextView("<b>${trait.name}</b> ${trait.description}")
}
private fun ViewGroup.action(action: MonsterAction, ctx: Context) {
verticalLayout {
htmlTextView("<b>${action.name}</b> ${action.description}")
onClick {
if (action.attacks.isNotEmpty()) {
val attacksText = Text.rollAttacks(action)
ctx.longToast(attacksText)
}
}
}
}
@SuppressWarnings("deprecation")
fun ViewGroup.htmlTextView(source: String) {
val text = source.replace("\n", "<br />")
val html = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY) else Html.fromHtml(text)
textView(html)
}
}
| mit | 895515a0411b5ed25a7b7f2ea76f1aec | 33.575342 | 143 | 0.573494 | 4.953876 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt | 1 | 4137 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.interaction.actions
import android.os.Bundle
import android.support.wearable.view.GridPagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventWearToMobile
import info.nightscout.androidaps.interaction.utils.EditPlusMinusViewAdapter
import info.nightscout.androidaps.interaction.utils.PlusMinusEditText
import info.nightscout.shared.SafeParse
import info.nightscout.shared.weardata.EventData.ActionProfileSwitchPreCheck
import java.text.DecimalFormat
class ProfileSwitchActivity : ViewSelectorActivity() {
var editPercentage: PlusMinusEditText? = null
var editTimeshift: PlusMinusEditText? = null
var percentage = -1
var timeshift = -25
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
percentage = intent.extras?.getInt("percentage", -1) ?: -1
timeshift = intent.extras?.getInt("timeshift", -25) ?: -25
if (percentage == -1 || timeshift == -25) {
finish()
return
}
if (timeshift < 0) timeshift += 24
setAdapter(MyGridViewPagerAdapter())
}
override fun onPause() {
super.onPause()
finish()
}
private inner class MyGridViewPagerAdapter : GridPagerAdapter() {
override fun getColumnCount(arg0: Int): Int = 3
override fun getRowCount(): Int = 1
override fun instantiateItem(container: ViewGroup, row: Int, col: Int): View = when (col) {
0 -> {
val viewAdapter = EditPlusMinusViewAdapter.getViewAdapter(sp, applicationContext, container, false)
val view = viewAdapter.root
var initValue = SafeParse.stringToDouble(editTimeshift?.editText?.text.toString(), timeshift.toDouble())
editTimeshift = PlusMinusEditText(viewAdapter, initValue, 0.0, 23.0, 1.0, DecimalFormat("0"), true, getString(R.string.action_timeshift), true)
container.addView(view)
view.requestFocus()
view
}
1 -> {
val viewAdapter = EditPlusMinusViewAdapter.getViewAdapter(sp, applicationContext, container, false)
val view = viewAdapter.root
var initValue = SafeParse.stringToDouble(editPercentage?.editText?.text.toString(), percentage.toDouble())
editPercentage = PlusMinusEditText(viewAdapter, initValue, 30.0, 250.0, 1.0, DecimalFormat("0"), false, getString(R.string.action_percentage))
container.addView(view)
view
}
else -> {
val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false)
val confirmButton = view.findViewById<ImageView>(R.id.confirmbutton)
confirmButton.setOnClickListener {
// check if it can happen that the fragment is never created that hold data?
// (you have to swipe past them anyways - but still)
val ps = ActionProfileSwitchPreCheck(SafeParse.stringToInt(editTimeshift?.editText?.text.toString()), SafeParse.stringToInt(editPercentage?.editText?.text.toString()))
rxBus.send(EventWearToMobile(ps))
showToast(this@ProfileSwitchActivity, R.string.action_profile_switch_confirmation)
finishAffinity()
}
container.addView(view)
view
}
}
override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) {
// Handle this to get the data before the view is destroyed?
// Object should still be kept by this, just setup for re-init?
container.removeView(view as View)
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
}
} | agpl-3.0 | 568f6b123498f02b76b43ed316d89f05 | 43.494624 | 187 | 0.648779 | 4.771626 | false | false | false | false |
square/wire | wire-library/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcCall.kt | 1 | 4618 | /*
* Copyright 2019 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.internal
import com.squareup.wire.GrpcCall
import com.squareup.wire.GrpcClient
import com.squareup.wire.GrpcMethod
import com.squareup.wire.GrpcResponse
import com.squareup.wire.use
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Callback
import okhttp3.Response
import okio.IOException
import okio.Timeout
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
internal class RealGrpcCall<S : Any, R : Any>(
private val grpcClient: GrpcClient,
override val method: GrpcMethod<S, R>
) : GrpcCall<S, R> {
/** Non-null once this is executed. */
private var call: Call? = null
private var canceled = false
override val timeout: Timeout = LateInitTimeout()
override var requestMetadata: Map<String, String> = mapOf()
override var responseMetadata: Map<String, String>? = null
private set
override fun cancel() {
canceled = true
call?.cancel()
}
override fun isCanceled(): Boolean = canceled || call?.isCanceled() == true
override suspend fun execute(request: S): R {
val call = initCall(request)
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
override fun onResponse(call: Call, response: GrpcResponse) {
try {
responseMetadata = response.headers.toMap()
val message = response.readExactlyOneAndClose()
continuation.resume(message)
} catch (e: IOException) {
continuation.resumeWithException(e)
}
}
})
}
}
override fun executeBlocking(request: S): R {
val call = initCall(request)
val response = call.execute()
responseMetadata = response.headers.toMap()
return response.readExactlyOneAndClose()
}
override fun enqueue(request: S, callback: GrpcCall.Callback<S, R>) {
val call = initCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(this@RealGrpcCall, e)
}
override fun onResponse(call: Call, response: GrpcResponse) {
try {
responseMetadata = response.headers.toMap()
val message = response.readExactlyOneAndClose()
callback.onSuccess(this@RealGrpcCall, message)
} catch (e: IOException) {
callback.onFailure(this@RealGrpcCall, e)
}
}
})
}
private fun Response.readExactlyOneAndClose(): R {
use {
messageSource(method.responseAdapter).use { reader ->
val result = try {
reader.readExactlyOneAndClose()
} catch (e: IOException) {
throw grpcResponseToException(e)!!
}
val exception = grpcResponseToException()
if (exception != null) throw exception
return result
}
}
}
override fun isExecuted(): Boolean = call?.isExecuted() ?: false
override fun clone(): GrpcCall<S, R> {
val result = RealGrpcCall(grpcClient, method)
val oldTimeout = this.timeout
result.timeout.also { newTimeout ->
newTimeout.timeout(oldTimeout.timeoutNanos(), TimeUnit.NANOSECONDS)
if (oldTimeout.hasDeadline()) newTimeout.deadlineNanoTime(oldTimeout.deadlineNanoTime())
}
result.requestMetadata += this.requestMetadata
return result
}
private fun initCall(request: S): Call {
check(this.call == null) { "already executed" }
val requestBody = newRequestBody(
minMessageToCompress = grpcClient.minMessageToCompress,
requestAdapter = method.requestAdapter,
onlyMessage = request
)
val result = grpcClient.newCall(method, requestMetadata, requestBody)
this.call = result
if (canceled) result.cancel()
(timeout as LateInitTimeout).init(result.timeout())
return result
}
}
| apache-2.0 | 0935f7b7f618fec362fd78fecafb0eb0 | 30.202703 | 94 | 0.686228 | 4.440385 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/main/kotlin/app/ss/media/playback/ui/nowPlaying/NowPlayingDetail.kt | 1 | 6114 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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 app.ss.media.playback.ui.nowPlaying
import android.view.MotionEvent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import app.ss.design.compose.theme.Dimens
import app.ss.media.playback.extensions.isPlaying
import app.ss.media.playback.ui.nowPlaying.components.BoxState
import app.ss.media.playback.ui.nowPlaying.components.CoverImage
import app.ss.media.playback.ui.nowPlaying.components.NowPlayingColumn
import app.ss.media.playback.ui.nowPlaying.components.PlaybackQueueList
import app.ss.media.playback.ui.spec.PlaybackQueueSpec
import app.ss.media.playback.ui.spec.toImageSpec
import app.ss.media.playback.ui.spec.toSpec
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun NowPlayingDetail(
spec: NowPlayingScreenSpec,
boxState: BoxState,
listState: LazyListState,
modifier: Modifier = Modifier
) {
val (nowPlayingAudio, playbackQueue, playbackState, _, playbackConnection, _, isDraggable) = spec
val expanded = boxState == BoxState.Expanded
var imageSize by remember { mutableStateOf(DpSize(0.dp, 0.dp)) }
val alignment = if (expanded) Alignment.TopCenter else Alignment.TopStart
val paddingTop by animateDpAsState(
if (expanded) 64.dp else 0.dp,
animationSpec = spring(
Spring.DampingRatioMediumBouncy,
stiffness = if (expanded) Spring.StiffnessVeryLow else Spring.StiffnessHigh
)
)
val textPaddingTop by animateDpAsState(
targetValue = if (expanded) imageSize.height.plus(16.dp) else
imageSize.height.div(4).minus(16.dp),
animationSpec = if (expanded) tween(50) else spring(
Spring.DampingRatioLowBouncy,
stiffness = Spring.StiffnessLow
)
)
val textPaddingStart by animateDpAsState(targetValue = if (expanded) 0.dp else imageSize.width)
Box(
modifier = modifier
.fillMaxWidth()
.padding(top = 16.dp)
.padding(horizontal = Dimens.grid_4)
.padding(top = paddingTop.coerceAtLeast(0.dp))
) {
CoverImage(
spec = nowPlayingAudio.toImageSpec(),
boxState = boxState,
modifier = Modifier.align(alignment),
heightCallback = {
imageSize = it
}
)
NowPlayingColumn(
spec = nowPlayingAudio.toSpec(),
boxState = boxState,
modifier = Modifier
.padding(
start = textPaddingStart,
top = textPaddingTop.coerceAtLeast(0.dp)
)
.align(alignment)
)
AnimatedVisibility(
visible = !expanded,
enter = fadeIn(spring(stiffness = Spring.StiffnessVeryLow)),
exit = fadeOut(spring(stiffness = Spring.StiffnessHigh))
) {
PlaybackQueueList(
spec = PlaybackQueueSpec(
listState = listState,
queue = playbackQueue.audiosList.map { it.toSpec() },
nowPlayingId = nowPlayingAudio.id,
isPlaying = playbackState.isPlaying,
onPlayAudio = { position ->
playbackConnection.transportControls?.skipToQueueItem(position.toLong())
}
),
modifier = Modifier
.padding(top = imageSize.height.plus(16.dp))
.pointerInteropFilter { event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
if (listState.firstVisibleItemIndex > 0) {
isDraggable(false)
}
}
MotionEvent.ACTION_UP -> {
isDraggable(true)
}
}
false
}
)
}
}
}
| mit | 41bc72cc864130138b447322585d4c17 | 40.033557 | 101 | 0.655708 | 4.825572 | false | false | false | false |
omaraa/ImageSURF | src/main/kotlin/imagesurf/feature/importance/ScrambleFeatureImportanceCalculator.kt | 1 | 2205 | package imagesurf.feature.importance
import imagesurf.classifier.Classifier
import imagesurf.feature.FeatureReader
import imagesurf.util.UtilityKt
import util.UtilityJava
import java.util.*
import java.util.stream.IntStream
class ScrambleFeatureImportanceCalculator(
val random: Random
) : FeatureImportanceCalculator {
constructor(randomSeed: Long) : this(Random(randomSeed))
override fun calculateFeatureImportance(classifier: Classifier, reader: FeatureReader, instanceIndices: IntArray): DoubleArray =
(0 until reader.numFeatures).map { attributeIndex ->
if (attributeIndex == reader.classIndex) java.lang.Double.NaN
else ScrambledFeatureReader(reader, attributeIndex, random.nextLong())
.let{ classifier.classForInstances(it, instanceIndices) }
.mapIndexed {index, predictedClass -> predictedClass == reader.getClassValue(instanceIndices[index])}
.filterNot { it }
.size
.toDouble()
.div(instanceIndices.size)
}.toDoubleArray()
private class ScrambledFeatureReader constructor(
val reader: FeatureReader,
val scrambledIndex: Int,
val randomSeed: Long) : FeatureReader {
val scrambledIndices: IntArray = IntStream.range(0, reader.numInstances).toArray()
.also { UtilityJava.shuffleArray(it, Random(randomSeed)) }
override fun getClassValue(instanceIndex: Int): Int {
return reader.getClassValue(instanceIndex)
}
override fun getValue(instanceIndex: Int, attributeIndex: Int): Double =
if (attributeIndex == scrambledIndex)
reader.getValue(scrambledIndices[instanceIndex], attributeIndex)
else
reader.getValue(instanceIndex, attributeIndex)
override fun getNumInstances(): Int = reader.numInstances
override fun getNumFeatures(): Int = reader.numFeatures
override fun getClassIndex(): Int = reader.classIndex
override fun getNumClasses(): Int = reader.numClasses
}
} | gpl-3.0 | b9dd76189f24a6de721df75b2e33f7c1 | 39.851852 | 132 | 0.655782 | 5.151869 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/tpr/TPRLayerParameters.kt | 1 | 3123 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.tpr
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.LayerParameters
/**
* The parameters of the layer of type TPR.
*
* @property inputSize the input size
* @property nSymbols the number of symbols
* @property dSymbols the embeddings size of the symbols
* @property nRoles the number of roles
* @property dRoles the embeddings size of the roles
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot)
*/
class TPRLayerParameters(
inputSize: Int,
val nSymbols: Int,
val dSymbols: Int,
val nRoles: Int,
val dRoles: Int,
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = GlorotInitializer()
) : LayerParameters(
inputSize = inputSize,
outputSize = dSymbols * dRoles,
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer
) {
companion object {
/**
* Private val used to serialize the class (needed by Serializable)
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The weights connecting input to the Symbol attention vector
*/
val wInS = ParamsArray(this.nSymbols, this.inputSize)
/**
* The weights connecting input to the Role attention vector
*/
val wInR = ParamsArray(this.nRoles, this.inputSize)
/**
* The weights connecting previous output to the Symbol attention vector
*/
val wRecS = ParamsArray(this.nSymbols, this.dRoles * this.dSymbols)
/**
* The weights connecting previous output to the Role attention vector
*/
val wRecR = ParamsArray(this.nRoles, this.dRoles * this.dSymbols)
/**
* The Symbol attention vector bias.
*/
val bS = ParamsArray(this.nSymbols)
/**
* The Role attention vector bias.
*/
val bR = ParamsArray(this.nRoles)
/**
* The Symbol attention embeddings.
*/
val s = ParamsArray(this.dSymbols, this.nSymbols)
/**
* The Role attention embeddings.
*/
val r = ParamsArray(this.dRoles, this.nRoles)
/**
* The list of weights parameters.
*/
override val weightsList: List<ParamsArray> = listOf(
this.wInS,
this.wInR,
this.wRecS,
this.wRecR,
this.s,
this.r
)
/**
* The list of biases parameters.
*/
override val biasesList: List<ParamsArray> = listOf(
this.bS,
this.bR
)
/**
* Initialize all parameters values.
*/
init {
this.initialize()
}
}
| mpl-2.0 | 6af5df74b3db60cecd560dd28795619e | 25.922414 | 92 | 0.691963 | 4.120053 | false | false | false | false |
javadev/moneytostr-russian | src/main/kt/com/github/moneytostr/MoneyToStr.kt | 1 | 41526 | /*
* $Id$
*
* Copyright 2017 Valentyn Kolesnikov
*
* 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.moneytostr
/**
* Converts numbers to symbols.
*
* @author Valentyn Kolesnikov
* @version $Revision$ $Date$
*/
class MoneyToStr {
private val messages = java.util.LinkedHashMap<String, Array<String>>()
private val rubOneUnit: String
private val rubTwoUnit: String
private val rubFiveUnit: String
private val rubSex: String
private val kopOneUnit: String
private val kopTwoUnit: String
private val kopFiveUnit: String
private val kopSex: String
private val rubShortUnit: String
private val currency: Currency
private val language: Language
private val pennies: Pennies
/** Currency. */
enum class Currency {
/**. */
RUR,
/**. */
UAH,
/**. */
USD,
/**. */
PER10,
/**. */
PER100,
/**. */
PER1000,
/**. */
PER10000,
/**. */
Custom
}
/** Language. */
enum class Language {
/**. */
RUS,
/**. */
UKR,
/**. */
ENG
}
/** Pennies. */
enum class Pennies {
/**. */
NUMBER,
/**. */
TEXT
}
/**
* Inits class with currency. Usage: MoneyToStr moneyToStr = new MoneyToStr(
* MoneyToStr.Currency.UAH, MoneyToStr.Language.UKR, MoneyToStr.Pennies.NUMBER);
* Definition for currency is placed into currlist.xml
*
* @param currency the currency (UAH, RUR, USD)
* @param language the language (UKR, RUS, ENG)
* @param pennies the pennies (NUMBER, TEXT)
*/
constructor(currency: Currency?, language: Language?, pennies: Pennies?) {
if (currency == null) {
throw IllegalArgumentException("currency is null")
}
if (language == null) {
throw IllegalArgumentException("language is null")
}
if (pennies == null) {
throw IllegalArgumentException("pennies is null")
}
this.currency = currency
this.language = language
this.pennies = pennies
val theISOstr = currency.name
val languageElement = xmlDoc!!.getElementsByTagName(language.name).item(0) as org.w3c.dom.Element
val items = languageElement.getElementsByTagName("item")
run {
var index = 0
while (index < items.length) {
val languageItem = items.item(index) as org.w3c.dom.Element
messages[languageItem.getAttribute("value")] = languageItem.getAttribute("text").split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
index += 1
}
}
val theISOElements = xmlDoc!!.getElementsByTagName(theISOstr) as org.w3c.dom.NodeList
var theISOElement: org.w3c.dom.Element? = null
var index = 0
while (index < theISOElements.length) {
if ((theISOElements.item(index) as org.w3c.dom.Element).getAttribute("language") == language.name) {
theISOElement = theISOElements.item(index) as org.w3c.dom.Element
break
}
index += 1
}
rubOneUnit = theISOElement!!.getAttribute("RubOneUnit")
rubTwoUnit = theISOElement.getAttribute("RubTwoUnit")
rubFiveUnit = theISOElement.getAttribute("RubFiveUnit")
kopOneUnit = theISOElement.getAttribute("KopOneUnit")
kopTwoUnit = theISOElement.getAttribute("KopTwoUnit")
kopFiveUnit = theISOElement.getAttribute("KopFiveUnit")
rubSex = theISOElement.getAttribute("RubSex")
kopSex = theISOElement.getAttribute("KopSex")
rubShortUnit = if (theISOElement.hasAttribute("RubShortUnit")) theISOElement.getAttribute("RubShortUnit") else ""
}
/**
* Inits class with currency. Usage: MoneyToStr moneyToStr = new MoneyToStr(
* MoneyToStr.Currency.UAH, MoneyToStr.Language.UKR, MoneyToStr.Pennies.NUMBER);
*
* @param currency the currency (UAH, RUR, USD)
* @param language the language (UKR, RUS, ENG)
* @param pennies the pennies (NUMBER, TEXT)
* @param names the custom names
*/
constructor(currency: Currency?, language: Language?, pennies: Pennies?, names: Array<String>?) {
if (currency == null) {
throw IllegalArgumentException("currency is null")
}
if (language == null) {
throw IllegalArgumentException("language is null")
}
if (pennies == null) {
throw IllegalArgumentException("pennies is null")
}
if (names == null || names.size != 8) {
throw IllegalArgumentException("names is null")
}
this.currency = currency
this.language = language
this.pennies = pennies
val languageElement = xmlDoc!!.getElementsByTagName(language.name).item(0) as org.w3c.dom.Element
val items = languageElement.getElementsByTagName("item")
var index = 0
while (index < items.length) {
val languageItem = items.item(index) as org.w3c.dom.Element
messages[languageItem.getAttribute("value")] = languageItem.getAttribute("text").split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
index += 1
}
rubOneUnit = names[0]
rubTwoUnit = names[1]
rubFiveUnit = names[2]
rubSex = names[3]
kopOneUnit = names[4]
kopTwoUnit = names[5]
kopFiveUnit = names[6]
kopSex = names[7]
rubShortUnit = names[0]
}
/**
* Converts double value to the text description.
*
* @param theMoney
* the amount of money in format major.minor
* @return the string description of money value
*/
fun convert(theMoney: Double?): String {
if (theMoney == null) {
throw IllegalArgumentException("theMoney is null")
}
val intPart = theMoney.toLong()
var fractPart: Long? = Math.round((theMoney - intPart) * NUM100)
if (currency == Currency.PER1000) {
fractPart = Math.round((theMoney - intPart) * NUM1000)
}
return convert(intPart, fractPart)
}
/**
* Converts amount to words. Usage: MoneyToStr moneyToStr =
* new MoneyToStr(MoneyToStr.Currency.UAH, MoneyToStr.Language.UKR, MoneyToStr.Pennies.NUMBER);
* String result = moneyToStr.convert(123D); Expected: result = сто двадцять три гривні 00 копійок
*
* @param theMoney
* the amount of money major currency
* @param theKopeiki
* the amount of money minor currency
* @return the string description of money value
*/
fun convert(theMoney: Long?, theKopeiki: Long?): String {
if (theMoney == null) {
throw IllegalArgumentException("theMoney is null")
}
if (theKopeiki == null) {
throw IllegalArgumentException("theKopeiki is null")
}
val money2str = StringBuilder()
var triadNum: Long = 0L
var theTriad: Long?
var intPart: Long = Math.abs(theMoney)
if (intPart == 0L) {
money2str.append(messages["0"]?.get(0) + " ")
}
do {
theTriad = intPart!! % NUM1000
money2str.insert(0, triad2Word(theTriad, triadNum, rubSex))
if (triadNum == 0L) {
if (theTriad % NUM100 / NUM10 == NUM1.toLong()) {
money2str.append(rubFiveUnit)
} else {
when (java.lang.Long.valueOf(theTriad % NUM10)!!.toInt()) {
NUM1 -> money2str.append(rubOneUnit)
NUM2, NUM3, NUM4 -> money2str.append(rubTwoUnit)
else -> money2str.append(rubFiveUnit)
}
}
}
intPart /= NUM1000.toLong()
triadNum += 1
} while (intPart > 0)
if (theMoney < 0) {
money2str.insert(0, messages["minus"]?.get(0) + " ")
}
if (pennies == Pennies.TEXT) {
money2str.append(if (language == Language.ENG) " and " else " ").append(
if (theKopeiki == 0L) messages["0"]?.get(0) + " " else triad2Word(Math.abs(theKopeiki), 0L, kopSex))
} else {
money2str.append(" " + (if (Math.abs(theKopeiki) < 10)
"0" + Math.abs(theKopeiki)
else
Math.abs(theKopeiki)) + " ")
}
if (theKopeiki >= NUM11 && theKopeiki <= NUM14) {
money2str.append(kopFiveUnit)
} else {
when ((theKopeiki % NUM10).toInt()) {
NUM1 -> money2str.append(kopOneUnit)
NUM2, NUM3, NUM4 -> money2str.append(kopTwoUnit)
else -> money2str.append(kopFiveUnit)
}
}
return money2str.toString().trim { it <= ' ' }
}
private fun triad2Word(triad: Long?, triadNum: Long?, sex: String): String {
val triadWord = StringBuilder(NUM100)
if (triad == 0L) {
return ""
}
triadWord.append(concat(arrayOf(""), messages["100_900"]!!)?.get(java.lang.Long.valueOf(triad!! / NUM100)!!.toInt()))
val range10 = triad!! % NUM100 / NUM10
triadWord.append(concat(arrayOf("", ""), messages["20_90"]!!)?.get(range10.toInt()))
if (language == Language.ENG && triadWord.length > 0 && triad!! % NUM10 == 0L) {
triadWord.deleteCharAt(triadWord.length - 1)
triadWord.append(" ")
}
check2(triadNum?.toInt(), sex, triadWord, triad, range10)
when (triadNum!!.toInt()) {
NUM0 -> {
}
NUM1, NUM2, NUM3, NUM4 -> if (range10.toInt() == NUM1) {
triadWord.append(messages["1000_10"]?.get(triadNum.toByte() - 1) + " ")
} else {
val range = triad % NUM10
when (range.toInt()) {
NUM1 -> triadWord.append(messages["1000_1"]?.get(triadNum.toByte() - 1) + " ")
NUM2, NUM3, NUM4 -> triadWord.append(messages["1000_234"]?.get(triadNum.toByte() - 1) + " ")
else -> triadWord.append(messages["1000_5"]?.get(triadNum.toByte() - 1) + " ")
}
}
else -> triadWord.append("??? ")
}
return triadWord.toString()
}
/**
* @param triadNum the triad num
* @param sex the sex
* @param triadWord the triad word
* @param triad the triad
* @param range10 the range 10
*/
private fun check2(triadNum: Int?, sex: String, triadWord: StringBuilder, triad: Long?, range10: Long?) {
val range = triad!! % NUM10
if (range10 == 1L) {
triadWord.append(messages["10_19"]?.get(range.toInt()) + " ")
} else {
when (range.toInt()) {
NUM1 -> if (triadNum == NUM1) {
triadWord.append(messages["1"]?.get(INDEX_0) + " ")
} else if (triadNum == NUM2 || triadNum == NUM3 || triadNum == NUM4) {
triadWord.append(messages["1"]?.get(INDEX_1) + " ")
} else if ("M" == sex) {
triadWord.append(messages["1"]?.get(INDEX_2) + " ")
} else if ("F" == sex) {
triadWord.append(messages["1"]?.get(INDEX_3) + " ")
}
NUM2 -> if (triadNum == NUM1) {
triadWord.append(messages["2"]?.get(INDEX_0) + " ")
} else if (triadNum == NUM2 || triadNum == NUM3 || triadNum == NUM4) {
triadWord.append(messages["2"]?.get(INDEX_1) + " ")
} else if ("M" == sex) {
triadWord.append(messages["2"]?.get(INDEX_2) + " ")
} else if ("F" == sex) {
triadWord.append(messages["2"]?.get(INDEX_3) + " ")
}
NUM3, NUM4, NUM5, NUM6, NUM7, NUM8, NUM9 -> triadWord.append(concat(arrayOf("", "", ""), messages["3_9"]!!)?.get(range.toInt()) + " ")
else -> {
}
}
}
}
private fun concat(first: Array<String>, second: Array<String>): Array<String> {
val result = java.util.Arrays.copyOf(first, first.size + second.size)
System.arraycopy(second, 0, result, first.size, second.size)
return result
}
fun getMessages(): MutableMap<String, Array<String>> {
return messages
}
companion object {
private val INDEX_3 = 3
private val INDEX_2 = 2
private val INDEX_1 = 1
private val INDEX_0 = 0
private var xmlDoc: org.w3c.dom.Document? = null
private val NUM0 = 0
private val NUM1 = 1
private val NUM2 = 2
private val NUM3 = 3
private val NUM4 = 4
private val NUM5 = 5
private val NUM6 = 6
private val NUM7 = 7
private val NUM8 = 8
private val NUM9 = 9
private val NUM10 = 10
private val NUM11 = 11
private val NUM14 = 14
private val NUM100 = 100
private val NUM1000 = 1000
private val NUM10000 = 10000
private val CURRENCY_LIST = (
"<CurrencyList>\n"
+ " \n"
+ " <language value=\"UKR\"/>\n"
+ " <UKR>\n"
+ " <item value=\"minus\" text=\"\u043C\u0456\u043D\u0443\u0441\"/>\n"
+ " <item value=\"0\" text=\"\u043d\u0443\u043b\u044c\"/>\n"
+ " <item value=\"1000_10\" text=\"\u0442\u0438\u0441\u044f\u0447,\u043c\u0456\u043b\u044c\u0439\u043e\u043d\u0456\u0432,\u043c\u0456\u043b\u044c\u044f\u0440\u0434\u0456\u0432,\u0442\u0440\u0438\u043b\u044c\u0439\u043e\u043d\u0456\u0432\"/>\n"
+ " <item value=\"1000_1\" text=\"\u0442\u0438\u0441\u044f\u0447\u0430,\u043c\u0456\u043b\u044c\u0439\u043e\u043d,\u043c\u0456\u043b\u044c\u044f\u0440\u0434,\u0442\u0440\u0438\u043b\u044c\u0439\u043e\u043d\"/>\n"
+ " <item value=\"1000_234\" text=\"\u0442\u0438\u0441\u044f\u0447\u0456,\u043c\u0456\u043b\u044c\u0439\u043e\u043d\u0430,\u043c\u0456\u043b\u044c\u044f\u0440\u0434\u0430,\u0442\u0440\u0438\u043b\u044c\u0439\u043e\u043d\u0430\"/>\n"
+ " <item value=\"1000_5\" text=\"\u0442\u0438\u0441\u044f\u0447,\u043c\u0456\u043b\u044c\u0439\u043e\u043d\u0456\u0432,\u043c\u0456\u043b\u044c\u044f\u0440\u0434\u0456\u0432,\u0442\u0440\u0438\u043b\u044c\u0439\u043e\u043d\u0456\u0432\"/>\n"
+ " <item value=\"10_19\" text=\"\u0434\u0435\u0441\u044f\u0442\u044c,\u043e\u0434\u0438\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0434\u0432\u0430\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0442\u0440\u0438\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0447\u043e\u0442\u0438\u0440\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u043f\u2019\u044f\u0442\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0448i\u0441\u0442\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0441i\u043c\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0432i\u0441i\u043c\u043d\u0430\u0434\u0446\u044f\u0442\u044c,\u0434\u0435\u0432\'\u044f\u0442\u043d\u0430\u0434\u0446\u044f\u0442\u044c\"/>\n"
+ " <item value=\"1\" text=\"\u043e\u0434\u043d\u0430,\u043e\u0434\u0438\u043d,\u043e\u0434\u0438\u043d,\u043e\u0434\u043d\u0430\"/>\n"
+ " <item value=\"2\" text=\"\u0434\u0432\u0456,\u0434\u0432\u0430,\u0434\u0432\u0430,\u0434\u0432\u0456\"/>\n"
+ " <item value=\"3_9\" text=\"\u0442\u0440\u0438,\u0447\u043e\u0442\u0438\u0440\u0438,\u043f\u2019\u044f\u0442\u044c,\u0448\u0456\u0441\u0442\u044c,\u0441\u0456\u043c,\u0432\u0456\u0441\u0456\u043c,\u0434\u0435\u0432\u2019\u044f\u0442\u044c\"/>\n"
+ " <item value=\"100_900\" text=\"\u0441\u0442\u043e ,\u0434\u0432\u0456\u0441\u0442\u0456 ,\u0442\u0440\u0438\u0441\u0442\u0430 ,\u0447\u043e\u0442\u0438\u0440\u0438\u0441\u0442\u0430 ,\u043f\u2019\u044f\u0442\u0441\u043e\u0442 ,\u0448\u0456\u0441\u0442\u0441\u043e\u0442 ,\u0441\u0456\u043c\u0441\u043e\u0442 ,\u0432\u0456\u0441\u0456\u043c\u0441\u043e\u0442 ,\u0434\u0435\u0432\u2019\u044f\u0442\u0441\u043e\u0442 \"/>\n"
+ " <item value=\"20_90\" text=\"\u0434\u0432\u0430\u0434\u0446\u044f\u0442\u044c ,\u0442\u0440\u0438\u0434\u0446\u044f\u0442\u044c ,\u0441\u043e\u0440\u043e\u043a ,\u043f\u2019\u044f\u0442\u0434\u0435\u0441\u044f\u0442 ,\u0448\u0456\u0441\u0442\u0434\u0435\u0441\u044f\u0442 ,\u0441\u0456\u043c\u0434\u0435\u0441\u044f\u0442 ,\u0432\u0456\u0441\u0456\u043c\u0434\u0435\u0441\u044f\u0442 ,\u0434\u0435\u0432\u2019\u044f\u043d\u043e\u0441\u0442\u043e \"/>\n"
+ " <item value=\"pdv\" text=\"\u0432 \u0442.\u0447. \u041f\u0414\u0412 \"/>\n"
+ " <item value=\"pdv_value\" text=\"20\"/>\n"
+ " </UKR>\n"
+ " <RUS>\n"
+ " <item value=\"minus\" text=\"\u043C\u0438\u043D\u0443\u0441\"/>\n"
+ " <item value=\"0\" text=\"\u043d\u043e\u043b\u044c\"/>\n"
+ " <item value=\"1000_10\" text=\"\u0442\u044b\u0441\u044f\u0447,\u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432,\u043c\u0438\u043b\u043b\u0438\u0430\u0440\u0434\u043e\u0432,\u0442\u0440\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432\"/>\n"
+ " <item value=\"1000_1\" text=\"\u0442\u044b\u0441\u044f\u0447\u0430,\u043c\u0438\u043b\u043b\u0438\u043e\u043d,\u043c\u0438\u043b\u043b\u0438\u0430\u0440\u0434,\u0442\u0440\u0438\u043b\u043b\u0438\u043e\u043d\"/>\n"
+ " <item value=\"1000_234\" text=\"\u0442\u044b\u0441\u044f\u0447\u0438,\u043c\u0438\u043b\u043b\u0438\u043e\u043d\u0430,\u043c\u0438\u043b\u043b\u0438\u0430\u0440\u0434\u0430,\u0442\u0440\u0438\u043b\u043b\u0438\u043e\u043d\u0430\"/>\n"
+ " <item value=\"1000_5\" text=\"\u0442\u044b\u0441\u044f\u0447,\u043c\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432,\u043c\u0438\u043b\u043b\u0438\u0430\u0440\u0434\u043e\u0432,\u0442\u0440\u0438\u043b\u043b\u0438\u043e\u043d\u043e\u0432\"/>\n"
+ " <item value=\"10_19\" text=\"\u0434\u0435\u0441\u044f\u0442\u044c,\u043e\u0434\u0438\u043d\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0434\u0432\u0435\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0442\u0440\u0438\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0447\u0435\u0442\u044b\u0440\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u043f\u044f\u0442\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0448\u0435\u0441\u0442\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0441\u0435\u043c\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0432\u043e\u0441\u0435\u043c\u043d\u0430\u0434\u0446\u0430\u0442\u044c,\u0434\u0435\u0432\u044f\u0442\u043d\u0430\u0434\u0446\u0430\u0442\u044c\"/>\n"
+ " <item value=\"1\" text=\"\u043e\u0434\u043d\u0430,\u043e\u0434\u0438\u043d,\u043e\u0434\u0438\u043d,\u043e\u0434\u043d\u0430\"/>\n"
+ " <item value=\"2\" text=\"\u0434\u0432\u0435,\u0434\u0432\u0430,\u0434\u0432\u0430,\u0434\u0432\u0435\"/>\n"
+ " <item value=\"3_9\" text=\"\u0442\u0440\u0438,\u0447\u0435\u0442\u044b\u0440\u0435,\u043f\u044f\u0442\u044c,\u0448\u0435\u0441\u0442\u044c,\u0441\u0435\u043c\u044c,\u0432\u043e\u0441\u0435\u043c\u044c,\u0434\u0435\u0432\u044f\u0442\u044c\"/>\n"
+ " <item value=\"100_900\" text=\"\u0441\u0442\u043e ,\u0434\u0432\u0435\u0441\u0442\u0438 ,\u0442\u0440\u0438\u0441\u0442\u0430 ,\u0447\u0435\u0442\u044b\u0440\u0435\u0441\u0442\u0430 ,\u043f\u044f\u0442\u044c\u0441\u043e\u0442 ,\u0448\u0435\u0441\u0442\u044c\u0441\u043e\u0442 ,\u0441\u0435\u043c\u044c\u0441\u043e\u0442 ,\u0432\u043e\u0441\u0435\u043c\u044c\u0441\u043e\u0442 ,\u0434\u0435\u0432\u044f\u0442\u044c\u0441\u043e\u0442 \"/>\n"
+ " <item value=\"20_90\" text=\"\u0434\u0432\u0430\u0434\u0446\u0430\u0442\u044c ,\u0442\u0440\u0438\u0434\u0446\u0430\u0442\u044c ,\u0441\u043e\u0440\u043e\u043a ,\u043f\u044f\u0442\u044c\u0434\u0435\u0441\u044f\u0442 ,\u0448\u0435\u0441\u0442\u044c\u0434\u0435\u0441\u044f\u0442 ,\u0441\u0435\u043c\u044c\u0434\u0435\u0441\u044f\u0442 ,\u0432\u043e\u0441\u0435\u043c\u044c\u0434\u0435\u0441\u044f\u0442 ,\u0434\u0435\u0432\u044f\u043d\u043e\u0441\u0442\u043e \"/>\n"
+ " <item value=\"pdv\" text=\"\u0432 \u0442.\u0447. \u041d\u0414\u0421 \"/>\n"
+ " <item value=\"pdv_value\" text=\"18\"/>\n"
+ " </RUS>\n"
+ " <ENG>\n"
+ " <item value=\"minus\" text=\"minus\"/>\n"
+ " <item value=\"0\" text=\"zero\"/>\n"
+ " <item value=\"1000_10\" text=\"thousand,million,billion,trillion\"/>\n"
+ " <item value=\"1000_1\" text=\"thousand,million,billion,trillion\"/>\n"
+ " <item value=\"1000_234\" text=\"thousand,million,billion,trillion\"/>\n"
+ " <item value=\"1000_5\" text=\"thousand,million,billion,trillion\"/>\n"
+ " <item value=\"10_19\" text=\"ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen\"/>\n"
+ " <item value=\"1\" text=\"one,one,one,one\"/>\n"
+ " <item value=\"2\" text=\"two,two,two,two\"/>\n"
+ " <item value=\"3_9\" text=\"three,four,five,six,seven,eight,nine\"/>\n"
+ " <item value=\"100_900\" text=\"one hundred ,two hundred ,three hundred ,four hundred ,five hundred ,six hundred ,seven hundred ,eight hundred ,nine hundred \"/>\n"
+ " <item value=\"20_90\" text=\"twenty-,thirty-,forty-,fifty-,sixty-,seventy-,eighty-,ninety-\"/>\n"
+ " <item value=\"pdv\" text=\"including VAT \"/>\n"
+ " <item value=\"pdv_value\" text=\"10\"/>\n"
+ " </ENG>\n"
+ "\n"
+ " <RUR CurrID=\"810\" CurrName=\"\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0438\u0435 \u0440\u0443\u0431\u043b\u0438\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0440\u0443\u0431\u043b\u044c\" RubTwoUnit=\"\u0440\u0443\u0431\u043b\u044f\" RubFiveUnit=\"\u0440\u0443\u0431\u043b\u0435\u0439\" RubSex=\"M\" RubShortUnit=\"\u0440\u0443\u0431.\"\n"
+ " KopOneUnit=\"\u043a\u043e\u043f\u0435\u0439\u043a\u0430\" KopTwoUnit=\"\u043a\u043e\u043f\u0435\u0439\u043a\u0438\" KopFiveUnit=\"\u043a\u043e\u043f\u0435\u0435\u043a\" KopSex=\"F\"\n"
+ " />\n"
+ " <UAH CurrID=\"980\" CurrName=\"\u0423\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0456 \u0433\u0440\u0438\u0432\u043d\u0456\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0433\u0440\u0438\u0432\u043d\u044f\" RubTwoUnit=\"\u0433\u0440\u0438\u0432\u043d\u0438\" RubFiveUnit=\"\u0433\u0440\u0438\u0432\u0435\u043d\u044c\" RubSex=\"F\" RubShortUnit=\"\u0433\u0440\u043d.\"\n"
+ " KopOneUnit=\"\u043a\u043e\u043f\u0435\u0439\u043a\u0430\" KopTwoUnit=\"\u043a\u043e\u043f\u0435\u0439\u043a\u0438\" KopFiveUnit=\"\u043a\u043e\u043f\u0435\u0435\u043a\" KopSex=\"F\"\n"
+ " />\n"
+ " <USD CurrID=\"840\" CurrName=\"\u0414\u043e\u043b\u0430\u0440\u0438 \u0421\u0428\u0410\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0434\u043e\u043b\u043b\u0430\u0440\" RubTwoUnit=\"\u0434\u043e\u043b\u043b\u0430\u0440\u0430\" RubFiveUnit=\"\u0434\u043e\u043b\u043b\u0430\u0440\u043e\u0432\" RubSex=\"M\" RubShortUnit=\"\u0434\u043e\u043b.\"\n"
+ " KopOneUnit=\"\u0446\u0435\u043d\u0442\" KopTwoUnit=\"\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0446\u0435\u043d\u0442\u043e\u0432\" KopSex=\"M\"\n"
+ " />\n"
+ "\n"
+ " <RUR CurrID=\"810\" CurrName=\"\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0438\u0435 \u0440\u0443\u0431\u043b\u0438\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0440\u0443\u0431\u043b\u044c\" RubTwoUnit=\"\u0440\u0443\u0431\u043b\u0456\" RubFiveUnit=\"\u0440\u0443\u0431\u043b\u0456\u0432\" RubSex=\"M\" RubShortUnit=\"\u0440\u0443\u0431.\"\n"
+ " KopOneUnit=\"\u043a\u043e\u043f\u0456\u0439\u043a\u0430\" KopTwoUnit=\"\u043a\u043e\u043f\u0456\u0439\u043a\u0438\" KopFiveUnit=\"\u043a\u043e\u043f\u0456\u0439\u043e\u043a\" KopSex=\"F\"\n"
+ " /> \n"
+ " <UAH CurrID=\"980\" CurrName=\"\u0423\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0456 \u0433\u0440\u0438\u0432\u043d\u0456\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0433\u0440\u0438\u0432\u043d\u044f\" RubTwoUnit=\"\u0433\u0440\u0438\u0432\u043d\u0456\" RubFiveUnit=\"\u0433\u0440\u0438\u0432\u0435\u043d\u044c\" RubSex=\"F\" RubShortUnit=\"\u0433\u0440\u043d.\"\n"
+ " KopOneUnit=\"\u043a\u043e\u043f\u0456\u0439\u043a\u0430\" KopTwoUnit=\"\u043a\u043e\u043f\u0456\u0439\u043a\u0438\" KopFiveUnit=\"\u043a\u043e\u043f\u0456\u0439\u043e\u043a\" KopSex=\"F\"\n"
+ " />\n"
+ " <USD CurrID=\"840\" CurrName=\"\u0414\u043e\u043b\u0430\u0440\u0438 \u0421\u0428\u0410\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0434\u043e\u043b\u0430\u0440\" RubTwoUnit=\"\u0434\u043e\u043b\u0430\u0440\u0430\" RubFiveUnit=\"\u0434\u043e\u043b\u0430\u0440\u0456\u0432\" RubSex=\"M\" RubShortUnit=\"\u0434\u043e\u043b.\"\n"
+ " KopOneUnit=\"\u0446\u0435\u043d\u0442\" KopTwoUnit=\"\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0446\u0435\u043d\u0442\u0456\u0432\" KopSex=\"M\"\n"
+ " />\n"
+ "\n"
+ " <RUR CurrID=\"810\" CurrName=\"\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u0438\u0435 \u0440\u0443\u0431\u043b\u0438\" language=\"ENG\"\n"
+ " RubOneUnit=\"ruble\" RubTwoUnit=\"rubles\" RubFiveUnit=\"rubles\" RubSex=\"M\" RubShortUnit=\"RUR.\"\n"
+ " KopOneUnit=\"kopeck\" KopTwoUnit=\"kopecks\" KopFiveUnit=\"kopecks\" KopSex=\"M\"\n"
+ " /> \n"
+ " <UAH CurrID=\"980\" CurrName=\"\u0423\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0456 \u0433\u0440\u0438\u0432\u043d\u0456\" language=\"ENG\"\n"
+ " RubOneUnit=\"hryvnia\" RubTwoUnit=\"hryvnias\" RubFiveUnit=\"hryvnias\" RubSex=\"M\" RubShortUnit=\"UAH.\"\n"
+ " KopOneUnit=\"kopeck\" KopTwoUnit=\"kopecks\" KopFiveUnit=\"kopecks\" KopSex=\"M\"\n"
+ " />\n"
+ " <USD CurrID=\"840\" CurrName=\"\u0414\u043e\u043b\u0430\u0440\u0438 \u0421\u0428\u0410\" language=\"ENG\"\n"
+ " RubOneUnit=\"dollar\" RubTwoUnit=\"dollars\" RubFiveUnit=\"dollars\" RubSex=\"M\" RubShortUnit=\"USD.\"\n"
+ " KopOneUnit=\"cent\" KopTwoUnit=\"cents\" KopFiveUnit=\"cents\" KopSex=\"M\"\n"
+ " />\n"
+ "\n"
+ " <PER10 CurrID=\"556\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0446\u0435\u043b\u0430\u044f,\" RubTwoUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubFiveUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0434\u0435\u0441\u044f\u0442\u0430\u044f \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopTwoUnit=\"\u0434\u0435\u0441\u044f\u0442\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0434\u0435\u0441\u044f\u0442\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER100 CurrID=\"557\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0441\u043e\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0446\u0435\u043b\u0430\u044f,\" RubTwoUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubFiveUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0441\u043e\u0442\u0430\u044f \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopTwoUnit=\"\u0441\u043e\u0442\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0441\u043e\u0442\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER1000 CurrID=\"558\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0446\u0435\u043b\u0430\u044f,\" RubTwoUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubFiveUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0442\u044b\u0441\u044f\u0447\u043d\u0430\u044f \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopTwoUnit=\"\u0442\u044b\u0441\u044f\u0447\u043d\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0442\u044b\u0441\u044f\u0447\u043d\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER10000 CurrID=\"559\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"RUS\"\n"
+ " RubOneUnit=\"\u0446\u0435\u043b\u0430\u044f,\" RubTwoUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubFiveUnit=\"\u0446\u0435\u043b\u044b\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u044b\u0441\u044f\u0447\u043d\u0430\u044f \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopTwoUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u044b\u0441\u044f\u0447\u043d\u044b\u0435 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopFiveUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u044b\u0441\u044f\u0447\u043d\u044b\u0445 \u043f\u0440\u043e\u0446\u0435\u043d\u0442\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER10 CurrID=\"556\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0446\u0456\u043b\u0430,\" RubTwoUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubFiveUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0434\u0435\u0441\u044f\u0442\u0430 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopTwoUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopFiveUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER100 CurrID=\"557\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0441\u043e\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0446\u0456\u043b\u0430,\" RubTwoUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubFiveUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0441\u043e\u0442\u0430 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopTwoUnit=\"\u0441\u043e\u0442\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopFiveUnit=\"\u0441\u043e\u0442\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER1000 CurrID=\"558\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0446\u0456\u043b\u0430,\" RubTwoUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubFiveUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0442\u0438\u0441\u044f\u0447\u043d\u0430 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopTwoUnit=\"\u0442\u0438\u0441\u044f\u0447\u043d\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopFiveUnit=\"\u0442\u0438\u0441\u044f\u0447\u043d\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER10000 CurrID=\"559\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"UKR\"\n"
+ " RubOneUnit=\"\u0446\u0456\u043b\u0430,\" RubTwoUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubFiveUnit=\"\u0446\u0456\u043b\u0438\u0445,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u0438\u0441\u044f\u0447\u043d\u0430 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopTwoUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u0438\u0441\u044f\u0447\u043d\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopFiveUnit=\"\u0434\u0435\u0441\u044f\u0442\u0438\u0442\u0438\u0441\u044f\u0447\u043d\u0438\u0445 \u0432\u0456\u0434\u0441\u043e\u0442\u043a\u0430\" KopSex=\"M\"\n"
+ " />\n"
+ "\n"
+ " <PER10 CurrID=\"560\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"ENG\"\n"
+ " RubOneUnit=\",\" RubTwoUnit=\"integers,\" RubFiveUnit=\"integers,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"tenth of one percent\" KopTwoUnit=\"tenth of one percent\" KopFiveUnit=\"tenth of one percent\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER100 CurrID=\"561\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0441\u043e\u0442\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"ENG\"\n"
+ " RubOneUnit=\",\" RubTwoUnit=\"integers,\" RubFiveUnit=\"integers,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"hundred percent\" KopTwoUnit=\"hundredth of percent\" KopFiveUnit=\"hundredth of percent\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER1000 CurrID=\"562\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"ENG\"\n"
+ " RubOneUnit=\",\" RubTwoUnit=\"integers,\" RubFiveUnit=\"integers,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"thousandth of percent\" KopTwoUnit=\"thousandths of percent\" KopFiveUnit=\"thousandths of percent\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ " <PER10000 CurrID=\"563\" CurrName=\"\u0412i\u0434\u0441\u043e\u0442\u043a\u0438 \u0437 \u0434\u0435\u0441\u044f\u0442\u0438 \u0442\u0438\u0441\u044f\u0447\u043d\u0438\u043c\u0438 \u0447\u0430\u0441\u0442\u0438\u043d\u0430\u043c\u0438\" language=\"ENG\"\n"
+ " RubOneUnit=\",\" RubTwoUnit=\"integers,\" RubFiveUnit=\"integers,\" RubSex=\"F\"\n"
+ " KopOneUnit=\"ten percent\" KopTwoUnit=\"ten-percent\" KopFiveUnit=\"ten-percent\" KopSex=\"F\"\n"
+ " />\n"
+ "\n"
+ "</CurrencyList>\n")
init {
initXmlDoc(CURRENCY_LIST)
}
fun initXmlDoc(xmlData: String) {
val docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance()
try {
val xmlDocBuilder = docFactory.newDocumentBuilder()
xmlDoc = xmlDocBuilder.parse(java.io.ByteArrayInputStream(xmlData.toByteArray(charset("UTF8"))))
} catch (ex: Exception) {
throw UnsupportedOperationException(ex)
}
}
/**
* Converts percent to string.
* @param amount the amount of percent
* @param lang the language (RUS, UKR, ENG)
* @param pennies the pennies (NUMBER, TEXT)
* @return the string of percent
*/
@JvmOverloads
fun percentToStr(amount: Double?, lang: Language?, pennies: Pennies? = Pennies.TEXT): String {
if (amount == null) {
throw IllegalArgumentException("amount is null")
}
if (lang == null) {
throw IllegalArgumentException("language is null")
}
if (pennies == null) {
throw IllegalArgumentException("pennies is null")
}
val intPart = amount.toLong()
var fractPart: Long? = 0L
val result: String
if (amount.toFloat() == amount.toInt().toFloat()) {
result = MoneyToStr(Currency.PER10, lang, pennies).convert(amount.toLong(), 0L)
} else if (java.lang.Double.valueOf(amount * NUM10).toFloat() == java.lang.Double.valueOf(amount * NUM10).toInt().toFloat()) {
fractPart = Math.round((amount - intPart) * NUM10)
result = MoneyToStr(Currency.PER10, lang, pennies).convert(intPart, fractPart)
} else if (java.lang.Double.valueOf(amount * NUM100).toFloat() == java.lang.Double.valueOf(amount * NUM100).toInt().toFloat()) {
fractPart = Math.round((amount - intPart) * NUM100)
result = MoneyToStr(Currency.PER100, lang, pennies).convert(intPart, fractPart)
} else if (java.lang.Double.valueOf(amount * NUM1000).toFloat() == java.lang.Double.valueOf(amount * NUM1000).toInt().toFloat()) {
fractPart = Math.round((amount - intPart) * NUM1000)
result = MoneyToStr(Currency.PER1000, lang, pennies).convert(intPart, fractPart)
} else {
fractPart = Math.round((amount - intPart) * NUM10000)
result = MoneyToStr(Currency.PER10000, lang, pennies).convert(intPart, fractPart)
}
return result
}
@JvmStatic
fun main(args: Array<String>) {
var amount = "123.25"
var language = "ENG"
var currency = "USD"
var pennies = "TEXT"
if (args.size == 0) {
println("Usage: java -jar moneytostr.jar --amount=123.25 --language=rus|ukr|eng --currency=rur|uah|usd --pennies=text|number")
} else {
for (arg in args) {
if (arg.startsWith("--amount=")) {
amount = arg.substring("--amount=".length).trim { it <= ' ' }.replace(",", ".")
} else if (arg.startsWith("--language=")) {
language = arg.substring("--language=".length).trim { it <= ' ' }.toUpperCase()
} else if (arg.startsWith("--currency=")) {
currency = arg.substring("--currency=".length).trim { it <= ' ' }.toUpperCase()
} else if (arg.startsWith("--pennies=")) {
pennies = arg.substring("--pennies=".length).trim { it <= ' ' }.toUpperCase()
}
}
val result = MoneyToStr(Currency.valueOf(currency), Language.valueOf(language), Pennies.valueOf(pennies)).convert(
java.lang.Double.valueOf(amount))
println(result)
}
}
}
}
| apache-2.0 | 2ca945a4cf6092b11d40677217c3a9a2 | 68.049917 | 697 | 0.584135 | 2.639382 | false | false | false | false |
android/play-billing-samples | PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/Constants.kt | 2 | 1302 | /*
* Copyright 2022 Google, 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
*
* 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.sample.subscriptionscodelab
/**
* Constants used by multiple classes.
*/
object Constants {
// Billing Client ProductDetails Offer Tags
const val MONTHLY_BASIC_PLANS_TAG = "monthlyBasic"
const val MONTHLY_PREMIUM_PLANS_TAG = "monthlyPremium"
const val YEARLY_BASIC_PLANS_TAG = "yearlyBasic"
const val PREPAID_BASIC_PLANS_TAG = "prepaidbasic"
const val YEARLY_PREMIUM_PLANS_TAG = "yearlyPremium"
const val PREPAID_PREMIUM_PLANS_TAG = "prepaidpremium"
// Compose Navigation route Strings
const val SUBSCRIPTION_ROUTE = "subscription"
const val BASIC_BASE_PLANS_ROUTE = "basicBasePlans"
const val PREMIUM_BASE_PLANS_ROUTE = "premiumBasePlans"
}
| apache-2.0 | 450bd8f082ad7d0c7e67557ab6ac40d3 | 34.189189 | 75 | 0.734255 | 3.875 | false | false | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/handler/TransferHelperHandler.kt | 1 | 955 | package com.janyo.janyoshare.handler
import android.content.Context
import android.os.Handler
import android.os.Message
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.adapter.FileTransferAdapter
import com.janyo.janyoshare.classes.TransferFile
class TransferHelperHandler : Handler()
{
lateinit var adapter: FileTransferAdapter
var list = ArrayList<TransferFile>()
override fun handleMessage(msg: Message)
{
when (msg.what)
{
UPDATE_UI ->
{
adapter.notifyDataSetChanged()
}
UPDATE_TOAST ->
{
@Suppress("UNCHECKED_CAST")
val map = msg.obj as HashMap<String, Any>
val context = map["context"] as Context
Toast.makeText(context, context.getString(R.string.hint_transfer_file_notification_done, map["fileName"].toString()), Toast.LENGTH_SHORT)
.show()
adapter.notifyDataSetChanged()
}
}
}
companion object
{
val UPDATE_UI = 1
val UPDATE_TOAST = 2
}
} | gpl-3.0 | a1a3ee2b442c1b3c205d674a403a6483 | 22.317073 | 141 | 0.729843 | 3.550186 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/common/BasePermissionsActivity.kt | 1 | 1171 | package csumissu.weatherforecast.common
import android.content.pm.PackageManager
import csumissu.weatherforecast.extensions.requirePermissions
/**
* @author yxsun
* @since 08/06/2017
*/
abstract class BasePermissionsActivity : BaseActivity() {
abstract fun requiredPermissions(): Array<String>
abstract fun onPermissionsResult(acquired: Boolean)
override fun onStart() {
super.onStart()
if (!requirePermissions(requiredPermissions(), REQUEST_PERMISSIONS_CODE)) {
onPermissionsResult(true)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_PERMISSIONS_CODE) {
onPermissionsResult(checkGrantResults(grantResults))
}
}
private fun checkGrantResults(grantResults: IntArray): Boolean {
return grantResults.all { it == PackageManager.PERMISSION_GRANTED }
}
companion object {
private val REQUEST_PERMISSIONS_CODE = 111
}
} | mit | 5a0da9acea49aeb4842d312104abdc85 | 28.3 | 93 | 0.685739 | 5.251121 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/plugin/test/org/jetbrains/kotlin/idea/artifacts/KotlinNativeVersion.kt | 1 | 2108 | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.artifacts
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.exists
import org.jetbrains.kotlin.konan.file.unzipTo
import java.io.File
import java.io.FileInputStream
import java.nio.file.Paths
import java.util.*
object KotlinNativeVersion {
/** This field is automatically setup from project-module-updater.
* See [org.jetbrains.tools.model.updater.updateKGPVersionForKotlinNativeTests]
*/
private const val kotlinGradlePluginVersion: String = "1.8.20-dev-1438"
/** Return bootstrap version or version from properties file of specified Kotlin Gradle Plugin.
* Make sure localMaven has kotlin-gradle-plugin with required version for cooperative development environment.
*/
val resolvedKotlinNativeVersion: String by lazy { getKotlinNativeVersionFromKotlinGradlePluginPropertiesFile() }
private fun getKotlinNativeVersionFromKotlinGradlePluginPropertiesFile(): String {
val outputPath = Paths.get(PathManager.getCommunityHomePath()).resolve("out")
.resolve("kotlin-gradle-plugin")
.resolve(kotlinGradlePluginVersion)
if (!outputPath.exists()) {
File(outputPath.toString()).mkdirs()
}
val propertiesPath = outputPath.resolve("project.properties")
if (!propertiesPath.exists()) {
val localRepository = File(FileUtil.getTempDirectory()).toPath()
val kotlinGradlePluginPath = KotlinGradlePluginDownloader.downloadKotlinGradlePlugin(kotlinGradlePluginVersion, localRepository)
kotlinGradlePluginPath.unzipTo(outputPath)
}
val propertiesFromKGP = Properties()
FileInputStream(propertiesPath.toFile()).use { propertiesFromKGP.load(it) }
return propertiesFromKGP.getProperty("kotlin.native.version")
}
} | apache-2.0 | 774ab50045e4ca73fec21e5816f84c9a | 42.9375 | 140 | 0.744307 | 4.758465 | false | false | false | false |
GunoH/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PySpecialMethodNamesCompletionContributor.kt | 9 | 2779 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.openapi.project.DumbAware
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyNames.PREPARE
import com.jetbrains.python.extensions.afterDefInFunction
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.types.TypeEvalContext
class PySpecialMethodNamesCompletionContributor : CompletionContributor(), DumbAware {
override fun handleAutoCompletionPossibility(context: AutoCompletionContext): AutoCompletionDecision = autoInsertSingleItem(context)
init {
extend(CompletionType.BASIC, PlatformPatterns.psiElement().afterDefInFunction(), MyCompletionProvider)
}
private object MyCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val typeEvalContext = parameters.getTypeEvalContext()
val pyClass = parameters.getPyClass()
if (pyClass != null) {
PyNames.getBuiltinMethods(LanguageLevel.forElement(pyClass))
?.forEach {
val name = it.key
val signature = it.value.signature
if (name == PREPARE) {
handlePrepare(result, pyClass, typeEvalContext, signature)
}
else {
addMethodToResult(result, pyClass, typeEvalContext, name, signature) { it.withTypeText("predefined") }
}
}
}
else {
val file = parameters.getFile()
if (file != null) {
PyNames
.getModuleBuiltinMethods(LanguageLevel.forElement(file))
.forEach {
addFunctionToResult(result, file as? PyFile, it.key, it.value.signature) {
it.withTypeText("predefined")
}
}
}
}
}
private fun handlePrepare(result: CompletionResultSet, pyClass: PyClass, context: TypeEvalContext, signature: String) {
addMethodToResult(result, pyClass, context, PREPARE, signature) {
it.withTypeText("predefined")
it.withInsertHandler { context, _ ->
val function = PsiTreeUtil.getParentOfType(context.file.findElementAt(context.startOffset), PyFunction::class.java)
if (function != null && function.modifier != PyFunction.Modifier.CLASSMETHOD) {
PyUtil.addDecorator(function, "@${PyNames.CLASSMETHOD}")
}
}
}
}
}
}
| apache-2.0 | bbe8e065aba509d0cdb812b478b9a29e | 39.867647 | 140 | 0.694494 | 4.953654 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsViewModel.kt | 1 | 6985 | package org.thoughtcrime.securesms.components.settings.app.privacy.advanced
import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint
import org.thoughtcrime.securesms.jobs.RefreshAttributesJob
import org.thoughtcrime.securesms.jobs.RefreshOwnProfileJob
import org.thoughtcrime.securesms.keyvalue.SettingsValues
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter
import org.thoughtcrime.securesms.util.SingleLiveEvent
import org.thoughtcrime.securesms.util.TextSecurePreferences
import org.thoughtcrime.securesms.util.livedata.Store
import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState
class AdvancedPrivacySettingsViewModel(
private val sharedPreferences: SharedPreferences,
private val repository: AdvancedPrivacySettingsRepository
) : ViewModel() {
private val store = Store(getState())
private val singleEvents = SingleLiveEvent<Event>()
val state: LiveData<AdvancedPrivacySettingsState> = store.stateLiveData
val events: LiveData<Event> = singleEvents
val disposables: CompositeDisposable = CompositeDisposable()
init {
disposables.add(
ApplicationDependencies.getSignalWebSocket().webSocketState
.observeOn(AndroidSchedulers.mainThread())
.subscribe { refresh() }
)
}
fun disablePushMessages() {
store.update { getState().copy(showProgressSpinner = true) }
repository.disablePushMessages {
when (it) {
AdvancedPrivacySettingsRepository.DisablePushMessagesResult.SUCCESS -> {
SignalStore.account().setRegistered(false)
SignalStore.registrationValues().clearRegistrationComplete()
SignalStore.registrationValues().clearHasUploadedProfile()
}
AdvancedPrivacySettingsRepository.DisablePushMessagesResult.NETWORK_ERROR -> {
singleEvents.postValue(Event.DISABLE_PUSH_FAILED)
}
}
store.update { getState().copy(showProgressSpinner = false) }
}
}
fun setAlwaysRelayCalls(enabled: Boolean) {
sharedPreferences.edit().putBoolean(TextSecurePreferences.ALWAYS_RELAY_CALLS_PREF, enabled).apply()
refresh()
}
fun setShowStatusIconForSealedSender(enabled: Boolean) {
sharedPreferences.edit().putBoolean(TextSecurePreferences.SHOW_UNIDENTIFIED_DELIVERY_INDICATORS, enabled).apply()
repository.syncShowSealedSenderIconState()
refresh()
}
fun setAllowSealedSenderFromAnyone(enabled: Boolean) {
sharedPreferences.edit().putBoolean(TextSecurePreferences.UNIVERSAL_UNIDENTIFIED_ACCESS, enabled).apply()
ApplicationDependencies.getJobManager().startChain(RefreshAttributesJob()).then(RefreshOwnProfileJob()).enqueue()
refresh()
}
fun setCensorshipCircumventionEnabled(enabled: Boolean) {
SignalStore.settings().setCensorshipCircumventionEnabled(enabled)
SignalStore.misc().isServiceReachableWithoutCircumvention = false
ApplicationDependencies.resetNetworkConnectionsAfterProxyChange()
refresh()
}
fun refresh() {
store.update { getState().copy(showProgressSpinner = it.showProgressSpinner) }
}
override fun onCleared() {
disposables.dispose()
}
private fun getState(): AdvancedPrivacySettingsState {
val censorshipCircumventionState = getCensorshipCircumventionState()
return AdvancedPrivacySettingsState(
isPushEnabled = SignalStore.account().isRegistered,
alwaysRelayCalls = TextSecurePreferences.isTurnOnly(ApplicationDependencies.getApplication()),
censorshipCircumventionState = censorshipCircumventionState,
censorshipCircumventionEnabled = getCensorshipCircumventionEnabled(censorshipCircumventionState),
showSealedSenderStatusIcon = TextSecurePreferences.isShowUnidentifiedDeliveryIndicatorsEnabled(
ApplicationDependencies.getApplication()
),
allowSealedSenderFromAnyone = TextSecurePreferences.isUniversalUnidentifiedAccess(
ApplicationDependencies.getApplication()
),
false
)
}
private fun getCensorshipCircumventionState(): CensorshipCircumventionState {
val countryCode: Int = PhoneNumberFormatter.getLocalCountryCode()
val isCountryCodeCensoredByDefault: Boolean = ApplicationDependencies.getSignalServiceNetworkAccess().isCountryCodeCensoredByDefault(countryCode)
val enabledState: SettingsValues.CensorshipCircumventionEnabled = SignalStore.settings().censorshipCircumventionEnabled
val hasInternet: Boolean = NetworkConstraint.isMet(ApplicationDependencies.getApplication())
val websocketConnected: Boolean = ApplicationDependencies.getSignalWebSocket().webSocketState.firstOrError().blockingGet() == WebSocketConnectionState.CONNECTED
return when {
SignalStore.internalValues().allowChangingCensorshipSetting() -> {
CensorshipCircumventionState.AVAILABLE
}
isCountryCodeCensoredByDefault && enabledState == SettingsValues.CensorshipCircumventionEnabled.DISABLED -> {
CensorshipCircumventionState.AVAILABLE_MANUALLY_DISABLED
}
isCountryCodeCensoredByDefault -> {
CensorshipCircumventionState.AVAILABLE_AUTOMATICALLY_ENABLED
}
!hasInternet && enabledState != SettingsValues.CensorshipCircumventionEnabled.ENABLED -> {
CensorshipCircumventionState.UNAVAILABLE_NO_INTERNET
}
websocketConnected && enabledState != SettingsValues.CensorshipCircumventionEnabled.ENABLED -> {
CensorshipCircumventionState.UNAVAILABLE_CONNECTED
}
else -> {
CensorshipCircumventionState.AVAILABLE
}
}
}
private fun getCensorshipCircumventionEnabled(state: CensorshipCircumventionState): Boolean {
return when (state) {
CensorshipCircumventionState.UNAVAILABLE_CONNECTED,
CensorshipCircumventionState.UNAVAILABLE_NO_INTERNET,
CensorshipCircumventionState.AVAILABLE_MANUALLY_DISABLED -> {
false
}
CensorshipCircumventionState.AVAILABLE_AUTOMATICALLY_ENABLED -> {
true
}
else -> {
SignalStore.settings().censorshipCircumventionEnabled == SettingsValues.CensorshipCircumventionEnabled.ENABLED
}
}
}
enum class Event {
DISABLE_PUSH_FAILED
}
class Factory(
private val sharedPreferences: SharedPreferences,
private val repository: AdvancedPrivacySettingsRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return requireNotNull(
modelClass.cast(
AdvancedPrivacySettingsViewModel(
sharedPreferences,
repository
)
)
)
}
}
}
| gpl-3.0 | 9b996f2bc4b7f20ad75842bfab8af527 | 39.143678 | 164 | 0.772942 | 5.094821 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/core/serialize/gson/RawCardGsonTypeAdapterFactory.kt | 1 | 3848 | /*
* RawCardGsonTypeAdapterFactory.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[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 com.codebutler.farebot.app.core.serialize.gson
import com.codebutler.farebot.app.core.sample.RawSampleCard
import com.codebutler.farebot.card.CardType
import com.codebutler.farebot.card.RawCard
import com.codebutler.farebot.card.cepas.raw.RawCEPASCard
import com.codebutler.farebot.card.classic.raw.RawClassicCard
import com.codebutler.farebot.card.desfire.raw.RawDesfireCard
import com.codebutler.farebot.card.felica.raw.RawFelicaCard
import com.codebutler.farebot.card.ultralight.raw.RawUltralightCard
import com.google.gson.Gson
import com.google.gson.JsonPrimitive
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.internal.Streams
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import java.util.HashMap
class RawCardGsonTypeAdapterFactory : TypeAdapterFactory {
companion object {
private val KEY_CARD_TYPE = "cardType"
private val CLASSES = mapOf(
CardType.MifareDesfire to RawDesfireCard::class.java,
CardType.MifareClassic to RawClassicCard::class.java,
CardType.MifareUltralight to RawUltralightCard::class.java,
CardType.CEPAS to RawCEPASCard::class.java,
CardType.FeliCa to RawFelicaCard::class.java,
CardType.Sample to RawSampleCard::class.java)
}
@Suppress("UNCHECKED_CAST")
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
if (!RawCard::class.java.isAssignableFrom(type.rawType)) {
return null
}
val delegates = HashMap<CardType, TypeAdapter<RawCard<*>>>()
for ((key, value) in CLASSES) {
delegates.put(key, gson.getDelegateAdapter(this, TypeToken.get(value) as TypeToken<RawCard<*>>))
}
return RawCardTypeAdapter(delegates) as TypeAdapter<T>
}
private class RawCardTypeAdapter internal constructor(
private val delegates: Map<CardType, TypeAdapter<RawCard<*>>>
) : TypeAdapter<RawCard<*>>() {
override fun write(out: JsonWriter, value: RawCard<*>) {
val delegateAdapter = delegates[value.cardType()]
?: throw IllegalArgumentException("Unknown type: ${value.cardType()}")
val jsonObject = delegateAdapter.toJsonTree(value).asJsonObject
jsonObject.add(KEY_CARD_TYPE, JsonPrimitive(value.cardType().name))
Streams.write(jsonObject, out)
}
override fun read(inJsonReader: JsonReader): RawCard<*> {
val rootElement = Streams.parse(inJsonReader)
val typeElement = rootElement.asJsonObject.remove(KEY_CARD_TYPE)
val cardType = CardType.valueOf(typeElement.asString)
val delegateAdapter = delegates[cardType]
?: throw IllegalArgumentException("Unknown type: $cardType")
return delegateAdapter.fromJsonTree(rootElement)
}
}
}
| gpl-3.0 | 21e39f21c6906ece020f1c242efb3bb1 | 41.755556 | 108 | 0.7092 | 4.289855 | false | false | false | false |
stanfy/helium | codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/builder/ObjCDefaultClassStructureBuilder.kt | 1 | 5456 | package com.stanfy.helium.handler.codegen.objectivec.entity.builder;
import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCEntitiesOptions
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.*
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.AccessModifier
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCPropertyDefinition
import com.stanfy.helium.model.Message
import com.stanfy.helium.model.Project
import com.stanfy.helium.model.Sequence
/**
* Created by ptaykalo on 8/17/14.
*/
class ObjCDefaultClassStructureBuilder(val typeTransformer: ObjCTypeTransformer,
val nameTransformer: ObjCPropertyNameTransformer) : ObjCBuilder<Project, ObjCProjectClassesTree> {
/**
* Performs parsing / translation of Helium DSL Project Structure to Objective-C Project structure
* Uses specified options for the generation @see ObjCProjectParserOptions
*/
override fun build(from: Project, options: ObjCEntitiesOptions?): ObjCProjectClassesTree {
val projectClassStructure = ObjCProjectClassesTree()
val filteredMessages =
from.messages.filter { message ->
!message.anonymous && (options == null || options.isTypeIncluded(message))
}
// Registering all direct transformations from messages
typeTransformer.registerTransformations(
filteredMessages.map { message ->
val className = (options?.prefix ?: "") + message.name
ObjCTypeTransformation(message.name, ObjCType(className), AccessModifier.STRONG)
})
// Register custom transformations
val customTypeMappings = options?.customTypesMappings?.entries
if (customTypeMappings != null) {
typeTransformer.registerTransformations(
customTypeMappings.map { e ->
val heliumType = e.key
val objcType = e.value
val isReference = objcType.contains("*")
val name = objcType.replace(" ", "").replace("*", "")
val accessModifier = if (isReference || name == "id") AccessModifier.STRONG else AccessModifier.ASSIGN
ObjCTypeTransformation(heliumType, ObjCType(name, isReference, true), accessModifier)
}
)
}
filteredMessages.forEach { message ->
projectClassStructure.addClass(objCClassForMessage(message, classPrefix = options?.prefix ?: ""), message.name);
}
val filteredSequences =
from.sequences.filter { seq ->
!seq.isAnonymous && (options == null || options.isTypeIncluded(seq))
}
// Registering all direct transformations from sequences
typeTransformer.registerTransformations(
filteredSequences.map { seq ->
val className = (options?.prefix ?: "") + seq.name
ObjCTypeTransformation(seq.name, ObjCType(className), AccessModifier.STRONG)
})
filteredSequences.forEach { seq ->
projectClassStructure.addClass(objcClassForSequence(seq, classPrefix = options?.prefix ?: ""), seq.name);
}
return projectClassStructure
}
private fun objcClassForSequence(seq: Sequence?, classPrefix: String): ObjCClass {
val className = classPrefix + seq!!.name
val classDefinition = ObjCClassInterface(className)
val classImplementation = ObjCClassImplementation(className)
val objCClass = ObjCClass(className, classDefinition, classImplementation)
return objCClass
}
private fun objCClassForMessage(message: Message, classPrefix: String): ObjCClass {
val className = classPrefix + message.name
val classDefinition = ObjCClassInterface(className)
val classImplementation = ObjCClassImplementation(className)
val objCClass = ObjCClass(className, classDefinition, classImplementation)
val usedPropertyNames = hashSetOf<String>()
// Transform fields to the objc properties
classDefinition.addPropertyDefinitionsList(
message.activeFields
.map { field ->
val heliumType = field.type
val propertyName = nameTransformer.propertyNameFrom(field.name, usedPropertyNames)
val propertyType = typeTransformer.objCType(heliumType, field.isSequence)
val accessModifier = typeTransformer.accessorModifierForType(heliumType)
val property = ObjCPropertyDefinition(propertyName, propertyType, accessModifier)
property.correspondingField = field
if (field.isSequence) {
val itemType = typeTransformer.objCType(heliumType, false)
property.isSequence = true
property.sequenceType = itemType
}
// Update used Names
usedPropertyNames.add(propertyName)
property
}
)
// Add forward declarations for property types
objCClass.addClassForwardDeclarations(
classDefinition.propertyDefinitions
.filter { prop -> prop.type.isReference && !prop.type.isFoundationType() }
.map { prop -> prop.type.name }
)
// Add forward declarations for property sequence types
objCClass.addClassForwardDeclarations(
classDefinition.propertyDefinitions
.filter { prop -> prop.isSequence && prop.sequenceType != null && prop.sequenceType!!.isReference && !prop.sequenceType!!.isFoundationType() }
.map { prop -> prop.sequenceType!!.name }
)
return objCClass
}
}
| apache-2.0 | 3a6c3f5e6fe381109bfba6a54b909ab8 | 40.333333 | 154 | 0.694465 | 5.023941 | false | false | false | false |
kdwink/intellij-community | platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt | 1 | 6416 | /*
* Copyright 2000-2014 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.io.fastCgi
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.util.containers.ConcurrentIntObjectMap
import com.intellij.util.containers.ContainerUtil
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.handler.codec.http.*
import org.jetbrains.builtInWebServer.SingleConnectionNetService
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.*
import java.util.concurrent.atomic.AtomicInteger
val LOG: Logger = Logger.getInstance(FastCgiService::class.java)
// todo send FCGI_ABORT_REQUEST if client channel disconnected
abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) {
private val requestIdCounter = AtomicInteger()
protected val requests: ConcurrentIntObjectMap<Channel> = ContainerUtil.createConcurrentIntObjectMap<Channel>()
override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) {
bootstrap.handler {
it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService))
it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance())
it.closeFuture().addListener {
requestIdCounter.set(0)
if (!requests.isEmpty) {
val waitingClients = requests.elements().toList()
requests.clear()
for (channel in waitingClients) {
sendBadGateway(channel)
}
}
}
}
}
fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) {
val notEmptyContent: ByteBuf?
if (content.isReadable) {
content.retain()
notEmptyContent = content
notEmptyContent.touch()
}
else {
notEmptyContent = null
}
try {
val promise: Promise<*>
if (processHandler.has()) {
val channel = processChannel.get()
if (channel == null || !channel.isOpen) {
// channel disconnected for some reason
promise = connectAgain()
}
else {
fastCgiRequest.writeToServerChannel(notEmptyContent, channel)
return
}
}
else {
promise = processHandler.get()
}
promise
.done { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel.get()!!) }
.rejected {
Promise.logError(LOG, it)
handleError(fastCgiRequest, notEmptyContent)
}
}
catch (e: Throwable) {
LOG.error(e)
handleError(fastCgiRequest, notEmptyContent)
}
}
private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) {
try {
if (content != null && content.refCnt() != 0) {
content.release()
}
}
finally {
val channel = requests.remove(fastCgiRequest.requestId)
if (channel != null) {
sendBadGateway(channel)
}
}
}
fun allocateRequestId(channel: Channel): Int {
var requestId = requestIdCounter.getAndIncrement()
if (requestId >= java.lang.Short.MAX_VALUE) {
requestIdCounter.set(0)
requestId = requestIdCounter.getAndDecrement()
}
requests.put(requestId, channel)
return requestId
}
fun responseReceived(id: Int, buffer: ByteBuf?) {
val channel = requests.remove(id)
if (channel == null || !channel.isActive) {
buffer?.release()
return
}
if (buffer == null) {
Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel)
return
}
val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer)
try {
parseHeaders(httpResponse, buffer)
Responses.addServer(httpResponse)
if (!HttpUtil.isContentLengthSet(httpResponse)) {
HttpUtil.setContentLength(httpResponse, buffer.readableBytes().toLong())
}
}
catch (e: Throwable) {
buffer.release()
try {
LOG.error(e)
}
finally {
Responses.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, channel)
}
return
}
channel.writeAndFlush(httpResponse)
}
}
private fun sendBadGateway(channel: Channel) {
try {
if (channel.isActive) {
Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel)
}
}
catch (e: Throwable) {
NettyUtil.log(e, LOG)
}
}
private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) {
val builder = StringBuilder()
while (buffer.isReadable) {
builder.setLength(0)
var key: String? = null
var valueExpected = true
while (true) {
val b = buffer.readByte().toInt()
if (b < 0 || b.toChar() == '\n') {
break
}
if (b.toChar() != '\r') {
if (valueExpected && b.toChar() == ':') {
valueExpected = false
key = builder.toString()
builder.setLength(0)
MessageDecoder.skipWhitespace(buffer)
}
else {
builder.append(b.toChar())
}
}
}
if (builder.length == 0) {
// end of headers
return
}
// skip standard headers
if (key.isNullOrEmpty() || key!!.startsWith("http", ignoreCase = true) || key.startsWith("X-Accel-", ignoreCase = true)) {
continue
}
val value = builder.toString()
if (key.equals("status", ignoreCase = true)) {
val index = value.indexOf(' ')
if (index == -1) {
LOG.warn("Cannot parse status: " + value)
response.setStatus(HttpResponseStatus.OK)
}
else {
response.setStatus(HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index))))
}
}
else if (!(key.startsWith("http") || key.startsWith("HTTP"))) {
response.headers().add(key, value)
}
}
} | apache-2.0 | 8d748e2ff34524829240e3c927df0074 | 28.168182 | 126 | 0.653522 | 4.403569 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/training/input/InputActivity.kt | 1 | 21377 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.training.input
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.databinding.DataBindingUtil
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.loader.app.LoaderManager
import androidx.loader.content.AsyncTaskLoader
import androidx.core.content.ContextCompat
import androidx.loader.content.Loader
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import android.text.InputType
import android.transition.Transition
import android.view.Menu
import android.view.MenuItem
import android.view.View.GONE
import android.view.View.VISIBLE
import com.afollestad.materialdialogs.MaterialDialog
import com.evernote.android.state.State
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.base.activities.ChildActivityBase
import de.dreier.mytargets.base.db.RoundRepository
import de.dreier.mytargets.base.db.TrainingRepository
import de.dreier.mytargets.base.db.dao.ArrowDAO
import de.dreier.mytargets.base.db.dao.BowDAO
import de.dreier.mytargets.base.db.dao.StandardRoundDAO
import de.dreier.mytargets.base.gallery.GalleryActivity
import de.dreier.mytargets.databinding.ActivityInputBinding
import de.dreier.mytargets.features.settings.ESettingsScreens
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.shared.models.db.End
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.models.db.Shot
import de.dreier.mytargets.shared.models.sum
import de.dreier.mytargets.shared.views.TargetViewBase
import de.dreier.mytargets.shared.views.TargetViewBase.EInputMethod
import de.dreier.mytargets.shared.wearable.WearableClientBase.Companion.BROADCAST_TIMER_SETTINGS_FROM_REMOTE
import de.dreier.mytargets.utils.*
import de.dreier.mytargets.utils.MobileWearableClient.Companion.BROADCAST_UPDATE_TRAINING_FROM_REMOTE
import de.dreier.mytargets.utils.Utils.getCurrentLocale
import de.dreier.mytargets.utils.transitions.FabTransform
import de.dreier.mytargets.utils.transitions.TransitionAdapter
import org.threeten.bp.LocalTime
import java.io.File
class InputActivity : ChildActivityBase(), TargetViewBase.OnEndFinishedListener,
TargetView.OnEndUpdatedListener, LoaderManager.LoaderCallbacks<LoaderResult> {
@State
var data: LoaderResult? = null
private lateinit var binding: ActivityInputBinding
private var transitionFinished = true
private var summaryShowScope = ETrainingScope.END
private var targetView: TargetView? = null
private val database = ApplicationInstance.db
private val trainingDAO = database.trainingDAO()
private val roundDAO = database.roundDAO()
private val endDAO = database.endDAO()
private val bowDAO = database.bowDAO()
private val arrowDAO = database.arrowDAO()
private val standardRoundDAO = database.standardRoundDAO()
private val roundRepository = RoundRepository(database)
private val trainingRepository = TrainingRepository(
database,
trainingDAO,
roundDAO,
roundRepository,
database.signatureDAO()
)
private val updateReceiver = object : MobileWearableClient.EndUpdateReceiver() {
override fun onUpdate(trainingId: Long, roundId: Long, end: End) {
val extras = intent.extras!!
extras.putLong(TRAINING_ID, trainingId)
extras.putLong(ROUND_ID, roundId)
extras.putInt(END_INDEX, end.index)
supportLoaderManager.restartLoader(0, extras, this@InputActivity).forceLoad()
}
}
private val timerReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
invalidateOptionsMenu()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_input)
setSupportActionBar(binding.toolbar)
ToolbarUtils.showHomeAsUp(this)
Utils.setupFabTransform(this, binding.root)
if (Utils.isLollipop) {
setupTransitionListener()
}
updateSummaryVisibility()
if (data == null) {
supportLoaderManager.initLoader(0, intent.extras, this).forceLoad()
}
LocalBroadcastManager.getInstance(this).registerReceiver(
updateReceiver,
IntentFilter(BROADCAST_UPDATE_TRAINING_FROM_REMOTE)
)
LocalBroadcastManager.getInstance(this).registerReceiver(
timerReceiver,
IntentFilter(BROADCAST_TIMER_SETTINGS_FROM_REMOTE)
)
}
override fun onResume() {
super.onResume()
if (data != null) {
onDataLoadFinished()
updateEnd()
}
Utils.setShowWhenLocked(this, SettingsManager.inputKeepAboveLockscreen)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
val imageList = GalleryActivity.getResult(data)
val currentEnd = this.data!!.currentEnd
currentEnd.images = imageList.toEndImageList()
for (image in imageList.removedImages) {
File(filesDir, image).delete()
}
endDAO.replaceImages(currentEnd.end, currentEnd.images)
updateEnd()
invalidateOptionsMenu()
}
}
private fun saveCurrentEnd() {
val currentEnd = data!!.currentEnd
if (currentEnd.end.saveTime == null) {
currentEnd.end.saveTime = LocalTime.now()
}
currentEnd.end.score = data!!.currentRound.round.target.getReachedScore(currentEnd.shots)
endDAO.updateEnd(currentEnd.end)
endDAO.updateShots(currentEnd.shots)
}
override fun onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(updateReceiver)
LocalBroadcastManager.getInstance(this).unregisterReceiver(timerReceiver)
super.onDestroy()
}
private fun updateSummaryVisibility() {
val (showEnd, showRound, showTraining, showAverage, averageScope) = SettingsManager.inputSummaryConfiguration
binding.endSummary.visibility = if (showEnd) VISIBLE else GONE
binding.roundSummary.visibility = if (showRound) VISIBLE else GONE
binding.trainingSummary.visibility = if (showTraining) VISIBLE else GONE
binding.averageSummary.visibility = if (showAverage) VISIBLE else GONE
summaryShowScope = averageScope
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private fun setupTransitionListener() {
val sharedElementEnterTransition = window.sharedElementEnterTransition
if (sharedElementEnterTransition != null && sharedElementEnterTransition is FabTransform) {
transitionFinished = false
window.sharedElementEnterTransition.addListener(object : TransitionAdapter() {
override fun onTransitionEnd(transition: Transition) {
transitionFinished = true
window.sharedElementEnterTransition.removeListener(this)
}
})
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.input_end, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val timer = menu.findItem(R.id.action_timer)
val newRound = menu.findItem(R.id.action_new_round)
val takePicture = menu.findItem(R.id.action_photo)
if (targetView == null || data!!.ends.size == 0) {
takePicture.isVisible = false
timer.isVisible = false
newRound.isVisible = false
} else {
takePicture.isVisible = Utils.hasCameraHardware(this)
timer.setIcon(
if (SettingsManager.timerEnabled)
R.drawable.ic_timer_off_white_24dp
else
R.drawable.ic_timer_white_24dp
)
timer.isVisible = true
timer.isChecked = SettingsManager.timerEnabled
newRound.isVisible = data!!.training.training.standardRoundId == null
takePicture.isVisible = Utils.hasCameraHardware(this)
takePicture.setIcon(
if (data!!.currentEnd.images.isEmpty())
R.drawable.ic_photo_camera_white_24dp
else
R.drawable.ic_image_white_24dp
)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_photo -> {
val imageList = ImageList(data!!.currentEnd.images)
val title = getString(R.string.end_n, data!!.endIndex + 1)
navigationController.navigateToGallery(imageList, title, GALLERY_REQUEST_CODE)
}
R.id.action_comment -> {
MaterialDialog.Builder(this)
.title(R.string.comment)
.inputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE)
.input("", data!!.currentEnd.end.comment) { _, input ->
data!!.currentEnd.end.comment = input.toString()
endDAO.updateEnd(data!!.currentEnd.end)
}
.negativeText(android.R.string.cancel)
.show()
}
R.id.action_timer -> {
val timerEnabled = !SettingsManager.timerEnabled
SettingsManager.timerEnabled = timerEnabled
ApplicationInstance.wearableClient.sendTimerSettingsFromLocal(SettingsManager.timerSettings)
openTimer()
item.isChecked = timerEnabled
invalidateOptionsMenu()
}
R.id.action_settings -> navigationController.navigateToSettings(ESettingsScreens.INPUT)
R.id.action_new_round -> navigationController.navigateToCreateRound(trainingId = data!!.training.training.id)
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<LoaderResult> {
if (args == null) {
throw IllegalArgumentException("Bundle expected")
}
val trainingId = args.getLong(TRAINING_ID)
val roundId = args.getLong(ROUND_ID)
val endIndex = args.getInt(END_INDEX)
return UITaskAsyncTaskLoader(
this,
trainingId,
roundId,
endIndex,
trainingRepository,
standardRoundDAO,
arrowDAO,
bowDAO
)
}
override fun onLoadFinished(loader: Loader<LoaderResult>, data: LoaderResult) {
this.data = data
onDataLoadFinished()
showEnd(data.endIndex)
}
private fun onDataLoadFinished() {
title = data!!.training.training.title
if (!binding.targetViewStub.isInflated) {
binding.targetViewStub.viewStub?.inflate()
}
targetView = binding.targetViewStub.binding?.root as TargetView
targetView!!.initWithTarget(data!!.currentRound.round.target)
targetView!!.setArrow(
data!!.arrowDiameter, data!!.training.training.arrowNumbering, data!!
.maxArrowNumber
)
targetView!!.setOnTargetSetListener(this@InputActivity)
targetView!!.setUpdateListener(this@InputActivity)
targetView!!.reloadSettings()
targetView!!.setAggregationStrategy(SettingsManager.aggregationStrategy)
targetView!!.inputMethod = SettingsManager.inputMethod
updateOldShoots()
}
override fun onLoaderReset(loader: Loader<LoaderResult>) {
}
private fun showEnd(endIndex: Int) {
// Create a new end
data!!.setAdjustEndIndex(endIndex)
if (endIndex >= data!!.ends.size) {
val end = data!!.currentRound.addEnd()
end.end.exact = SettingsManager.inputMethod === EInputMethod.PLOTTING
updateOldShoots()
}
// Open timer if end has not been saved yet
openTimer()
updateEnd()
invalidateOptionsMenu()
}
private fun updateOldShoots() {
val currentEnd = data!!.currentEnd
val currentRoundId = data!!.currentRound.round.id
val currentEndId = currentEnd.end.id
val shotShowScope = SettingsManager.showMode
val data = this.data
val shots = data!!.training.rounds
.filter { r -> shouldShowRound(r.round, shotShowScope, currentRoundId) }
.flatMap { r -> r.ends }
.filter { end -> shouldShowEnd(end.end, currentEndId) }
.flatMap { (_, shots) -> shots }
targetView!!.setTransparentShots(shots)
}
private fun openTimer() {
if (data!!.currentEnd.isEmpty && SettingsManager.timerEnabled) {
if (transitionFinished) {
navigationController.navigateToTimer(true)
} else if (Utils.isLollipop) {
startTimerDelayed()
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private fun startTimerDelayed() {
window.sharedElementEnterTransition.addListener(object : TransitionAdapter() {
override fun onTransitionEnd(transition: Transition) {
navigationController.navigateToTimer(true)
window.sharedElementEnterTransition.removeListener(this)
}
})
}
private fun updateEnd() {
targetView?.replaceWithEnd(data!!.currentEnd.shots, data!!.currentEnd.end.exact)
val totalEnds = data!!.currentRound.round.maxEndCount ?: data!!.ends.size
binding.endTitle.text = getString(R.string.end_x_of_y, data!!.endIndex + 1, totalEnds)
binding.roundTitle.text = getString(
R.string.round_x_of_y,
data!!.currentRound.round.index + 1,
data!!.training.rounds.size
)
updateNavigationButtons()
updateWearNotification()
}
private fun updateWearNotification() {
ApplicationInstance.wearableClient.sendUpdateTrainingFromLocalBroadcast(data!!.training)
}
private fun updateNavigationButtons() {
updatePreviousButton()
updateNextButton()
}
private fun updatePreviousButton() {
val isFirstEnd = data!!.endIndex == 0
val isFirstRound = data!!.roundIndex == 0
val showPreviousRound = isFirstEnd && !isFirstRound
val isEnabled = !isFirstEnd || !isFirstRound
val color: Int
if (showPreviousRound) {
val round = data!!.training.rounds[data!!.roundIndex - 1]
binding.prev.setOnClickListener { openRound(round.round, round.ends.size - 1) }
binding.prev.setText(R.string.previous_round)
color = ContextCompat.getColor(this, R.color.colorPrimary)
} else {
binding.prev.setOnClickListener { showEnd(data!!.endIndex - 1) }
binding.prev.setText(R.string.prev)
color = Color.BLACK
}
binding.prev.setTextColor(Utils.argb(if (isEnabled) 0xFF else 0x42, color))
binding.prev.isEnabled = isEnabled
}
private fun updateNextButton() {
val dataLoaded = data != null
val isLastEnd = dataLoaded &&
data!!.currentRound.round.maxEndCount != null &&
data!!.endIndex + 1 == data!!.currentRound.round.maxEndCount
val hasOneMoreRound = dataLoaded && data!!.roundIndex + 1 < data!!.training.rounds.size
val showNextRound = isLastEnd && hasOneMoreRound
val isEnabled = dataLoaded && (!isLastEnd || hasOneMoreRound)
val color: Int
if (showNextRound) {
val round = data!!.training.rounds[data!!.roundIndex + 1].round
binding.next.setOnClickListener { openRound(round, 0) }
binding.next.setText(R.string.next_round)
color = ContextCompat.getColor(this, R.color.colorPrimary)
} else {
binding.next.setOnClickListener { showEnd(data!!.endIndex + 1) }
binding.next.setText(R.string.next)
color = Color.BLACK
}
binding.next.setTextColor(Utils.argb(if (isEnabled) 0xFF else 0x42, color))
binding.next.isEnabled = isEnabled
}
private fun openRound(round: Round, endIndex: Int) {
finish()
navigationController.navigateToRound(round)
.noAnimation()
.start()
navigationController.navigateToEditEnd(round, endIndex)
.start()
}
override fun onEndUpdated(shots: List<Shot>) {
data!!.currentEnd.shots = shots.toMutableList()
saveCurrentEnd()
// Set current end score
val reachedEndScore = data!!.currentRound.round.target
.getReachedScore(data!!.currentEnd.shots)
binding.endScore.text = reachedEndScore.toString()
// Set current round score
val reachedRoundScore = data!!.ends
.map { end -> data!!.currentRound.round.target.getReachedScore(end.shots) }
.sum()
binding.roundScore.text = reachedRoundScore.toString()
// Set current training score
val reachedTrainingScore = data!!.training.rounds
.flatMap { r -> r.ends.map { end -> r.round.target.getReachedScore(end.shots) } }
.sum()
binding.trainingScore.text = reachedTrainingScore.toString()
when (summaryShowScope) {
ETrainingScope.END -> binding.averageScore.text =
reachedEndScore.getShotAverageFormatted(getCurrentLocale(this))
ETrainingScope.ROUND -> binding.averageScore.text =
reachedRoundScore.getShotAverageFormatted(getCurrentLocale(this))
ETrainingScope.TRAINING -> binding.averageScore.text = reachedTrainingScore
.getShotAverageFormatted(getCurrentLocale(this))
}
}
override fun onEndFinished(shotList: List<Shot>) {
data!!.currentEnd.shots = shotList.toMutableList()
data!!.currentEnd.end.exact = targetView!!.inputMode === EInputMethod.PLOTTING
saveCurrentEnd()
updateWearNotification()
updateNavigationButtons()
invalidateOptionsMenu()
}
private class UITaskAsyncTaskLoader(
context: Context,
private val trainingId: Long,
private val roundId: Long,
private val endIndex: Int,
val trainingRepository: TrainingRepository,
val standardRoundDAO: StandardRoundDAO,
val arrowDAO: ArrowDAO,
val bowDAO: BowDAO
) : AsyncTaskLoader<LoaderResult>(context) {
override fun loadInBackground(): LoaderResult? {
val training = trainingRepository.loadAugmentedTraining(trainingId)
val standardRound =
if (training.training.standardRoundId == null) null else standardRoundDAO.loadStandardRound(
training.training.standardRoundId!!
)
val result = LoaderResult(training, standardRound)
result.setRoundId(roundId)
result.setAdjustEndIndex(endIndex)
if (training.training.arrowId != null) {
val arrow = arrowDAO.loadArrow(training.training.arrowId!!)
result.maxArrowNumber = arrow.maxArrowNumber
result.arrowDiameter = arrow.diameter
}
if (training.training.bowId != null) {
result.sightMark = bowDAO.loadSightMarks(training.training.bowId!!)
.firstOrNull { it.distance == result.distance!! }
}
return result
}
}
companion object {
internal const val TRAINING_ID = "training_id"
internal const val ROUND_ID = "round_id"
internal const val END_INDEX = "end_ind"
internal const val GALLERY_REQUEST_CODE = 1
private fun shouldShowRound(
r: Round,
shotShowScope: ETrainingScope,
roundId: Long?
): Boolean {
return shotShowScope !== ETrainingScope.END && (shotShowScope === ETrainingScope.TRAINING || r.id == roundId)
}
private fun shouldShowEnd(end: End, currentEndId: Long?): Boolean {
return end.id != currentEndId && end.exact
}
}
}
| gpl-2.0 | 6c2d150b7a60eb94111c293c1203dc5d | 39.106942 | 121 | 0.654067 | 4.768459 | false | false | false | false |
paplorinc/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/common/IdentifiersTestBase.kt | 1 | 2082 | /*
* 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.uast.test.common
import com.intellij.psi.PsiCodeBlock
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import junit.framework.TestCase
import org.jetbrains.uast.*
import kotlin.reflect.KClass
fun UFile.asIdentifiers(): String = UElementToParentMap { it.toUElementOfType<UIdentifier>() }.alsoCheck {
//check uIdentifier is walkable to top (e.g. IDEA-200372)
TestCase.assertEquals("should be able to reach the file from identifier '${it.text}'",
this@asIdentifiers,
it.toUElementOfType<UIdentifier>()!!.getParentOfType<UFile>()
)
}.visitUFileAndGetResult(this)
fun UFile.asRefNames() = UElementToParentMap { it.toUElementOfType<UReferenceExpression>()?.referenceNameElement }
.visitUFileAndGetResult(this)
open class UElementToParentMap(shouldIndent: (PsiElement) -> Boolean,
val retriever: (PsiElement) -> UElement?) : IndentedPrintingVisitor(shouldIndent) {
constructor(kClass: KClass<*>, retriever: (PsiElement) -> UElement?) : this({ kClass.isInstance(it) }, retriever)
constructor(retriever: (PsiElement) -> UElement?) : this(PsiCodeBlock::class, retriever)
private val additionalChecks = mutableListOf<(PsiElement) -> Unit>()
override fun render(element: PsiElement): CharSequence? = retriever(element)?.let { uElement ->
StringBuilder().apply {
append(uElement.sourcePsiElement!!.text)
append(" -> ")
append(uElement.uastParent?.asLogString())
append(" from ")
append(renderSource(element))
}
}
protected open fun renderSource(element: PsiElement): String = element.toString()
fun alsoCheck(checker: (PsiElement) -> Unit): UElementToParentMap {
additionalChecks.add(checker)
return this
}
}
fun IndentedPrintingVisitor.visitUFileAndGetResult(uFile: UFile): String {
(uFile.sourcePsi as PsiFile).accept(this)
return result
}
| apache-2.0 | 9b1ccea5ad45f918ba80d46dfcaa9953 | 36.854545 | 140 | 0.719981 | 4.487069 | false | true | false | false |
google/intellij-community | plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/StdlibDetectorFacility.kt | 3 | 1772 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.platforms
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
sealed class StdlibDetectorFacility {
abstract fun getStdlibJar(roots: List<VirtualFile>): VirtualFile?
protected abstract val supportedLibraryKind: KotlinLibraryKind?
fun isStdlib(project: Project, library: Library, ignoreKind: Boolean = false): Boolean {
if (library !is LibraryEx || library.isDisposed) {
return false
}
if (!ignoreKind && !isSupported(project, library)) {
return false
}
val classes = listOf(*library.getFiles(OrderRootType.CLASSES))
return getStdlibJar(classes) != null
}
fun getStdlibVersion(roots: List<VirtualFile>): IdeKotlinVersion? {
val stdlibJar = getStdlibJar(roots) ?: return null
return IdeKotlinVersion.fromManifest(stdlibJar)
}
fun getStdlibVersion(project: Project, library: Library): IdeKotlinVersion? {
if (library !is LibraryEx || library.isDisposed || !isSupported(project, library)) {
return null
}
return getStdlibVersion(library.getFiles(OrderRootType.CLASSES).asList())
}
protected fun isSupported(project: Project, library: LibraryEx): Boolean {
return LibraryEffectiveKindProvider.getInstance(project).getEffectiveKind(library) == supportedLibraryKind
}
} | apache-2.0 | 99ab5725c94e43db8432be84906d6943 | 38.4 | 120 | 0.72912 | 4.815217 | false | false | false | false |
LWJGL-CI/lwjgl3 | modules/lwjgl/fmod/src/templates/kotlin/fmod/templates/FMOD.kt | 2 | 120190 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package fmod.templates
import org.lwjgl.generator.*
import fmod.*
val FMOD = "FMOD".nativeClass(
Module.FMOD,
prefix = "FMOD",
prefixMethod = "FMOD_",
binding = simpleBinding(Module.FMOD, libraryName = "FMOD", libraryExpression = "Configuration.FMOD_LIBRARY_NAME, \"fmod\"")
) {
IntConstant("", "VERSION"..0x00020209)
IntConstant("", "DEBUG_LEVEL_NONE"..0x00000000)
IntConstant("", "DEBUG_LEVEL_ERROR"..0x00000001)
IntConstant("", "DEBUG_LEVEL_WARNING"..0x00000002)
IntConstant("", "DEBUG_LEVEL_LOG"..0x00000004)
IntConstant("", "DEBUG_TYPE_MEMORY"..0x00000100)
IntConstant("", "DEBUG_TYPE_FILE"..0x00000200)
IntConstant("", "DEBUG_TYPE_CODEC"..0x00000400)
IntConstant("", "DEBUG_TYPE_TRACE"..0x00000800)
IntConstant("", "DEBUG_DISPLAY_TIMESTAMPS"..0x00010000)
IntConstant("", "DEBUG_DISPLAY_LINENUMBERS"..0x00020000)
IntConstant("", "DEBUG_DISPLAY_THREAD"..0x00040000)
IntConstant("", "MEMORY_NORMAL"..0x00000000)
IntConstant("", "MEMORY_STREAM_FILE"..0x00000001)
IntConstant("", "MEMORY_STREAM_DECODE"..0x00000002)
IntConstant("", "MEMORY_SAMPLEDATA"..0x00000004)
IntConstant("", "MEMORY_DSP_BUFFER"..0x00000008)
IntConstant("", "MEMORY_PLUGIN"..0x00000010)
IntConstant("", "MEMORY_PERSISTENT"..0x00200000)
IntConstant("", "MEMORY_ALL"..0xFFFFFFFF.i)
IntConstant("", "INIT_NORMAL"..0x00000000)
IntConstant("", "INIT_STREAM_FROM_UPDATE"..0x00000001)
IntConstant("", "INIT_MIX_FROM_UPDATE"..0x00000002)
IntConstant("", "INIT_3D_RIGHTHANDED"..0x00000004)
IntConstant("", "INIT_CLIP_OUTPUT"..0x00000008)
IntConstant("", "INIT_CHANNEL_LOWPASS"..0x00000100)
IntConstant("", "INIT_CHANNEL_DISTANCEFILTER"..0x00000200)
IntConstant("", "INIT_PROFILE_ENABLE"..0x00010000)
IntConstant("", "INIT_VOL0_BECOMES_VIRTUAL"..0x00020000)
IntConstant("", "INIT_GEOMETRY_USECLOSEST"..0x00040000)
IntConstant("", "INIT_PREFER_DOLBY_DOWNMIX"..0x00080000)
IntConstant("", "INIT_THREAD_UNSAFE"..0x00100000)
IntConstant("", "INIT_PROFILE_METER_ALL"..0x00200000)
IntConstant("", "INIT_MEMORY_TRACKING"..0x00400000)
IntConstant("", "DRIVER_STATE_CONNECTED"..0x00000001)
IntConstant("", "DRIVER_STATE_DEFAULT"..0x00000002)
IntConstant("", "TIMEUNIT_MS"..0x00000001)
IntConstant("", "TIMEUNIT_PCM"..0x00000002)
IntConstant("", "TIMEUNIT_PCMBYTES"..0x00000004)
IntConstant("", "TIMEUNIT_RAWBYTES"..0x00000008)
IntConstant("", "TIMEUNIT_PCMFRACTION"..0x00000010)
IntConstant("", "TIMEUNIT_MODORDER"..0x00000100)
IntConstant("", "TIMEUNIT_MODROW"..0x00000200)
IntConstant("", "TIMEUNIT_MODPATTERN"..0x00000400)
IntConstant("", "SYSTEM_CALLBACK_DEVICELISTCHANGED"..0x00000001)
IntConstant("", "SYSTEM_CALLBACK_DEVICELOST"..0x00000002)
IntConstant("", "SYSTEM_CALLBACK_MEMORYALLOCATIONFAILED"..0x00000004)
IntConstant("", "SYSTEM_CALLBACK_THREADCREATED"..0x00000008)
IntConstant("", "SYSTEM_CALLBACK_BADDSPCONNECTION"..0x00000010)
IntConstant("", "SYSTEM_CALLBACK_PREMIX"..0x00000020)
IntConstant("", "SYSTEM_CALLBACK_POSTMIX"..0x00000040)
IntConstant("", "SYSTEM_CALLBACK_ERROR"..0x00000080)
IntConstant("", "SYSTEM_CALLBACK_MIDMIX"..0x00000100)
IntConstant("", "SYSTEM_CALLBACK_THREADDESTROYED"..0x00000200)
IntConstant("", "SYSTEM_CALLBACK_PREUPDATE"..0x00000400)
IntConstant("", "SYSTEM_CALLBACK_POSTUPDATE"..0x00000800)
IntConstant("", "SYSTEM_CALLBACK_RECORDLISTCHANGED"..0x00001000)
IntConstant("", "SYSTEM_CALLBACK_BUFFEREDNOMIX"..0x00002000)
IntConstant("", "SYSTEM_CALLBACK_DEVICEREINITIALIZE"..0x00004000)
IntConstant("", "SYSTEM_CALLBACK_OUTPUTUNDERRUN"..0x00008000)
IntConstant("", "SYSTEM_CALLBACK_RECORDPOSITIONCHANGED"..0x00010000)
IntConstant("", "SYSTEM_CALLBACK_ALL"..0xFFFFFFFF.i)
IntConstant("", "DEFAULT"..0x00000000)
IntConstant("", "LOOP_OFF"..0x00000001)
IntConstant("", "LOOP_NORMAL"..0x00000002)
IntConstant("", "LOOP_BIDI"..0x00000004)
IntConstant("", "2D"..0x00000008)
IntConstant("", "3D"..0x00000010)
IntConstant("", "CREATESTREAM"..0x00000080)
IntConstant("", "CREATESAMPLE"..0x00000100)
IntConstant("", "CREATECOMPRESSEDSAMPLE"..0x00000200)
IntConstant("", "OPENUSER"..0x00000400)
IntConstant("", "OPENMEMORY"..0x00000800)
IntConstant("", "OPENMEMORY_POINT"..0x10000000)
IntConstant("", "OPENRAW"..0x00001000)
IntConstant("", "OPENONLY"..0x00002000)
IntConstant("", "ACCURATETIME"..0x00004000)
IntConstant("", "MPEGSEARCH"..0x00008000)
IntConstant("", "NONBLOCKING"..0x00010000)
IntConstant("", "UNIQUE"..0x00020000)
IntConstant("", "3D_HEADRELATIVE"..0x00040000)
IntConstant("", "3D_WORLDRELATIVE"..0x00080000)
IntConstant("", "3D_INVERSEROLLOFF"..0x00100000)
IntConstant("", "3D_LINEARROLLOFF"..0x00200000)
IntConstant("", "3D_LINEARSQUAREROLLOFF"..0x00400000)
IntConstant("", "3D_INVERSETAPEREDROLLOFF"..0x00800000)
IntConstant("", "3D_CUSTOMROLLOFF"..0x04000000)
IntConstant("", "3D_IGNOREGEOMETRY"..0x40000000)
IntConstant("", "IGNORETAGS"..0x02000000)
IntConstant("", "LOWMEM"..0x08000000)
IntConstant("", "VIRTUAL_PLAYFROMSTART"..0x80000000.i)
IntConstant("", "CHANNELMASK_FRONT_LEFT"..0x00000001)
IntConstant("", "CHANNELMASK_FRONT_RIGHT"..0x00000002)
IntConstant("", "CHANNELMASK_FRONT_CENTER"..0x00000004)
IntConstant("", "CHANNELMASK_LOW_FREQUENCY"..0x00000008)
IntConstant("", "CHANNELMASK_SURROUND_LEFT"..0x00000010)
IntConstant("", "CHANNELMASK_SURROUND_RIGHT"..0x00000020)
IntConstant("", "CHANNELMASK_BACK_LEFT"..0x00000040)
IntConstant("", "CHANNELMASK_BACK_RIGHT"..0x00000080)
IntConstant("", "CHANNELMASK_BACK_CENTER"..0x00000100)
IntConstant("", "CHANNELMASK_MONO".."FMOD_CHANNELMASK_FRONT_LEFT")
IntConstant("", "CHANNELMASK_STEREO".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT")
IntConstant("", "CHANNELMASK_LRC".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER")
IntConstant("", "CHANNELMASK_QUAD".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_SURROUND_LEFT | FMOD_CHANNELMASK_SURROUND_RIGHT")
IntConstant("", "CHANNELMASK_SURROUND".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER | FMOD_CHANNELMASK_SURROUND_LEFT | FMOD_CHANNELMASK_SURROUND_RIGHT")
IntConstant("", "CHANNELMASK_5POINT1".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER | FMOD_CHANNELMASK_LOW_FREQUENCY | FMOD_CHANNELMASK_SURROUND_LEFT | FMOD_CHANNELMASK_SURROUND_RIGHT")
IntConstant("", "CHANNELMASK_5POINT1_REARS".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER | FMOD_CHANNELMASK_LOW_FREQUENCY | FMOD_CHANNELMASK_BACK_LEFT | FMOD_CHANNELMASK_BACK_RIGHT")
IntConstant("", "CHANNELMASK_7POINT0".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER | FMOD_CHANNELMASK_SURROUND_LEFT | FMOD_CHANNELMASK_SURROUND_RIGHT | FMOD_CHANNELMASK_BACK_LEFT | FMOD_CHANNELMASK_BACK_RIGHT")
IntConstant("", "CHANNELMASK_7POINT1".."FMOD_CHANNELMASK_FRONT_LEFT | FMOD_CHANNELMASK_FRONT_RIGHT | FMOD_CHANNELMASK_FRONT_CENTER | FMOD_CHANNELMASK_LOW_FREQUENCY | FMOD_CHANNELMASK_SURROUND_LEFT | FMOD_CHANNELMASK_SURROUND_RIGHT | FMOD_CHANNELMASK_BACK_LEFT | FMOD_CHANNELMASK_BACK_RIGHT")
LongConstant("", "PORT_INDEX_NONE".."0xFFFFFFFFFFFFFFFFL")
LongConstant("", "PORT_INDEX_FLAG_VR_CONTROLLER"..0x1000000000000000)
IntConstant("", "THREAD_PRIORITY_PLATFORM_MIN".."-32 * 1024") // TODO
IntConstant("", "THREAD_PRIORITY_PLATFORM_MAX".."32 * 1024")
IntConstant("", "THREAD_PRIORITY_DEFAULT".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 1")
IntConstant("", "THREAD_PRIORITY_LOW".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 2")
IntConstant("", "THREAD_PRIORITY_MEDIUM".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 3")
IntConstant("", "THREAD_PRIORITY_HIGH".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 4")
IntConstant("", "THREAD_PRIORITY_VERY_HIGH".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 5")
IntConstant("", "THREAD_PRIORITY_EXTREME".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 6")
IntConstant("", "THREAD_PRIORITY_CRITICAL".."FMOD_THREAD_PRIORITY_PLATFORM_MIN - 7")
IntConstant("", "THREAD_PRIORITY_MIXER".."FMOD_THREAD_PRIORITY_EXTREME")
IntConstant("", "THREAD_PRIORITY_FEEDER".."FMOD_THREAD_PRIORITY_CRITICAL")
IntConstant("", "THREAD_PRIORITY_STREAM".."FMOD_THREAD_PRIORITY_VERY_HIGH")
IntConstant("", "THREAD_PRIORITY_FILE".."FMOD_THREAD_PRIORITY_HIGH")
IntConstant("", "THREAD_PRIORITY_NONBLOCKING".."FMOD_THREAD_PRIORITY_HIGH")
IntConstant("", "THREAD_PRIORITY_RECORD".."FMOD_THREAD_PRIORITY_HIGH")
IntConstant("", "THREAD_PRIORITY_GEOMETRY".."FMOD_THREAD_PRIORITY_LOW")
IntConstant("", "THREAD_PRIORITY_PROFILER".."FMOD_THREAD_PRIORITY_MEDIUM")
IntConstant("", "THREAD_PRIORITY_STUDIO_UPDATE".."FMOD_THREAD_PRIORITY_MEDIUM")
IntConstant("", "THREAD_PRIORITY_STUDIO_LOAD_BANK".."FMOD_THREAD_PRIORITY_MEDIUM")
IntConstant("", "THREAD_PRIORITY_STUDIO_LOAD_SAMPLE".."FMOD_THREAD_PRIORITY_MEDIUM")
IntConstant("", "THREAD_PRIORITY_CONVOLUTION1".."FMOD_THREAD_PRIORITY_VERY_HIGH")
IntConstant("", "THREAD_PRIORITY_CONVOLUTION2".."FMOD_THREAD_PRIORITY_VERY_HIGH")
IntConstant("", "THREAD_STACK_SIZE_DEFAULT".."0")
IntConstant("", "THREAD_STACK_SIZE_MIXER".."80 * 1024")
IntConstant("", "THREAD_STACK_SIZE_FEEDER".."16 * 1024")
IntConstant("", "THREAD_STACK_SIZE_STREAM".."96 * 1024")
IntConstant("", "THREAD_STACK_SIZE_FILE".."64 * 1024")
IntConstant("", "THREAD_STACK_SIZE_NONBLOCKING".."112 * 1024")
IntConstant("", "THREAD_STACK_SIZE_RECORD".."16 * 1024")
IntConstant("", "THREAD_STACK_SIZE_GEOMETRY".."48 * 1024")
IntConstant("", "THREAD_STACK_SIZE_PROFILER".."128 * 1024")
IntConstant("", "THREAD_STACK_SIZE_STUDIO_UPDATE".."96 * 1024")
IntConstant("", "THREAD_STACK_SIZE_STUDIO_LOAD_BANK".."96 * 1024")
IntConstant("", "THREAD_STACK_SIZE_STUDIO_LOAD_SAMPLE".."96 * 1024")
IntConstant("", "THREAD_STACK_SIZE_CONVOLUTION1".."16 * 1024")
IntConstant("", "THREAD_STACK_SIZE_CONVOLUTION2".."16 * 1024")
LongConstant("", "THREAD_AFFINITY_GROUP_DEFAULT".."0x4000000000000000L")
LongConstant("", "THREAD_AFFINITY_GROUP_A".."0x4000000000000001L")
LongConstant("", "THREAD_AFFINITY_GROUP_B".."0x4000000000000002L")
LongConstant("", "THREAD_AFFINITY_GROUP_C".."0x4000000000000003L")
LongConstant("", "THREAD_AFFINITY_MIXER".."FMOD_THREAD_AFFINITY_GROUP_A")
LongConstant("", "THREAD_AFFINITY_FEEDER".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_STREAM".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_FILE".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_NONBLOCKING".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_RECORD".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_GEOMETRY".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_PROFILER".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_STUDIO_UPDATE".."FMOD_THREAD_AFFINITY_GROUP_B")
LongConstant("", "THREAD_AFFINITY_STUDIO_LOAD_BANK".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_STUDIO_LOAD_SAMPLE".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_CONVOLUTION1".."FMOD_THREAD_AFFINITY_GROUP_C")
LongConstant("", "THREAD_AFFINITY_CONVOLUTION2".."FMOD_THREAD_AFFINITY_GROUP_C")
IntConstant("", "THREAD_AFFINITY_CORE_ALL".."0")
IntConstant("", "THREAD_AFFINITY_CORE_0".."1 << 0")
IntConstant("", "THREAD_AFFINITY_CORE_1".."1 << 1")
IntConstant("", "THREAD_AFFINITY_CORE_2".."1 << 2")
IntConstant("", "THREAD_AFFINITY_CORE_3".."1 << 3")
IntConstant("", "THREAD_AFFINITY_CORE_4".."1 << 4")
IntConstant("", "THREAD_AFFINITY_CORE_5".."1 << 5")
IntConstant("", "THREAD_AFFINITY_CORE_6".."1 << 6")
IntConstant("", "THREAD_AFFINITY_CORE_7".."1 << 7")
IntConstant("", "THREAD_AFFINITY_CORE_8".."1 << 8")
IntConstant("", "THREAD_AFFINITY_CORE_9".."1 << 9")
IntConstant("", "THREAD_AFFINITY_CORE_10".."1 << 10")
IntConstant("", "THREAD_AFFINITY_CORE_11".."1 << 11")
IntConstant("", "THREAD_AFFINITY_CORE_12".."1 << 12")
IntConstant("", "THREAD_AFFINITY_CORE_13".."1 << 13")
IntConstant("", "THREAD_AFFINITY_CORE_14".."1 << 14")
IntConstant("", "THREAD_AFFINITY_CORE_15".."1 << 15")
/* Preset for FMOD_REVERB_PROPERTIES */
// TODO
/*#define FMOD_PRESET_OFF { 1000, 7, 11, 5000, 100, 100, 100, 250, 0, 20, 96, -80.0f }
#define FMOD_PRESET_GENERIC { 1500, 7, 11, 5000, 83, 100, 100, 250, 0, 14500, 96, -8.0f }
#define FMOD_PRESET_PADDEDCELL { 170, 1, 2, 5000, 10, 100, 100, 250, 0, 160, 84, -7.8f }
#define FMOD_PRESET_ROOM { 400, 2, 3, 5000, 83, 100, 100, 250, 0, 6050, 88, -9.4f }
#define FMOD_PRESET_BATHROOM { 1500, 7, 11, 5000, 54, 100, 60, 250, 0, 2900, 83, 0.5f }
#define FMOD_PRESET_LIVINGROOM { 500, 3, 4, 5000, 10, 100, 100, 250, 0, 160, 58, -19.0f }
#define FMOD_PRESET_STONEROOM { 2300, 12, 17, 5000, 64, 100, 100, 250, 0, 7800, 71, -8.5f }
#define FMOD_PRESET_AUDITORIUM { 4300, 20, 30, 5000, 59, 100, 100, 250, 0, 5850, 64, -11.7f }
#define FMOD_PRESET_CONCERTHALL { 3900, 20, 29, 5000, 70, 100, 100, 250, 0, 5650, 80, -9.8f }
#define FMOD_PRESET_CAVE { 2900, 15, 22, 5000, 100, 100, 100, 250, 0, 20000, 59, -11.3f }
#define FMOD_PRESET_ARENA { 7200, 20, 30, 5000, 33, 100, 100, 250, 0, 4500, 80, -9.6f }
#define FMOD_PRESET_HANGAR { 10000, 20, 30, 5000, 23, 100, 100, 250, 0, 3400, 72, -7.4f }
#define FMOD_PRESET_CARPETTEDHALLWAY { 300, 2, 30, 5000, 10, 100, 100, 250, 0, 500, 56, -24.0f }
#define FMOD_PRESET_HALLWAY { 1500, 7, 11, 5000, 59, 100, 100, 250, 0, 7800, 87, -5.5f }
#define FMOD_PRESET_STONECORRIDOR { 270, 13, 20, 5000, 79, 100, 100, 250, 0, 9000, 86, -6.0f }
#define FMOD_PRESET_ALLEY { 1500, 7, 11, 5000, 86, 100, 100, 250, 0, 8300, 80, -9.8f }
#define FMOD_PRESET_FOREST { 1500, 162, 88, 5000, 54, 79, 100, 250, 0, 760, 94, -12.3f }
#define FMOD_PRESET_CITY { 1500, 7, 11, 5000, 67, 50, 100, 250, 0, 4050, 66, -26.0f }
#define FMOD_PRESET_MOUNTAINS { 1500, 300, 100, 5000, 21, 27, 100, 250, 0, 1220, 82, -24.0f }
#define FMOD_PRESET_QUARRY { 1500, 61, 25, 5000, 83, 100, 100, 250, 0, 3400, 100, -5.0f }
#define FMOD_PRESET_PLAIN { 1500, 179, 100, 5000, 50, 21, 100, 250, 0, 1670, 65, -28.0f }
#define FMOD_PRESET_PARKINGLOT { 1700, 8, 12, 5000, 100, 100, 100, 250, 0, 20000, 56, -19.5f }
#define FMOD_PRESET_SEWERPIPE { 2800, 14, 21, 5000, 14, 80, 60, 250, 0, 3400, 66, 1.2f }
#define FMOD_PRESET_UNDERWATER { 1500, 7, 11, 5000, 10, 100, 100, 250, 0, 500, 92, 7.0f }*/
IntConstant("", "MAX_CHANNEL_WIDTH".."32")
IntConstant("", "MAX_SYSTEMS".."8")
IntConstant("", "MAX_LISTENERS".."8")
IntConstant("", "REVERB_MAXINSTANCES".."4")
IntConstant("", "CODEC_PLUGIN_VERSION".."1")
IntConstant("", "CODEC_SEEK_METHOD_SET".."0")
IntConstant("", "CODEC_SEEK_METHOD_CURRENT".."1")
IntConstant("", "CODEC_SEEK_METHOD_END".."2")
IntConstant("", "DSP_LOUDNESS_METER_HISTOGRAM_SAMPLES".."66")
IntConstant("", "PLUGIN_SDK_VERSION".."110")
IntConstant("", "DSP_GETPARAM_VALUESTR_LENGTH".."32")
IntConstant("", "OUTPUT_PLUGIN_VERSION".."5")
IntConstant("", "OUTPUT_METHOD_MIX_DIRECT".."0")
IntConstant("", "OUTPUT_METHOD_MIX_BUFFERED".."1")
EnumConstant(
"{@code FMOD_THREAD_TYPE}",
"THREAD_TYPE_MIXER".enum("", "0"),
"THREAD_TYPE_FEEDER".enum,
"THREAD_TYPE_STREAM".enum,
"THREAD_TYPE_FILE".enum,
"THREAD_TYPE_NONBLOCKING".enum,
"THREAD_TYPE_RECORD".enum,
"THREAD_TYPE_GEOMETRY".enum,
"THREAD_TYPE_PROFILER".enum,
"THREAD_TYPE_STUDIO_UPDATE".enum,
"THREAD_TYPE_STUDIO_LOAD_BANK".enum,
"THREAD_TYPE_STUDIO_LOAD_SAMPLE".enum,
"THREAD_TYPE_CONVOLUTION1".enum,
"THREAD_TYPE_CONVOLUTION2".enum,
"THREAD_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_RESULT}",
"OK".enum("", "0"),
"ERR_BADCOMMAND".enum,
"ERR_CHANNEL_ALLOC".enum,
"ERR_CHANNEL_STOLEN".enum,
"ERR_DMA".enum,
"ERR_DSP_CONNECTION".enum,
"ERR_DSP_DONTPROCESS".enum,
"ERR_DSP_FORMAT".enum,
"ERR_DSP_INUSE".enum,
"ERR_DSP_NOTFOUND".enum,
"ERR_DSP_RESERVED".enum,
"ERR_DSP_SILENCE".enum,
"ERR_DSP_TYPE".enum,
"ERR_FILE_BAD".enum,
"ERR_FILE_COULDNOTSEEK".enum,
"ERR_FILE_DISKEJECTED".enum,
"ERR_FILE_EOF".enum,
"ERR_FILE_ENDOFDATA".enum,
"ERR_FILE_NOTFOUND".enum,
"ERR_FORMAT".enum,
"ERR_HEADER_MISMATCH".enum,
"ERR_HTTP".enum,
"ERR_HTTP_ACCESS".enum,
"ERR_HTTP_PROXY_AUTH".enum,
"ERR_HTTP_SERVER_ERROR".enum,
"ERR_HTTP_TIMEOUT".enum,
"ERR_INITIALIZATION".enum,
"ERR_INITIALIZED".enum,
"ERR_INTERNAL".enum,
"ERR_INVALID_FLOAT".enum,
"ERR_INVALID_HANDLE".enum,
"ERR_INVALID_PARAM".enum,
"ERR_INVALID_POSITION".enum,
"ERR_INVALID_SPEAKER".enum,
"ERR_INVALID_SYNCPOINT".enum,
"ERR_INVALID_THREAD".enum,
"ERR_INVALID_VECTOR".enum,
"ERR_MAXAUDIBLE".enum,
"ERR_MEMORY".enum,
"ERR_MEMORY_CANTPOINT".enum,
"ERR_NEEDS3D".enum,
"ERR_NEEDSHARDWARE".enum,
"ERR_NET_CONNECT".enum,
"ERR_NET_SOCKET_ERROR".enum,
"ERR_NET_URL".enum,
"ERR_NET_WOULD_BLOCK".enum,
"ERR_NOTREADY".enum,
"ERR_OUTPUT_ALLOCATED".enum,
"ERR_OUTPUT_CREATEBUFFER".enum,
"ERR_OUTPUT_DRIVERCALL".enum,
"ERR_OUTPUT_FORMAT".enum,
"ERR_OUTPUT_INIT".enum,
"ERR_OUTPUT_NODRIVERS".enum,
"ERR_PLUGIN".enum,
"ERR_PLUGIN_MISSING".enum,
"ERR_PLUGIN_RESOURCE".enum,
"ERR_PLUGIN_VERSION".enum,
"ERR_RECORD".enum,
"ERR_REVERB_CHANNELGROUP".enum,
"ERR_REVERB_INSTANCE".enum,
"ERR_SUBSOUNDS".enum,
"ERR_SUBSOUND_ALLOCATED".enum,
"ERR_SUBSOUND_CANTMOVE".enum,
"ERR_TAGNOTFOUND".enum,
"ERR_TOOMANYCHANNELS".enum,
"ERR_TRUNCATED".enum,
"ERR_UNIMPLEMENTED".enum,
"ERR_UNINITIALIZED".enum,
"ERR_UNSUPPORTED".enum,
"ERR_VERSION".enum,
"ERR_EVENT_ALREADY_LOADED".enum,
"ERR_EVENT_LIVEUPDATE_BUSY".enum,
"ERR_EVENT_LIVEUPDATE_MISMATCH".enum,
"ERR_EVENT_LIVEUPDATE_TIMEOUT".enum,
"ERR_EVENT_NOTFOUND".enum,
"ERR_STUDIO_UNINITIALIZED".enum,
"ERR_STUDIO_NOT_LOADED".enum,
"ERR_INVALID_STRING".enum,
"ERR_ALREADY_LOCKED".enum,
"ERR_NOT_LOCKED".enum,
"ERR_RECORD_DISCONNECTED".enum,
"ERR_TOOMANYSAMPLES".enum
)
EnumConstant(
"{@code FMOD_CHANNELCONTROL_TYPE}",
"CHANNELCONTROL_CHANNEL".enum("", "0"),
"CHANNELCONTROL_CHANNELGROUP".enum,
"CHANNELCONTROL_MAX".enum
)
EnumConstant(
"{@code FMOD_OUTPUTTYPE}",
"OUTPUTTYPE_AUTODETECT".enum("", "0"),
"OUTPUTTYPE_UNKNOWN".enum,
"OUTPUTTYPE_NOSOUND".enum,
"OUTPUTTYPE_WAVWRITER".enum,
"OUTPUTTYPE_NOSOUND_NRT".enum,
"OUTPUTTYPE_WAVWRITER_NRT".enum,
"OUTPUTTYPE_WASAPI".enum,
"OUTPUTTYPE_ASIO".enum,
"OUTPUTTYPE_PULSEAUDIO".enum,
"OUTPUTTYPE_ALSA".enum,
"OUTPUTTYPE_COREAUDIO".enum,
"OUTPUTTYPE_AUDIOTRACK".enum,
"OUTPUTTYPE_OPENSL".enum,
"OUTPUTTYPE_AUDIOOUT".enum,
"OUTPUTTYPE_AUDIO3D".enum,
"OUTPUTTYPE_WEBAUDIO".enum,
"OUTPUTTYPE_NNAUDIO".enum,
"OUTPUTTYPE_WINSONIC".enum,
"OUTPUTTYPE_AAUDIO".enum,
"OUTPUTTYPE_AUDIOWORKLET".enum,
"OUTPUTTYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_DEBUG_MODE}",
"DEBUG_MODE_TTY".enum("", "0"),
"DEBUG_MODE_FILE".enum,
"DEBUG_MODE_CALLBACK".enum
)
EnumConstant(
"{@code FMOD_SPEAKERMODE}",
"SPEAKERMODE_DEFAULT".enum("", "0"),
"SPEAKERMODE_RAW".enum,
"SPEAKERMODE_MONO".enum,
"SPEAKERMODE_STEREO".enum,
"SPEAKERMODE_QUAD".enum,
"SPEAKERMODE_SURROUND".enum,
"SPEAKERMODE_5POINT1".enum,
"SPEAKERMODE_7POINT1".enum,
"SPEAKERMODE_7POINT1POINT4".enum,
"SPEAKERMODE_MAX".enum
)
EnumConstant(
"{@code FMOD_SPEAKER}",
"SPEAKER_NONE".enum("", "-1"),
"SPEAKER_FRONT_LEFT".enum,
"SPEAKER_FRONT_RIGHT".enum,
"SPEAKER_FRONT_CENTER".enum,
"SPEAKER_LOW_FREQUENCY".enum,
"SPEAKER_SURROUND_LEFT".enum,
"SPEAKER_SURROUND_RIGHT".enum,
"SPEAKER_BACK_LEFT".enum,
"SPEAKER_BACK_RIGHT".enum,
"SPEAKER_TOP_FRONT_LEFT".enum,
"SPEAKER_TOP_FRONT_RIGHT".enum,
"SPEAKER_TOP_BACK_LEFT".enum,
"SPEAKER_TOP_BACK_RIGHT".enum,
"SPEAKER_MAX".enum
)
EnumConstant(
"{@code FMOD_CHANNELORDER}",
"CHANNELORDER_DEFAULT".enum("", "0"),
"CHANNELORDER_WAVEFORMAT".enum,
"CHANNELORDER_PROTOOLS".enum,
"CHANNELORDER_ALLMONO".enum,
"CHANNELORDER_ALLSTEREO".enum,
"CHANNELORDER_ALSA".enum,
"CHANNELORDER_MAX".enum
)
EnumConstant(
"{@code FMOD_PLUGINTYPE}",
"PLUGINTYPE_OUTPUT".enum("", "0"),
"PLUGINTYPE_CODEC".enum,
"PLUGINTYPE_DSP".enum,
"PLUGINTYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_SOUND_TYPE}",
"SOUND_TYPE_UNKNOWN".enum("", "0"),
"SOUND_TYPE_AIFF".enum,
"SOUND_TYPE_ASF".enum,
"SOUND_TYPE_DLS".enum,
"SOUND_TYPE_FLAC".enum,
"SOUND_TYPE_FSB".enum,
"SOUND_TYPE_IT".enum,
"SOUND_TYPE_MIDI".enum,
"SOUND_TYPE_MOD".enum,
"SOUND_TYPE_MPEG".enum,
"SOUND_TYPE_OGGVORBIS".enum,
"SOUND_TYPE_PLAYLIST".enum,
"SOUND_TYPE_RAW".enum,
"SOUND_TYPE_S3M".enum,
"SOUND_TYPE_USER".enum,
"SOUND_TYPE_WAV".enum,
"SOUND_TYPE_XM".enum,
"SOUND_TYPE_XMA".enum,
"SOUND_TYPE_AUDIOQUEUE".enum,
"SOUND_TYPE_AT9".enum,
"SOUND_TYPE_VORBIS".enum,
"SOUND_TYPE_MEDIA_FOUNDATION".enum,
"SOUND_TYPE_MEDIACODEC".enum,
"SOUND_TYPE_FADPCM".enum,
"SOUND_TYPE_OPUS".enum,
"SOUND_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_SOUND_FORMAT}",
"SOUND_FORMAT_NONE".enum("", "0"),
"SOUND_FORMAT_PCM8".enum,
"SOUND_FORMAT_PCM16".enum,
"SOUND_FORMAT_PCM24".enum,
"SOUND_FORMAT_PCM32".enum,
"SOUND_FORMAT_PCMFLOAT".enum,
"SOUND_FORMAT_BITSTREAM".enum,
"SOUND_FORMAT_MAX".enum
)
EnumConstant(
"{@code FMOD_OPENSTATE}",
"OPENSTATE_READY".enum("", "0"),
"OPENSTATE_LOADING".enum,
"OPENSTATE_ERROR".enum,
"OPENSTATE_CONNECTING".enum,
"OPENSTATE_BUFFERING".enum,
"OPENSTATE_SEEKING".enum,
"OPENSTATE_PLAYING".enum,
"OPENSTATE_SETPOSITION".enum,
"OPENSTATE_MAX".enum
)
EnumConstant(
"{@code FMOD_SOUNDGROUP_BEHAVIOR}",
"SOUNDGROUP_BEHAVIOR_FAIL".enum("", "0"),
"SOUNDGROUP_BEHAVIOR_MUTE".enum,
"SOUNDGROUP_BEHAVIOR_STEALLOWEST".enum,
"SOUNDGROUP_BEHAVIOR_MAX".enum
)
EnumConstant(
"{@code FMOD_CHANNELCONTROL_CALLBACK_TYPE}",
"CHANNELCONTROL_CALLBACK_END".enum("", "0"),
"CHANNELCONTROL_CALLBACK_VIRTUALVOICE".enum,
"CHANNELCONTROL_CALLBACK_SYNCPOINT".enum,
"CHANNELCONTROL_CALLBACK_OCCLUSION".enum,
"CHANNELCONTROL_CALLBACK_MAX".enum
)
EnumConstant(
"{@code FMOD_CHANNELCONTROL_DSP_INDEX}",
"CHANNELCONTROL_DSP_HEAD".enum("", "-1"),
"CHANNELCONTROL_DSP_FADER".enum("", "-2"),
"CHANNELCONTROL_DSP_TAIL".enum("", "-3")
)
EnumConstant(
"{@code FMOD_ERRORCALLBACK_INSTANCETYPE}",
"ERRORCALLBACK_INSTANCETYPE_NONE".enum("", "0"),
"ERRORCALLBACK_INSTANCETYPE_SYSTEM".enum,
"ERRORCALLBACK_INSTANCETYPE_CHANNEL".enum,
"ERRORCALLBACK_INSTANCETYPE_CHANNELGROUP".enum,
"ERRORCALLBACK_INSTANCETYPE_CHANNELCONTROL".enum,
"ERRORCALLBACK_INSTANCETYPE_SOUND".enum,
"ERRORCALLBACK_INSTANCETYPE_SOUNDGROUP".enum,
"ERRORCALLBACK_INSTANCETYPE_DSP".enum,
"ERRORCALLBACK_INSTANCETYPE_DSPCONNECTION".enum,
"ERRORCALLBACK_INSTANCETYPE_GEOMETRY".enum,
"ERRORCALLBACK_INSTANCETYPE_REVERB3D".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_SYSTEM".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_EVENTDESCRIPTION".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_EVENTINSTANCE".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_PARAMETERINSTANCE".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_BUS".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_VCA".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_BANK".enum,
"ERRORCALLBACK_INSTANCETYPE_STUDIO_COMMANDREPLAY".enum
)
EnumConstant(
"{@code FMOD_DSP_RESAMPLER}",
"DSP_RESAMPLER_DEFAULT".enum("", "0"),
"DSP_RESAMPLER_NOINTERP".enum,
"DSP_RESAMPLER_LINEAR".enum,
"DSP_RESAMPLER_CUBIC".enum,
"DSP_RESAMPLER_SPLINE".enum,
"DSP_RESAMPLER_MAX".enum
)
EnumConstant(
"{@code FMOD_DSPCONNECTION_TYPE}",
"DSPCONNECTION_TYPE_STANDARD".enum("", "0"),
"DSPCONNECTION_TYPE_SIDECHAIN".enum,
"DSPCONNECTION_TYPE_SEND".enum,
"DSPCONNECTION_TYPE_SEND_SIDECHAIN".enum,
"DSPCONNECTION_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_TAGTYPE}",
"TAGTYPE_UNKNOWN".enum("", "0"),
"TAGTYPE_ID3V1".enum,
"TAGTYPE_ID3V2".enum,
"TAGTYPE_VORBISCOMMENT".enum,
"TAGTYPE_SHOUTCAST".enum,
"TAGTYPE_ICECAST".enum,
"TAGTYPE_ASF".enum,
"TAGTYPE_MIDI".enum,
"TAGTYPE_PLAYLIST".enum,
"TAGTYPE_FMOD".enum,
"TAGTYPE_USER".enum,
"TAGTYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_TAGDATATYPE}",
"TAGDATATYPE_BINARY".enum("", "0"),
"TAGDATATYPE_INT".enum,
"TAGDATATYPE_FLOAT".enum,
"TAGDATATYPE_STRING".enum,
"TAGDATATYPE_STRING_UTF16".enum,
"TAGDATATYPE_STRING_UTF16BE".enum,
"TAGDATATYPE_STRING_UTF8".enum,
"TAGDATATYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_PORT_TYPE}",
"PORT_TYPE_MUSIC".enum("", "0"),
"PORT_TYPE_COPYRIGHT_MUSIC".enum,
"PORT_TYPE_VOICE".enum,
"PORT_TYPE_CONTROLLER".enum,
"PORT_TYPE_PERSONAL".enum,
"PORT_TYPE_VIBRATION".enum,
"PORT_TYPE_AUX".enum,
"PORT_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_DSP_TYPE}",
"DSP_TYPE_UNKNOWN".enum("", "0"),
"DSP_TYPE_MIXER".enum,
"DSP_TYPE_OSCILLATOR".enum,
"DSP_TYPE_LOWPASS".enum,
"DSP_TYPE_ITLOWPASS".enum,
"DSP_TYPE_HIGHPASS".enum,
"DSP_TYPE_ECHO".enum,
"DSP_TYPE_FADER".enum,
"DSP_TYPE_FLANGE".enum,
"DSP_TYPE_DISTORTION".enum,
"DSP_TYPE_NORMALIZE".enum,
"DSP_TYPE_LIMITER".enum,
"DSP_TYPE_PARAMEQ".enum,
"DSP_TYPE_PITCHSHIFT".enum,
"DSP_TYPE_CHORUS".enum,
"DSP_TYPE_VSTPLUGIN".enum,
"DSP_TYPE_WINAMPPLUGIN".enum,
"DSP_TYPE_ITECHO".enum,
"DSP_TYPE_COMPRESSOR".enum,
"DSP_TYPE_SFXREVERB".enum,
"DSP_TYPE_LOWPASS_SIMPLE".enum,
"DSP_TYPE_DELAY".enum,
"DSP_TYPE_TREMOLO".enum,
"DSP_TYPE_LADSPAPLUGIN".enum,
"DSP_TYPE_SEND".enum,
"DSP_TYPE_RETURN".enum,
"DSP_TYPE_HIGHPASS_SIMPLE".enum,
"DSP_TYPE_PAN".enum,
"DSP_TYPE_THREE_EQ".enum,
"DSP_TYPE_FFT".enum,
"DSP_TYPE_LOUDNESS_METER".enum,
"DSP_TYPE_ENVELOPEFOLLOWER".enum,
"DSP_TYPE_CONVOLUTIONREVERB".enum,
"DSP_TYPE_CHANNELMIX".enum,
"DSP_TYPE_TRANSCEIVER".enum,
"DSP_TYPE_OBJECTPAN".enum,
"DSP_TYPE_MULTIBAND_EQ".enum,
"DSP_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_DSP_OSCILLATOR}",
"DSP_OSCILLATOR_TYPE".enum("", "0"),
"DSP_OSCILLATOR_RATE".enum
)
EnumConstant(
"{@code FMOD_DSP_LOWPASS}",
"DSP_LOWPASS_CUTOFF".enum("", "0"),
"DSP_LOWPASS_RESONANCE".enum
)
EnumConstant(
"{@code FMOD_DSP_ITLOWPASS}",
"DSP_ITLOWPASS_CUTOFF".enum("", "0"),
"DSP_ITLOWPASS_RESONANCE".enum
)
EnumConstant(
"{@code FMOD_DSP_HIGHPASS}",
"DSP_HIGHPASS_CUTOFF".enum("", "0"),
"DSP_HIGHPASS_RESONANCE".enum
)
EnumConstant(
"{@code FMOD_DSP_ECHO}",
"DSP_ECHO_DELAY".enum("", "0"),
"DSP_ECHO_FEEDBACK".enum,
"DSP_ECHO_DRYLEVEL".enum,
"DSP_ECHO_WETLEVEL".enum
)
EnumConstant(
"{@code FMOD_DSP_FADER}",
"DSP_FADER_GAIN".enum("", "0"),
"DSP_FADER_OVERALL_GAIN".enum
)
EnumConstant(
"{@code FMOD_DSP_FLANGE}",
"DSP_FLANGE_MIX".enum("", "0"),
"DSP_FLANGE_DEPTH".enum,
"DSP_FLANGE_RATE".enum
)
EnumConstant(
"{@code FMOD_DSP_DISTORTION}",
"DSP_DISTORTION_LEVEL".enum("", "0")
)
EnumConstant(
"{@code FMOD_DSP_NORMALIZE}",
"DSP_NORMALIZE_FADETIME".enum("", "0"),
"DSP_NORMALIZE_THRESHOLD".enum,
"DSP_NORMALIZE_MAXAMP".enum
)
EnumConstant(
"{@code FMOD_DSP_LIMITER}",
"DSP_LIMITER_RELEASETIME".enum("", "0"),
"DSP_LIMITER_CEILING".enum,
"DSP_LIMITER_MAXIMIZERGAIN".enum,
"DSP_LIMITER_MODE".enum
)
EnumConstant(
"{@code FMOD_DSP_PARAMEQ}",
"DSP_PARAMEQ_CENTER".enum("", "0"),
"DSP_PARAMEQ_BANDWIDTH".enum,
"DSP_PARAMEQ_GAIN".enum
)
EnumConstant(
"{@code FMOD_DSP_MULTIBAND_EQ}",
"DSP_MULTIBAND_EQ_A_FILTER".enum("", "0"),
"DSP_MULTIBAND_EQ_A_FREQUENCY".enum,
"DSP_MULTIBAND_EQ_A_Q".enum,
"DSP_MULTIBAND_EQ_A_GAIN".enum,
"DSP_MULTIBAND_EQ_B_FILTER".enum,
"DSP_MULTIBAND_EQ_B_FREQUENCY".enum,
"DSP_MULTIBAND_EQ_B_Q".enum,
"DSP_MULTIBAND_EQ_B_GAIN".enum,
"DSP_MULTIBAND_EQ_C_FILTER".enum,
"DSP_MULTIBAND_EQ_C_FREQUENCY".enum,
"DSP_MULTIBAND_EQ_C_Q".enum,
"DSP_MULTIBAND_EQ_C_GAIN".enum,
"DSP_MULTIBAND_EQ_D_FILTER".enum,
"DSP_MULTIBAND_EQ_D_FREQUENCY".enum,
"DSP_MULTIBAND_EQ_D_Q".enum,
"DSP_MULTIBAND_EQ_D_GAIN".enum,
"DSP_MULTIBAND_EQ_E_FILTER".enum,
"DSP_MULTIBAND_EQ_E_FREQUENCY".enum,
"DSP_MULTIBAND_EQ_E_Q".enum,
"DSP_MULTIBAND_EQ_E_GAIN".enum
)
EnumConstant(
"{@code FMOD_DSP_MULTIBAND_EQ_FILTER_TYPE}",
"DSP_MULTIBAND_EQ_FILTER_DISABLED".enum("", "0"),
"DSP_MULTIBAND_EQ_FILTER_LOWPASS_12DB".enum,
"DSP_MULTIBAND_EQ_FILTER_LOWPASS_24DB".enum,
"DSP_MULTIBAND_EQ_FILTER_LOWPASS_48DB".enum,
"DSP_MULTIBAND_EQ_FILTER_HIGHPASS_12DB".enum,
"DSP_MULTIBAND_EQ_FILTER_HIGHPASS_24DB".enum,
"DSP_MULTIBAND_EQ_FILTER_HIGHPASS_48DB".enum,
"DSP_MULTIBAND_EQ_FILTER_LOWSHELF".enum,
"DSP_MULTIBAND_EQ_FILTER_HIGHSHELF".enum,
"DSP_MULTIBAND_EQ_FILTER_PEAKING".enum,
"DSP_MULTIBAND_EQ_FILTER_BANDPASS".enum,
"DSP_MULTIBAND_EQ_FILTER_NOTCH".enum,
"DSP_MULTIBAND_EQ_FILTER_ALLPASS".enum
)
EnumConstant(
"{@code FMOD_DSP_PITCHSHIFT}",
"DSP_PITCHSHIFT_PITCH".enum("", "0"),
"DSP_PITCHSHIFT_FFTSIZE".enum,
"DSP_PITCHSHIFT_OVERLAP".enum,
"DSP_PITCHSHIFT_MAXCHANNELS".enum
)
EnumConstant(
"{@code FMOD_DSP_CHORUS}",
"DSP_CHORUS_MIX".enum("", "0"),
"DSP_CHORUS_RATE".enum,
"DSP_CHORUS_DEPTH".enum
)
EnumConstant(
"{@code FMOD_DSP_ITECHO}",
"DSP_ITECHO_WETDRYMIX".enum("", "0"),
"DSP_ITECHO_FEEDBACK".enum,
"DSP_ITECHO_LEFTDELAY".enum,
"DSP_ITECHO_RIGHTDELAY".enum,
"DSP_ITECHO_PANDELAY".enum
)
EnumConstant(
"{@code FMOD_DSP_COMPRESSOR}",
"DSP_COMPRESSOR_THRESHOLD".enum("", "0"),
"DSP_COMPRESSOR_RATIO".enum,
"DSP_COMPRESSOR_ATTACK".enum,
"DSP_COMPRESSOR_RELEASE".enum,
"DSP_COMPRESSOR_GAINMAKEUP".enum,
"DSP_COMPRESSOR_USESIDECHAIN".enum,
"DSP_COMPRESSOR_LINKED".enum
)
EnumConstant(
"{@code FMOD_DSP_SFXREVERB}",
"DSP_SFXREVERB_DECAYTIME".enum("", "0"),
"DSP_SFXREVERB_EARLYDELAY".enum,
"DSP_SFXREVERB_LATEDELAY".enum,
"DSP_SFXREVERB_HFREFERENCE".enum,
"DSP_SFXREVERB_HFDECAYRATIO".enum,
"DSP_SFXREVERB_DIFFUSION".enum,
"DSP_SFXREVERB_DENSITY".enum,
"DSP_SFXREVERB_LOWSHELFFREQUENCY".enum,
"DSP_SFXREVERB_LOWSHELFGAIN".enum,
"DSP_SFXREVERB_HIGHCUT".enum,
"DSP_SFXREVERB_EARLYLATEMIX".enum,
"DSP_SFXREVERB_WETLEVEL".enum,
"DSP_SFXREVERB_DRYLEVEL".enum
)
EnumConstant(
"{@code FMOD_DSP_LOWPASS_SIMPLE}",
"DSP_LOWPASS_SIMPLE_CUTOFF".enum("", "0")
)
EnumConstant(
"{@code FMOD_DSP_DELAY}",
"DSP_DELAY_CH0".enum("", "0"),
"DSP_DELAY_CH1".enum,
"DSP_DELAY_CH2".enum,
"DSP_DELAY_CH3".enum,
"DSP_DELAY_CH4".enum,
"DSP_DELAY_CH5".enum,
"DSP_DELAY_CH6".enum,
"DSP_DELAY_CH7".enum,
"DSP_DELAY_CH8".enum,
"DSP_DELAY_CH9".enum,
"DSP_DELAY_CH10".enum,
"DSP_DELAY_CH11".enum,
"DSP_DELAY_CH12".enum,
"DSP_DELAY_CH13".enum,
"DSP_DELAY_CH14".enum,
"DSP_DELAY_CH15".enum,
"DSP_DELAY_MAXDELAY".enum
)
EnumConstant(
"{@code FMOD_DSP_TREMOLO}",
"DSP_TREMOLO_FREQUENCY".enum("", "0"),
"DSP_TREMOLO_DEPTH".enum,
"DSP_TREMOLO_SHAPE".enum,
"DSP_TREMOLO_SKEW".enum,
"DSP_TREMOLO_DUTY".enum,
"DSP_TREMOLO_SQUARE".enum,
"DSP_TREMOLO_PHASE".enum,
"DSP_TREMOLO_SPREAD".enum
)
EnumConstant(
"{@code FMOD_DSP_SEND}",
"DSP_SEND_RETURNID".enum("", "0"),
"DSP_SEND_LEVEL".enum
)
EnumConstant(
"{@code FMOD_DSP_RETURN}",
"DSP_RETURN_ID".enum("", "0"),
"DSP_RETURN_INPUT_SPEAKER_MODE".enum
)
EnumConstant(
"{@code FMOD_DSP_HIGHPASS_SIMPLE}",
"DSP_HIGHPASS_SIMPLE_CUTOFF".enum("", "0")
)
EnumConstant(
"{@code FMOD_DSP_PAN_2D_STEREO_MODE_TYPE}",
"DSP_PAN_2D_STEREO_MODE_DISTRIBUTED".enum("", "0"),
"DSP_PAN_2D_STEREO_MODE_DISCRETE".enum
)
EnumConstant(
"{@code FMOD_DSP_PAN_MODE_TYPE}",
"DSP_PAN_MODE_MONO".enum("", "0"),
"DSP_PAN_MODE_STEREO".enum,
"DSP_PAN_MODE_SURROUND".enum
)
EnumConstant(
"{@code FMOD_DSP_PAN_3D_ROLLOFF_TYPE}",
"DSP_PAN_3D_ROLLOFF_LINEARSQUARED".enum("", "0"),
"DSP_PAN_3D_ROLLOFF_LINEAR".enum,
"DSP_PAN_3D_ROLLOFF_INVERSE".enum,
"DSP_PAN_3D_ROLLOFF_INVERSETAPERED".enum,
"DSP_PAN_3D_ROLLOFF_CUSTOM".enum
)
EnumConstant(
"{@code FMOD_DSP_PAN_3D_EXTENT_MODE_TYPE}",
"DSP_PAN_3D_EXTENT_MODE_AUTO".enum("", "0"),
"DSP_PAN_3D_EXTENT_MODE_USER".enum,
"DSP_PAN_3D_EXTENT_MODE_OFF".enum
)
EnumConstant(
"{@code FMOD_DSP_PAN}",
"DSP_PAN_MODE".enum("", "0"),
"DSP_PAN_2D_STEREO_POSITION".enum,
"DSP_PAN_2D_DIRECTION".enum,
"DSP_PAN_2D_EXTENT".enum,
"DSP_PAN_2D_ROTATION".enum,
"DSP_PAN_2D_LFE_LEVEL".enum,
"DSP_PAN_2D_STEREO_MODE".enum,
"DSP_PAN_2D_STEREO_SEPARATION".enum,
"DSP_PAN_2D_STEREO_AXIS".enum,
"DSP_PAN_ENABLED_SPEAKERS".enum,
"DSP_PAN_3D_POSITION".enum,
"DSP_PAN_3D_ROLLOFF".enum,
"DSP_PAN_3D_MIN_DISTANCE".enum,
"DSP_PAN_3D_MAX_DISTANCE".enum,
"DSP_PAN_3D_EXTENT_MODE".enum,
"DSP_PAN_3D_SOUND_SIZE".enum,
"DSP_PAN_3D_MIN_EXTENT".enum,
"DSP_PAN_3D_PAN_BLEND".enum,
"DSP_PAN_LFE_UPMIX_ENABLED".enum,
"DSP_PAN_OVERALL_GAIN".enum,
"DSP_PAN_SURROUND_SPEAKER_MODE".enum,
"DSP_PAN_2D_HEIGHT_BLEND".enum,
"DSP_PAN_ATTENUATION_RANGE".enum,
"DSP_PAN_OVERRIDE_RANGE".enum
)
EnumConstant(
"{@code FMOD_DSP_THREE_EQ_CROSSOVERSLOPE_TYPE}",
"DSP_THREE_EQ_CROSSOVERSLOPE_12DB".enum("", "0"),
"DSP_THREE_EQ_CROSSOVERSLOPE_24DB".enum,
"DSP_THREE_EQ_CROSSOVERSLOPE_48DB".enum
)
EnumConstant(
"{@code FMOD_DSP_THREE_EQ}",
"DSP_THREE_EQ_LOWGAIN".enum("", "0"),
"DSP_THREE_EQ_MIDGAIN".enum,
"DSP_THREE_EQ_HIGHGAIN".enum,
"DSP_THREE_EQ_LOWCROSSOVER".enum,
"DSP_THREE_EQ_HIGHCROSSOVER".enum,
"DSP_THREE_EQ_CROSSOVERSLOPE".enum
)
EnumConstant(
"{@code FMOD_DSP_FFT_WINDOW}",
"DSP_FFT_WINDOW_RECT".enum("", "0"),
"DSP_FFT_WINDOW_TRIANGLE".enum,
"DSP_FFT_WINDOW_HAMMING".enum,
"DSP_FFT_WINDOW_HANNING".enum,
"DSP_FFT_WINDOW_BLACKMAN".enum,
"DSP_FFT_WINDOW_BLACKMANHARRIS".enum
)
EnumConstant(
"{@code FMOD_DSP_FFT}",
"DSP_FFT_WINDOWSIZE".enum("", "0"),
"DSP_FFT_WINDOWTYPE".enum,
"DSP_FFT_SPECTRUMDATA".enum,
"DSP_FFT_DOMINANT_FREQ".enum
)
EnumConstant(
"{@code FMOD_DSP_LOUDNESS_METER}",
"DSP_LOUDNESS_METER_STATE".enum("", "0"),
"DSP_LOUDNESS_METER_WEIGHTING".enum,
"DSP_LOUDNESS_METER_INFO".enum
)
EnumConstant(
"{@code FMOD_DSP_LOUDNESS_METER_STATE_TYPE}",
"DSP_LOUDNESS_METER_STATE_RESET_INTEGRATED".enum("", "-3"),
"DSP_LOUDNESS_METER_STATE_RESET_MAXPEAK".enum,
"DSP_LOUDNESS_METER_STATE_RESET_ALL".enum,
"DSP_LOUDNESS_METER_STATE_PAUSED".enum,
"DSP_LOUDNESS_METER_STATE_ANALYZING".enum
)
EnumConstant(
"{@code FMOD_DSP_ENVELOPEFOLLOWER}",
"DSP_ENVELOPEFOLLOWER_ATTACK".enum("", "0"),
"DSP_ENVELOPEFOLLOWER_RELEASE".enum,
"DSP_ENVELOPEFOLLOWER_ENVELOPE".enum,
"DSP_ENVELOPEFOLLOWER_USESIDECHAIN".enum
)
EnumConstant(
"{@code FMOD_DSP_CONVOLUTION_REVERB}",
"DSP_CONVOLUTION_REVERB_PARAM_IR".enum("", "0"),
"DSP_CONVOLUTION_REVERB_PARAM_WET".enum,
"DSP_CONVOLUTION_REVERB_PARAM_DRY".enum,
"DSP_CONVOLUTION_REVERB_PARAM_LINKED".enum
)
EnumConstant(
"{@code FMOD_DSP_CHANNELMIX_OUTPUT}",
"DSP_CHANNELMIX_OUTPUT_DEFAULT".enum("", "0"),
"DSP_CHANNELMIX_OUTPUT_ALLMONO".enum,
"DSP_CHANNELMIX_OUTPUT_ALLSTEREO".enum,
"DSP_CHANNELMIX_OUTPUT_ALLQUAD".enum,
"DSP_CHANNELMIX_OUTPUT_ALL5POINT1".enum,
"DSP_CHANNELMIX_OUTPUT_ALL7POINT1".enum,
"DSP_CHANNELMIX_OUTPUT_ALLLFE".enum,
"DSP_CHANNELMIX_OUTPUT_ALL7POINT1POINT4".enum
)
EnumConstant(
"{@code FMOD_DSP_CHANNELMIX}",
"DSP_CHANNELMIX_OUTPUTGROUPING".enum("", "0"),
"DSP_CHANNELMIX_GAIN_CH0".enum,
"DSP_CHANNELMIX_GAIN_CH1".enum,
"DSP_CHANNELMIX_GAIN_CH2".enum,
"DSP_CHANNELMIX_GAIN_CH3".enum,
"DSP_CHANNELMIX_GAIN_CH4".enum,
"DSP_CHANNELMIX_GAIN_CH5".enum,
"DSP_CHANNELMIX_GAIN_CH6".enum,
"DSP_CHANNELMIX_GAIN_CH7".enum,
"DSP_CHANNELMIX_GAIN_CH8".enum,
"DSP_CHANNELMIX_GAIN_CH9".enum,
"DSP_CHANNELMIX_GAIN_CH10".enum,
"DSP_CHANNELMIX_GAIN_CH11".enum,
"DSP_CHANNELMIX_GAIN_CH12".enum,
"DSP_CHANNELMIX_GAIN_CH13".enum,
"DSP_CHANNELMIX_GAIN_CH14".enum,
"DSP_CHANNELMIX_GAIN_CH15".enum,
"DSP_CHANNELMIX_GAIN_CH16".enum,
"DSP_CHANNELMIX_GAIN_CH17".enum,
"DSP_CHANNELMIX_GAIN_CH18".enum,
"DSP_CHANNELMIX_GAIN_CH19".enum,
"DSP_CHANNELMIX_GAIN_CH20".enum,
"DSP_CHANNELMIX_GAIN_CH21".enum,
"DSP_CHANNELMIX_GAIN_CH22".enum,
"DSP_CHANNELMIX_GAIN_CH23".enum,
"DSP_CHANNELMIX_GAIN_CH24".enum,
"DSP_CHANNELMIX_GAIN_CH25".enum,
"DSP_CHANNELMIX_GAIN_CH26".enum,
"DSP_CHANNELMIX_GAIN_CH27".enum,
"DSP_CHANNELMIX_GAIN_CH28".enum,
"DSP_CHANNELMIX_GAIN_CH29".enum,
"DSP_CHANNELMIX_GAIN_CH30".enum,
"DSP_CHANNELMIX_GAIN_CH31".enum,
"DSP_CHANNELMIX_OUTPUT_CH0".enum,
"DSP_CHANNELMIX_OUTPUT_CH1".enum,
"DSP_CHANNELMIX_OUTPUT_CH2".enum,
"DSP_CHANNELMIX_OUTPUT_CH3".enum,
"DSP_CHANNELMIX_OUTPUT_CH4".enum,
"DSP_CHANNELMIX_OUTPUT_CH5".enum,
"DSP_CHANNELMIX_OUTPUT_CH6".enum,
"DSP_CHANNELMIX_OUTPUT_CH7".enum,
"DSP_CHANNELMIX_OUTPUT_CH8".enum,
"DSP_CHANNELMIX_OUTPUT_CH9".enum,
"DSP_CHANNELMIX_OUTPUT_CH10".enum,
"DSP_CHANNELMIX_OUTPUT_CH11".enum,
"DSP_CHANNELMIX_OUTPUT_CH12".enum,
"DSP_CHANNELMIX_OUTPUT_CH13".enum,
"DSP_CHANNELMIX_OUTPUT_CH14".enum,
"DSP_CHANNELMIX_OUTPUT_CH15".enum,
"DSP_CHANNELMIX_OUTPUT_CH16".enum,
"DSP_CHANNELMIX_OUTPUT_CH17".enum,
"DSP_CHANNELMIX_OUTPUT_CH18".enum,
"DSP_CHANNELMIX_OUTPUT_CH19".enum,
"DSP_CHANNELMIX_OUTPUT_CH20".enum,
"DSP_CHANNELMIX_OUTPUT_CH21".enum,
"DSP_CHANNELMIX_OUTPUT_CH22".enum,
"DSP_CHANNELMIX_OUTPUT_CH23".enum,
"DSP_CHANNELMIX_OUTPUT_CH24".enum,
"DSP_CHANNELMIX_OUTPUT_CH25".enum,
"DSP_CHANNELMIX_OUTPUT_CH26".enum,
"DSP_CHANNELMIX_OUTPUT_CH27".enum,
"DSP_CHANNELMIX_OUTPUT_CH28".enum,
"DSP_CHANNELMIX_OUTPUT_CH29".enum,
"DSP_CHANNELMIX_OUTPUT_CH30".enum,
"DSP_CHANNELMIX_OUTPUT_CH31".enum
)
EnumConstant(
"{@code FMOD_DSP_TRANSCEIVER_SPEAKERMODE}",
"DSP_TRANSCEIVER_SPEAKERMODE_AUTO".enum("", "-1"),
"DSP_TRANSCEIVER_SPEAKERMODE_MONO".enum,
"DSP_TRANSCEIVER_SPEAKERMODE_STEREO".enum,
"DSP_TRANSCEIVER_SPEAKERMODE_SURROUND".enum
)
EnumConstant(
"{@code FMOD_DSP_TRANSCEIVER}",
"DSP_TRANSCEIVER_TRANSMIT".enum("", "0"),
"DSP_TRANSCEIVER_GAIN".enum,
"DSP_TRANSCEIVER_CHANNEL".enum,
"DSP_TRANSCEIVER_TRANSMITSPEAKERMODE".enum
)
EnumConstant(
"{@code FMOD_DSP_OBJECTPAN}",
"DSP_OBJECTPAN_3D_POSITION".enum("", "0"),
"DSP_OBJECTPAN_3D_ROLLOFF".enum,
"DSP_OBJECTPAN_3D_MIN_DISTANCE".enum,
"DSP_OBJECTPAN_3D_MAX_DISTANCE".enum,
"DSP_OBJECTPAN_3D_EXTENT_MODE".enum,
"DSP_OBJECTPAN_3D_SOUND_SIZE".enum,
"DSP_OBJECTPAN_3D_MIN_EXTENT".enum,
"DSP_OBJECTPAN_OVERALL_GAIN".enum,
"DSP_OBJECTPAN_OUTPUTGAIN".enum,
"DSP_OBJECTPAN_ATTENUATION_RANGE".enum,
"DSP_OBJECTPAN_OVERRIDE_RANGE".enum
)
EnumConstant(
"{@code FMOD_DSP_PROCESS_OPERATION}",
"DSP_PROCESS_PERFORM".enum("", "0"),
"DSP_PROCESS_QUERY".enum
)
EnumConstant(
"{@code FMOD_DSP_PAN_SURROUND_FLAGS}",
"DSP_PAN_SURROUND_DEFAULT".enum("", "0"),
"DSP_PAN_SURROUND_ROTATION_NOT_BIASED".enum
)
EnumConstant(
"{@code FMOD_DSP_PARAMETER_TYPE}",
"DSP_PARAMETER_TYPE_FLOAT".enum("", "0"),
"DSP_PARAMETER_TYPE_INT".enum,
"DSP_PARAMETER_TYPE_BOOL".enum,
"DSP_PARAMETER_TYPE_DATA".enum,
"DSP_PARAMETER_TYPE_MAX".enum
)
EnumConstant(
"{@code FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE}",
"DSP_PARAMETER_FLOAT_MAPPING_TYPE_LINEAR".enum("", "0"),
"DSP_PARAMETER_FLOAT_MAPPING_TYPE_AUTO".enum,
"DSP_PARAMETER_FLOAT_MAPPING_TYPE_PIECEWISE_LINEAR".enum
)
EnumConstant(
"{@code FMOD_DSP_PARAMETER_DATA_TYPE}",
"DSP_PARAMETER_DATA_TYPE_USER".enum("", "0"),
"DSP_PARAMETER_DATA_TYPE_OVERALLGAIN".enum("", "-1"),
"DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES".enum("", "-2"),
"DSP_PARAMETER_DATA_TYPE_SIDECHAIN".enum("", "-3"),
"DSP_PARAMETER_DATA_TYPE_FFT".enum("", "-4"),
"DSP_PARAMETER_DATA_TYPE_3DATTRIBUTES_MULTI".enum("", "-5"),
"DSP_PARAMETER_DATA_TYPE_ATTENUATION_RANGE".enum("", "-6")
)
FMOD_RESULT(
"Memory_Initialize",
"",
nullable..void.p("poolmem", ""),
AutoSize("poolmem")..int("poollen", ""),
nullable..FMOD_MEMORY_ALLOC_CALLBACK("useralloc", ""),
nullable..FMOD_MEMORY_REALLOC_CALLBACK("userrealloc", ""),
nullable..FMOD_MEMORY_FREE_CALLBACK("userfree", ""),
FMOD_MEMORY_TYPE("memtypeflags", "")
)
FMOD_RESULT(
"Memory_GetStats",
"",
nullable..Check(1)..int.p("currentalloced", ""),
nullable..Check(1)..int.p("maxalloced", ""),
FMOD_BOOL("blocking", "")
)
FMOD_RESULT(
"Debug_Initialize",
"",
FMOD_DEBUG_FLAGS("flags", ""),
FMOD_DEBUG_MODE("mode", ""),
nullable..FMOD_DEBUG_CALLBACK("callback", ""),
nullable..charUTF8.const.p("filename", "")
)
FMOD_RESULT(
"File_SetDiskBusy",
"",
int("busy", "")
)
FMOD_RESULT(
"File_GetDiskBusy",
"",
Check(1)..int.p("busy", "")
)
FMOD_RESULT(
"Thread_SetAttributes",
"",
FMOD_THREAD_TYPE("type", ""),
FMOD_THREAD_AFFINITY("affinity", ""),
FMOD_THREAD_PRIORITY("priority", ""),
FMOD_THREAD_STACK_SIZE("stacksize", "")
)
FMOD_RESULT(
"System_Create",
"FMOD System factory functions. Use this to create an FMOD System Instance. below you will see FMOD_System_Init/Close to get started.",
Check(1)..FMOD_SYSTEM.p.p("system", ""),
unsigned_int("headerversion", "")
)
FMOD_RESULT(
"System_Release",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_SetOutput",
"Setup functions.",
FMOD_SYSTEM.p("system", ""),
FMOD_OUTPUTTYPE("output", "")
)
FMOD_RESULT(
"System_GetOutput",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..FMOD_OUTPUTTYPE.p("output", "")
)
FMOD_RESULT(
"System_GetNumDrivers",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..int.p("numdrivers", "")
)
FMOD_RESULT(
"System_GetDriverInfo",
"",
FMOD_SYSTEM.p("system", ""),
int("id", ""),
nullable..char.p("name", ""),
AutoSize("name")..int("namelen", ""),
nullable..FMOD_GUID.p("guid", ""),
nullable..Check(1)..int.p("systemrate", ""),
nullable..Check(1)..FMOD_SPEAKERMODE.p("speakermode", ""),
nullable..Check(1)..int.p("speakermodechannels", "")
)
FMOD_RESULT(
"System_SetDriver",
"",
FMOD_SYSTEM.p("system", ""),
int("driver", "")
)
FMOD_RESULT(
"System_GetDriver",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..int.p("driver", "")
)
FMOD_RESULT(
"System_SetSoftwareChannels",
"",
FMOD_SYSTEM.p("system", ""),
int("numsoftwarechannels", "")
)
FMOD_RESULT(
"System_GetSoftwareChannels",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..int.p("numsoftwarechannels", "")
)
FMOD_RESULT(
"System_SetSoftwareFormat",
"",
FMOD_SYSTEM.p("system", ""),
int("samplerate", ""),
FMOD_SPEAKERMODE("speakermode", ""),
int("numrawspeakers", "")
)
FMOD_RESULT(
"System_GetSoftwareFormat",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..int.p("samplerate", ""),
nullable..Check(1)..FMOD_SPEAKERMODE.p("speakermode", ""),
nullable..Check(1)..int.p("numrawspeakers", "")
)
FMOD_RESULT(
"System_SetDSPBufferSize",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("bufferlength", ""),
int("numbuffers", "")
)
FMOD_RESULT(
"System_GetDSPBufferSize",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..unsigned_int.p("bufferlength", ""),
nullable..Check(1)..int.p("numbuffers", "")
)
FMOD_RESULT(
"System_SetFileSystem",
"",
FMOD_SYSTEM.p("system", ""),
nullable..FMOD_FILE_OPEN_CALLBACK("useropen", ""),
nullable..FMOD_FILE_CLOSE_CALLBACK("userclose", ""),
nullable..FMOD_FILE_READ_CALLBACK("userread", ""),
nullable..FMOD_FILE_SEEK_CALLBACK("userseek", ""),
nullable..FMOD_FILE_ASYNCREAD_CALLBACK("userasyncread", ""),
nullable..FMOD_FILE_ASYNCCANCEL_CALLBACK("userasynccancel", ""),
int("blockalign", "")
)
FMOD_RESULT(
"System_AttachFileSystem",
"",
FMOD_SYSTEM.p("system", ""),
nullable..FMOD_FILE_OPEN_CALLBACK("useropen", ""),
nullable..FMOD_FILE_CLOSE_CALLBACK("userclose", ""),
nullable..FMOD_FILE_READ_CALLBACK("userread", ""),
nullable..FMOD_FILE_SEEK_CALLBACK("userseek", "")
)
FMOD_RESULT(
"System_SetAdvancedSettings",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_ADVANCEDSETTINGS.p("settings", "")
)
FMOD_RESULT(
"System_GetAdvancedSettings",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_ADVANCEDSETTINGS.p("settings", "")
)
FMOD_RESULT(
"System_SetCallback",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SYSTEM_CALLBACK("callback", ""),
FMOD_SYSTEM_CALLBACK_TYPE("callbackmask", "")
)
FMOD_RESULT(
"System_SetPluginPath",
"Plug-in support.",
FMOD_SYSTEM.p("system", ""),
charUTF8.const.p("path", "")
)
FMOD_RESULT(
"System_LoadPlugin",
"",
FMOD_SYSTEM.p("system", ""),
charUTF8.const.p("filename", ""),
Check(1)..unsigned_int.p("handle", ""),
unsigned_int("priority", "")
)
FMOD_RESULT(
"System_UnloadPlugin",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", "")
)
FMOD_RESULT(
"System_GetNumNestedPlugins",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", ""),
Check(1)..int.p("count", "")
)
FMOD_RESULT(
"System_GetNestedPlugin",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", ""),
int("index", ""),
Check(1)..unsigned_int.p("nestedhandle", "")
)
FMOD_RESULT(
"System_GetNumPlugins",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_PLUGINTYPE("plugintype", ""),
Check(1)..int.p("numplugins", "")
)
FMOD_RESULT(
"System_GetPluginHandle",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_PLUGINTYPE("plugintype", ""),
int("index", ""),
Check(1)..unsigned_int.p("handle", "")
)
FMOD_RESULT(
"System_GetPluginInfo",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", ""),
nullable..Check(1)..FMOD_PLUGINTYPE.p("plugintype", ""),
nullable..char.p("name", ""),
AutoSize("name")..int("namelen", ""),
nullable..Check(1)..unsigned_int.p("version", "")
)
FMOD_RESULT(
"System_SetOutputByPlugin",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", "")
)
FMOD_RESULT(
"System_GetOutputByPlugin",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..unsigned_int.p("handle", "")
)
FMOD_RESULT(
"System_CreateDSPByPlugin",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", ""),
Check(1)..FMOD_DSP.p.p("dsp", "")
)
FMOD_RESULT(
"System_GetDSPInfoByPlugin",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("handle", ""),
Check(1)..FMOD_DSP_DESCRIPTION.const.p.p("description", "")
)
FMOD_RESULT(
"System_RegisterCodec",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_CODEC_DESCRIPTION.p("description", ""),
Check(1)..unsigned_int.p("handle", ""),
unsigned_int("priority", "")
)
FMOD_RESULT(
"System_RegisterDSP",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_DSP_DESCRIPTION.const.p("description", ""),
Check(1)..unsigned_int.p("handle", "")
)
FMOD_RESULT(
"System_RegisterOutput",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_OUTPUT_DESCRIPTION.const.p("description", ""),
Check(1)..unsigned_int.p("handle", "")
)
FMOD_RESULT(
"System_Init",
"",
FMOD_SYSTEM.p("system", ""),
int("maxchannels", ""),
FMOD_INITFLAGS("flags", ""),
nullable..opaque_p("extradriverdata", "")
)
FMOD_RESULT(
"System_Close",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_Update",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_SetSpeakerPosition",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SPEAKER("speaker", ""),
float("x", ""),
float("y", ""),
FMOD_BOOL("active", "")
)
FMOD_RESULT(
"System_GetSpeakerPosition",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SPEAKER("speaker", ""),
nullable..Check(1)..float.p("x", ""),
nullable..Check(1)..float.p("y", ""),
nullable..Check(1)..FMOD_BOOL.p("active", "")
)
FMOD_RESULT(
"System_SetStreamBufferSize",
"",
FMOD_SYSTEM.p("system", ""),
unsigned_int("filebuffersize", ""),
FMOD_TIMEUNIT("filebuffersizetype", "")
)
FMOD_RESULT(
"System_GetStreamBufferSize",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..unsigned_int.p("filebuffersize", ""),
nullable..Check(1)..FMOD_TIMEUNIT.p("filebuffersizetype", "")
)
FMOD_RESULT(
"System_Set3DSettings",
"",
FMOD_SYSTEM.p("system", ""),
float("dopplerscale", ""),
float("distancefactor", ""),
float("rolloffscale", "")
)
FMOD_RESULT(
"System_Get3DSettings",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..float.p("dopplerscale", ""),
nullable..Check(1)..float.p("distancefactor", ""),
nullable..Check(1)..float.p("rolloffscale", "")
)
FMOD_RESULT(
"System_Set3DNumListeners",
"",
FMOD_SYSTEM.p("system", ""),
int("numlisteners", "")
)
FMOD_RESULT(
"System_Get3DNumListeners",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..int.p("numlisteners", "")
)
FMOD_RESULT(
"System_Set3DListenerAttributes",
"",
FMOD_SYSTEM.p("system", ""),
int("listener", ""),
nullable..FMOD_VECTOR.const.p("pos", ""),
nullable..FMOD_VECTOR.const.p("vel", ""),
nullable..FMOD_VECTOR.const.p("forward", ""),
nullable..FMOD_VECTOR.const.p("up", "")
)
FMOD_RESULT(
"System_Get3DListenerAttributes",
"",
FMOD_SYSTEM.p("system", ""),
int("listener", ""),
nullable..FMOD_VECTOR.p("pos", ""),
nullable..FMOD_VECTOR.p("vel", ""),
nullable..FMOD_VECTOR.p("forward", ""),
nullable..FMOD_VECTOR.p("up", "")
)
FMOD_RESULT(
"System_Set3DRolloffCallback",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_3D_ROLLOFF_CALLBACK("callback", "")
)
FMOD_RESULT(
"System_MixerSuspend",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_MixerResume",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_GetDefaultMixMatrix",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SPEAKERMODE("sourcespeakermode", ""),
FMOD_SPEAKERMODE("targetspeakermode", ""),
Unsafe..float.p("matrix", ""),
int("matrixhop", "")
)
FMOD_RESULT(
"System_GetSpeakerModeChannels",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SPEAKERMODE("mode", ""),
Check(1)..int.p("channels", "")
)
FMOD_RESULT(
"System_GetVersion",
"System information functions.",
FMOD_SYSTEM.p("system", ""),
Check(1)..unsigned_int.p("version", "")
)
FMOD_RESULT(
"System_GetOutputHandle",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..void.p.p("handle", "")
)
FMOD_RESULT(
"System_GetChannelsPlaying",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..int.p("channels", ""),
nullable..Check(1)..int.p("realchannels", "")
)
FMOD_RESULT(
"System_GetCPUUsage",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_CPU_USAGE.p("usage", "")
)
FMOD_RESULT(
"System_GetFileUsage",
"",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..long_long.p("sampleBytesRead", ""),
nullable..Check(1)..long_long.p("streamBytesRead", ""),
nullable..Check(1)..long_long.p("otherBytesRead", "")
)
FMOD_RESULT(
"System_CreateSound",
"Sound/DSP/Channel/FX creation and retrieval.",
FMOD_SYSTEM.p("system", ""),
Unsafe..char.const.p("name_or_data", ""),
FMOD_MODE("mode", ""),
nullable..FMOD_CREATESOUNDEXINFO.p("exinfo", ""),
Check(1)..FMOD_SOUND.p.p("sound", "")
)
FMOD_RESULT(
"System_CreateStream",
"",
FMOD_SYSTEM.p("system", ""),
Unsafe..char.const.p("name_or_data", ""),
FMOD_MODE("mode", ""),
nullable..FMOD_CREATESOUNDEXINFO.p("exinfo", ""),
Check(1)..FMOD_SOUND.p.p("sound", "")
)
FMOD_RESULT(
"System_CreateDSP",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_DSP_DESCRIPTION.const.p("description", ""),
Check(1)..FMOD_DSP.p.p("dsp", "")
)
FMOD_RESULT(
"System_CreateDSPByType",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_DSP_TYPE("type", ""),
Check(1)..FMOD_DSP.p.p("dsp", "")
)
FMOD_RESULT(
"System_CreateChannelGroup",
"",
FMOD_SYSTEM.p("system", ""),
nullable..charUTF8.const.p("name", ""),
Check(1)..FMOD_CHANNELGROUP.p.p("channelgroup", "")
)
FMOD_RESULT(
"System_CreateSoundGroup",
"",
FMOD_SYSTEM.p("system", ""),
charUTF8.const.p("name", ""),
Check(1)..FMOD_SOUNDGROUP.p.p("soundgroup", "")
)
FMOD_RESULT(
"System_CreateReverb3D",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..FMOD_REVERB3D.p.p("reverb", "")
)
FMOD_RESULT(
"System_PlaySound",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_SOUND.p("sound", ""),
nullable..FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("paused", ""),
nullable..Check(1)..FMOD_CHANNEL.p.p("channel", "")
)
FMOD_RESULT(
"System_PlayDSP",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_DSP.p("dsp", ""),
nullable..FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("paused", ""),
nullable..Check(1)..FMOD_CHANNEL.p.p("channel", "")
)
FMOD_RESULT(
"System_GetChannel",
"",
FMOD_SYSTEM.p("system", ""),
int("channelid", ""),
Check(1)..FMOD_CHANNEL.p.p("channel", "")
)
FMOD_RESULT(
"System_GetDSPInfoByType",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_DSP_TYPE("type", ""),
Check(1)..FMOD_DSP_DESCRIPTION.const.p.p("description", "")
)
FMOD_RESULT(
"System_GetMasterChannelGroup",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..FMOD_CHANNELGROUP.p.p("channelgroup", "")
)
FMOD_RESULT(
"System_GetMasterSoundGroup",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..FMOD_SOUNDGROUP.p.p("soundgroup", "")
)
FMOD_RESULT(
"System_AttachChannelGroupToPort",
"Routing to ports.",
FMOD_SYSTEM.p("system", ""),
FMOD_PORT_TYPE("portType", ""),
FMOD_PORT_INDEX("portIndex", ""),
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("passThru", "")
)
FMOD_RESULT(
"System_DetachChannelGroupFromPort",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_CHANNELGROUP.p("channelgroup", "")
)
FMOD_RESULT(
"System_SetReverbProperties",
"Reverb API.",
FMOD_SYSTEM.p("system", ""),
int("instance", ""),
nullable..FMOD_REVERB_PROPERTIES.const.p("prop", "")
)
FMOD_RESULT(
"System_GetReverbProperties",
"",
FMOD_SYSTEM.p("system", ""),
int("instance", ""),
FMOD_REVERB_PROPERTIES.p("prop", "")
)
FMOD_RESULT(
"System_LockDSP",
"System level DSP functionality.",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_UnlockDSP",
"",
FMOD_SYSTEM.p("system", "")
)
FMOD_RESULT(
"System_GetRecordNumDrivers",
"Recording API.",
FMOD_SYSTEM.p("system", ""),
nullable..Check(1)..int.p("numdrivers", ""),
nullable..Check(1)..int.p("numconnected", "")
)
FMOD_RESULT(
"System_GetRecordDriverInfo",
"",
FMOD_SYSTEM.p("system", ""),
int("id", ""),
nullable..char.p("name", ""),
AutoSize("name")..int("namelen", ""),
nullable..FMOD_GUID.p("guid", ""),
nullable..Check(1)..int.p("systemrate", ""),
nullable..Check(1)..FMOD_SPEAKERMODE.p("speakermode", ""),
nullable..Check(1)..int.p("speakermodechannels", ""),
nullable..Check(1)..FMOD_DRIVER_STATE.p("state", "")
)
FMOD_RESULT(
"System_GetRecordPosition",
"",
FMOD_SYSTEM.p("system", ""),
int("id", ""),
Check(1)..unsigned_int.p("position", "")
)
FMOD_RESULT(
"System_RecordStart",
"",
FMOD_SYSTEM.p("system", ""),
int("id", ""),
FMOD_SOUND.p("sound", ""),
FMOD_BOOL("loop", "")
)
FMOD_RESULT(
"System_RecordStop",
"",
FMOD_SYSTEM.p("system", ""),
int("id", "")
)
FMOD_RESULT(
"System_IsRecording",
"",
FMOD_SYSTEM.p("system", ""),
int("id", ""),
nullable..Check(1)..FMOD_BOOL.p("recording", "")
)
FMOD_RESULT(
"System_CreateGeometry",
"Geometry API.",
FMOD_SYSTEM.p("system", ""),
int("maxpolygons", ""),
int("maxvertices", ""),
Check(1)..FMOD_GEOMETRY.p.p("geometry", "")
)
FMOD_RESULT(
"System_SetGeometrySettings",
"",
FMOD_SYSTEM.p("system", ""),
float("maxworldsize", "")
)
FMOD_RESULT(
"System_GetGeometrySettings",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..float.p("maxworldsize", "")
)
FMOD_RESULT(
"System_LoadGeometry",
"",
FMOD_SYSTEM.p("system", ""),
void.const.p("data", ""),
AutoSize("data")..int("datasize", ""),
Check(1)..FMOD_GEOMETRY.p.p("geometry", "")
)
FMOD_RESULT(
"System_GetGeometryOcclusion",
"",
FMOD_SYSTEM.p("system", ""),
FMOD_VECTOR.const.p("listener", ""),
FMOD_VECTOR.const.p("source", ""),
nullable..Check(1)..float.p("direct", ""),
nullable..Check(1)..float.p("reverb", "")
)
FMOD_RESULT(
"System_SetNetworkProxy",
"Network functions.",
FMOD_SYSTEM.p("system", ""),
charUTF8.const.p("proxy", "")
)
FMOD_RESULT(
"System_GetNetworkProxy",
"",
FMOD_SYSTEM.p("system", ""),
char.p("proxy", ""),
AutoSize("proxy")..int("proxylen", "")
)
FMOD_RESULT(
"System_SetNetworkTimeout",
"",
FMOD_SYSTEM.p("system", ""),
int("timeout", "")
)
FMOD_RESULT(
"System_GetNetworkTimeout",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..int.p("timeout", "")
)
FMOD_RESULT(
"System_SetUserData",
"",
FMOD_SYSTEM.p("system", ""),
opaque_p("userdata", "")
)
FMOD_RESULT(
"System_GetUserData",
"",
FMOD_SYSTEM.p("system", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"Sound_Release",
"",
FMOD_SOUND.p("sound", "")
)
FMOD_RESULT(
"Sound_GetSystemObject",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..FMOD_SYSTEM.p.p("system", "")
)
FMOD_RESULT(
"Sound_Lock",
"",
FMOD_SOUND.p("sound", ""),
unsigned_int("offset", ""),
unsigned_int("length", ""),
Check(1)..void.p.p("ptr1", ""),
Check(1)..void.p.p("ptr2", ""),
Check(1)..unsigned_int.p("len1", ""),
Check(1)..unsigned_int.p("len2", "")
)
FMOD_RESULT(
"Sound_Unlock",
"",
FMOD_SOUND.p("sound", ""),
void.p("ptr1", ""),
void.p("ptr2", ""),
AutoSize("ptr1")..unsigned_int("len1", ""),
AutoSize("ptr2")..unsigned_int("len2", "")
)
FMOD_RESULT(
"Sound_SetDefaults",
"",
FMOD_SOUND.p("sound", ""),
float("frequency", ""),
int("priority", "")
)
FMOD_RESULT(
"Sound_GetDefaults",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..float.p("frequency", ""),
nullable..Check(1)..int.p("priority", "")
)
FMOD_RESULT(
"Sound_Set3DMinMaxDistance",
"",
FMOD_SOUND.p("sound", ""),
float("min", ""),
float("max", "")
)
FMOD_RESULT(
"Sound_Get3DMinMaxDistance",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..float.p("min", ""),
nullable..Check(1)..float.p("max", "")
)
FMOD_RESULT(
"Sound_Set3DConeSettings",
"",
FMOD_SOUND.p("sound", ""),
float("insideconeangle", ""),
float("outsideconeangle", ""),
float("outsidevolume", "")
)
FMOD_RESULT(
"Sound_Get3DConeSettings",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..float.p("insideconeangle", ""),
nullable..Check(1)..float.p("outsideconeangle", ""),
nullable..Check(1)..float.p("outsidevolume", "")
)
FMOD_RESULT(
"Sound_Set3DCustomRolloff",
"",
FMOD_SOUND.p("sound", ""),
FMOD_VECTOR.p("points", ""),
AutoSize("points")..int("numpoints", "")
)
FMOD_RESULT(
"Sound_Get3DCustomRolloff",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..FMOD_VECTOR.p.p("points", ""),
nullable..Check(1)..int.p("numpoints", "")
)
FMOD_RESULT(
"Sound_GetSubSound",
"",
FMOD_SOUND.p("sound", ""),
int("index", ""),
Check(1)..FMOD_SOUND.p.p("subsound", "")
)
FMOD_RESULT(
"Sound_GetSubSoundParent",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..FMOD_SOUND.p.p("parentsound", "")
)
FMOD_RESULT(
"Sound_GetName",
"",
FMOD_SOUND.p("sound", ""),
char.p("name", ""),
AutoSize("name")..int("namelen", "")
)
FMOD_RESULT(
"Sound_GetLength",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..unsigned_int.p("length", ""),
FMOD_TIMEUNIT("lengthtype", "")
)
FMOD_RESULT(
"Sound_GetFormat",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..FMOD_SOUND_TYPE.p("type", ""),
nullable..Check(1)..FMOD_SOUND_FORMAT.p("format", ""),
nullable..Check(1)..int.p("channels", ""),
nullable..Check(1)..int.p("bits", "")
)
FMOD_RESULT(
"Sound_GetNumSubSounds",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..int.p("numsubsounds", "")
)
FMOD_RESULT(
"Sound_GetNumTags",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..int.p("numtags", ""),
nullable..Check(1)..int.p("numtagsupdated", "")
)
FMOD_RESULT(
"Sound_GetTag",
"",
FMOD_SOUND.p("sound", ""),
charUTF8.const.p("name", ""),
int("index", ""),
FMOD_TAG.p("tag", "")
)
FMOD_RESULT(
"Sound_GetOpenState",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..FMOD_OPENSTATE.p("openstate", ""),
nullable..Check(1)..unsigned_int.p("percentbuffered", ""),
nullable..Check(1)..FMOD_BOOL.p("starving", ""),
nullable..Check(1)..FMOD_BOOL.p("diskbusy", "")
)
FMOD_RESULT(
"Sound_ReadData",
"",
FMOD_SOUND.p("sound", ""),
void.p("buffer", ""),
AutoSize("buffer")..unsigned_int("length", ""),
nullable..Check(1)..unsigned_int.p("read", "")
)
FMOD_RESULT(
"Sound_SeekData",
"",
FMOD_SOUND.p("sound", ""),
unsigned_int("pcm", "")
)
FMOD_RESULT(
"Sound_SetSoundGroup",
"",
FMOD_SOUND.p("sound", ""),
FMOD_SOUNDGROUP.p("soundgroup", "")
)
FMOD_RESULT(
"Sound_GetSoundGroup",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..FMOD_SOUNDGROUP.p.p("soundgroup", "")
)
FMOD_RESULT(
"Sound_GetNumSyncPoints",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..int.p("numsyncpoints", "")
)
FMOD_RESULT(
"Sound_GetSyncPoint",
"",
FMOD_SOUND.p("sound", ""),
int("index", ""),
Check(1)..FMOD_SYNCPOINT.p.p("point", "")
)
FMOD_RESULT(
"Sound_GetSyncPointInfo",
"",
FMOD_SOUND.p("sound", ""),
FMOD_SYNCPOINT.p("point", ""),
char.p("name", ""),
AutoSize("name")..int("namelen", ""),
nullable..Check(1)..unsigned_int.p("offset", ""),
FMOD_TIMEUNIT("offsettype", "")
)
FMOD_RESULT(
"Sound_AddSyncPoint",
"",
FMOD_SOUND.p("sound", ""),
unsigned_int("offset", ""),
FMOD_TIMEUNIT("offsettype", ""),
charUTF8.const.p("name", ""),
nullable..Check(1)..FMOD_SYNCPOINT.p.p("point", "")
)
FMOD_RESULT(
"Sound_DeleteSyncPoint",
"",
FMOD_SOUND.p("sound", ""),
FMOD_SYNCPOINT.p("point", "")
)
FMOD_RESULT(
"Sound_SetMode",
"Functions also in Channel class but here they are the 'default' to save having to change it in Channel all the time.",
FMOD_SOUND.p("sound", ""),
FMOD_MODE("mode", "")
)
FMOD_RESULT(
"Sound_GetMode",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..FMOD_MODE.p("mode", "")
)
FMOD_RESULT(
"Sound_SetLoopCount",
"",
FMOD_SOUND.p("sound", ""),
int("loopcount", "")
)
FMOD_RESULT(
"Sound_GetLoopCount",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..int.p("loopcount", "")
)
FMOD_RESULT(
"Sound_SetLoopPoints",
"",
FMOD_SOUND.p("sound", ""),
unsigned_int("loopstart", ""),
FMOD_TIMEUNIT("loopstarttype", ""),
unsigned_int("loopend", ""),
FMOD_TIMEUNIT("loopendtype", "")
)
FMOD_RESULT(
"Sound_GetLoopPoints",
"",
FMOD_SOUND.p("sound", ""),
nullable..Check(1)..unsigned_int.p("loopstart", ""),
FMOD_TIMEUNIT("loopstarttype", ""),
nullable..Check(1)..unsigned_int.p("loopend", ""),
FMOD_TIMEUNIT("loopendtype", "")
)
FMOD_RESULT(
"Sound_GetMusicNumChannels",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..int.p("numchannels", "")
)
FMOD_RESULT(
"Sound_SetMusicChannelVolume",
"",
FMOD_SOUND.p("sound", ""),
int("channel", ""),
float("volume", "")
)
FMOD_RESULT(
"Sound_GetMusicChannelVolume",
"",
FMOD_SOUND.p("sound", ""),
int("channel", ""),
Check(1)..float.p("volume", "")
)
FMOD_RESULT(
"Sound_SetMusicSpeed",
"",
FMOD_SOUND.p("sound", ""),
float("speed", "")
)
FMOD_RESULT(
"Sound_GetMusicSpeed",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..float.p("speed", "")
)
FMOD_RESULT(
"Sound_SetUserData",
"",
FMOD_SOUND.p("sound", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"Sound_GetUserData",
"",
FMOD_SOUND.p("sound", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"Channel_GetSystemObject",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_SYSTEM.p.p("system", "")
)
FMOD_RESULT(
"Channel_Stop",
"",
FMOD_CHANNEL.p("channel", "")
)
FMOD_RESULT(
"Channel_SetPaused",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_BOOL("paused", "")
)
FMOD_RESULT(
"Channel_GetPaused",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_BOOL.p("paused", "")
)
FMOD_RESULT(
"Channel_SetVolume",
"",
FMOD_CHANNEL.p("channel", ""),
float("volume", "")
)
FMOD_RESULT(
"Channel_GetVolume",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("volume", "")
)
FMOD_RESULT(
"Channel_SetVolumeRamp",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_BOOL("ramp", "")
)
FMOD_RESULT(
"Channel_GetVolumeRamp",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_BOOL.p("ramp", "")
)
FMOD_RESULT(
"Channel_GetAudibility",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("audibility", "")
)
FMOD_RESULT(
"Channel_SetPitch",
"",
FMOD_CHANNEL.p("channel", ""),
float("pitch", "")
)
FMOD_RESULT(
"Channel_GetPitch",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("pitch", "")
)
FMOD_RESULT(
"Channel_SetMute",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_BOOL("mute", "")
)
FMOD_RESULT(
"Channel_GetMute",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_BOOL.p("mute", "")
)
FMOD_RESULT(
"Channel_SetReverbProperties",
"",
FMOD_CHANNEL.p("channel", ""),
int("instance", ""),
float("wet", "")
)
FMOD_RESULT(
"Channel_GetReverbProperties",
"",
FMOD_CHANNEL.p("channel", ""),
int("instance", ""),
Check(1)..float.p("wet", "")
)
FMOD_RESULT(
"Channel_SetLowPassGain",
"",
FMOD_CHANNEL.p("channel", ""),
float("gain", "")
)
FMOD_RESULT(
"Channel_GetLowPassGain",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("gain", "")
)
FMOD_RESULT(
"Channel_SetMode",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_MODE("mode", "")
)
FMOD_RESULT(
"Channel_GetMode",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_MODE.p("mode", "")
)
FMOD_RESULT(
"Channel_SetCallback",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..FMOD_CHANNELCONTROL_CALLBACK("callback", "")
)
FMOD_RESULT(
"Channel_IsPlaying",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_BOOL.p("isplaying", "")
)
FMOD_RESULT(
"Channel_SetPan",
"""
Note all 'set' functions alter a final matrix, this is why the only get function is getMixMatrix, to avoid other get functions returning
incorrect/obsolete values.
""",
FMOD_CHANNEL.p("channel", ""),
float("pan", "")
)
FMOD_RESULT(
"Channel_SetMixLevelsOutput",
"",
FMOD_CHANNEL.p("channel", ""),
float("frontleft", ""),
float("frontright", ""),
float("center", ""),
float("lfe", ""),
float("surroundleft", ""),
float("surroundright", ""),
float("backleft", ""),
float("backright", "")
)
FMOD_RESULT(
"Channel_SetMixLevelsInput",
"",
FMOD_CHANNEL.p("channel", ""),
float.p("levels", ""),
AutoSize("levels")..int("numlevels", "")
)
FMOD_RESULT(
"Channel_SetMixMatrix",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check("outchannels * (inchannel_hop == 0 ? inchannels : inchannel_hop)")..float.p("matrix", ""),
int("outchannels", ""),
int("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"Channel_GetMixMatrix",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Unsafe..float.p("matrix", ""),
nullable..Check(1)..int.p("outchannels", ""),
nullable..Check(1)..int.p("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"Channel_GetDSPClock",
"Clock based functionality.",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock", ""),
nullable..Check(1)..unsigned_long_long.p("parentclock", "")
)
FMOD_RESULT(
"Channel_SetDelay",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_long_long("dspclock_start", ""),
unsigned_long_long("dspclock_end", ""),
FMOD_BOOL("stopchannels", "")
)
FMOD_RESULT(
"Channel_GetDelay",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock_start", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock_end", ""),
nullable..Check(1)..FMOD_BOOL.p("stopchannels", "")
)
FMOD_RESULT(
"Channel_AddFadePoint",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_long_long("dspclock", ""),
float("volume", "")
)
FMOD_RESULT(
"Channel_SetFadePointRamp",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_long_long("dspclock", ""),
float("volume", "")
)
FMOD_RESULT(
"Channel_RemoveFadePoints",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_long_long("dspclock_start", ""),
unsigned_long_long("dspclock_end", "")
)
FMOD_RESULT(
"Channel_GetFadePoints",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..unsigned_int.p("numpoints", ""),
nullable..Check(1)..unsigned_long_long.p("point_dspclock", ""),
nullable..Check(1)..float.p("point_volume", "")
)
FMOD_RESULT(
"Channel_GetDSP",
"DSP effects.",
FMOD_CHANNEL.p("channel", ""),
int("index", ""),
Check(1)..FMOD_DSP.p.p("dsp", "")
)
FMOD_RESULT(
"Channel_AddDSP",
"",
FMOD_CHANNEL.p("channel", ""),
int("index", ""),
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"Channel_RemoveDSP",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"Channel_GetNumDSPs",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..int.p("numdsps", "")
)
FMOD_RESULT(
"Channel_SetDSPIndex",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_DSP.p("dsp", ""),
int("index", "")
)
FMOD_RESULT(
"Channel_GetDSPIndex",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_DSP.p("dsp", ""),
Check(1)..int.p("index", "")
)
FMOD_RESULT(
"Channel_Set3DAttributes",
"3D functionality.",
FMOD_CHANNEL.p("channel", ""),
nullable..FMOD_VECTOR.const.p("pos", ""),
nullable..FMOD_VECTOR.const.p("vel", "")
)
FMOD_RESULT(
"Channel_Get3DAttributes",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..FMOD_VECTOR.p("pos", ""),
nullable..FMOD_VECTOR.p("vel", "")
)
FMOD_RESULT(
"Channel_Set3DMinMaxDistance",
"",
FMOD_CHANNEL.p("channel", ""),
float("mindistance", ""),
float("maxdistance", "")
)
FMOD_RESULT(
"Channel_Get3DMinMaxDistance",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..float.p("mindistance", ""),
nullable..Check(1)..float.p("maxdistance", "")
)
FMOD_RESULT(
"Channel_Set3DConeSettings",
"",
FMOD_CHANNEL.p("channel", ""),
float("insideconeangle", ""),
float("outsideconeangle", ""),
float("outsidevolume", "")
)
FMOD_RESULT(
"Channel_Get3DConeSettings",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..float.p("insideconeangle", ""),
nullable..Check(1)..float.p("outsideconeangle", ""),
nullable..Check(1)..float.p("outsidevolume", "")
)
FMOD_RESULT(
"Channel_Set3DConeOrientation",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_VECTOR.p("orientation", "")
)
FMOD_RESULT(
"Channel_Get3DConeOrientation",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_VECTOR.p("orientation", "")
)
FMOD_RESULT(
"Channel_Set3DCustomRolloff",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_VECTOR.p("points", ""),
AutoSize("points")..int("numpoints", "")
)
FMOD_RESULT(
"Channel_Get3DCustomRolloff",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..FMOD_VECTOR.p.p("points", ""),
nullable..Check(1)..int.p("numpoints", "")
)
FMOD_RESULT(
"Channel_Set3DOcclusion",
"",
FMOD_CHANNEL.p("channel", ""),
float("directocclusion", ""),
float("reverbocclusion", "")
)
FMOD_RESULT(
"Channel_Get3DOcclusion",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..float.p("directocclusion", ""),
nullable..Check(1)..float.p("reverbocclusion", "")
)
FMOD_RESULT(
"Channel_Set3DSpread",
"",
FMOD_CHANNEL.p("channel", ""),
float("angle", "")
)
FMOD_RESULT(
"Channel_Get3DSpread",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("angle", "")
)
FMOD_RESULT(
"Channel_Set3DLevel",
"",
FMOD_CHANNEL.p("channel", ""),
float("level", "")
)
FMOD_RESULT(
"Channel_Get3DLevel",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("level", "")
)
FMOD_RESULT(
"Channel_Set3DDopplerLevel",
"",
FMOD_CHANNEL.p("channel", ""),
float("level", "")
)
FMOD_RESULT(
"Channel_Get3DDopplerLevel",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("level", "")
)
FMOD_RESULT(
"Channel_Set3DDistanceFilter",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_BOOL("custom", ""),
float("customLevel", ""),
float("centerFreq", "")
)
FMOD_RESULT(
"Channel_Get3DDistanceFilter",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..FMOD_BOOL.p("custom", ""),
nullable..Check(1)..float.p("customLevel", ""),
nullable..Check(1)..float.p("centerFreq", "")
)
FMOD_RESULT(
"Channel_SetUserData",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"Channel_GetUserData",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"Channel_SetFrequency",
"Channel specific control functionality.",
FMOD_CHANNEL.p("channel", ""),
float("frequency", "")
)
FMOD_RESULT(
"Channel_GetFrequency",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..float.p("frequency", "")
)
FMOD_RESULT(
"Channel_SetPriority",
"",
FMOD_CHANNEL.p("channel", ""),
int("priority", "")
)
FMOD_RESULT(
"Channel_GetPriority",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..int.p("priority", "")
)
FMOD_RESULT(
"Channel_SetPosition",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_int("position", ""),
FMOD_TIMEUNIT("postype", "")
)
FMOD_RESULT(
"Channel_GetPosition",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..unsigned_int.p("position", ""),
FMOD_TIMEUNIT("postype", "")
)
FMOD_RESULT(
"Channel_SetChannelGroup",
"",
FMOD_CHANNEL.p("channel", ""),
FMOD_CHANNELGROUP.p("channelgroup", "")
)
FMOD_RESULT(
"Channel_GetChannelGroup",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_CHANNELGROUP.p.p("channelgroup", "")
)
FMOD_RESULT(
"Channel_SetLoopCount",
"",
FMOD_CHANNEL.p("channel", ""),
int("loopcount", "")
)
FMOD_RESULT(
"Channel_GetLoopCount",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..int.p("loopcount", "")
)
FMOD_RESULT(
"Channel_SetLoopPoints",
"",
FMOD_CHANNEL.p("channel", ""),
unsigned_int("loopstart", ""),
FMOD_TIMEUNIT("loopstarttype", ""),
unsigned_int("loopend", ""),
FMOD_TIMEUNIT("loopendtype", "")
)
FMOD_RESULT(
"Channel_GetLoopPoints",
"",
FMOD_CHANNEL.p("channel", ""),
nullable..Check(1)..unsigned_int.p("loopstart", ""),
FMOD_TIMEUNIT("loopstarttype", ""),
nullable..Check(1)..unsigned_int.p("loopend", ""),
FMOD_TIMEUNIT("loopendtype", "")
)
FMOD_RESULT(
"Channel_IsVirtual",
"Information only functions.",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_BOOL.p("isvirtual", "")
)
FMOD_RESULT(
"Channel_GetCurrentSound",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..FMOD_SOUND.p.p("sound", "")
)
FMOD_RESULT(
"Channel_GetIndex",
"",
FMOD_CHANNEL.p("channel", ""),
Check(1)..int.p("index", "")
)
FMOD_RESULT(
"ChannelGroup_GetSystemObject",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_SYSTEM.p.p("system", "")
)
FMOD_RESULT(
"ChannelGroup_Stop",
"General control functionality for Channels and ChannelGroups.",
FMOD_CHANNELGROUP.p("channelgroup", "")
)
FMOD_RESULT(
"ChannelGroup_SetPaused",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("paused", "")
)
FMOD_RESULT(
"ChannelGroup_GetPaused",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_BOOL.p("paused", "")
)
FMOD_RESULT(
"ChannelGroup_SetVolume",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("volume", "")
)
FMOD_RESULT(
"ChannelGroup_GetVolume",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("volume", "")
)
FMOD_RESULT(
"ChannelGroup_SetVolumeRamp",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("ramp", "")
)
FMOD_RESULT(
"ChannelGroup_GetVolumeRamp",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_BOOL.p("ramp", "")
)
FMOD_RESULT(
"ChannelGroup_GetAudibility",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("audibility", "")
)
FMOD_RESULT(
"ChannelGroup_SetPitch",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("pitch", "")
)
FMOD_RESULT(
"ChannelGroup_GetPitch",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("pitch", "")
)
FMOD_RESULT(
"ChannelGroup_SetMute",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("mute", "")
)
FMOD_RESULT(
"ChannelGroup_GetMute",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_BOOL.p("mute", "")
)
FMOD_RESULT(
"ChannelGroup_SetReverbProperties",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("instance", ""),
float("wet", "")
)
FMOD_RESULT(
"ChannelGroup_GetReverbProperties",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("instance", ""),
Check(1)..float.p("wet", "")
)
FMOD_RESULT(
"ChannelGroup_SetLowPassGain",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("gain", "")
)
FMOD_RESULT(
"ChannelGroup_GetLowPassGain",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("gain", "")
)
FMOD_RESULT(
"ChannelGroup_SetMode",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_MODE("mode", "")
)
FMOD_RESULT(
"ChannelGroup_GetMode",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_MODE.p("mode", "")
)
FMOD_RESULT(
"ChannelGroup_SetCallback",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..FMOD_CHANNELCONTROL_CALLBACK("callback", "")
)
FMOD_RESULT(
"ChannelGroup_IsPlaying",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_BOOL.p("isplaying", "")
)
FMOD_RESULT(
"ChannelGroup_SetPan",
"""
Note all 'set' functions alter a final matrix, this is why the only get function is getMixMatrix, to avoid other get functions returning
incorrect/obsolete values.
""",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("pan", "")
)
FMOD_RESULT(
"ChannelGroup_SetMixLevelsOutput",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("frontleft", ""),
float("frontright", ""),
float("center", ""),
float("lfe", ""),
float("surroundleft", ""),
float("surroundright", ""),
float("backleft", ""),
float("backright", "")
)
FMOD_RESULT(
"ChannelGroup_SetMixLevelsInput",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float.p("levels", ""),
AutoSize("levels")..int("numlevels", "")
)
FMOD_RESULT(
"ChannelGroup_SetMixMatrix",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check("outchannels * (inchannel_hop == 0 ? inchannels : inchannel_hop)")..float.p("matrix", ""),
int("outchannels", ""),
int("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"ChannelGroup_GetMixMatrix",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Unsafe..float.p("matrix", ""),
nullable..Check(1)..int.p("outchannels", ""),
nullable..Check(1)..int.p("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"ChannelGroup_GetDSPClock",
"Clock based functionality.",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock", ""),
nullable..Check(1)..unsigned_long_long.p("parentclock", "")
)
FMOD_RESULT(
"ChannelGroup_SetDelay",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
unsigned_long_long("dspclock_start", ""),
unsigned_long_long("dspclock_end", ""),
FMOD_BOOL("stopchannels", "")
)
FMOD_RESULT(
"ChannelGroup_GetDelay",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock_start", ""),
nullable..Check(1)..unsigned_long_long.p("dspclock_end", ""),
nullable..Check(1)..FMOD_BOOL.p("stopchannels", "")
)
FMOD_RESULT(
"ChannelGroup_AddFadePoint",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
unsigned_long_long("dspclock", ""),
float("volume", "")
)
FMOD_RESULT(
"ChannelGroup_SetFadePointRamp",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
unsigned_long_long("dspclock", ""),
float("volume", "")
)
FMOD_RESULT(
"ChannelGroup_RemoveFadePoints",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
unsigned_long_long("dspclock_start", ""),
unsigned_long_long("dspclock_end", "")
)
FMOD_RESULT(
"ChannelGroup_GetFadePoints",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..unsigned_int.p("numpoints", ""),
nullable..Check(1)..unsigned_long_long.p("point_dspclock", ""),
nullable..Check(1)..float.p("point_volume", "")
)
FMOD_RESULT(
"ChannelGroup_GetDSP",
"DSP effects.",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("index", ""),
Check(1)..FMOD_DSP.p.p("dsp", "")
)
FMOD_RESULT(
"ChannelGroup_AddDSP",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("index", ""),
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"ChannelGroup_RemoveDSP",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"ChannelGroup_GetNumDSPs",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..int.p("numdsps", "")
)
FMOD_RESULT(
"ChannelGroup_SetDSPIndex",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_DSP.p("dsp", ""),
int("index", "")
)
FMOD_RESULT(
"ChannelGroup_GetDSPIndex",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_DSP.p("dsp", ""),
Check(1)..int.p("index", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DAttributes",
"3D functionality.",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..FMOD_VECTOR.const.p("pos", ""),
nullable..FMOD_VECTOR.const.p("vel", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DAttributes",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..FMOD_VECTOR.p("pos", ""),
nullable..FMOD_VECTOR.p("vel", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DMinMaxDistance",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("mindistance", ""),
float("maxdistance", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DMinMaxDistance",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..float.p("mindistance", ""),
nullable..Check(1)..float.p("maxdistance", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DConeSettings",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("insideconeangle", ""),
float("outsideconeangle", ""),
float("outsidevolume", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DConeSettings",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..float.p("insideconeangle", ""),
nullable..Check(1)..float.p("outsideconeangle", ""),
nullable..Check(1)..float.p("outsidevolume", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DConeOrientation",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_VECTOR.p("orientation", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DConeOrientation",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_VECTOR.p("orientation", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DCustomRolloff",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_VECTOR.p("points", ""),
AutoSize("points")..int("numpoints", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DCustomRolloff",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..FMOD_VECTOR.p.p("points", ""),
nullable..Check(1)..int.p("numpoints", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DOcclusion",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("directocclusion", ""),
float("reverbocclusion", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DOcclusion",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..float.p("directocclusion", ""),
nullable..Check(1)..float.p("reverbocclusion", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DSpread",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("angle", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DSpread",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("angle", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DLevel",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("level", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DLevel",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("level", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DDopplerLevel",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
float("level", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DDopplerLevel",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..float.p("level", "")
)
FMOD_RESULT(
"ChannelGroup_Set3DDistanceFilter",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_BOOL("custom", ""),
float("customLevel", ""),
float("centerFreq", "")
)
FMOD_RESULT(
"ChannelGroup_Get3DDistanceFilter",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..Check(1)..FMOD_BOOL.p("custom", ""),
nullable..Check(1)..float.p("customLevel", ""),
nullable..Check(1)..float.p("centerFreq", "")
)
FMOD_RESULT(
"ChannelGroup_SetUserData",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"ChannelGroup_GetUserData",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"ChannelGroup_Release",
"",
FMOD_CHANNELGROUP.p("channelgroup", "")
)
FMOD_RESULT(
"ChannelGroup_AddGroup",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
FMOD_CHANNELGROUP.p("group", ""),
FMOD_BOOL("propagatedspclock", ""),
nullable..Check(1)..FMOD_DSPCONNECTION.p.p("connection", "")
)
FMOD_RESULT(
"ChannelGroup_GetNumGroups",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..int.p("numgroups", "")
)
FMOD_RESULT(
"ChannelGroup_GetGroup",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("index", ""),
Check(1)..FMOD_CHANNELGROUP.p.p("group", "")
)
FMOD_RESULT(
"ChannelGroup_GetParentGroup",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..FMOD_CHANNELGROUP.p.p("group", "")
)
FMOD_RESULT(
"ChannelGroup_GetName",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
char.p("name", ""),
AutoSize("name")..int("namelen", "")
)
FMOD_RESULT(
"ChannelGroup_GetNumChannels",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
Check(1)..int.p("numchannels", "")
)
FMOD_RESULT(
"ChannelGroup_GetChannel",
"",
FMOD_CHANNELGROUP.p("channelgroup", ""),
int("index", ""),
Check(1)..FMOD_CHANNEL.p.p("channel", "")
)
FMOD_RESULT(
"SoundGroup_Release",
"",
FMOD_SOUNDGROUP.p("soundgroup", "")
)
FMOD_RESULT(
"SoundGroup_GetSystemObject",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..FMOD_SYSTEM.p.p("system", "")
)
FMOD_RESULT(
"SoundGroup_SetMaxAudible",
"SoundGroup control functions.",
FMOD_SOUNDGROUP.p("soundgroup", ""),
int("maxaudible", "")
)
FMOD_RESULT(
"SoundGroup_GetMaxAudible",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..int.p("maxaudible", "")
)
FMOD_RESULT(
"SoundGroup_SetMaxAudibleBehavior",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
FMOD_SOUNDGROUP_BEHAVIOR("behavior", "")
)
FMOD_RESULT(
"SoundGroup_GetMaxAudibleBehavior",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..FMOD_SOUNDGROUP_BEHAVIOR.p("behavior", "")
)
FMOD_RESULT(
"SoundGroup_SetMuteFadeSpeed",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
float("speed", "")
)
FMOD_RESULT(
"SoundGroup_GetMuteFadeSpeed",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..float.p("speed", "")
)
FMOD_RESULT(
"SoundGroup_SetVolume",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
float("volume", "")
)
FMOD_RESULT(
"SoundGroup_GetVolume",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..float.p("volume", "")
)
FMOD_RESULT(
"SoundGroup_Stop",
"",
FMOD_SOUNDGROUP.p("soundgroup", "")
)
FMOD_RESULT(
"SoundGroup_GetName",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
char.p("name", ""),
AutoSize("name")..int("namelen", "")
)
FMOD_RESULT(
"SoundGroup_GetNumSounds",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..int.p("numsounds", "")
)
FMOD_RESULT(
"SoundGroup_GetSound",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
int("index", ""),
Check(1)..FMOD_SOUND.p.p("sound", "")
)
FMOD_RESULT(
"SoundGroup_GetNumPlaying",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..int.p("numplaying", "")
)
FMOD_RESULT(
"SoundGroup_SetUserData",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"SoundGroup_GetUserData",
"",
FMOD_SOUNDGROUP.p("soundgroup", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"DSP_Release",
"",
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"DSP_GetSystemObject",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..FMOD_SYSTEM.p.p("system", "")
)
FMOD_RESULT(
"DSP_AddInput",
"",
FMOD_DSP.p("dsp", ""),
FMOD_DSP.p("input", ""),
nullable..Check(1)..FMOD_DSPCONNECTION.p.p("connection", ""),
FMOD_DSPCONNECTION_TYPE("type", "")
)
FMOD_RESULT(
"DSP_DisconnectFrom",
"",
FMOD_DSP.p("dsp", ""),
nullable..FMOD_DSP.p("target", ""),
nullable..FMOD_DSPCONNECTION.p("connection", "")
)
FMOD_RESULT(
"DSP_DisconnectAll",
"",
FMOD_DSP.p("dsp", ""),
FMOD_BOOL("inputs", ""),
FMOD_BOOL("outputs", "")
)
FMOD_RESULT(
"DSP_GetNumInputs",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..int.p("numinputs", "")
)
FMOD_RESULT(
"DSP_GetNumOutputs",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..int.p("numoutputs", "")
)
FMOD_RESULT(
"DSP_GetInput",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..FMOD_DSP.p.p("input", ""),
nullable..Check(1)..FMOD_DSPCONNECTION.p.p("inputconnection", "")
)
FMOD_RESULT(
"DSP_GetOutput",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..FMOD_DSP.p.p("output", ""),
nullable..Check(1)..FMOD_DSPCONNECTION.p.p("outputconnection", "")
)
FMOD_RESULT(
"DSP_SetActive",
"DSP unit control.",
FMOD_DSP.p("dsp", ""),
FMOD_BOOL("active", "")
)
FMOD_RESULT(
"DSP_GetActive",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..FMOD_BOOL.p("active", "")
)
FMOD_RESULT(
"DSP_SetBypass",
"",
FMOD_DSP.p("dsp", ""),
FMOD_BOOL("bypass", "")
)
FMOD_RESULT(
"DSP_GetBypass",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..FMOD_BOOL.p("bypass", "")
)
FMOD_RESULT(
"DSP_SetWetDryMix",
"",
FMOD_DSP.p("dsp", ""),
float("prewet", ""),
float("postwet", ""),
float("dry", "")
)
FMOD_RESULT(
"DSP_GetWetDryMix",
"",
FMOD_DSP.p("dsp", ""),
nullable..Check(1)..float.p("prewet", ""),
nullable..Check(1)..float.p("postwet", ""),
nullable..Check(1)..float.p("dry", "")
)
FMOD_RESULT(
"DSP_SetChannelFormat",
"",
FMOD_DSP.p("dsp", ""),
FMOD_CHANNELMASK("channelmask", ""),
int("numchannels", ""),
FMOD_SPEAKERMODE("source_speakermode", "")
)
FMOD_RESULT(
"DSP_GetChannelFormat",
"",
FMOD_DSP.p("dsp", ""),
nullable..Check(1)..FMOD_CHANNELMASK.p("channelmask", ""),
nullable..Check(1)..int.p("numchannels", ""),
nullable..Check(1)..FMOD_SPEAKERMODE.p("source_speakermode", "")
)
FMOD_RESULT(
"DSP_GetOutputChannelFormat",
"",
FMOD_DSP.p("dsp", ""),
FMOD_CHANNELMASK("inmask", ""),
int("inchannels", ""),
FMOD_SPEAKERMODE("inspeakermode", ""),
nullable..Check(1)..FMOD_CHANNELMASK.p("outmask", ""),
nullable..Check(1)..int.p("outchannels", ""),
nullable..Check(1)..FMOD_SPEAKERMODE.p("outspeakermode", "")
)
FMOD_RESULT(
"DSP_Reset",
"",
FMOD_DSP.p("dsp", "")
)
FMOD_RESULT(
"DSP_SetParameterFloat",
"DSP parameter control.",
FMOD_DSP.p("dsp", ""),
int("index", ""),
float("value", "")
)
FMOD_RESULT(
"DSP_SetParameterInt",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
int("value", "")
)
FMOD_RESULT(
"DSP_SetParameterBool",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
FMOD_BOOL("value", "")
)
FMOD_RESULT(
"DSP_SetParameterData",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
void.p("data", ""),
AutoSize("data")..unsigned_int("length", "")
)
FMOD_RESULT(
"DSP_GetParameterFloat",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..float.p("value", ""),
nullable..char.p("valuestr", ""),
AutoSize("valuestr")..int("valuestrlen", "")
)
FMOD_RESULT(
"DSP_GetParameterInt",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..int.p("value", ""),
nullable..char.p("valuestr", ""),
AutoSize("valuestr")..int("valuestrlen", "")
)
FMOD_RESULT(
"DSP_GetParameterBool",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..FMOD_BOOL.p("value", ""),
nullable..char.p("valuestr", ""),
AutoSize("valuestr")..int("valuestrlen", "")
)
FMOD_RESULT(
"DSP_GetParameterData",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
nullable..Check(1)..void.p.p("data", ""),
nullable..Check(1)..unsigned_int.p("length", ""),
nullable..char.p("valuestr", ""),
AutoSize("valuestr")..int("valuestrlen", "")
)
FMOD_RESULT(
"DSP_GetNumParameters",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..int.p("numparams", "")
)
FMOD_RESULT(
"DSP_GetParameterInfo",
"",
FMOD_DSP.p("dsp", ""),
int("index", ""),
Check(1)..FMOD_DSP_PARAMETER_DESC.p.p("desc", "")
)
FMOD_RESULT(
"DSP_GetDataParameterIndex",
"",
FMOD_DSP.p("dsp", ""),
int("datatype", ""),
Check(1)..int.p("index", "")
)
FMOD_RESULT(
"DSP_ShowConfigDialog",
"",
FMOD_DSP.p("dsp", ""),
opaque_p("hwnd", ""),
FMOD_BOOL("show", "")
)
FMOD_RESULT(
"DSP_GetInfo",
"DSP attributes.",
FMOD_DSP.p("dsp", ""),
nullable..Check(32)..char.p("name", ""),
nullable..Check(1)..unsigned_int.p("version", ""),
nullable..Check(1)..int.p("channels", ""),
nullable..Check(1)..int.p("configwidth", ""),
nullable..Check(1)..int.p("configheight", "")
)
FMOD_RESULT(
"DSP_GetType",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..FMOD_DSP_TYPE.p("type", "")
)
FMOD_RESULT(
"DSP_GetIdle",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..FMOD_BOOL.p("idle", "")
)
FMOD_RESULT(
"DSP_SetUserData",
"",
FMOD_DSP.p("dsp", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"DSP_GetUserData",
"",
FMOD_DSP.p("dsp", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"DSP_SetMeteringEnabled",
"Metering.",
FMOD_DSP.p("dsp", ""),
FMOD_BOOL("inputEnabled", ""),
FMOD_BOOL("outputEnabled", "")
)
FMOD_RESULT(
"DSP_GetMeteringEnabled",
"",
FMOD_DSP.p("dsp", ""),
nullable..Check(1)..FMOD_BOOL.p("inputEnabled", ""),
nullable..Check(1)..FMOD_BOOL.p("outputEnabled", "")
)
FMOD_RESULT(
"DSP_GetMeteringInfo",
"",
FMOD_DSP.p("dsp", ""),
nullable..FMOD_DSP_METERING_INFO.p("inputInfo", ""),
nullable..FMOD_DSP_METERING_INFO.p("outputInfo", "")
)
FMOD_RESULT(
"DSP_GetCPUUsage",
"",
FMOD_DSP.p("dsp", ""),
nullable..Check(1)..unsigned_int.p("exclusive", ""),
nullable..Check(1)..unsigned_int.p("inclusive", "")
)
FMOD_RESULT(
"DSPConnection_GetInput",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
Check(1)..FMOD_DSP.p.p("input", "")
)
FMOD_RESULT(
"DSPConnection_GetOutput",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
Check(1)..FMOD_DSP.p.p("output", "")
)
FMOD_RESULT(
"DSPConnection_SetMix",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
float("volume", "")
)
FMOD_RESULT(
"DSPConnection_GetMix",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
Check(1)..float.p("volume", "")
)
FMOD_RESULT(
"DSPConnection_SetMixMatrix",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
nullable..Check("outchannels * (inchannel_hop == 0 ? inchannels : inchannel_hop)")..float.p("matrix", ""),
int("outchannels", ""),
int("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"DSPConnection_GetMixMatrix",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
nullable..Unsafe..float.p("matrix", ""),
nullable..Check(1)..int.p("outchannels", ""),
nullable..Check(1)..int.p("inchannels", ""),
int("inchannel_hop", "")
)
FMOD_RESULT(
"DSPConnection_GetType",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
Check(1)..FMOD_DSPCONNECTION_TYPE.p("type", "")
)
FMOD_RESULT(
"DSPConnection_SetUserData",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"DSPConnection_GetUserData",
"",
FMOD_DSPCONNECTION.p("dspconnection", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"Geometry_Release",
"",
FMOD_GEOMETRY.p("geometry", "")
)
FMOD_RESULT(
"Geometry_AddPolygon",
"Polygon manipulation.",
FMOD_GEOMETRY.p("geometry", ""),
float("directocclusion", ""),
float("reverbocclusion", ""),
FMOD_BOOL("doublesided", ""),
AutoSize("vertices")..int("numvertices", ""),
FMOD_VECTOR.const.p("vertices", ""),
nullable..Check(1)..int.p("polygonindex", "")
)
FMOD_RESULT(
"Geometry_GetNumPolygons",
"",
FMOD_GEOMETRY.p("geometry", ""),
Check(1)..int.p("numpolygons", "")
)
FMOD_RESULT(
"Geometry_GetMaxPolygons",
"",
FMOD_GEOMETRY.p("geometry", ""),
nullable..Check(1)..int.p("maxpolygons", ""),
nullable..Check(1)..int.p("maxvertices", "")
)
FMOD_RESULT(
"Geometry_GetPolygonNumVertices",
"",
FMOD_GEOMETRY.p("geometry", ""),
int("index", ""),
Check(1)..int.p("numvertices", "")
)
FMOD_RESULT(
"Geometry_SetPolygonVertex",
"",
FMOD_GEOMETRY.p("geometry", ""),
int("index", ""),
int("vertexindex", ""),
FMOD_VECTOR.const.p("vertex", "")
)
FMOD_RESULT(
"Geometry_GetPolygonVertex",
"",
FMOD_GEOMETRY.p("geometry", ""),
int("index", ""),
int("vertexindex", ""),
FMOD_VECTOR.p("vertex", "")
)
FMOD_RESULT(
"Geometry_SetPolygonAttributes",
"",
FMOD_GEOMETRY.p("geometry", ""),
int("index", ""),
float("directocclusion", ""),
float("reverbocclusion", ""),
FMOD_BOOL("doublesided", "")
)
FMOD_RESULT(
"Geometry_GetPolygonAttributes",
"",
FMOD_GEOMETRY.p("geometry", ""),
int("index", ""),
nullable..Check(1)..float.p("directocclusion", ""),
nullable..Check(1)..float.p("reverbocclusion", ""),
nullable..Check(1)..FMOD_BOOL.p("doublesided", "")
)
FMOD_RESULT(
"Geometry_SetActive",
"Object manipulation.",
FMOD_GEOMETRY.p("geometry", ""),
FMOD_BOOL("active", "")
)
FMOD_RESULT(
"Geometry_GetActive",
"",
FMOD_GEOMETRY.p("geometry", ""),
Check(1)..FMOD_BOOL.p("active", "")
)
FMOD_RESULT(
"Geometry_SetRotation",
"",
FMOD_GEOMETRY.p("geometry", ""),
nullable..FMOD_VECTOR.const.p("forward", ""),
nullable..FMOD_VECTOR.const.p("up", "")
)
FMOD_RESULT(
"Geometry_GetRotation",
"",
FMOD_GEOMETRY.p("geometry", ""),
nullable..FMOD_VECTOR.p("forward", ""),
nullable..FMOD_VECTOR.p("up", "")
)
FMOD_RESULT(
"Geometry_SetPosition",
"",
FMOD_GEOMETRY.p("geometry", ""),
FMOD_VECTOR.const.p("position", "")
)
FMOD_RESULT(
"Geometry_GetPosition",
"",
FMOD_GEOMETRY.p("geometry", ""),
FMOD_VECTOR.p("position", "")
)
FMOD_RESULT(
"Geometry_SetScale",
"",
FMOD_GEOMETRY.p("geometry", ""),
FMOD_VECTOR.const.p("scale", "")
)
FMOD_RESULT(
"Geometry_GetScale",
"",
FMOD_GEOMETRY.p("geometry", ""),
FMOD_VECTOR.p("scale", "")
)
FMOD_RESULT(
"Geometry_Save",
"",
FMOD_GEOMETRY.p("geometry", ""),
nullable..Unsafe..void.p("data", ""),
Check(1)..int.p("datasize", "")
)
FMOD_RESULT(
"Geometry_SetUserData",
"",
FMOD_GEOMETRY.p("geometry", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"Geometry_GetUserData",
"",
FMOD_GEOMETRY.p("geometry", ""),
Check(1)..void.p.p("userdata", "")
)
FMOD_RESULT(
"Reverb3D_Release",
"",
FMOD_REVERB3D.p("reverb3d", "")
)
FMOD_RESULT(
"Reverb3D_Set3DAttributes",
"",
FMOD_REVERB3D.p("reverb3d", ""),
nullable..FMOD_VECTOR.const.p("position", ""),
float("mindistance", ""),
float("maxdistance", "")
)
FMOD_RESULT(
"Reverb3D_Get3DAttributes",
"",
FMOD_REVERB3D.p("reverb3d", ""),
nullable..FMOD_VECTOR.p("position", ""),
nullable..Check(1)..float.p("mindistance", ""),
nullable..Check(1)..float.p("maxdistance", "")
)
FMOD_RESULT(
"Reverb3D_SetProperties",
"",
FMOD_REVERB3D.p("reverb3d", ""),
FMOD_REVERB_PROPERTIES.const.p("properties", "")
)
FMOD_RESULT(
"Reverb3D_GetProperties",
"",
FMOD_REVERB3D.p("reverb3d", ""),
FMOD_REVERB_PROPERTIES.p("properties", "")
)
FMOD_RESULT(
"Reverb3D_SetActive",
"",
FMOD_REVERB3D.p("reverb3d", ""),
FMOD_BOOL("active", "")
)
FMOD_RESULT(
"Reverb3D_GetActive",
"",
FMOD_REVERB3D.p("reverb3d", ""),
Check(1)..FMOD_BOOL.p("active", "")
)
FMOD_RESULT(
"Reverb3D_SetUserData",
"",
FMOD_REVERB3D.p("reverb3d", ""),
nullable..opaque_p("userdata", "")
)
FMOD_RESULT(
"Reverb3D_GetUserData",
"",
FMOD_REVERB3D.p("reverb3d", ""),
Check(1)..void.p.p("userdata", "")
)
}
| bsd-3-clause | 573b68b9ff95caf7eaf26360f4e3181d | 25.009522 | 297 | 0.52962 | 3.432529 | false | false | false | false |
nathanj/ogsdroid | app/src/main/java/com/ogsdroid/AutomatchFragment.kt | 1 | 2121 | package com.ogsdroid
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import com.ogs.OGS
import java.util.*
class AutomatchFragment : Fragment() {
lateinit var rootView: View
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
Log.d(javaClass.name, "onCreateView")
rootView = inflater!!.inflate(R.layout.fragment_automatch, container, false)
val b = rootView.findViewById<Button>(R.id.blitz_automatch)
b.setOnClickListener {
go("blitz")
}
val n = rootView.findViewById<Button>(R.id.normal_automatch)
n.setOnClickListener {
go("live")
}
return rootView
}
fun go(speed: String) {
Log.d(javaClass.name, "go speed=$speed")
val ogs = OGS(Globals.uiConfig!!)
var dialog: AlertDialog? = null
val sizeList = ArrayList<String>()
if (rootView.findViewById<CheckBox>(R.id.checkbox_9).isChecked)
sizeList.add("9x9")
if (rootView.findViewById<CheckBox>(R.id.checkbox_13).isChecked)
sizeList.add("13x13")
if (rootView.findViewById<CheckBox>(R.id.checkbox_19).isChecked)
sizeList.add("19x19")
val uuid = ogs.createAutomatch(speed, sizeList) { obj ->
println("listenForGameData: onSuccess")
dialog?.dismiss()
ogs.closeSocket()
val intent = Intent(activity, Main3Activity::class.java)
intent.putExtra("id", obj.getInt("game_id"))
startActivity(intent)
}
dialog = AlertDialog.Builder(activity)
.setMessage("Searching for opponent...")
.setNegativeButton("Cancel") { dialogInterface, i ->
ogs.cancelAutomatch(uuid)
}
.show()
}
}
| mit | 6e766c60d998cc5555aba9cfb061bb99 | 31.136364 | 117 | 0.632249 | 4.242 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt | 2 | 10352 | // 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.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnDocumentsAndVirtualFilesChanges
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.changes.NewFilesListener.Companion.whenNewFilesCreated
import com.intellij.openapi.externalSystem.autoimport.settings.CachingAsyncSupplier
import com.intellij.openapi.externalSystem.autoimport.settings.EdtAsyncSupplier.Companion.invokeOnEdt
import com.intellij.openapi.externalSystem.autoimport.settings.ReadAsyncSupplier.Companion.readAction
import com.intellij.openapi.externalSystem.util.calculateCrc
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LocalTimeCounter.currentTime
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
@ApiStatus.Internal
class ProjectSettingsTracker(
private val project: Project,
private val projectTracker: AutoImportProjectTracker,
private val backgroundExecutor: Executor,
private val projectAware: ExternalSystemProjectAware,
private val parentDisposable: Disposable
) {
private val status = ProjectStatus(debugName = "Settings ${projectAware.projectId.readableName}")
private val settingsFilesStatus = AtomicReference(SettingsFilesStatus())
private val applyChangesOperation = AnonymousParallelOperationTrace(debugName = "Apply changes operation")
private val settingsProvider = ProjectSettingsProvider()
private fun calculateSettingsFilesCRC(settingsFiles: Set<String>): Map<String, Long> {
val localFileSystem = LocalFileSystem.getInstance()
return settingsFiles
.mapNotNull { localFileSystem.findFileByPath(it) }
.associate { it.path to calculateCrc(it) }
}
private fun calculateCrc(file: VirtualFile): Long {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getCachedDocument(file)
if (document != null) return document.calculateCrc(project, file)
return file.calculateCrc(project)
}
fun isUpToDate() = status.isUpToDate()
fun getModificationType() = status.getModificationType()
fun getSettingsContext(): ExternalSystemSettingsFilesReloadContext = settingsFilesStatus.get()
private fun createSettingsFilesStatus(
oldSettingsFilesCRC: Map<String, Long>,
newSettingsFilesCRC: Map<String, Long>
): SettingsFilesStatus {
val updatedFiles = oldSettingsFilesCRC.keys.intersect(newSettingsFilesCRC.keys)
.filterTo(HashSet()) { oldSettingsFilesCRC[it] != newSettingsFilesCRC[it] }
val createdFiles = newSettingsFilesCRC.keys.minus(oldSettingsFilesCRC.keys)
val deletedFiles = oldSettingsFilesCRC.keys.minus(newSettingsFilesCRC.keys)
return SettingsFilesStatus(oldSettingsFilesCRC, newSettingsFilesCRC, updatedFiles, createdFiles, deletedFiles)
}
/**
* Usually all crc hashes must be previously calculated
* => this apply will be fast
* => collisions is a rare thing
*/
private fun applyChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefreshAndCRCCalculation("applyChanges") { newSettingsFilesCRC ->
settingsFilesStatus.set(SettingsFilesStatus(newSettingsFilesCRC))
status.markSynchronized(currentTime())
applyChangesOperation.finishTask()
}
}
/**
* Applies changes for newly registered files
* Needed to cases: tracked files are registered during project reload
*/
private fun applyUnknownChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefreshAndCRCCalculation("applyUnknownChanges") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(newSettingsFilesCRC + it.oldCRC, newSettingsFilesCRC)
}
if (!settingsFilesStatus.hasChanges()) {
status.markSynchronized(currentTime())
}
applyChangesOperation.finishTask()
}
}
fun refreshChanges() {
submitSettingsFilesRefreshAndCRCCalculation("refreshChanges") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC)
}
LOG.info("Settings file status: ${settingsFilesStatus}")
when (settingsFilesStatus.hasChanges()) {
true -> status.markDirty(currentTime(), EXTERNAL)
else -> status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
fun getState() = State(status.isDirty(), settingsFilesStatus.get().oldCRC.toMap())
fun loadState(state: State) {
if (state.isDirty) status.markDirty(currentTime(), EXTERNAL)
settingsFilesStatus.set(SettingsFilesStatus(state.settingsFiles.toMap()))
}
private fun submitSettingsFilesRefreshAndCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) {
submitSettingsFilesRefresh { settingsPaths ->
submitSettingsFilesCRCCalculation(id, settingsPaths, callback)
}
}
private fun submitSettingsFilesCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) {
settingsProvider.supply({ settingsPaths ->
submitSettingsFilesCRCCalculation(id, settingsPaths, callback)
}, parentDisposable)
}
private fun submitSettingsFilesRefresh(callback: (Set<String>) -> Unit) {
invokeOnEdt(settingsProvider::isBlocking, {
val fileDocumentManager = FileDocumentManager.getInstance()
fileDocumentManager.saveAllDocuments()
settingsProvider.invalidate()
settingsProvider.supply({ settingsPaths ->
val localFileSystem = LocalFileSystem.getInstance()
val settingsFiles = settingsPaths.map { Path.of(it) }
localFileSystem.refreshNioFiles(settingsFiles, projectTracker.isAsyncChangesProcessing, false) {
callback(settingsPaths)
}
}, parentDisposable)
}, parentDisposable)
}
private fun submitSettingsFilesCRCCalculation(id: Any, settingsPaths: Set<String>, callback: (Map<String, Long>) -> Unit) {
readAction(settingsProvider::isBlocking, { calculateSettingsFilesCRC(settingsPaths) }, backgroundExecutor, this, id)
.supply(callback, parentDisposable)
}
fun beforeApplyChanges(listener: () -> Unit) = applyChangesOperation.beforeOperation(listener)
fun afterApplyChanges(listener: () -> Unit) = applyChangesOperation.afterOperation(listener)
init {
val projectRefreshListener = object : ExternalSystemProjectRefreshListener {
override fun beforeProjectRefresh() {
applyChangesOperation.startTask()
applyChanges()
}
override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) {
applyUnknownChanges()
applyChangesOperation.finishTask()
}
}
projectAware.subscribe(projectRefreshListener, parentDisposable)
}
init {
whenNewFilesCreated(settingsProvider::invalidate, parentDisposable)
subscribeOnDocumentsAndVirtualFilesChanges(settingsProvider, ProjectSettingsListener(), parentDisposable)
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap())
private data class SettingsFilesStatus(
val oldCRC: Map<String, Long> = emptyMap(),
val newCRC: Map<String, Long> = emptyMap(),
override val updated: Set<String> = emptySet(),
override val created: Set<String> = emptySet(),
override val deleted: Set<String> = emptySet()
) : ExternalSystemSettingsFilesReloadContext {
constructor(CRC: Map<String, Long>) : this(oldCRC = CRC)
fun hasChanges() = updated.isNotEmpty() || created.isNotEmpty() || deleted.isNotEmpty()
}
private inner class ProjectSettingsListener : FilesChangesListener {
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ModificationType) {
logModificationAsDebug(path, modificationStamp, modificationType)
if (applyChangesOperation.isOperationCompleted()) {
status.markModified(currentTime(), modificationType)
}
else {
status.markDirty(currentTime(), modificationType)
}
}
override fun apply() {
submitSettingsFilesCRCCalculation("apply") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC)
}
if (!settingsFilesStatus.hasChanges()) {
status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ModificationType) {
if (LOG.isDebugEnabled) {
val projectPath = projectAware.projectId.externalProjectPath
val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path
LOG.debug("File $relativePath is modified at ${modificationStamp} as $type")
}
}
}
private inner class ProjectSettingsProvider : CachingAsyncSupplier<Set<String>>() {
override fun get() = projectAware.settingsFiles
override fun isBlocking() = !projectTracker.isAsyncChangesProcessing
override fun supply(callback: (Set<String>) -> Unit, parentDisposable: Disposable) {
super.supply({ callback(it + settingsFilesStatus.get().oldCRC.keys) }, parentDisposable)
}
}
} | apache-2.0 | a243a874bc174ec65dad3cef2ff0d200 | 41.604938 | 140 | 0.762558 | 5.518124 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/option/HtlDataSlyCallOptionCompletionProvider.kt | 1 | 1800 | package com.aemtools.completion.htl.provider.option
import com.aemtools.analysis.htl.callchain
import com.aemtools.analysis.htl.callchain.typedescriptor.template.TemplateTypeDescriptor
import com.aemtools.common.util.findParentByType
import com.aemtools.completion.htl.inserthandler.HtlElAssignmentInsertHandler
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtlDataSlyCallOptionCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val currentPosition = parameters.position
val hel = currentPosition.findParentByType(com.aemtools.lang.htl.psi.mixin.HtlElExpressionMixin::class.java)
?: return
val outputType = hel
.getMainPropertyAccess()
?.callchain()
?.getLastOutputType()
as? TemplateTypeDescriptor
?: return
val templateParameters = outputType.parameters()
val presentOptions = hel.getOptions()
.map { it.name() }
.filterNot { it == "" }
val variants = templateParameters
.filterNot { presentOptions.contains(it) }
.map {
LookupElementBuilder.create(it)
.withIcon(AllIcons.Nodes.Parameter)
.withTypeText("HTL Template Parameter")
.withInsertHandler(HtlElAssignmentInsertHandler())
}
result.addAllElements(variants)
result.stopHere()
}
}
| gpl-3.0 | bac80d07479acaebe1552fcea9d1d0bf | 34.294118 | 112 | 0.742778 | 5.128205 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotCover/DotCoverToolTypeAdapter.kt | 1 | 1476 | package jetbrains.buildServer.dotCover
import jetbrains.buildServer.dotnet.DotnetConstants
import jetbrains.buildServer.tools.ToolTypeAdapter
class DotCoverToolTypeAdapter : ToolTypeAdapter() {
override fun getType()= DotnetConstants.DOTCOVER_PACKAGE_TYPE
override fun getDisplayName() = DotnetConstants.DOTCOVER_PACKAGE_TOOL_TYPE_NAME
override fun getDescription(): String? = "Is used in JetBrains dotCover-specific build steps to get code coverage."
override fun getShortDisplayName() = DotnetConstants.DOTCOVER_PACKAGE_SHORT_TOOL_TYPE_NAME
override fun getTargetFileDisplayName() = DotnetConstants.DOTCOVER_PACKAGE_TARGET_FILE_DISPLAY_NAME
override fun isSupportDownload() = true
override fun getToolSiteUrl() = "https://www.jetbrains.com/dotcover/download/#section=commandline"
override fun getToolLicenseUrl() = "https://www.jetbrains.com/dotcover/download/command_line_license.html"
override fun getTeamCityHelpFile() = "JetBrains+dotCover"
override fun getValidPackageDescription() = "Specify the path to a " + displayName + " (.nupkg).\n" +
"<br/>Download <em>${DotnetConstants.DOTCOVER_PACKAGE_TYPE}.<VERSION>.nupkg</em> from\n" +
"<a href=\"https://www.nuget.org/packages/${DotnetConstants.DOTCOVER_PACKAGE_TYPE}/\" target=\"_blank\" rel=\"noreferrer\">www.nuget.org</a>"
companion object {
internal val Shared: ToolTypeAdapter = DotCoverToolTypeAdapter()
}
} | apache-2.0 | 15a2a2542292c085123744f31d51183a | 45.15625 | 157 | 0.743225 | 4.290698 | false | false | false | false |
fboldog/anko | anko/library/generator/src/org/jetbrains/android/anko/utils/stringUtils.kt | 4 | 1444 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.utils
fun String.toCamelCase(separator: Char = '_', firstCapital: Boolean = true): String {
val builder = StringBuilder()
var capitalFlag = firstCapital
for (c in this) {
when (c) {
separator -> capitalFlag = true
else -> {
builder.append(if (capitalFlag) Character.toUpperCase(c) else Character.toLowerCase(c))
capitalFlag = false
}
}
}
return builder.toString()
}
internal fun String.toUPPER_CASE(): String {
val builder = StringBuilder()
for (c in this) {
if (c.isUpperCase() && builder.isNotEmpty()) builder.append('_')
builder.append(c.toUpperCase())
}
return builder.toString()
}
val Char.isPackageSymbol: Boolean
get() = isLowerCase() || isDigit() || this == '_' | apache-2.0 | f513933f9ffcf890d3db2bb65d76fdc6 | 31.840909 | 103 | 0.657895 | 4.209913 | false | false | false | false |
leafclick/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenConfigurationProducer.kt | 1 | 2826 | /*
* Copyright 2000-2010 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.idea.maven.execution
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.LazyRunConfigurationProducer
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
class MavenConfigurationProducer : LazyRunConfigurationProducer<MavenRunConfiguration>() {
override fun getConfigurationFactory(): ConfigurationFactory {
return MavenRunConfigurationType.getInstance().configurationFactories[0];
}
override fun setupConfigurationFromContext(configuration: MavenRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>): Boolean {
val location = context.location ?: return false
val file = location.virtualFile ?: return false
if (!MavenUtil.isPomFile(location.project, file)) return false
if (location !is MavenGoalLocation) return false
if (context.module == null) return false
val goals = location.goals
val profiles = MavenProjectsManager.getInstance(location.getProject()).explicitProfiles
configuration.runnerParameters = MavenRunnerParameters(true, file.parent.path, file.name, goals, profiles.enabledProfiles,
profiles.disabledProfiles)
return true
}
override fun isConfigurationFromContext(configuration: MavenRunConfiguration,
context: ConfigurationContext): Boolean {
val location = context.location ?: return false
val file = location.virtualFile ?: return false
if (!MavenUtil.isPomFile(location.project, file)) return false
if (location !is MavenGoalLocation) return false
if (context.module == null) return false
val tasks: List<String> = location.goals
val taskNames: List<String> = configuration.runnerParameters.goals
if (tasks.isEmpty() && taskNames.isEmpty()) {
return true
}
return tasks.containsAll(taskNames) && !taskNames.isEmpty()
}
} | apache-2.0 | b07ae4e479735f59f4755802020c3961 | 43.873016 | 126 | 0.724345 | 5.166362 | false | true | false | false |
agoda-com/Kakao | sample/src/main/kotlin/com/agoda/sample/NestedRecyclerAdapter.kt | 1 | 1158 | package com.agoda.sample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class NestedRecyclerAdapter : RecyclerView.Adapter<NestedRecyclerAdapter.ViewHolder>() {
override fun getItemCount() = 1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// no-op
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(parent.inflate(R.layout.item_nested_recycler))
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.findViewById<RecyclerView>(R.id.nested_recycler_view).run {
layoutManager = LinearLayoutManager(itemView.context, LinearLayoutManager.HORIZONTAL, false)
adapter = RecyclerAdapter().apply { items = RecyclerAdapter.textItems + RecyclerAdapter.finalItem }
}
}
}
fun ViewGroup.inflate(@LayoutRes layout: Int) = LayoutInflater.from(context).inflate(layout, this, false)
}
| apache-2.0 | 0a328c858fb56e87da72eccfe0b19c7e | 37.6 | 115 | 0.734024 | 4.92766 | false | false | false | false |
mpcjanssen/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/AddLinkBackground.kt | 1 | 3153 | /**
* This file is part of Simpletask.
* Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com)
* Copyright (c) 2013- Mark Janssen
* LICENSE:
* Todo.txt Touch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
* Todo.txt Touch 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 Todo.txt Touch. If not, see
* //www.gnu.org/licenses/>.
* @author Mark Janssen
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2009-2012 Todo.txt contributors (http://todotxt.com)
* *
* @copyright 2013- Mark Janssen
*/
package nl.mpcjanssen.simpletask
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.core.app.ShareCompat
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.task.TodoList
import nl.mpcjanssen.simpletask.util.Config
import nl.mpcjanssen.simpletask.util.showToastLong
import nl.mpcjanssen.simpletask.util.showToastShort
import nl.mpcjanssen.simpletask.util.todayAsString
import java.io.IOException
class AddLinkBackground : Activity() {
val tag = "AddLinkBackground"
public override fun onCreate(instance: Bundle?) {
Log.d(tag, "onCreate()")
super.onCreate(instance)
val append_text = TodoApplication.config.shareAppendText
val intentReader = ShareCompat.IntentReader.from(this)
val uri = intentReader.stream
val subject = intentReader.subject ?: ""
val mimeType = intentReader.type
Log.i(tag, "Added link to content ($mimeType)")
if (uri == null) {
showToastLong(TodoApplication.app, R.string.share_link_failed)
} else {
addBackgroundTask("$subject $uri", append_text)
}
}
private fun addBackgroundTask(sharedText: String, appendText: String) {
val todoList = TodoApplication.todoList
Log.d(tag, "Adding background tasks to todolist $todoList")
val rawLines = sharedText.split("\r\n|\r|\n".toRegex()).filterNot(String::isBlank)
val lines = if (appendText.isBlank()) { rawLines } else {
rawLines.map { "$it $appendText" }
}
val tasks = lines.map { text ->
if (TodoApplication.config.hasPrependDate) { Task(text, todayAsString) } else { Task(text) }
}
todoList.add(tasks, TodoApplication.config.hasAppendAtEnd)
todoList.notifyTasklistChanged(TodoApplication.config.todoFile, save = true, refreshMainUI = true)
showToastShort(TodoApplication.app, R.string.link_added)
if (TodoApplication.config.hasShareTaskShowsEdit) {
todoList.editTasks(this, tasks, "")
}
finish()
}
}
| gpl-3.0 | 6ffd5ff2fa98502503e250f046697cbb | 36.535714 | 119 | 0.701237 | 4.121569 | false | true | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/inventory/FilteredItemHandler.kt | 1 | 1671 | package net.ndrei.teslacorelib.inventory
import net.minecraft.item.ItemStack
import net.minecraftforge.items.IItemHandler
import net.minecraftforge.items.IItemHandlerModifiable
/**
* Created by CF on 2017-06-28.
*/
open class FilteredItemHandler protected constructor(val innerHandler: IItemHandler)
: IFilteredItemHandler {
override fun canInsertItem(slot: Int, stack: ItemStack)
= if (this.innerHandler is IFilteredItemHandler) this.innerHandler.canInsertItem(slot, stack) else true
override fun canExtractItem(slot: Int)
= if (this.innerHandler is IFilteredItemHandler) this.innerHandler.canExtractItem(slot) else true
override fun getSlots() = this.innerHandler.slots
override fun getStackInSlot(slot: Int) = this.innerHandler.getStackInSlot(slot)
override fun insertItem(slot: Int, stack: ItemStack, simulate: Boolean): ItemStack {
if (!this.canInsertItem(slot, stack)) {
return stack
}
return this.innerHandler.insertItem(slot, stack, simulate)
}
override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack {
if (!this.canExtractItem(slot)) {
return ItemStack.EMPTY
}
return this.innerHandler.extractItem(slot, amount, simulate)
}
override fun getSlotLimit(slot: Int) = this.innerHandler.getSlotLimit(slot)
override fun setStackInSlot(slot: Int, stack: ItemStack) {
if (this.innerHandler is IItemHandlerModifiable) {
this.innerHandler.setStackInSlot(slot, stack)
} else {
throw RuntimeException("Inner item handler is not modifiable.")
}
}
}
| mit | 67d9b2cdf3cb359abe60af22d393f960 | 35.326087 | 115 | 0.706164 | 4.420635 | false | false | false | false |
blokadaorg/blokada | android5/app/src/engine/kotlin/engine/ScreenOnService.kt | 1 | 1698 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2022 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package engine
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import service.ContextService
import utils.Logger
object ScreenOnService {
private val ctx by lazy { ContextService }
private val frequencyMillis = 60 * 1000
private var lastScreenOffMillis = 0L
var onScreenOn = {}
init {
val intentFilter = IntentFilter(Intent.ACTION_SCREEN_ON)
intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
val mReceiver: BroadcastReceiver = ScreenStateBroadcastReceiver()
ctx.requireAppContext().registerReceiver(mReceiver, intentFilter)
Logger.v("ScreenOn", "Registered for Screen ON")
}
class ScreenStateBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
Intent.ACTION_SCREEN_OFF -> {
lastScreenOffMillis = System.currentTimeMillis()
}
Intent.ACTION_SCREEN_ON -> {
if (lastScreenOffMillis + frequencyMillis < System.currentTimeMillis()) {
Logger.v("ScreenOn", "Received Screen ON")
onScreenOn()
}
}
}
}
}
} | mpl-2.0 | 2d1441d8178f37e8fe6f11d4753e689f | 29.872727 | 93 | 0.638185 | 4.727019 | false | false | false | false |
AndroidX/androidx | camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/internal/Camera2CameraImplForceOpenCameraTest.kt | 3 | 8453 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.internal
import android.content.Context
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import androidx.camera.camera2.AsyncCameraDevice
import androidx.camera.camera2.Camera2Config
import androidx.camera.camera2.internal.compat.CameraManagerCompat
import androidx.camera.core.CameraSelector
import androidx.camera.core.Logger
import androidx.camera.core.impl.CameraInternal.State
import androidx.camera.core.impl.CameraStateRegistry
import androidx.camera.core.impl.Observable.Observer
import androidx.camera.core.impl.utils.executor.CameraXExecutors
import androidx.camera.testing.CameraUtil
import androidx.camera.testing.CameraUtil.PreTestCameraIdList
import androidx.core.os.HandlerCompat
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.AfterClass
import org.junit.Assume.assumeFalse
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests [Camera2CameraImpl]'s force opening camera behavior.
*
* The test opens a camera with Camera2 (using [CameraDevice]), then attempts to open the same
* camera with CameraX (using [Camera2CameraImpl]).
*
* Camera opening behavior is different in API levels 21/22 compared to API levels 23 and above.
* In API levels 21 and 22, a second camera client cannot open a camera until the first client
* closes it, whereas in later API levels, the camera service steals the camera away from a
* client when another one with the same or a higher priority attempts to open it.
*/
@LargeTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 21)
class Camera2CameraImplForceOpenCameraTest {
@get:Rule
val cameraRule = CameraUtil.grantCameraPermissionAndPreTest(
PreTestCameraIdList(Camera2Config.defaultConfig())
)
private lateinit var cameraId: String
private lateinit var camera2Camera: AsyncCameraDevice
private val mCameraXCameraToStateObserver = mutableMapOf<Camera2CameraImpl, Observer<State>>()
@Before
fun getCameraId() {
val camId = CameraUtil.getCameraIdWithLensFacing(CameraSelector.LENS_FACING_BACK)
assumeFalse("Device doesn't have a back facing camera", camId == null)
cameraId = camId!!
}
@After
fun releaseCameraResources() {
if (::camera2Camera.isInitialized) {
camera2Camera.closeAsync()
}
for (entry in mCameraXCameraToStateObserver) {
releaseCameraXCameraResource(entry)
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.M)
@Test
fun openCameraImmediately_ifCameraCanBeStolen() {
// Open the camera with Camera2
val camera2CameraOpen = openCamera_camera2(cameraId)
camera2CameraOpen.get()
// Open the camera with CameraX, this steals it away from Camera2
val cameraXCameraOpen = openCamera_cameraX(cameraId)
cameraXCameraOpen.await()
}
@SdkSuppress(minSdkVersion = 21, maxSdkVersion = Build.VERSION_CODES.LOLLIPOP_MR1)
@Test
fun openCameraWhenAvailable_ifCameraCannotBeStolen() {
// Open the camera with Camera2
val camera2CameraOpen = openCamera_camera2(cameraId)
camera2CameraOpen.get()
// Attempt to open the camera with CameraX, this will fail
val cameraXCameraOpen = openCamera_cameraX(cameraId)
assertThat(cameraXCameraOpen.timesOutWhileWaiting()).isTrue()
// Close the camera with Camera2, and wait for it to be opened with CameraX
camera2Camera.closeAsync()
cameraXCameraOpen.await()
}
@Test
fun openCameraWhenAvailable_ifMaxAllowedOpenedCamerasReached() {
// Open the camera with CameraX
val cameraOpen1 = openCamera_cameraX(cameraId)
cameraOpen1.await()
// Open the camera again with CameraX
val cameraOpen2 = openCamera_cameraX(cameraId)
assertThat(cameraOpen2.timesOutWhileWaiting()).isTrue()
// Close the first camera instance, and wait for it to be opened with the second instance
releaseCameraXCameraResource(mCameraXCameraToStateObserver.entries.first())
cameraOpen2.await()
}
private fun openCamera_camera2(camId: String): ListenableFuture<CameraDevice> {
val context = ApplicationProvider.getApplicationContext<Context>()
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
camera2Camera = AsyncCameraDevice(cameraManager, camId, cameraHandler)
return camera2Camera.openAsync()
}
private fun openCamera_cameraX(camId: String): Semaphore {
// Build camera manager wrapper
val context = ApplicationProvider.getApplicationContext<Context>()
val cameraManagerCompat = CameraManagerCompat.from(context)
// Build camera info from cameraId
val camera2CameraInfo = Camera2CameraInfoImpl(
camId,
cameraManagerCompat
)
// Initialize camera instance
val camera = Camera2CameraImpl(
cameraManagerCompat,
camId,
camera2CameraInfo,
cameraRegistry,
cameraExecutor,
cameraHandler,
DisplayInfoManager.getInstance(ApplicationProvider.getApplicationContext())
)
// Open the camera
camera.open()
val cameraOpenSemaphore = Semaphore(0)
val stateObserver = object : Observer<State> {
override fun onNewData(value: State?) {
if (value == State.OPEN) {
Logger.d(TAG, "CameraX: Camera open")
cameraOpenSemaphore.release()
}
}
override fun onError(throwable: Throwable) {
Logger.e(TAG, "CameraX: Camera error $throwable")
}
}
camera.cameraState.addObserver(cameraExecutor, stateObserver)
mCameraXCameraToStateObserver[camera] = stateObserver
return cameraOpenSemaphore
}
private fun releaseCameraXCameraResource(
entry: MutableMap.MutableEntry<Camera2CameraImpl, Observer<State>>
) {
entry.key.cameraState.removeObserver(entry.value)
entry.key.release().get()
}
private fun Semaphore.await() {
assertThat(tryAcquire(5, TimeUnit.SECONDS)).isTrue()
}
private fun Semaphore.timesOutWhileWaiting(): Boolean {
val acquired = tryAcquire(5, TimeUnit.SECONDS)
return !acquired
}
companion object {
private const val TAG = "ForceOpenCameraTest"
private lateinit var cameraHandlerThread: HandlerThread
private lateinit var cameraHandler: Handler
private lateinit var cameraExecutor: ExecutorService
private val cameraRegistry: CameraStateRegistry by lazy { CameraStateRegistry(1) }
@BeforeClass
@JvmStatic
fun classSetup() {
cameraHandlerThread = HandlerThread("cameraThread")
cameraHandlerThread.start()
cameraHandler = HandlerCompat.createAsync(cameraHandlerThread.looper)
cameraExecutor = CameraXExecutors.newHandlerExecutor(cameraHandler)
}
@AfterClass
@JvmStatic
fun classTeardown() {
cameraHandlerThread.quitSafely()
}
}
} | apache-2.0 | af81e8021c15a6c989fad39ff122d673 | 36.078947 | 98 | 0.714421 | 4.794668 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/ManagerThreadExecutor.kt | 2 | 2186 | // 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.debugger.coroutine.proxy
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaDebugProcess
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.events.SuspendContextCommandImpl
import com.intellij.debugger.impl.PrioritizedTask
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.frame.XSuspendContext
import java.awt.Component
class ManagerThreadExecutor(val debugProcess: DebugProcessImpl) {
constructor(session: XDebugSession) : this(session.debugProcess)
constructor(debugProcess: XDebugProcess) : this((debugProcess as JavaDebugProcess).debuggerSession.process)
fun on(suspendContext: XSuspendContext, priority: PrioritizedTask.Priority = PrioritizedTask.Priority.NORMAL) =
ManagerThreadExecutorInstance(suspendContext, priority)
inner class ManagerThreadExecutorInstance(
val suspendContext: SuspendContextImpl,
val priority: PrioritizedTask.Priority = PrioritizedTask.Priority.NORMAL
) {
constructor(sc: XSuspendContext, priority: PrioritizedTask.Priority) : this(sc as SuspendContextImpl, priority)
fun invoke(f: (SuspendContextImpl) -> Unit) {
debugProcess.managerThread.invoke(makeCommand(f))
}
private fun makeCommand(f: (SuspendContextImpl) -> Unit) =
object : SuspendContextCommandImpl(suspendContext) {
override fun getPriority() = [email protected]
override fun contextAction(suspendContext: SuspendContextImpl) {
f(suspendContext)
}
}
}
}
fun invokeLater(component: Component, f: () -> Unit) =
ApplicationManager.getApplication().invokeLater({ f() }, ModalityState.stateForComponent(component))
| apache-2.0 | b7074ba3b0c4d9928e43d033a8373cff | 43.612245 | 158 | 0.762123 | 5.107477 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-api/src/com/intellij/ide/util/PropertiesComponentEx.kt | 10 | 3443 | // 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.util
import com.intellij.openapi.project.Project
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private fun propComponent(project: Project?): PropertiesComponent {
return if (project == null) PropertiesComponent.getInstance() else PropertiesComponent.getInstance(project)
}
private fun propName(name: String?, thisRef: Any?, property: KProperty<*>): String {
return name
?: thisRef?.let { it::class.qualifiedName + "." + property.name }
?: error("Either name must be specified or the property must belong to a class")
}
private class PropertiesComponentIntProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: Int
) : ReadWriteProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return propComponent(project).getInt(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
private class PropertiesComponentStringProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: String
) : ReadWriteProperty<Any?, String> {
override fun getValue(thisRef: Any?, property: KProperty<*>): String {
return propComponent(project).getValue(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
private class PropertiesComponentBooleanProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: Boolean
) : ReadWriteProperty<Any?, Boolean> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Boolean {
return propComponent(project).getBoolean(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
fun propComponentProperty(project: Project? = null, defaultValue: Int = 0): ReadWriteProperty<Any, Int> =
PropertiesComponentIntProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: Int = 0): ReadWriteProperty<Any?, Int> =
PropertiesComponentIntProperty(project, name, defaultValue)
fun propComponentProperty(project: Project? = null, defaultValue: String = ""): ReadWriteProperty<Any, String> =
PropertiesComponentStringProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: String = ""): ReadWriteProperty<Any?, String> =
PropertiesComponentStringProperty(project, name, defaultValue)
fun propComponentProperty(project: Project? = null, defaultValue: Boolean = false): ReadWriteProperty<Any, Boolean> =
PropertiesComponentBooleanProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: Boolean = false): ReadWriteProperty<Any?, Boolean> =
PropertiesComponentBooleanProperty(project, name, defaultValue)
| apache-2.0 | 66c19a4a4e4e52641a287beb25d407c3 | 42.0375 | 140 | 0.761255 | 4.652703 | false | false | false | false |
smmribeiro/intellij-community | platform/credential-store/src/macOsKeychainLibrary.kt | 5 | 10388 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ArrayUtilRt
import com.intellij.util.text.nullize
import com.sun.jna.*
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.PointerByReference
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
val isMacOsCredentialStoreSupported: Boolean
get() = SystemInfo.isMac
private const val errSecSuccess = 0
private const val errSecItemNotFound = -25300
private const val errSecInvalidRecord = -67701
// or if Deny clicked on access dialog
private const val errUserNameNotCorrect = -25293
// https://developer.apple.com/documentation/security/1542001-security_framework_result_codes/errsecusercanceled?language=objc
private const val errSecUserCanceled = -128
private const val kSecFormatUnknown = 0
private const val kSecAccountItemAttr = (('a'.toInt() shl 8 or 'c'.toInt()) shl 8 or 'c'.toInt()) shl 8 or 't'.toInt()
internal class KeyChainCredentialStore : CredentialStore {
companion object {
private val library = Native.load("Security", MacOsKeychainLibrary::class.java)
private fun findGenericPassword(serviceName: ByteArray, accountName: String?): Credentials? {
val accountNameBytes = accountName?.toByteArray()
val passwordSize = IntArray(1)
val passwordRef = PointerByReference()
val itemRef = PointerByReference()
val errorCode = checkForError("find", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes?.size ?: 0, accountNameBytes, passwordSize, passwordRef, itemRef))
if (errorCode == errSecUserCanceled) {
return ACCESS_TO_KEY_CHAIN_DENIED
}
if (errorCode == errUserNameNotCorrect) {
return CANNOT_UNLOCK_KEYCHAIN
}
val pointer = passwordRef.value ?: return null
val password = OneTimeString(pointer.getByteArray(0, passwordSize.get(0)))
library.SecKeychainItemFreeContent(null, pointer)
var effectiveAccountName = accountName
if (effectiveAccountName == null) {
val attributes = PointerByReference()
checkForError("SecKeychainItemCopyAttributesAndData", library.SecKeychainItemCopyAttributesAndData(itemRef.value!!, SecKeychainAttributeInfo(kSecAccountItemAttr), null, attributes, null, null))
val attributeList = SecKeychainAttributeList(attributes.value)
try {
attributeList.read()
effectiveAccountName = readAttributes(attributeList).get(kSecAccountItemAttr)
}
finally {
library.SecKeychainItemFreeAttributesAndData(attributeList, null)
}
}
return Credentials(effectiveAccountName, password)
}
private fun checkForError(message: String, code: Int): Int {
if (code == errSecSuccess || code == errSecItemNotFound) {
return code
}
val translated = library.SecCopyErrorMessageString(code, null)
val builder = StringBuilder(message).append(": ")
if (translated == null) {
builder.append(code)
}
else {
val buf = CharArray(library.CFStringGetLength(translated).toInt())
for (i in buf.indices) {
buf[i] = library.CFStringGetCharacterAtIndex(translated, i.toLong())
}
library.CFRelease(translated)
builder.append(buf).append(" (").append(code).append(')')
}
if (code == errUserNameNotCorrect || code == errSecUserCanceled || code == -25299 /* The specified item already exists in the keychain */) {
LOG.warn(builder.toString())
}
else {
LOG.error(builder.toString())
}
return code
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
return findGenericPassword(attributes.serviceName.toByteArray(), attributes.userName.nullize())
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceName = attributes.serviceName.toByteArray()
if (credentials.isEmpty()) {
val itemRef = PointerByReference()
val userName = attributes.userName.nullize()?.toByteArray()
val code = library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, null, null, itemRef)
if (code == errSecItemNotFound || code == errSecInvalidRecord) {
return
}
checkForError("find (for delete)", code)
itemRef.value?.let {
checkForError("delete", library.SecKeychainItemDelete(it))
library.CFRelease(it)
}
return
}
val userName = (attributes.userName.nullize() ?: credentials!!.userName)?.toByteArray()
val searchUserName = if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null
val itemRef = PointerByReference()
val library = library
checkForError("find (for save)", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, searchUserName?.size ?: 0, searchUserName, null, null, itemRef))
val password = if (attributes.isPasswordMemoryOnly || credentials!!.password == null) null else credentials.password!!.toByteArray(false)
val pointer = itemRef.value
if (pointer == null) {
checkForError("save (new)", library.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, password?.size ?: 0, password))
}
else {
val attribute = SecKeychainAttribute()
attribute.tag = kSecAccountItemAttr
attribute.length = userName?.size ?: 0
if (userName != null && userName.isNotEmpty()) {
val userNamePointer = Memory(userName.size.toLong())
userNamePointer.write(0, userName, 0, userName.size)
attribute.data = userNamePointer
}
val attributeList = SecKeychainAttributeList()
attributeList.count = 1
attribute.write()
attributeList.attr = attribute.pointer
checkForError("save (update)", library.SecKeychainItemModifyContent(pointer, attributeList, password?.size ?: 0, password ?: ArrayUtilRt.EMPTY_BYTE_ARRAY))
library.CFRelease(pointer)
}
password?.fill(0)
}
}
// https://developer.apple.com/library/mac/documentation/Security/Reference/keychainservices/index.html
// It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered."
@Suppress("FunctionName")
private interface MacOsKeychainLibrary : Library {
fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: Int, passwordData: ByteArray?, itemRef: Pointer? = null): Int
fun SecKeychainItemModifyContent(itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Any?, length: Int, data: ByteArray?): Int
fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?,
serviceNameLength: Int,
serviceName: ByteArray,
accountNameLength: Int,
accountName: ByteArray?,
passwordLength: IntArray?,
passwordData: PointerByReference?,
itemRef: PointerByReference?): Int
fun SecKeychainItemCopyAttributesAndData(itemRef: Pointer,
info: SecKeychainAttributeInfo,
itemClass: IntByReference?,
attrList: PointerByReference,
length: IntByReference?,
outData: PointerByReference?): Int
fun SecKeychainItemFreeAttributesAndData(attrList: SecKeychainAttributeList, data: Pointer?): Int
fun SecKeychainItemDelete(itemRef: Pointer): Int
fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer?
// http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long
fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char
fun CFRelease(/*CFTypeRef*/ cf: Pointer)
fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?)
}
// must be not private
@Structure.FieldOrder("count", "tag", "format")
internal class SecKeychainAttributeInfo : Structure() {
@JvmField var count: Int = 0
@JvmField var tag: Pointer? = null
@JvmField var format: Pointer? = null
}
@Suppress("FunctionName")
private fun SecKeychainAttributeInfo(vararg ids: Int): SecKeychainAttributeInfo {
val info = SecKeychainAttributeInfo()
val length = ids.size
info.count = length
val size = length shl 2
val tag = Memory((size shl 1).toLong())
val format = tag.share(size.toLong(), size.toLong())
info.tag = tag
info.format = format
var offset = 0
for (id in ids) {
tag.setInt(offset.toLong(), id)
format.setInt(offset.toLong(), kSecFormatUnknown)
offset += 4
}
return info
}
// must be not private
@Structure.FieldOrder("count", "attr")
internal class SecKeychainAttributeList : Structure {
@JvmField var count = 0
@JvmField var attr: Pointer? = null
constructor(p: Pointer) : super(p)
constructor() : super()
}
// must be not private
@Structure.FieldOrder("tag", "length", "data")
internal class SecKeychainAttribute : Structure, Structure.ByReference {
@JvmField var tag = 0
@JvmField var length = 0
@JvmField var data: Pointer? = null
internal constructor(p: Pointer) : super(p)
internal constructor() : super()
}
private fun readAttributes(list: SecKeychainAttributeList): Int2ObjectMap<String> {
val map = Int2ObjectOpenHashMap<String>()
val attrList = SecKeychainAttribute(list.attr!!)
attrList.read()
@Suppress("UNCHECKED_CAST")
for (attr in attrList.toArray(list.count) as Array<SecKeychainAttribute>) {
val data = attr.data ?: continue
map.put(attr.tag, String(data.getByteArray(0, attr.length)))
}
return map
}
| apache-2.0 | a79d47fb3ba069c4960f32a98e04996e | 41.05668 | 230 | 0.6933 | 4.456456 | false | false | false | false |
leafclick/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/history/FileHistoryPersistence.kt | 1 | 1660 | package com.intellij.filePrediction.history
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.PathUtil
import com.intellij.util.io.exists
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
object FileHistoryPersistence {
private val LOG: Logger = Logger.getInstance(FileHistoryPersistence::class.java)
fun saveFileHistory(project: Project, state: FilePredictionHistoryState) {
val path: Path? = getPathToStorage(project)
try {
if (path != null) {
JDOMUtil.write(state.serialize(), path)
}
}
catch (e: IOException) {
LOG.warn("Cannot serialize opened files history", e)
}
}
fun loadFileHistory(project: Project): FilePredictionHistoryState {
val state = FilePredictionHistoryState()
val path: Path? = getPathToStorage(project)
try {
if (path != null && path.exists()) {
state.deserialize(JDOMUtil.load(path))
}
}
catch (e: Exception) {
LOG.warn("Cannot deserialize opened files history", e)
}
return state
}
private fun getPathToStorage(project: Project): Path? {
val url = project.presentableUrl ?: return null
val projectPath = Paths.get(VirtualFileManager.extractPath(url))
val dirName = PathUtil.suggestFileName(projectPath.fileName.toString() + Integer.toHexString(projectPath.toString().hashCode()))
return Paths.get(PathManager.getSystemPath(), "fileHistory", "$dirName.xml")
}
} | apache-2.0 | 51554dd85df69a7403e7702d23ac687a | 32.22 | 132 | 0.729518 | 4.334204 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/EqualsOrHashCodeInspection.kt | 1 | 4462 | // 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.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateEqualsAndHashcodeAction
import org.jetbrains.kotlin.idea.actions.generate.findDeclaredEquals
import org.jetbrains.kotlin.idea.actions.generate.findDeclaredHashCode
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.classOrObjectVisitor
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.source.getPsi
object DeleteEqualsAndHashCodeFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("delete.equals.and.hash.code.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return
val objectDeclaration = descriptor.psiElement.getStrictParentOfType<KtObjectDeclaration>() ?: return
val classDescriptor = objectDeclaration.resolveToDescriptorIfAny() ?: return
classDescriptor.findDeclaredEquals(false)?.source?.getPsi()?.delete()
classDescriptor.findDeclaredHashCode(false)?.source?.getPsi()?.delete()
}
}
sealed class GenerateEqualsOrHashCodeFix : LocalQuickFix {
object Equals : GenerateEqualsOrHashCodeFix() {
override fun getName() = KotlinBundle.message("equals.text")
}
object HashCode : GenerateEqualsOrHashCodeFix() {
override fun getName() = KotlinBundle.message("hash.code.text")
}
override fun getFamilyName() = name
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return
KotlinGenerateEqualsAndHashcodeAction().doInvoke(project, null, descriptor.psiElement.parent as KtClass)
}
}
class EqualsOrHashCodeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return classOrObjectVisitor(fun(classOrObject) {
val nameIdentifier = classOrObject.nameIdentifier ?: return
val classDescriptor = classOrObject.resolveToDescriptorIfAny() ?: return
val hasEquals = classDescriptor.findDeclaredEquals(false) != null
val hasHashCode = classDescriptor.findDeclaredHashCode(false) != null
if (!hasEquals && !hasHashCode) return
when (classDescriptor.kind) {
ClassKind.OBJECT -> {
if (classOrObject.superTypeListEntries.isNotEmpty()) return
holder.registerProblem(
nameIdentifier,
KotlinBundle.message("equals.hashcode.in.object.declaration"),
DeleteEqualsAndHashCodeFix
)
}
ClassKind.CLASS -> {
if (hasEquals && hasHashCode) return
val description = InspectionsBundle.message(
"inspection.equals.hashcode.only.one.defined.problem.descriptor",
if (hasEquals) "<code>equals()</code>" else "<code>hashCode()</code>",
if (hasEquals) "<code>hashCode()</code>" else "<code>equals()</code>"
)
holder.registerProblem(
nameIdentifier,
description,
if (hasEquals) GenerateEqualsOrHashCodeFix.HashCode else GenerateEqualsOrHashCodeFix.Equals
)
}
else -> return
}
})
}
} | apache-2.0 | 43a8c2805e42593492e802b202c469fc | 47.51087 | 158 | 0.699686 | 5.556663 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt | 5 | 6122 | // 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.refactoring.rename
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.usageView.UsageInfo
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RenameKotlinClassifierProcessor : RenameKotlinPsiProcessor() {
override fun canProcessElement(element: PsiElement): Boolean {
return element is KtClassOrObject || element is KtLightClass || element is KtConstructor<*> || element is KtTypeAlias
}
override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_CLASS
override fun setToSearchInComments(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = enabled
}
override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_CLASS
override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_CLASS = enabled
}
override fun substituteElementToRename(element: PsiElement, editor: Editor?) = getClassOrObject(element)
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>) {
super.prepareRenaming(element, newName, allRenames)
val classOrObject = getClassOrObject(element) as? KtClassOrObject ?: return
classOrObject.withExpectedActuals().forEach {
val file = it.containingKtFile
val virtualFile = file.virtualFile
if (virtualFile != null) {
val nameWithoutExtensions = virtualFile.nameWithoutExtension
if (nameWithoutExtensions == it.name) {
val newFileName = newName + "." + virtualFile.extension
allRenames.put(file, newFileName)
forElement(file).prepareRenaming(file, newFileName, allRenames)
}
}
}
}
protected fun processFoundReferences(
element: PsiElement,
references: Collection<PsiReference>
): Collection<PsiReference> {
if (element is KtObjectDeclaration && element.isCompanion()) {
return references.filter { !it.isCompanionObjectClassReference() }
}
return references
}
private fun PsiReference.isCompanionObjectClassReference(): Boolean {
if (this !is KtSimpleNameReference) {
return false
}
val bindingContext = element.analyze(BodyResolveMode.PARTIAL)
return bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element] != null
}
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: MutableMap<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return
val collisions = SmartList<UsageInfo>()
checkRedeclarations(declaration, newName, collisions)
checkOriginalUsagesRetargeting(declaration, newName, result, collisions)
checkNewNameUsagesRetargeting(declaration, newName, collisions)
result += collisions
}
private fun getClassOrObject(element: PsiElement?): PsiElement? = when (element) {
is KtLightClass ->
when (element) {
is KtLightClassForSourceDeclaration -> element.kotlinOrigin
is KtLightClassForFacade -> element
else -> throw AssertionError("Should not be suggested to rename element of type " + element::class.java + " " + element)
}
is KtConstructor<*> ->
element.getContainingClassOrObject()
is KtClassOrObject, is KtTypeAlias -> element
else -> null
}
override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) {
val simpleUsages = ArrayList<UsageInfo>(usages.size)
val ambiguousImportUsages = SmartList<UsageInfo>()
val simpleImportUsages = SmartList<UsageInfo>()
for (usage in usages) when (usage.importState()) {
ImportState.AMBIGUOUS -> ambiguousImportUsages += usage
ImportState.SIMPLE -> simpleImportUsages += usage
ImportState.NOT_IMPORT -> simpleUsages += usage
}
element.ambiguousImportUsages = ambiguousImportUsages
val usagesToRename = if (simpleImportUsages.isEmpty()) simpleUsages else simpleImportUsages + simpleUsages
super.renameElement(element, newName, usagesToRename.toTypedArray(), listener)
usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() }
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val references = super.findReferences(element, searchScope, searchInCommentsAndStrings)
return processFoundReferences(element, references)
}
}
| apache-2.0 | d5b1d9adf57112b51639698adcf6fefb | 43.043165 | 158 | 0.72117 | 5.379613 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/api/fixes/HLDiagnosticFixFactory.kt | 1 | 5801 | // 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.fir.api.fixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.api.applicator.HLApplicator
import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi
import org.jetbrains.kotlin.idea.quickfix.QuickFixActionBase
import kotlin.reflect.KClass
sealed class HLDiagnosticFixFactory<DIAGNOSTIC : KtDiagnosticWithPsi<*>> {
abstract fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<QuickFixActionBase<*>>
abstract val diagnosticClass: KClass<DIAGNOSTIC>
}
private class HLDiagnosticFixFactoryWithFixedApplicator<DIAGNOSTIC : KtDiagnosticWithPsi<*>, TARGET_PSI : PsiElement, INPUT : HLApplicatorInput>(
override val diagnosticClass: KClass<DIAGNOSTIC>,
private val applicator: HLApplicator<TARGET_PSI, INPUT>,
private val createTargets: KtAnalysisSession.(DIAGNOSTIC) -> List<HLApplicatorTargetWithInput<TARGET_PSI, INPUT>>,
) : HLDiagnosticFixFactory<DIAGNOSTIC>() {
override fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<HLQuickFix<TARGET_PSI, INPUT>> =
createTargets.invoke(this, diagnostic).map { (target, input) -> HLQuickFix(target, input, applicator) }
}
private class HLDiagnosticFixFactoryUsingQuickFixActionBase<DIAGNOSTIC : KtDiagnosticWithPsi<*>>(
override val diagnosticClass: KClass<DIAGNOSTIC>,
private val createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>>
) : HLDiagnosticFixFactory<DIAGNOSTIC>() {
override fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<QuickFixActionBase<*>> =
createQuickFixes.invoke(this, diagnostic)
}
internal fun <DIAGNOSTIC : KtDiagnosticWithPsi<PsiElement>> KtAnalysisSession.createPlatformQuickFixes(
diagnostic: DIAGNOSTIC,
factory: HLDiagnosticFixFactory<DIAGNOSTIC>
): List<IntentionAction> = with(factory) { createQuickFixes(diagnostic) }
/**
* Returns a [HLDiagnosticFixFactory] that creates targets and inputs ([HLApplicatorTargetWithInput]) from a diagnostic.
* The targets and inputs are consumed by the given applicator to apply fixes.
*/
fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>, TARGET_PSI : PsiElement, INPUT : HLApplicatorInput> diagnosticFixFactory(
diagnosticClass: KClass<DIAGNOSTIC>,
applicator: HLApplicator<TARGET_PSI, INPUT>,
createTargets: KtAnalysisSession.(DIAGNOSTIC) -> List<HLApplicatorTargetWithInput<TARGET_PSI, INPUT>>
): HLDiagnosticFixFactory<DIAGNOSTIC> =
HLDiagnosticFixFactoryWithFixedApplicator(diagnosticClass, applicator, createTargets)
/**
* Returns a [HLDiagnosticFixFactory] that creates [QuickFixActionBase]s from a diagnostic.
*/
fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> diagnosticFixFactory(
diagnosticClass: KClass<DIAGNOSTIC>,
createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>>
): HLDiagnosticFixFactory<DIAGNOSTIC> =
HLDiagnosticFixFactoryUsingQuickFixActionBase(diagnosticClass, createQuickFixes)
/**
* Returns a [Collection] of [HLDiagnosticFixFactory] that creates [QuickFixActionBase]s from diagnostics that have the same type of
* [PsiElement].
*/
fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> diagnosticFixFactories(
vararg diagnosticClasses: KClass<out DIAGNOSTIC>,
createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>>
): Collection<HLDiagnosticFixFactory<out DIAGNOSTIC>> =
diagnosticClasses.map { HLDiagnosticFixFactoryUsingQuickFixActionBase(it, createQuickFixes) }
/**
* Returns a [HLDiagnosticFixFactory] that creates [IntentionAction]s from a diagnostic.
*/
fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> diagnosticFixFactoryFromIntentionActions(
diagnosticClass: KClass<DIAGNOSTIC>,
createIntentionActions: KtAnalysisSession.(DIAGNOSTIC) -> List<IntentionAction>
): HLDiagnosticFixFactory<DIAGNOSTIC> {
// Wrap the IntentionActions as QuickFixActionBase. This ensures all fixes are of type QuickFixActionBase.
val createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>> = { diagnostic ->
val intentionActions = createIntentionActions.invoke(this, diagnostic)
intentionActions.map { IntentionActionAsQuickFixWrapper(it, diagnostic.psi) }
}
return HLDiagnosticFixFactoryUsingQuickFixActionBase(diagnosticClass, createQuickFixes)
}
/**
* Returns a [Collection] of [HLDiagnosticFixFactory] that creates [IntentionAction]s from diagnostics that have the same type of
* [PsiElement].
*/
fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> diagnosticFixFactoriesFromIntentionActions(
vararg diagnosticClasses: KClass<out DIAGNOSTIC>,
createIntentionActions: KtAnalysisSession.(DIAGNOSTIC) -> List<IntentionAction>
): Collection<HLDiagnosticFixFactory<out DIAGNOSTIC>> =
diagnosticClasses.map { diagnosticFixFactoryFromIntentionActions(it, createIntentionActions) }
private class IntentionActionAsQuickFixWrapper<T : PsiElement>(val intentionAction: IntentionAction, element: T) :
QuickFixActionBase<T>(element) {
override fun getText(): String = intentionAction.text
override fun getFamilyName(): String = intentionAction.familyName
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) = intentionAction.invoke(project, editor, file)
}
| apache-2.0 | c414897245a759981f05091c807f633a | 54.778846 | 158 | 0.798483 | 4.600317 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/build/buildTreeFilters.kt | 8 | 4099 | // 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.
@file:JvmName("BuildTreeFilters")
package com.intellij.build
import com.intellij.icons.AllIcons
import com.intellij.ide.util.PropertiesComponent
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.ApiStatus
import java.util.function.Predicate
private val SUCCESSFUL_STEPS_FILTER = Predicate { node: ExecutionNode -> !node.isFailed && !node.hasWarnings() }
private val WARNINGS_FILTER = Predicate { node: ExecutionNode -> node.hasWarnings() || node.hasInfos() }
@ApiStatus.Experimental
fun createFilteringActionsGroup(filterable: Filterable<ExecutionNode>): DefaultActionGroup {
val actionGroup = DefaultActionGroup(LangBundle.message("action.filters.text"), true)
actionGroup.templatePresentation.icon = AllIcons.Actions.Show
actionGroup.add(WarningsToggleAction(filterable))
actionGroup.add(SuccessfulStepsToggleAction(filterable))
return actionGroup
}
@ApiStatus.Experimental
fun install(filterable: Filterable<ExecutionNode>) {
val filteringEnabled = filterable.isFilteringEnabled
if (!filteringEnabled) return
SuccessfulStepsToggleAction.install(filterable)
WarningsToggleAction.install(filterable)
}
@ApiStatus.Experimental
open class FilterToggleAction constructor(@NlsContexts.Command text: String,
private val stateKey: String?,
private val filterable: Filterable<ExecutionNode>,
private val filter: Predicate<ExecutionNode>,
private val defaultState: Boolean) : ToggleAction(text), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
val presentation = e.presentation
val filteringEnabled = filterable.isFilteringEnabled
presentation.isEnabledAndVisible = filteringEnabled
if (filteringEnabled && stateKey != null &&
PropertiesComponent.getInstance().getBoolean(stateKey, defaultState) &&
!filterable.contains(filter)) {
setSelected(e, true)
}
return filterable.contains(filter)
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
filterable.addFilter(filter)
}
else {
filterable.removeFilter(filter)
}
if (stateKey != null) {
PropertiesComponent.getInstance().setValue(stateKey, state, defaultState)
}
}
companion object {
fun install(filterable: Filterable<ExecutionNode>,
filter: Predicate<ExecutionNode>,
stateKey: String,
defaultState: Boolean) {
if (PropertiesComponent.getInstance().getBoolean(stateKey, defaultState) &&
!filterable.contains(filter)) {
filterable.addFilter(filter)
}
}
}
}
@ApiStatus.Experimental
class SuccessfulStepsToggleAction(filterable: Filterable<ExecutionNode>) :
FilterToggleAction(LangBundle.message("build.tree.filters.show.succesful"), STATE_KEY, filterable, SUCCESSFUL_STEPS_FILTER, false), DumbAware {
companion object {
private const val STATE_KEY = "build.toolwindow.show.successful.steps.selection.state"
fun install(filterable: Filterable<ExecutionNode>) {
install(filterable, SUCCESSFUL_STEPS_FILTER, STATE_KEY, false)
}
}
}
@ApiStatus.Experimental
class WarningsToggleAction(filterable: Filterable<ExecutionNode>) :
FilterToggleAction(LangBundle.message("build.tree.filters.show.warnings"), STATE_KEY, filterable, WARNINGS_FILTER, true), DumbAware {
companion object {
private const val STATE_KEY = "build.toolwindow.show.warnings.selection.state"
fun install(filterable: Filterable<ExecutionNode>) {
install(filterable, WARNINGS_FILTER, STATE_KEY, true)
}
}
}
| apache-2.0 | 7b1b1223a801f79b844b2d37daaf7528 | 39.99 | 145 | 0.731886 | 4.657955 | false | false | false | false |
androidx/androidx | constraintlayout/constraintlayout-compose/src/androidMain/kotlin/androidx/constraintlayout/compose/MotionLayout.kt | 5 | 22495 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.compose
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.LayoutScopeMarker
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.layout.MultiMeasureLayout
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.core.widgets.Optimizer
import java.util.EnumSet
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
/**
* Measure flags for MotionLayout
*/
enum class MotionLayoutFlag(@Suppress("UNUSED_PARAMETER") value: Long) {
Default(0),
FullMeasure(1)
}
/**
* Layout that interpolate its children layout given two sets of constraint and
* a progress (from 0 to 1)
*/
@ExperimentalMotionApi
@Suppress("NOTHING_TO_INLINE")
@Composable
inline fun MotionLayout(
start: ConstraintSet,
end: ConstraintSet,
modifier: Modifier = Modifier,
transition: Transition? = null,
progress: Float,
debug: EnumSet<MotionLayoutDebugFlags> = EnumSet.of(MotionLayoutDebugFlags.NONE),
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
crossinline content: @Composable MotionLayoutScope.() -> Unit
) {
val motionProgress = createAndUpdateMotionProgress(progress = progress)
MotionLayoutCore(
start = start,
end = end,
transition = transition as? TransitionImpl,
motionProgress = motionProgress,
debugFlag = debug.firstOrNull() ?: MotionLayoutDebugFlags.NONE,
informationReceiver = null,
modifier = modifier,
optimizationLevel = optimizationLevel,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
/**
* Layout that animates the default transition of a [MotionScene] with a progress value (from 0 to
* 1).
*/
@ExperimentalMotionApi
@Suppress("NOTHING_TO_INLINE")
@Composable
inline fun MotionLayout(
motionScene: MotionScene,
progress: Float,
modifier: Modifier = Modifier,
transitionName: String = "default",
debug: EnumSet<MotionLayoutDebugFlags> = EnumSet.of(MotionLayoutDebugFlags.NONE),
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
crossinline content: @Composable (MotionLayoutScope.() -> Unit),
) {
MotionLayoutCore(
motionScene = motionScene,
progress = progress,
debug = debug,
modifier = modifier,
optimizationLevel = optimizationLevel,
transitionName = transitionName,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
/**
* Layout that takes a MotionScene and animates by providing a [constraintSetName] to animate to.
*
* During recomposition, MotionLayout will interpolate from whichever ConstraintSet it is currently
* in, to [constraintSetName].
*
* Typically the first value of [constraintSetName] should match the start ConstraintSet in the
* default transition, or be null.
*
* Animation is run by [animationSpec], and will only start another animation once any other ones
* are finished. Use [finishedAnimationListener] to know when a transition has stopped.
*/
@ExperimentalMotionApi
@Composable
inline fun MotionLayout(
motionScene: MotionScene,
modifier: Modifier = Modifier,
constraintSetName: String? = null,
animationSpec: AnimationSpec<Float> = tween(),
debug: EnumSet<MotionLayoutDebugFlags> = EnumSet.of(MotionLayoutDebugFlags.NONE),
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
noinline finishedAnimationListener: (() -> Unit)? = null,
crossinline content: @Composable (MotionLayoutScope.() -> Unit)
) {
MotionLayoutCore(
motionScene = motionScene,
constraintSetName = constraintSetName,
animationSpec = animationSpec,
debugFlag = debug.firstOrNull() ?: MotionLayoutDebugFlags.NONE,
modifier = modifier,
optimizationLevel = optimizationLevel,
finishedAnimationListener = finishedAnimationListener,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
@Suppress("NOTHING_TO_INLINE")
@ExperimentalMotionApi
@Composable
inline fun MotionLayout(
start: ConstraintSet,
end: ConstraintSet,
modifier: Modifier = Modifier,
transition: Transition? = null,
progress: Float,
debug: EnumSet<MotionLayoutDebugFlags> = EnumSet.of(MotionLayoutDebugFlags.NONE),
informationReceiver: LayoutInformationReceiver? = null,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
crossinline content: @Composable (MotionLayoutScope.() -> Unit)
) {
val motionProgress = createAndUpdateMotionProgress(progress = progress)
MotionLayoutCore(
start = start,
end = end,
transition = transition as? TransitionImpl,
motionProgress = motionProgress,
debugFlag = debug.firstOrNull() ?: MotionLayoutDebugFlags.NONE,
informationReceiver = informationReceiver,
modifier = modifier,
optimizationLevel = optimizationLevel,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
@ExperimentalMotionApi
@PublishedApi
@Composable
@Suppress("UnavailableSymbol")
internal inline fun MotionLayoutCore(
@Suppress("HiddenTypeParameter")
motionScene: MotionScene,
modifier: Modifier = Modifier,
constraintSetName: String? = null,
animationSpec: AnimationSpec<Float> = tween(),
debugFlag: MotionLayoutDebugFlags = MotionLayoutDebugFlags.NONE,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
noinline finishedAnimationListener: (() -> Unit)? = null,
@Suppress("HiddenTypeParameter")
crossinline content: @Composable (MotionLayoutScope.() -> Unit)
) {
val needsUpdate = remember {
mutableStateOf(0L)
}
val transition = remember(motionScene, needsUpdate.value) {
motionScene.getTransitionInstance("default")
}
val initialStart = remember(motionScene, needsUpdate.value) {
val startId = transition?.getStartConstraintSetId() ?: "start"
motionScene.getConstraintSetInstance(startId)
}
val initialEnd = remember(motionScene, needsUpdate.value) {
val endId = transition?.getEndConstraintSetId() ?: "end"
motionScene.getConstraintSetInstance(endId)
}
if (initialStart == null || initialEnd == null) {
return
}
var start: ConstraintSet by remember(motionScene) {
mutableStateOf(initialStart)
}
var end: ConstraintSet by remember(motionScene) {
mutableStateOf(initialEnd)
}
val targetConstraintSet = remember(motionScene, constraintSetName) {
constraintSetName?.let { motionScene.getConstraintSetInstance(constraintSetName) }
}
val progress = remember { Animatable(0f) }
var animateToEnd by remember(motionScene) { mutableStateOf(true) }
val channel = remember { Channel<ConstraintSet>(Channel.CONFLATED) }
if (targetConstraintSet != null) {
SideEffect {
channel.trySend(targetConstraintSet)
}
LaunchedEffect(motionScene, channel) {
for (constraints in channel) {
val newConstraintSet = channel.tryReceive().getOrNull() ?: constraints
val animTargetValue = if (animateToEnd) 1f else 0f
val currentSet = if (animateToEnd) start else end
if (newConstraintSet != currentSet) {
if (animateToEnd) {
end = newConstraintSet
} else {
start = newConstraintSet
}
progress.animateTo(animTargetValue, animationSpec)
animateToEnd = !animateToEnd
finishedAnimationListener?.invoke()
}
}
}
}
val scope = rememberCoroutineScope()
val motionProgress = remember {
MotionProgress.fromState(progress.asState()) {
scope.launch { progress.snapTo(it) }
}
}
MotionLayoutCore(
start = start,
end = end,
transition = transition as? TransitionImpl,
motionProgress = motionProgress,
debugFlag = debugFlag,
informationReceiver = motionScene as? LayoutInformationReceiver,
modifier = modifier,
optimizationLevel = optimizationLevel,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
@ExperimentalMotionApi
@PublishedApi
@Composable
@Suppress("UnavailableSymbol")
internal inline fun MotionLayoutCore(
@Suppress("HiddenTypeParameter")
motionScene: MotionScene,
progress: Float,
modifier: Modifier = Modifier,
debug: EnumSet<MotionLayoutDebugFlags> = EnumSet.of(MotionLayoutDebugFlags.NONE),
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
transitionName: String,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
@Suppress("HiddenTypeParameter")
crossinline content: @Composable MotionLayoutScope.() -> Unit,
) {
val transition = remember(motionScene, transitionName) {
motionScene.getTransitionInstance(transitionName)
}
val start = remember(motionScene) {
val startId = transition?.getStartConstraintSetId() ?: "start"
motionScene.getConstraintSetInstance(startId)
}
val end = remember(motionScene, transition) {
val endId = transition?.getEndConstraintSetId() ?: "end"
motionScene.getConstraintSetInstance(endId)
}
if (start == null || end == null) {
return
}
MotionLayout(
start = start,
end = end,
transition = transition,
progress = progress,
debug = debug,
informationReceiver = motionScene as? LayoutInformationReceiver,
modifier = modifier,
optimizationLevel = optimizationLevel,
motionLayoutFlags = motionLayoutFlags,
content = content
)
}
@ExperimentalMotionApi
@PublishedApi
@Composable
@Suppress("UnavailableSymbol")
internal inline fun MotionLayoutCore(
start: ConstraintSet,
end: ConstraintSet,
modifier: Modifier = Modifier,
@SuppressWarnings("HiddenTypeParameter") transition: TransitionImpl? = null,
motionProgress: MotionProgress,
debugFlag: MotionLayoutDebugFlags = MotionLayoutDebugFlags.NONE,
informationReceiver: LayoutInformationReceiver? = null,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
@Suppress("HiddenTypeParameter")
crossinline content: @Composable MotionLayoutScope.() -> Unit
) {
// TODO: Merge this snippet with UpdateWithForcedIfNoUserChange
val needsUpdate = remember { mutableStateOf(0L) }
needsUpdate.value // Read the value to allow recomposition from informationReceiver
informationReceiver?.setUpdateFlag(needsUpdate)
UpdateWithForcedIfNoUserChange(
motionProgress = motionProgress,
informationReceiver = informationReceiver
)
var usedDebugMode = debugFlag
val forcedDebug = informationReceiver?.getForcedDrawDebug()
if (forcedDebug != null && forcedDebug != MotionLayoutDebugFlags.UNKNOWN) {
usedDebugMode = forcedDebug
}
val measurer = remember { MotionMeasurer() }
val scope = remember { MotionLayoutScope(measurer, motionProgress) }
val debug = EnumSet.of(usedDebugMode)
val measurePolicy =
rememberMotionLayoutMeasurePolicy(
optimizationLevel,
debug,
start,
end,
transition,
motionProgress,
motionLayoutFlags,
measurer
)
measurer.addLayoutInformationReceiver(informationReceiver)
val forcedScaleFactor = measurer.forcedScaleFactor
var debugModifications: Modifier = Modifier
if (!debug.contains(MotionLayoutDebugFlags.NONE) || !forcedScaleFactor.isNaN()) {
if (!forcedScaleFactor.isNaN()) {
debugModifications = debugModifications.scale(forcedScaleFactor)
}
debugModifications = debugModifications.drawBehind {
with(measurer) {
if (!forcedScaleFactor.isNaN()) {
drawDebugBounds(forcedScaleFactor)
}
if (!debug.contains(MotionLayoutDebugFlags.NONE)) {
drawDebug()
}
}
}
}
@Suppress("DEPRECATION")
(MultiMeasureLayout(
modifier = modifier
.then(debugModifications)
.motionPointerInput(measurePolicy, motionProgress, measurer)
.semantics { designInfoProvider = measurer },
measurePolicy = measurePolicy,
content = { scope.content() }
))
}
@ExperimentalMotionApi
@Composable
inline fun MotionLayout(
modifier: Modifier = Modifier,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutState: MotionLayoutState,
motionScene: MotionScene,
crossinline content: @Composable MotionLayoutScope.() -> Unit
) {
MotionLayoutCore(
modifier = modifier,
optimizationLevel = optimizationLevel,
motionLayoutState = motionLayoutState as MotionLayoutStateImpl,
motionScene = motionScene,
content = content
)
}
@PublishedApi
@ExperimentalMotionApi
@Composable
@Suppress("UnavailableSymbol")
internal inline fun MotionLayoutCore(
modifier: Modifier = Modifier,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
motionLayoutState: MotionLayoutStateImpl,
@Suppress("HiddenTypeParameter")
motionScene: MotionScene,
transitionName: String = "default",
@Suppress("HiddenTypeParameter")
crossinline content: @Composable MotionLayoutScope.() -> Unit
) {
val transition = remember(motionScene, transitionName) {
motionScene.getTransitionInstance(transitionName)
}
val startId = transition?.getStartConstraintSetId() ?: "start"
val endId = transition?.getEndConstraintSetId() ?: "end"
val start = remember(motionScene) {
motionScene.getConstraintSetInstance(startId)
}
val end = remember(motionScene) {
motionScene.getConstraintSetInstance(endId)
}
if (start == null || end == null) {
return
}
MotionLayoutCore(
start = start,
end = end,
transition = transition as? TransitionImpl,
motionProgress = motionLayoutState.motionProgress,
debugFlag = motionLayoutState.debugMode,
informationReceiver = motionScene as? JSONMotionScene,
modifier = modifier,
optimizationLevel = optimizationLevel,
content = content
)
}
@LayoutScopeMarker
@ExperimentalMotionApi
class MotionLayoutScope @Suppress("ShowingMemberInHiddenClass")
@PublishedApi internal constructor(
private val measurer: MotionMeasurer,
private val motionProgress: MotionProgress
) {
@ExperimentalMotionApi
inner class MotionProperties internal constructor(
id: String,
tag: String?
) {
private var myId = id
private var myTag = tag
fun id(): String {
return myId
}
fun tag(): String? {
return myTag
}
fun color(name: String): Color {
return measurer.getCustomColor(myId, name, motionProgress.currentProgress)
}
fun float(name: String): Float {
return measurer.getCustomFloat(myId, name, motionProgress.currentProgress)
}
fun int(name: String): Int {
return measurer.getCustomFloat(myId, name, motionProgress.currentProgress).toInt()
}
fun distance(name: String): Dp {
return measurer.getCustomFloat(myId, name, motionProgress.currentProgress).dp
}
fun fontSize(name: String): TextUnit {
return measurer.getCustomFloat(myId, name, motionProgress.currentProgress).sp
}
}
@Composable
fun motionProperties(id: String): State<MotionProperties> =
// TODO: There's no point on returning a [State] object, and probably no point on this being
// a Composable
remember(id) {
mutableStateOf(MotionProperties(id, null))
}
fun motionProperties(id: String, tag: String): MotionProperties {
return MotionProperties(id, tag)
}
fun motionColor(id: String, name: String): Color {
return measurer.getCustomColor(id, name, motionProgress.currentProgress)
}
fun motionFloat(id: String, name: String): Float {
return measurer.getCustomFloat(id, name, motionProgress.currentProgress)
}
fun motionInt(id: String, name: String): Int {
return measurer.getCustomFloat(id, name, motionProgress.currentProgress).toInt()
}
fun motionDistance(id: String, name: String): Dp {
return measurer.getCustomFloat(id, name, motionProgress.currentProgress).dp
}
fun motionFontSize(id: String, name: String): TextUnit {
return measurer.getCustomFloat(id, name, motionProgress.currentProgress).sp
}
}
enum class MotionLayoutDebugFlags {
NONE,
SHOW_ALL,
UNKNOWN
}
@Composable
@PublishedApi
@ExperimentalMotionApi
internal fun rememberMotionLayoutMeasurePolicy(
optimizationLevel: Int,
debug: EnumSet<MotionLayoutDebugFlags>,
constraintSetStart: ConstraintSet,
constraintSetEnd: ConstraintSet,
@SuppressWarnings("HiddenTypeParameter") transition: TransitionImpl?,
motionProgress: MotionProgress,
motionLayoutFlags: Set<MotionLayoutFlag> = setOf<MotionLayoutFlag>(),
measurer: MotionMeasurer
): MeasurePolicy {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
return remember(
optimizationLevel,
motionLayoutFlags,
debug,
constraintSetStart,
constraintSetEnd,
transition
) {
measurer.initWith(
constraintSetStart,
constraintSetEnd,
density,
layoutDirection,
transition,
motionProgress.currentProgress
)
MeasurePolicy { measurables, constraints ->
val layoutSize = measurer.performInterpolationMeasure(
constraints,
layoutDirection,
constraintSetStart,
constraintSetEnd,
transition,
measurables,
optimizationLevel,
motionProgress.currentProgress,
motionLayoutFlags,
this
)
layout(layoutSize.width, layoutSize.height) {
with(measurer) {
performLayout(measurables)
}
}
}
}
}
/**
* Updates [motionProgress] from changes in [LayoutInformationReceiver.getForcedProgress].
*
* User changes, (reflected in [MotionProgress.currentProgress]) take priority.
*/
@PublishedApi
@Composable
internal fun UpdateWithForcedIfNoUserChange(
motionProgress: MotionProgress,
informationReceiver: LayoutInformationReceiver?
) {
if (informationReceiver == null) {
return
}
val currentUserProgress = motionProgress.currentProgress
val forcedProgress = informationReceiver.getForcedProgress()
// Save the initial progress
val lastUserProgress = remember { Ref<Float>().apply { value = currentUserProgress } }
if (!forcedProgress.isNaN() && lastUserProgress.value == currentUserProgress) {
// Use the forced progress if the user progress hasn't changed
motionProgress.updateProgress(forcedProgress)
} else {
informationReceiver.resetForcedProgress()
}
lastUserProgress.value = currentUserProgress
}
/**
* Creates a [MotionProgress] that may be manipulated internally, but can also be updated by user
* calls with different [progress] values.
*
* @param progress User progress, if changed, updates the underlying [MotionProgress]
* @return A [MotionProgress] instance that may change from internal or external calls
*/
@Suppress("NOTHING_TO_INLINE")
@PublishedApi
@Composable
internal inline fun createAndUpdateMotionProgress(progress: Float): MotionProgress {
val motionProgress = remember {
MotionProgress.fromMutableState(mutableStateOf(progress))
}
val last = remember { Ref<Float>().apply { value = progress } }
if (last.value != progress) {
// Update on progress change
last.value = progress
motionProgress.updateProgress(progress)
}
return motionProgress
} | apache-2.0 | 677ff2c95459a7e40dba4d735f0e5a76 | 33.033283 | 99 | 0.692421 | 4.907286 | false | false | false | false |
GunoH/intellij-community | java/execution/impl/src/com/intellij/execution/application/JavaApplicationRunConfigurationImporter.kt | 12 | 2706 | /*
* 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.execution.application
import com.intellij.execution.ShortenCommandLine
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.settings.RunConfigurationImporter
import com.intellij.openapi.project.Project
import com.intellij.util.ObjectUtils.consumeIfCast
class JavaApplicationRunConfigurationImporter : RunConfigurationImporter {
override fun process(project: Project, runConfiguration: RunConfiguration, cfg: Map<String, *>, modelsProvider: IdeModifiableModelsProvider) {
if (runConfiguration !is ApplicationConfiguration) {
throw IllegalArgumentException("Unexpected type of run configuration: ${runConfiguration::class.java}")
}
consumeIfCast(cfg["moduleName"], String::class.java) {
val module = modelsProvider.modifiableModuleModel.findModuleByName(it)
if (module != null) {
runConfiguration.setModule(module)
}
}
consumeIfCast(cfg["mainClass"], String::class.java) { runConfiguration.mainClassName = it }
consumeIfCast(cfg["jvmArgs"], String::class.java) { runConfiguration.vmParameters = it }
consumeIfCast(cfg["programParameters"], String::class.java) { runConfiguration.programParameters = it }
consumeIfCast(cfg["envs"], Map::class.java) { runConfiguration.envs = it as MutableMap<String, String> }
consumeIfCast(cfg["workingDirectory"], String::class.java) { runConfiguration.workingDirectory = it }
runConfiguration.setIncludeProvidedScope(cfg["includeProvidedDependencies"] as? Boolean ?: false)
consumeIfCast(cfg["shortenCommandLine"], String::class.java) {
try {
runConfiguration.shortenCommandLine = ShortenCommandLine.valueOf(it)
} catch (e: IllegalArgumentException) {
LOG.warn("Illegal value of 'shortenCommandLine': $it", e)
}
}
}
override fun canImport(typeName: String): Boolean = typeName == "application"
override fun getConfigurationFactory(): ConfigurationFactory =
ConfigurationTypeUtil.findConfigurationType<ApplicationConfigurationType>(
ApplicationConfigurationType::class.java)
.configurationFactories[0]
companion object {
val LOG = Logger.getInstance(JavaApplicationRunConfigurationImporter::class.java)
}
} | apache-2.0 | 86510877ac7bc1ac6da6cd30e830ab7f | 48.218182 | 144 | 0.773466 | 4.928962 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt | 4 | 1387 | // 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.memberInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.refactoring.ui.AbstractMemberSelectionPanel
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SeparatorFactory
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.awt.BorderLayout
class KotlinMemberSelectionPanel(
@NlsContexts.DialogTitle title: String,
memberInfo: List<KotlinMemberInfo>,
@Nls abstractColumnHeader: String? = null
) : AbstractMemberSelectionPanel<KtNamedDeclaration, KotlinMemberInfo>() {
private val table = createMemberSelectionTable(memberInfo, abstractColumnHeader)
init {
layout = BorderLayout()
val scrollPane = ScrollPaneFactory.createScrollPane(table)
add(SeparatorFactory.createSeparator(title, table), BorderLayout.NORTH)
add(scrollPane, BorderLayout.CENTER)
}
private fun createMemberSelectionTable(
memberInfo: List<KotlinMemberInfo>,
@Nls abstractColumnHeader: String?
): KotlinMemberSelectionTable {
return KotlinMemberSelectionTable(memberInfo, null, abstractColumnHeader)
}
override fun getTable() = table
} | apache-2.0 | bf5108b196a1bdc48c02d9fd0e8e319a | 37.555556 | 158 | 0.777938 | 4.91844 | false | false | false | false |
GunoH/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/RawPluginDescriptor.kt | 5 | 2559 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.xml.dom.XmlElement
import org.jetbrains.annotations.ApiStatus
import java.time.LocalDate
@ApiStatus.Internal
class RawPluginDescriptor {
@JvmField var id: String? = null
@JvmField internal var name: String? = null
@JvmField internal var description: @NlsSafe String? = null
@JvmField internal var category: String? = null
@JvmField internal var changeNotes: String? = null
@JvmField internal var version: String? = null
@JvmField internal var sinceBuild: String? = null
@JvmField internal var untilBuild: String? = null
@JvmField internal var `package`: String? = null
@JvmField internal var url: String? = null
@JvmField internal var vendor: String? = null
@JvmField internal var vendorEmail: String? = null
@JvmField internal var vendorUrl: String? = null
@JvmField internal var resourceBundleBaseName: String? = null
@JvmField internal var isUseIdeaClassLoader = false
@JvmField internal var isBundledUpdateAllowed = false
@JvmField internal var implementationDetail = false
@ApiStatus.Experimental @JvmField internal var onDemand = false
@JvmField internal var isRestartRequired = false
@JvmField internal var isLicenseOptional = false
@JvmField internal var productCode: String? = null
@JvmField internal var releaseDate: LocalDate? = null
@JvmField internal var releaseVersion = 0
@JvmField internal var modules: MutableList<PluginId>? = null
@JvmField internal var depends: MutableList<PluginDependency>? = null
@JvmField internal var actions: MutableList<ActionDescriptor>? = null
@JvmField var incompatibilities: MutableList<PluginId>? = null
@JvmField val appContainerDescriptor = ContainerDescriptor()
@JvmField val projectContainerDescriptor = ContainerDescriptor()
@JvmField val moduleContainerDescriptor = ContainerDescriptor()
@JvmField var epNameToExtensions: MutableMap<String, MutableList<ExtensionDescriptor>>? = null
@JvmField internal var contentModules: MutableList<PluginContentDescriptor.ModuleItem>? = null
@JvmField internal var dependencies = ModuleDependenciesDescriptor.EMPTY
class ActionDescriptor(
@JvmField val name: String,
@JvmField val element: XmlElement,
@JvmField val resourceBundle: String?,
)
}
| apache-2.0 | 4a65b548155e9b0e6052a5d706287e9f | 38.984375 | 120 | 0.783118 | 4.874286 | false | false | false | false |
actions-on-google/app-actions-dynamic-shortcuts | app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsViewModel.kt | 1 | 2308 | /*
* Copyright (C) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Error
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import kotlinx.coroutines.launch
/**
* ViewModel for the statistics screen.
*/
class StatisticsViewModel(
private val tasksRepository: TasksRepository
) : ViewModel() {
private val tasks: LiveData<Result<List<Task>>> = tasksRepository.observeTasks()
private val _dataLoading = MutableLiveData(false)
private val stats: LiveData<StatsResult?> = tasks.map {
if (it is Success) {
getActiveAndCompletedStats(it.data)
} else {
null
}
}
val activeTasksPercent = stats.map {
it?.activeTasksPercent ?: 0f }
val completedTasksPercent: LiveData<Float> = stats.map { it?.completedTasksPercent ?: 0f }
val dataLoading: LiveData<Boolean> = _dataLoading
val error: LiveData<Boolean> = tasks.map { it is Error }
val empty: LiveData<Boolean> = tasks.map { (it as? Success)?.data.isNullOrEmpty() }
fun refresh() {
_dataLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTasks()
_dataLoading.value = false
}
}
}
| apache-2.0 | 6ab24e99e44f818f5008073a8335ff6e | 36.225806 | 94 | 0.733102 | 4.338346 | false | false | false | false |
jwren/intellij-community | plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/ShowDecompiledClassAction.kt | 2 | 2165 | // 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.java.decompiler
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilBase
class ShowDecompiledClassAction : AnAction(IdeaDecompilerBundle.message("action.show.decompiled.name")), UpdateInBackground {
override fun update(e: AnActionEvent) {
val psiElement = getPsiElement(e)
val visible = psiElement?.containingFile is PsiClassOwner
e.presentation.isVisible = visible
e.presentation.isEnabled = visible && getOriginalFile(psiElement) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
if (project != null) {
val file = getOriginalFile(getPsiElement(e))
if (file != null) {
PsiNavigationSupport.getInstance().createNavigatable(project, file, -1).navigate(true)
}
}
}
private fun getPsiElement(e: AnActionEvent): PsiElement? {
val project = e.project ?: return null
val editor = e.getData(CommonDataKeys.EDITOR) ?: return e.getData(CommonDataKeys.PSI_ELEMENT)
return PsiUtilBase.getPsiFileInEditor(editor, project)?.findElementAt(editor.caretModel.offset)
}
private fun getOriginalFile(psiElement: PsiElement?): VirtualFile? {
val psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass::class.java, false)
val file = psiClass?.originalElement?.containingFile?.virtualFile
return if (file != null && FileTypeRegistry.getInstance().isFileOfType(file, JavaClassFileType.INSTANCE)) file else null
}
}
| apache-2.0 | b2b2ae79a0c3e94dfec37d51941da094 | 45.06383 | 158 | 0.781524 | 4.519833 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/mpp/populateModuleDependenciesBySourceSetVisibilityGraph.kt | 2 | 9764 | // 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.gradleJava.configuration.mpp
import com.google.common.graph.Graph
import com.intellij.openapi.externalSystem.model.DataNode
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinAndroidSourceSets
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinSourceSetData
import org.jetbrains.kotlin.idea.gradle.configuration.utils.createSourceSetVisibilityGraph
import org.jetbrains.kotlin.idea.gradle.configuration.utils.transitiveClosure
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinMPPGradleProjectResolver
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinMPPGradleProjectResolver.Companion.CompilationWithDependencies
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.fullName
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.getKotlinModuleId
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
import org.jetbrains.plugins.gradle.model.ExternalDependency
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
internal fun KotlinMPPGradleProjectResolver.Companion.populateModuleDependenciesBySourceSetVisibilityGraph(
context: KotlinMppPopulateModuleDependenciesContext
): Unit = with(context) {
val sourceSetVisibilityGraph = createSourceSetVisibilityGraph(mppModel).transitiveClosure
for (sourceSet in sourceSetVisibilityGraph.nodes()) {
if (shouldDelegateToOtherPlugin(sourceSet)) continue
val visibleSourceSets = sourceSetVisibilityGraph.successors(sourceSet) - sourceSet
val fromDataNode = getSiblingKotlinModuleData(sourceSet, gradleModule, ideModule, resolverCtx)?.cast<GradleSourceSetData>()
?: continue
/* Add dependencies from current sourceSet to all visible source sets (dependsOn, test to production, ...)*/
for (visibleSourceSet in visibleSourceSets) {
val toDataNode = getSiblingKotlinModuleData(visibleSourceSet, gradleModule, ideModule, resolverCtx) ?: continue
addDependency(fromDataNode, toDataNode, visibleSourceSet.isTestComponent)
}
if (!processedModuleIds.add(getKotlinModuleId(gradleModule, sourceSet, resolverCtx))) continue
val settings = dependencyPopulationSettings(mppModel, sourceSet)
val directDependencies = getDependencies(sourceSet).toSet()
val directIntransitiveDependencies = getIntransitiveDependencies(sourceSet).toSet()
val dependenciesFromVisibleSourceSets = getDependenciesFromVisibleSourceSets(settings, visibleSourceSets)
val dependenciesFromNativePropagation = getPropagatedNativeDependencies(settings, sourceSet)
val dependenciesFromPlatformPropagation = getPropagatedPlatformDependencies(sourceSet)
val dependencies = dependenciesPreprocessor(
dependenciesFromNativePropagation + dependenciesFromPlatformPropagation
+ dependenciesFromVisibleSourceSets + directDependencies + directIntransitiveDependencies
)
buildDependencies(resolverCtx, sourceSetMap, artifactsMap, fromDataNode, dependencies, ideProject)
}
}
private data class DependencyPopulationSettings(
val forceNativeDependencyPropagation: Boolean,
val excludeInheritedNativeDependencies: Boolean
)
private fun dependencyPopulationSettings(mppModel: KotlinMPPGradleModel, sourceSet: KotlinSourceSet): DependencyPopulationSettings {
val forceNativeDependencyPropagation: Boolean
val excludeInheritedNativeDependencies: Boolean
if (mppModel.extraFeatures.isHMPPEnabled && sourceSet.actualPlatforms.singleOrNull() == KotlinPlatform.NATIVE) {
forceNativeDependencyPropagation = mppModel.extraFeatures.isNativeDependencyPropagationEnabled
excludeInheritedNativeDependencies = !forceNativeDependencyPropagation
} else {
forceNativeDependencyPropagation = false
excludeInheritedNativeDependencies = false
}
return DependencyPopulationSettings(
forceNativeDependencyPropagation = forceNativeDependencyPropagation,
excludeInheritedNativeDependencies = excludeInheritedNativeDependencies
)
}
private fun KotlinMppPopulateModuleDependenciesContext.getDependenciesFromVisibleSourceSets(
settings: DependencyPopulationSettings,
visibleSourceSets: Set<KotlinSourceSet>
): Set<KotlinDependency> {
val inheritedDependencies = visibleSourceSets
.flatMap { visibleSourceSet -> getRegularDependencies(visibleSourceSet) }
return if (settings.excludeInheritedNativeDependencies) {
inheritedDependencies.filter { !it.name.startsWith(KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) }
} else {
inheritedDependencies
}.toSet()
}
private fun KotlinMppPopulateModuleDependenciesContext.getPropagatedNativeDependencies(
settings: DependencyPopulationSettings,
sourceSet: KotlinSourceSet
): Set<KotlinDependency> {
if (!settings.forceNativeDependencyPropagation) {
return emptySet()
}
return getPropagatedNativeDependencies(getCompilationsWithDependencies(sourceSet)).toSet()
}
/**
* We can't really commonize native platform libraries yet.
* But APIs for different targets may be very similar.
* E.g. ios_arm64 and ios_x64 have almost identical platform libraries
* We handle these special cases and resolve common sources for such
* targets against libraries of one of them. E.g. common sources for
* ios_x64 and ios_arm64 will be resolved against ios_arm64 libraries.
* Currently such special casing is available for Apple platforms
* (iOS, watchOS and tvOS) and native Android (ARM, X86).
* TODO: Do we need to support user's interop libraries too?
*/
private fun getPropagatedNativeDependencies(compilations: List<CompilationWithDependencies>): List<ExternalDependency> {
if (compilations.size <= 1) {
return emptyList()
}
val copyFrom = when {
compilations.all { it.isAppleCompilation } ->
compilations.selectFirstAvailableTarget(
"watchos_arm64", "watchos_arm32", "watchos_x86",
"ios_arm64", "ios_arm32", "ios_x64",
"tvos_arm64", "tvos_x64"
)
compilations.all { it.konanTarget?.startsWith("android") == true } ->
compilations.selectFirstAvailableTarget(
"android_arm64", "android_arm32", "android_x64", "android_x86"
)
else -> return emptyList()
}
return copyFrom.dependencyNames.mapNotNull { (name, dependency) ->
when {
!name.startsWith(KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) -> null // Support only default platform libs for now.
compilations.all { it.dependencyNames.containsKey(name) } -> dependency
else -> null
}
}
}
private val CompilationWithDependencies.isAppleCompilation: Boolean
get() = konanTarget?.let {
it.startsWith("ios") || it.startsWith("watchos") || it.startsWith("tvos")
} ?: false
private fun Iterable<CompilationWithDependencies>.selectFirstAvailableTarget(
@NonNls vararg targetsByPriority: String
): CompilationWithDependencies {
for (target in targetsByPriority) {
val result = firstOrNull { it.konanTarget == target }
if (result != null) {
return result
}
}
return first()
}
private fun KotlinMppPopulateModuleDependenciesContext.getPropagatedPlatformDependencies(
sourceSet: KotlinSourceSet
): Set<KotlinDependency> {
if (!mppModel.extraFeatures.isHMPPEnabled) {
return emptySet()
}
return getPropagatedPlatformDependencies(mppModel, sourceSet)
}
/**
* Source sets sharing code between JVM and Android are the only intermediate source sets that
* can effectively consume a dependency's platform artifact.
* When a library only offers a JVM variant, then Android and JVM consume this variant of the library.
*
* This will be replaced later on by [KT-43450](https://youtrack.jetbrains.com/issue/KT-43450)
*
* @return all dependencies being present across given JVM and Android compilations that this [sourceSet] can also participates in.
*/
private fun getPropagatedPlatformDependencies(
mppModel: KotlinMPPGradleModel,
sourceSet: KotlinSourceSet,
): Set<ExternalDependency> {
if (
sourceSet.actualPlatforms.platforms.sorted() == listOf(KotlinPlatform.JVM, KotlinPlatform.ANDROID).sorted()
) {
return mppModel.targets
.filter { target -> target.platform == KotlinPlatform.JVM || target.platform == KotlinPlatform.ANDROID }
.flatMap { target -> target.compilations }
.filter { compilation -> compilation.dependsOnSourceSet(mppModel, sourceSet) }
.map { targetCompilations -> targetCompilations.dependencies.mapNotNull(mppModel.dependencyMap::get).toSet() }
.reduceOrNull { acc, dependencies -> acc.intersect(dependencies) }.orEmpty()
}
return emptySet()
}
inline fun <reified T : Any> DataNode<*>.cast(): DataNode<T> {
if (data !is T) {
throw ClassCastException("DataNode<${data.javaClass.canonicalName}> cannot be cast to DataNode<${T::class.java.canonicalName}>")
}
@Suppress("UNCHECKED_CAST")
return this as DataNode<T>
}
| apache-2.0 | dbea429e848126d8442344e8d251151c | 46.398058 | 158 | 0.759115 | 5.412417 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/rebase/log/drop/GitDropLogAction.kt | 7 | 1952 | // 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 git4idea.rebase.log.drop
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import git4idea.i18n.GitBundle
import git4idea.rebase.log.GitCommitEditingOperationResult
import git4idea.rebase.log.GitMultipleCommitEditingAction
import git4idea.rebase.log.getOrLoadDetails
import git4idea.rebase.log.notifySuccess
internal class GitDropLogAction : GitMultipleCommitEditingAction() {
override fun update(e: AnActionEvent, commitEditingData: MultipleCommitEditingData) {
e.presentation.text = GitBundle.message("rebase.log.drop.action.custom.text", commitEditingData.selectedCommitList.size)
}
override fun actionPerformedAfterChecks(commitEditingData: MultipleCommitEditingData) {
val project = commitEditingData.project
val commitDetails = getOrLoadDetails(project, commitEditingData.logData, commitEditingData.selectedCommitList)
object : Task.Backgroundable(project, GitBundle.message("rebase.log.drop.progress.indicator.title", commitDetails.size)) {
override fun run(indicator: ProgressIndicator) {
val operationResult = GitDropOperation(commitEditingData.repository).execute(commitDetails)
if (operationResult is GitCommitEditingOperationResult.Complete) {
operationResult.notifySuccess(
GitBundle.message("rebase.log.drop.success.notification.title", commitDetails.size),
GitBundle.message("rebase.log.drop.undo.progress.title"),
GitBundle.message("rebase.log.drop.undo.impossible.title"),
GitBundle.message("rebase.log.drop.undo.failed.title")
)
}
}
}.queue()
}
override fun getFailureTitle(): String = GitBundle.message("rebase.log.drop.action.failure.title")
} | apache-2.0 | 7ef32d2b8ab96737c4331f0abf12988a | 51.783784 | 140 | 0.779201 | 4.29011 | false | false | false | false |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/activities/MainActivity.kt | 1 | 41167 | package com.amar.NoteDirector.activities
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.GridLayoutManager
import android.widget.FrameLayout
import com.google.gson.Gson
import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.Release
import com.simplemobiletools.commons.views.MyScalableRecyclerView
import com.amar.NoteDirector.adapters.DirectoryAdapter
import com.amar.NoteDirector.asynctasks.GetDirectoriesAsynctask
import com.amar.NoteDirector.dialogs.ChangeSortingDialog
import com.amar.NoteDirector.dialogs.FilterMediaDialog
import com.amar.NoteDirector.extensions.*
import com.amar.NoteDirector.helpers.*
import com.amar.NoteDirector.models.Directory
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.util.*
import android.system.Os.mkdir
import android.os.Environment.getExternalStorageDirectory
import android.support.design.widget.FloatingActionButton
import android.util.Log
import com.amar.NoteDirector.R
import android.content.DialogInterface
import android.content.res.ColorStateList
import android.database.Cursor
import android.graphics.Bitmap
import android.provider.DocumentsContract
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatDialogFragment
import android.system.Os.mkdir
import android.view.*
import android.widget.EditText
import android.widget.ImageButton
import android.widget.Toast
import com.amar.notesapp.activities.PrefManager
import com.amar.notesapp.activities.WelcomeActivity
import com.google.android.gms.ads.*
import kotlinx.android.synthetic.main.dialog_new_folder.view.*
import org.apache.commons.io.FileUtils
import java.nio.channels.FileChannel
import java.text.SimpleDateFormat
import kotlin.collections.ArrayList
class MainActivity : SimpleActivity(), DirectoryAdapter.DirOperationsListener {
var img: String? = null
var gname: String? = null
var alertbox: android.support.v7.app.AlertDialog? = null
private val STORAGE_PERMISSION = 1
private val IMAGE_REQUEST=1
private val PICK_MEDIA = 2
private val PICK_WALLPAPER = 3
private val LAST_MEDIA_CHECK_PERIOD = 3000L
lateinit var mDirs: ArrayList<Directory>
private var mIsPickImageIntent = false
private var mIsPickVideoIntent = false
private var mIsGetImageContentIntent = false
private var mIsGetVideoContentIntent = false
private var mIsGetAnyContentIntent = false
private var mIsSetWallpaperIntent = false
private var mIsThirdPartyIntent = false
private var mIsGettingDirs = false
private var mStoredAnimateGifs = true
private var mStoredCropThumbnails = true
private var mStoredScrollHorizontally = true
private var mLoadedInitialPhotos = false
private var mLastMediaModified = 0
private var mLastMediaHandler = Handler()
private lateinit var floatclick: FloatingActionButton
private lateinit var camera: ImageButton
private lateinit var video: ImageButton
private lateinit var addcam: ImageButton
private lateinit var addvid: ImageButton
private lateinit var mAdView: AdView
private lateinit var mInterstitialAd: InterstitialAd
private var mCurrAsyncTask: GetDirectoriesAsynctask? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.amar.NoteDirector.R.layout.activity_main)
MobileAds.initialize(this,"")
mInterstitialAd =InterstitialAd(this)
mInterstitialAd.setAdUnitId("");
mInterstitialAd.loadAd(AdRequest.Builder().build())
mAdView = findViewById<View>(R.id.adView) as AdView
val adRequest = AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build()
mAdView.loadAd(adRequest)
val folder = File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/NoteDirector")
if (!folder.exists()) {
folder.mkdir()
}
else
mIsPickImageIntent = isPickImageIntent(intent)
mIsPickVideoIntent = isPickVideoIntent(intent)
mIsGetImageContentIntent = isGetImageContentIntent(intent)
mIsGetVideoContentIntent = isGetVideoContentIntent(intent)
mIsGetAnyContentIntent = isGetAnyContentIntent(intent)
mIsSetWallpaperIntent = isSetWallpaperIntent(intent)
mIsThirdPartyIntent = mIsPickImageIntent || mIsPickVideoIntent || mIsGetImageContentIntent || mIsGetVideoContentIntent ||
mIsGetAnyContentIntent || mIsSetWallpaperIntent
removeTempFolder()
directories_refresh_layout.setOnRefreshListener({ getDirectories() })
mDirs = ArrayList()
mStoredAnimateGifs = config.animateGifs
mStoredCropThumbnails = config.cropThumbnails
mStoredScrollHorizontally = config.scrollHorizontally
storeStoragePaths()
directories_empty_text.setOnClickListener {
showFilterMediaDialog()
}
floatclick = findViewById(R.id.floatbut)
// set on-click listener
floatclick.setOnClickListener {
createNewFolder()
}
}
override fun onSaveInstanceState(savedInstanceState:Bundle) {
savedInstanceState.putString("PUT", img)
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
img=savedInstanceState?.getString("PUT")
// Always call the superclass so it can save the view hierarchy state
super.onRestoreInstanceState(savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (mIsThirdPartyIntent) {
menuInflater.inflate(com.amar.NoteDirector.R.menu.menu_main_intent, menu)
} else {
menuInflater.inflate(com.amar.NoteDirector.R.menu.menu_main, menu)
menu.findItem(com.amar.NoteDirector.R.id.increase_column_count).isVisible = config.dirColumnCnt < 10
menu.findItem(com.amar.NoteDirector.R.id.reduce_column_count).isVisible = config.dirColumnCnt > 1
}
return true
}
fun ins()
{
val prefManager = PrefManager(applicationContext)
// make first time launch TRUE
prefManager.setFirstTimeLaunch(true)
startActivity(Intent(this@MainActivity, WelcomeActivity::class.java))
finish()
}
fun ad()
{
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show()
} else {
}
launchSettings()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
com.amar.NoteDirector.R.id.sort -> showSortingDialog()
com.amar.NoteDirector.R.id.filter -> showFilterMediaDialog()
com.amar.NoteDirector.R.id.temporarily_show_hidden -> tryToggleTemporarilyShowHidden()
com.amar.NoteDirector.R.id.stop_showing_hidden -> tryToggleTemporarilyShowHidden()
com.amar.NoteDirector.R.id.increase_column_count -> increaseColumnCount()
com.amar.NoteDirector.R.id.reduce_column_count -> reduceColumnCount()
com.amar.NoteDirector.R.id.instructions -> ins()
com.amar.NoteDirector.R.id.settings -> ad()
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun onResume() {
super.onResume()
config.isThirdPartyIntent = false
if (mStoredAnimateGifs != config.animateGifs) {
directories_grid.adapter?.notifyDataSetChanged()
}
if (mStoredCropThumbnails != config.cropThumbnails) {
directories_grid.adapter?.notifyDataSetChanged()
}
if (mStoredScrollHorizontally != config.scrollHorizontally) {
directories_grid.adapter?.let {
(it as DirectoryAdapter).scrollVertically = !config.scrollHorizontally
it.notifyDataSetChanged()
}
setupScrollDirection()
}
tryloadGallery()
invalidateOptionsMenu()
floatbut.setBackgroundTintList(ColorStateList.valueOf(config.primaryColor))
directories_empty_text_label.setTextColor(config.textColor)
directories_empty_text.setTextColor(config.primaryColor)
}
override fun onPause() {
super.onPause()
mCurrAsyncTask?.shouldStop = true
storeDirectories()
directories_refresh_layout.isRefreshing = false
mIsGettingDirs = false
mStoredAnimateGifs = config.animateGifs
mStoredCropThumbnails = config.cropThumbnails
mStoredScrollHorizontally = config.scrollHorizontally
directories_grid.listener = null
mLastMediaHandler.removeCallbacksAndMessages(null)
}
override fun onDestroy() {
super.onDestroy()
config.temporarilyShowHidden = false
removeTempFolder()
}
private fun removeTempFolder() {
val newFolder = File(config.tempFolderPath)
if (newFolder.exists() && newFolder.isDirectory) {
if (newFolder.list()?.isEmpty() == true) {
deleteFileBg(newFolder, true) { }
}
}
config.tempFolderPath = ""
}
private fun tryloadGallery() {
if (hasWriteStoragePermission()) {
getDirectories()
setupLayoutManager()
checkIfColorChanged()
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == STORAGE_PERMISSION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getDirectories()
} else {
toast(com.amar.NoteDirector.R.string.no_storage_permissions)
finish()
}
}
}
private fun getDirectories() {
if (mIsGettingDirs)
return
mIsGettingDirs = true
val dirs = getCachedDirectories()
if (dirs.isNotEmpty() && !mLoadedInitialPhotos) {
gotDirectories(dirs, true)
}
if (!mLoadedInitialPhotos) {
directories_refresh_layout.isRefreshing = true
}
mLoadedInitialPhotos = true
mCurrAsyncTask = GetDirectoriesAsynctask(applicationContext, mIsPickVideoIntent || mIsGetVideoContentIntent, mIsPickImageIntent || mIsGetImageContentIntent) {
gotDirectories(addTempFolderIfNeeded(it), false)
}
mCurrAsyncTask!!.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
private fun showSortingDialog() {
ChangeSortingDialog(this, true, false) {
getDirectories()
}
}
private fun showFilterMediaDialog() {
FilterMediaDialog(this) {
directories_refresh_layout.isRefreshing = true
getDirectories()
}
}
private fun tryToggleTemporarilyShowHidden() {
if (config.temporarilyShowHidden) {
toggleTemporarilyShowHidden(false)
} else {
handleHiddenFolderPasswordProtection {
toggleTemporarilyShowHidden(true)
}
}
}
private fun toggleTemporarilyShowHidden(show: Boolean) {
config.temporarilyShowHidden = show
getDirectories()
invalidateOptionsMenu()
}
private fun checkIfColorChanged() {
if (directories_grid.adapter != null && getRecyclerAdapter().primaryColor != config.primaryColor) {
getRecyclerAdapter().primaryColor = config.primaryColor
directories_vertical_fastscroller.updateHandleColor()
directories_horizontal_fastscroller.updateHandleColor()
floatbut.setBackgroundTintList(ColorStateList.valueOf(config.primaryColor))
}
}
override fun tryDeleteFolders(folders: ArrayList<File>) {
for (file in folders) {
deleteFolders(folders) {
runOnUiThread {
refreshItems()
}
}
}
}
private fun getRecyclerAdapter() = (directories_grid.adapter as DirectoryAdapter)
private fun setupLayoutManager() {
val layoutManager = directories_grid.layoutManager as GridLayoutManager
if (config.scrollHorizontally) {
layoutManager.orientation = GridLayoutManager.HORIZONTAL
directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
} else {
layoutManager.orientation = GridLayoutManager.VERTICAL
directories_refresh_layout.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
directories_grid.isDragSelectionEnabled = true
directories_grid.isZoomingEnabled = true
layoutManager.spanCount = config.dirColumnCnt
directories_grid.listener = object : MyScalableRecyclerView.MyScalableRecyclerViewListener {
override fun zoomIn() {
if (layoutManager.spanCount > 1) {
reduceColumnCount()
getRecyclerAdapter().actMode?.finish()
}
}
override fun zoomOut() {
if (layoutManager.spanCount < 10) {
increaseColumnCount()
getRecyclerAdapter().actMode?.finish()
}
}
override fun selectItem(position: Int) {
getRecyclerAdapter().selectItem(position)
}
override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
getRecyclerAdapter().selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
}
}
}
private fun createNewFolder() {
val view = this.layoutInflater.inflate(R.layout.dialog_new_folder, null)
val path=Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector"
view.folder_path.text = this.humanizePath(path).trimEnd('/') + "/"
android.support.v7.app.AlertDialog.Builder(this)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
context.setupDialogStuff(view, this, R.string.create_new_folder)
getButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener {
val name = view.folder_name.value
when {
name.isEmpty() -> Toast.makeText(applicationContext,"Enter cabin name !!!",Toast.LENGTH_SHORT).show()
name.isAValidFilename() -> {
val file = File(path, name)
if (file.exists()) {
Toast.makeText(applicationContext,"cabin name already exists !!!",Toast.LENGTH_SHORT).show()
return@OnClickListener
}
gname=name
createFolder(name,file, this)
}
else -> Toast.makeText(applicationContext,"Invalid name !!!",Toast.LENGTH_SHORT).show()
}
})
}
}
private fun createFolder(name:String,file: File, alertDialog: android.support.v7.app.AlertDialog) {
if (this.needsStupidWritePermissions(file.absolutePath)) {
this.handleSAFDialog(file) {
val documentFile = this.getFileDocument(file.absolutePath)
documentFile?.createDirectory(file.name)
}
} else if (file.mkdirs()) {
}
alertDialog.dismiss()
media_selector(name)
}
private fun increaseColumnCount() {
config.dirColumnCnt = ++(directories_grid.layoutManager as GridLayoutManager).spanCount
invalidateOptionsMenu()
directories_grid.adapter?.notifyDataSetChanged()
}
private fun reduceColumnCount() {
config.dirColumnCnt = --(directories_grid.layoutManager as GridLayoutManager).spanCount
invalidateOptionsMenu()
directories_grid.adapter?.notifyDataSetChanged()
}
private fun isPickImageIntent(intent: Intent) = isPickIntent(intent) && (hasImageContentData(intent) || isImageType(intent))
private fun isPickVideoIntent(intent: Intent) = isPickIntent(intent) && (hasVideoContentData(intent) || isVideoType(intent))
private fun isPickIntent(intent: Intent) = intent.action == Intent.ACTION_PICK
private fun isGetContentIntent(intent: Intent) = intent.action == Intent.ACTION_GET_CONTENT && intent.type != null
private fun isGetImageContentIntent(intent: Intent) = isGetContentIntent(intent) &&
(intent.type.startsWith("image/") || intent.type == MediaStore.Images.Media.CONTENT_TYPE)
private fun isGetVideoContentIntent(intent: Intent) = isGetContentIntent(intent) &&
(intent.type.startsWith("video/") || intent.type == MediaStore.Video.Media.CONTENT_TYPE)
private fun isGetAnyContentIntent(intent: Intent) = isGetContentIntent(intent) && intent.type == "*/*"
private fun isSetWallpaperIntent(intent: Intent?) = intent?.action == Intent.ACTION_SET_WALLPAPER
private fun hasImageContentData(intent: Intent) = (intent.data == MediaStore.Images.Media.EXTERNAL_CONTENT_URI ||
intent.data == MediaStore.Images.Media.INTERNAL_CONTENT_URI)
private fun hasVideoContentData(intent: Intent) = (intent.data == MediaStore.Video.Media.EXTERNAL_CONTENT_URI ||
intent.data == MediaStore.Video.Media.INTERNAL_CONTENT_URI)
private fun isImageType(intent: Intent) = (intent.type?.startsWith("image/") == true || intent.type == MediaStore.Images.Media.CONTENT_TYPE)
private fun isVideoType(intent: Intent) = (intent.type?.startsWith("video/") == true || intent.type == MediaStore.Video.Media.CONTENT_TYPE)
private fun opencamera(imgn : String)
{
val uriSavedImage:Uri
val imageIntent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
val timeStamp = SimpleDateFormat("yyyyMMdd-HHmmss").format(Date())
val imagesFolder = File(Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+imgn)
if(!imagesFolder.exists())
imagesFolder.mkdirs()
val imgname="NoteDirector-"+timeStamp+".jpg"
img=Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+imgn+"/"+imgname
val image = File(imagesFolder, imgname)
if (Build.VERSION.SDK_INT < 24) {
uriSavedImage=Uri.fromFile(image)
}
else
{
uriSavedImage =FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", image)
}
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage)
startActivityForResult(imageIntent, IMAGE_REQUEST)
}
private fun openvideo(imgn : String)
{
val uriSavedImage:Uri
val imageIntent = Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE)
val timeStamp = SimpleDateFormat("yyyyMMdd-HHmmss").format(Date())
val imagesFolder = File(Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+imgn)
if(!imagesFolder.exists())
imagesFolder.mkdirs()
val imgname="NoteDirector-"+timeStamp+".mp4"
img=Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+imgn+"/"+imgname
val image = File(imagesFolder, imgname)
if (Build.VERSION.SDK_INT < 24) {
uriSavedImage=Uri.fromFile(image)
}
else
{
uriSavedImage =FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", image)
}
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage)
startActivityForResult(imageIntent, IMAGE_REQUEST)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_MEDIA && resultData?.data != null) {
Intent().apply {
val path = resultData.data.path
val uri = Uri.fromFile(File(path))
if (mIsGetImageContentIntent || mIsGetVideoContentIntent || mIsGetAnyContentIntent) {
if (intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true) {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val output = intent.extras.get(MediaStore.EXTRA_OUTPUT) as Uri
inputStream = FileInputStream(File(path))
outputStream = contentResolver.openOutputStream(output)
inputStream.copyTo(outputStream)
} catch (ignored: FileNotFoundException) {
} finally {
inputStream?.close()
outputStream?.close()
}
} else {
val type = File(path).getMimeType("image/jpeg")
setDataAndTypeAndNormalize(uri, type)
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
}
} else if (mIsPickImageIntent || mIsPickVideoIntent) {
data = uri
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
}
setResult(Activity.RESULT_OK, this)
}
finish()
} else if (requestCode == PICK_WALLPAPER) {
setResult(Activity.RESULT_OK)
finish()
}
else if(requestCode==IMAGE_REQUEST)
{
Toast.makeText(applicationContext,"Cabin created",Toast.LENGTH_SHORT).show()
val imagepath = File(img)
val mPath = Uri.fromFile(imagepath)
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
mediaScanIntent.setData(mPath)
this.sendBroadcast(mediaScanIntent)
Handler(Looper.getMainLooper()).postDelayed(object:Runnable {
override fun run() {
getDirectories()
}
}, 2000)
}
else if(requestCode==10)
{
if(resultData?.getData()!=null){
val mImageUri=resultData.getData()
copyimagefile(FilePickUtils.getSmartFilePath(this,mImageUri),gname)
}else{
if(resultData?.getClipData()!=null){
val mClipData=resultData.getClipData()
val mArrayUri=ArrayList<Uri>()
for(i in 0..mClipData.getItemCount()-1){
val item = mClipData.getItemAt(i)
val uri = item.getUri()
mArrayUri.add(uri)
}
for(i in 0..mArrayUri.size-1)
{
copyimagefile(FilePickUtils.getSmartFilePath(this,mArrayUri[i]),gname)
}
}
}
Toast.makeText(applicationContext,"Cabin created",Toast.LENGTH_SHORT).show()
Toast.makeText(this,"Added!!!",Toast.LENGTH_SHORT).show()
}
else if(requestCode==11)
{
if(resultData?.getData()!=null){
val mImageUri=resultData.getData()
copyvideofile(FilePickUtils.getSmartFilePath(this,mImageUri),gname)
}else{
if(resultData?.getClipData()!=null){
val mClipData=resultData.getClipData()
val mArrayUri=ArrayList<Uri>()
for(i in 0..mClipData.getItemCount()-1){
val item = mClipData.getItemAt(i)
val uri = item.getUri()
mArrayUri.add(uri)
}
for(i in 0..mArrayUri.size-1)
{
copyvideofile(FilePickUtils.getSmartFilePath(this,mArrayUri[i]),gname)
}
}
}
Toast.makeText(applicationContext,"Cabin created",Toast.LENGTH_SHORT).show()
Toast.makeText(this,"Added!!!",Toast.LENGTH_SHORT).show()
}
}
else if (resultCode == RESULT_CANCELED) {
if(requestCode==IMAGE_REQUEST) {
val p = img!!.lastIndexOf("/")
val folder = img?.substring(0, p)
val dir = File(folder)
if (dir.exists()) {
dir.delete()
}
}
else if( requestCode==10||requestCode==11) {
val folder = Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+gname
val dir = File(folder)
if (dir.exists()) {
dir.delete()
}
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun copyimagefile(source:String?,dest:String?)
{
if(source!=null && dest!=null) {
val srcfile = File(source)
val timeStamp = SimpleDateFormat("yyyyMMdd-HHmmssSSS").format(Date())
val imagesFolder = File(Environment.getExternalStorageDirectory().absolutePath + "/NoteDirector/" + dest)
if (!imagesFolder.exists())
imagesFolder.mkdirs()
val imgname = "NoteDirector-" + timeStamp + ".jpg"
img = Environment.getExternalStorageDirectory().absolutePath + "/NoteDirector/" + dest + "/" + imgname
val destfile = File(imagesFolder, imgname)
val sources: FileChannel?
val destinations: FileChannel?
sources = FileInputStream(srcfile).getChannel()
destinations = FileOutputStream(destfile).getChannel()
if (destinations != null && sources != null) {
destinations.transferFrom(sources, 0, sources.size())
}
if (sources != null) {
sources.close()
}
if (destinations != null) {
destinations.close()
}
}
val imagepath = File(img)
val mPath = Uri.fromFile(imagepath)
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
mediaScanIntent.setData(mPath)
this.sendBroadcast(mediaScanIntent)
Handler(Looper.getMainLooper()).postDelayed(object:Runnable {
override fun run() {
getDirectories()
}
}, 2000)
}
private fun copyvideofile(source:String?,dest:String?)
{
if(source!=null && dest!=null) {
val srcfile = File(source)
val timeStamp = SimpleDateFormat("yyyyMMdd-HHmmssSSS").format(Date())
val imagesFolder = File(Environment.getExternalStorageDirectory().absolutePath + "/NoteDirector/" + dest)
if (!imagesFolder.exists())
imagesFolder.mkdirs()
val imgname = "NoteDirector-" + timeStamp + ".mp4"
img = Environment.getExternalStorageDirectory().absolutePath + "/NoteDirector/" + dest + "/" + imgname
val destfile = File(imagesFolder, imgname)
val sources: FileChannel?
val destinations: FileChannel?
sources = FileInputStream(srcfile).getChannel()
destinations = FileOutputStream(destfile).getChannel()
if (destinations != null && source != null) {
destinations.transferFrom(sources, 0, sources.size())
}
if (sources != null) {
sources.close()
}
if (destinations != null) {
destinations.close()
}
}
val imagepath = File(img)
val mPath = Uri.fromFile(imagepath)
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
mediaScanIntent.setData(mPath)
this.sendBroadcast(mediaScanIntent)
Handler(Looper.getMainLooper()).postDelayed(object:Runnable {
override fun run() {
getDirectories()
}
}, 2000)
}
private fun itemClicked(path: String) {
Intent(this, MediaActivity::class.java).apply {
putExtra(DIRECTORY, path)
if (mIsSetWallpaperIntent) {
putExtra(SET_WALLPAPER_INTENT, true)
startActivityForResult(this, PICK_WALLPAPER)
} else {
putExtra(GET_IMAGE_INTENT, mIsPickImageIntent || mIsGetImageContentIntent)
putExtra(GET_VIDEO_INTENT, mIsPickVideoIntent || mIsGetVideoContentIntent)
putExtra(GET_ANY_INTENT, mIsGetAnyContentIntent)
startActivityForResult(this, PICK_MEDIA)
}
}
}
private fun gotDirectories(dirs: ArrayList<Directory>, isFromCache: Boolean) {
mLastMediaModified = getLastMediaModified()
directories_refresh_layout.isRefreshing = false
mIsGettingDirs = false
directories_empty_text_label.beVisibleIf(dirs.isEmpty() && !isFromCache)
directories_empty_text.beVisibleIf(dirs.isEmpty() && !isFromCache)
checkLastMediaChanged()
if (dirs.hashCode() == mDirs.hashCode())
return
mDirs = dirs
runOnUiThread {
setupAdapter()
}
storeDirectories()
}
private fun storeDirectories() {
if (!config.temporarilyShowHidden && config.tempFolderPath.isEmpty()) {
val directories = Gson().toJson(mDirs)
config.directories = directories
}
}
private fun setupAdapter() {
val currAdapter = directories_grid.adapter
if (currAdapter == null) {
directories_grid.adapter = DirectoryAdapter(this, mDirs, this, isPickIntent(intent) || isGetAnyContentIntent(intent)) {
itemClicked(it.path)
}
} else {
(currAdapter as DirectoryAdapter).updateDirs(mDirs)
}
setupScrollDirection()
}
private fun setupScrollDirection() {
directories_refresh_layout.isEnabled = !config.scrollHorizontally
directories_vertical_fastscroller.isHorizontal = false
directories_vertical_fastscroller.beGoneIf(config.scrollHorizontally)
directories_horizontal_fastscroller.isHorizontal = true
directories_horizontal_fastscroller.beVisibleIf(config.scrollHorizontally)
if (config.scrollHorizontally) {
directories_horizontal_fastscroller.setViews(directories_grid, directories_refresh_layout)
} else {
directories_vertical_fastscroller.setViews(directories_grid, directories_refresh_layout)
}
}
private fun checkLastMediaChanged() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed)
return
mLastMediaHandler.removeCallbacksAndMessages(null)
mLastMediaHandler.postDelayed({
Thread({
val lastModified = getLastMediaModified()
if (mLastMediaModified != lastModified) {
mLastMediaModified = lastModified
runOnUiThread {
getDirectories()
}
} else {
checkLastMediaChanged()
}
}).start()
}, LAST_MEDIA_CHECK_PERIOD)
}
override fun refreshItems() {
getDirectories()
}
override fun itemLongClicked(position: Int) {
directories_grid.setDragSelectActive(position)
}
private fun media_selector(imgn :String) {
val view = this.layoutInflater.inflate(R.layout.cam_vid_selector, null)
android.support.v7.app.AlertDialog.Builder(this)
.create().apply {
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
context.setupDialogStuff(view, this, R.string.media_selector)
camera(this)
this.setCanceledOnTouchOutside(false)
this.setOnCancelListener(DialogInterface.OnCancelListener {
val folder = Environment.getExternalStorageDirectory().absolutePath+"/NoteDirector/"+gname
val dir = File(folder)
if (dir.exists()) {
dir.delete()
}
})
camera = findViewById<ImageButton>(R.id.camera) as ImageButton
camera.setOnClickListener {
alertbox?.dismiss()
opencamera(imgn)
}
video = findViewById<ImageButton>(R.id.video) as ImageButton
video.setOnClickListener {
alertbox?.dismiss()
openvideo(imgn)
}
addcam = findViewById<ImageButton>(R.id.addcam) as ImageButton
addcam.setOnClickListener {
alertbox?.dismiss()
ImageFromCard()
}
addvid = findViewById<ImageButton>(R.id.addvid) as ImageButton
addvid.setOnClickListener {
alertbox?.dismiss()
VideoFromCard()
}
}
}
private fun ImageFromCard() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(Intent.createChooser(intent,
"select multiple images"), 10)
}
private fun VideoFromCard() {
val intent = Intent()
intent.type = "video/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(Intent.createChooser(intent,
"select multiple videos"), 11)
}
private fun camera( alertDialog: android.support.v7.app.AlertDialog) {
alertbox=alertDialog
}
object FilePickUtils {
private fun getPathDeprecated(ctx: Context, uri: Uri?): String? {
if (uri == null) {
return null
}
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = ctx.contentResolver.query(uri, projection, null, null, null)
if (cursor != null) {
val column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
return uri.path
}
fun getSmartFilePath(ctx: Context, uri: Uri): String? {
if (Build.VERSION.SDK_INT < 19) {
return getPathDeprecated(ctx, uri)
}
return FilePickUtils.getPath(ctx, uri)
}
@SuppressLint("NewApi")
fun getPath(context: Context, uri: Uri): String? {
val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
if ("primary".equals(type, ignoreCase = true)) {
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
}
// TODO handle non-primary volumes
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)!!)
return getDataColumn(context, contentUri, null, null)
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
var contentUri: Uri? = null
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
return contentUri?.let { getDataColumn(context, it, selection, selectionArgs) }
}// MediaProvider
// DownloadsProvider
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
return getDataColumn(context, uri, null, null)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
return uri.path
}// File
// MediaStore (and general)
return null
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
* @param context The context.
* *
* @param uri The Uri to query.
* *
* @param selection (Optional) Filter used in the query.
* *
* @param selectionArgs (Optional) Selection arguments used in the query.
* *
* @return The value of the _data column, which is typically a file path.
*/
fun getDataColumn(context: Context, uri: Uri, selection: String?,
selectionArgs: Array<String>?): String? {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
if (cursor != null && cursor.moveToFirst()) {
val column_index = cursor.getColumnIndexOrThrow(column)
return cursor.getString(column_index)
}
} finally {
if (cursor != null)
cursor.close()
}
return null
}
/**
* @param uri The Uri to check.
* *
* @return Whether the Uri authority is ExternalStorageProvider.
*/
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri.authority
}
/**
* @param uri The Uri to check.
* *
* @return Whether the Uri authority is DownloadsProvider.
*/
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri.authority
}
/**
* @param uri The Uri to check.
* *
* @return Whether the Uri authority is MediaProvider.
*/
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri.authority
}
}
} | apache-2.0 | f7f042b40581a9ebc8faf286958b197a | 39.760396 | 166 | 0.608181 | 5.071077 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/fragments/st/STCrewAndShipVitalStatisticsFragment.kt | 1 | 3941 | package pt.joaomneto.titancompanion.adventurecreation.impl.fragments.st
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventurecreation.impl.STAdventureCreation
class STCrewAndShipVitalStatisticsFragment : Fragment() {
internal var scienceOfficerSkill: TextView? = null
internal var medicalOfficerSkill: TextView? = null
internal var engineeringOfficerSkill: TextView? = null
internal var securityOfficerSkill: TextView? = null
internal var securityGuard1Skill: TextView? = null
internal var securityGuard2Skill: TextView? = null
internal var shipWeapons: TextView? = null
internal var scienceOfficerStamina: TextView? = null
internal var medicalOfficerStamina: TextView? = null
internal var engineeringOfficerStamina: TextView? = null
internal var securityOfficerStamina: TextView? = null
internal var securityGuard1Stamina: TextView? = null
internal var securityGuard2Stamina: TextView? = null
internal var shipShields: TextView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
val rootView = inflater.inflate(
R.layout.fragment_04st_adventurecreation_crewshipvitalstats,
container, false
)
scienceOfficerSkill = rootView
.findViewById(R.id.scienceOfficerSkillValue)
medicalOfficerSkill = rootView
.findViewById(R.id.medicalOfficerSkillValue)
engineeringOfficerSkill = rootView
.findViewById(R.id.engineeringOfficerSkillValue)
securityOfficerSkill = rootView
.findViewById(R.id.securityOfficerSkillValue)
securityGuard1Skill = rootView
.findViewById(R.id.securityGuard1SkillValue)
securityGuard2Skill = rootView
.findViewById(R.id.securityGuard2SkillValue)
shipWeapons = rootView.findViewById(R.id.shipWeaponsValue)
scienceOfficerStamina = rootView
.findViewById(R.id.scienceOfficerStaminaValue)
medicalOfficerStamina = rootView
.findViewById(R.id.medicalOfficerStaminaValue)
engineeringOfficerStamina = rootView
.findViewById(R.id.engineeringOfficerStaminaValue)
securityOfficerStamina = rootView
.findViewById(R.id.securityOfficerStaminaValue)
securityGuard1Stamina = rootView
.findViewById(R.id.securityGuard1StaminaValue)
securityGuard2Stamina = rootView
.findViewById(R.id.securityGuard2StaminaValue)
shipShields = rootView.findViewById(R.id.shipShieldsValue)
return rootView
}
fun updateFields() {
val act = activity as STAdventureCreation?
scienceOfficerSkill!!.text = "" + act!!.scienceOfficerSkill
medicalOfficerSkill!!.text = "" + act.medicalOfficerSkill
engineeringOfficerSkill!!.text = "" + act.engineeringOfficerSkill
securityOfficerSkill!!.text = "" + act.securityOfficerSkill
securityGuard1Skill!!.text = "" + act.securityGuard1Skill
securityGuard2Skill!!.text = "" + act.securityGuard2Skill
shipWeapons!!.text = "" + act.shipWeapons
scienceOfficerStamina!!.text = "" + act.scienceOfficerStamina
medicalOfficerStamina!!.text = "" + act.medicalOfficerStamina
engineeringOfficerStamina!!.text = "" + act.engineeringOfficerStamina
securityOfficerStamina!!.text = "" + act.securityOfficerStamina
securityGuard1Stamina!!.text = "" + act.securityGuard1Stamina
securityGuard2Stamina!!.text = "" + act.securityGuard2Stamina
shipShields!!.text = "" + act.shipShields
}
}
| lgpl-3.0 | 7423191a2c28c5a3152fb28b5f0c0a16 | 42.307692 | 77 | 0.717331 | 4.378889 | false | false | false | false |
neverwoodsS/StudyWithKotlin | src/queue/ChainQueue.kt | 1 | 835 | package queue
import linearlist.Node
/**
* Created by zhangll on 2017/2/7.
*/
class ChainQueue {
var first: Node? = null
var last: Node? = null
init {
}
fun isEmpty(): Boolean {
return first == null && last == null
}
fun put(element: String) {
val node = Node(element)
if (isEmpty()) {
first = node
last = node
} else {
last?.next = node
last = node
}
}
fun pop(): Node? {
if (isEmpty()) {
return null
}
val temp = first
first = first?.next
return temp
}
fun log() {
var temp: Node? = first
while (temp != null) {
print("${temp.content} -> ")
temp = temp.next
}
println("\n")
}
} | mit | e00190a7ffdae01c7ff76a50ff9441e1 | 15.72 | 44 | 0.441916 | 4.175 | false | false | false | false |
koma-im/koma | src/main/kotlin/link/continuum/desktop/gui/notification/desktopPopUp.kt | 1 | 3081 | package link.continuum.desktop.gui.notification
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.media.AudioClip
import javafx.scene.text.Text
import javafx.scene.text.TextFlow
import koma.koma_app.AppStore
import koma.matrix.NotificationResponse
import koma.matrix.event.room_message.RoomEventType
import link.continuum.desktop.gui.StackPane
import link.continuum.desktop.gui.StyleBuilder
import link.continuum.desktop.gui.em
import link.continuum.desktop.gui.util.Recyclable
import link.continuum.desktop.util.debugAssertUiThread
import link.continuum.desktop.util.http.MediaServer
import mu.KotlinLogging
import org.controlsfx.control.Notifications
private typealias NotificationData = NotificationResponse.Notification
private val logger = KotlinLogging.logger {}
fun popNotify(notification: NotificationData, store: AppStore, server: MediaServer) {
debugAssertUiThread()
val graphic = NotificationGraphic(store)
val popup = Notifications.create()
.onAction {
graphic.close()
}
.title("Incoming message")
.position(Pos.TOP_RIGHT)
graphic.updateItem(notification, server)
popup.graphic(graphic.graphic)
popup.show()
}
/**
* AudioClip can be played on any thread
* But there seems to be no sound when played without starting JFX
*/
object AudioResources {
val message by lazy {
AudioClip(javaClass.getResource("/sound/message.m4a").toExternalForm())
}
}
private class NotificationGraphic(
store: AppStore
) {
var graphic: Node? = null
get() = field
private set(value) {field = value}
val root = object : StackPane() {
init {
style = boxStyle
}
override fun computeMinHeight(width: Double): Double {
return super.computeMinHeight(width) + 60.0
}
}
private val messageView = Recyclable(store.messageCells)
private val fallbackCell = TextFlow()
fun updateItem(item: NotificationData?, server: MediaServer) {
messageView.recycle()
if (null == item) {
graphic = null
return
}
val event = item.event
val content = event.content
root.children.clear()
when {
event.type == RoomEventType.Message -> if(content is NotificationResponse.Content.Message) {
val msgView = messageView.get()
val msg = content.message
msgView.update(event, server, msg)
root.children.add(msgView.root)
} else {
logger.debug { "msg content $content"}
}
else -> {
fallbackCell.children.setAll(Text("type: ${event.type}, content: ${event.content}"))
root.children.add(fallbackCell)
}
}
graphic = root
}
init {
}
companion object {
private val boxStyle = StyleBuilder {
prefWidth = 12.em
}.toStyle()
}
fun close() {
messageView.recycle()
}
} | gpl-3.0 | 0f46f3cc9c743b4feb51523fe1d4599d | 29.215686 | 104 | 0.64492 | 4.517595 | false | false | false | false |
blademainer/intellij-community | platform/testFramework/test-framework-java8/TemporaryDirectory.kt | 2 | 3157 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.lang.CompoundRuntimeException
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.properties.Delegates
class TemporaryDirectory : ExternalResource() {
private val paths = SmartList<Path>()
private var sanitizedName: String by Delegates.notNull()
override fun apply(base: Statement, description: Description): Statement {
sanitizedName = FileUtil.sanitizeFileName(description.methodName, false)
return super.apply(base, description)
}
override fun after() {
val errors = SmartList<Throwable>()
for (path in paths) {
try {
path.deleteRecursively()
}
catch (e: Throwable) {
errors.add(e)
}
}
CompoundRuntimeException.throwIfNotEmpty(errors)
paths.clear()
}
/**
* Directory is not created.
*/
public fun newDirectory(directoryName: String? = null): File = generatePath(directoryName).toFile()
public fun newPath(directoryName: String? = null, refreshVfs: Boolean = true): Path {
val path = generatePath(directoryName)
if (refreshVfs) {
path.refreshVfs()
}
return path
}
private fun generatePath(suffix: String?): Path {
var fileName = sanitizedName
if (suffix != null) {
fileName += "_$suffix"
}
var path = generateTemporaryPath(fileName)
paths.add(path)
return path
}
public fun newVirtualDirectory(directoryName: String? = null): VirtualFile {
val path = generatePath(directoryName)
path.createDirectories()
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath)
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
return virtualFile!!
}
}
public fun generateTemporaryPath(fileName: String?): Path {
val tempDirectory = Paths.get(FileUtilRt.getTempDirectory())
var path = tempDirectory.resolve(fileName)
var i = 0
while (path.exists() && i < 9) {
path = tempDirectory.resolve("${fileName}_$i")
i++
}
if (path.exists()) {
throw IOException("Cannot generate unique random path")
}
return path
} | apache-2.0 | 3f14c488cc0f33f88846a04b67e37a94 | 29.365385 | 104 | 0.727273 | 4.384722 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/listener/PlayerInteractListener.kt | 1 | 8311 | package com.rpkit.locks.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.locks.bukkit.RPKLocksBukkit
import com.rpkit.locks.bukkit.keyring.RPKKeyringProvider
import com.rpkit.locks.bukkit.lock.RPKLockProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.block.Block
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.ItemStack
class PlayerInteractListener(private val plugin: RPKLocksBukkit): Listener {
@EventHandler
fun onPlayerInteract(event: PlayerInteractEvent) {
val clickedBlock = event.clickedBlock
if (clickedBlock != null) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
val lockProvider = plugin.core.serviceManager.getServiceProvider(RPKLockProvider::class)
var block: Block? = null
xLoop@ for (x in clickedBlock.x - 1..clickedBlock.x + 1) {
for (y in clickedBlock.y - 1..clickedBlock.y + 1) {
for (z in clickedBlock.z - 1..clickedBlock.z + 1) {
if (lockProvider.isLocked(clickedBlock.world.getBlockAt(x, y, z))) {
block = clickedBlock.world.getBlockAt(x, y, z)
break@xLoop
}
}
}
}
if (lockProvider.isClaiming(minecraftProfile)) {
if (block == null) {
if (event.player.inventory.itemInMainHand.amount == 1) {
event.player.inventory.setItemInMainHand(null)
} else {
event.player.inventory.itemInMainHand.amount = event.player.inventory.itemInMainHand.amount - 1
}
lockProvider.setLocked(clickedBlock, true)
for (item in event.player.inventory.addItem(lockProvider.getKeyFor(clickedBlock)).values) {
event.player.world.dropItem(event.player.location, item)
}
event.player.updateInventory()
event.player.sendMessage(plugin.messages["lock-successful"])
} else {
event.player.sendMessage(plugin.messages["lock-invalid-already-locked"])
}
event.isCancelled = true
} else if (lockProvider.isUnclaiming(minecraftProfile)) {
if (block != null) {
if (hasKey(character, block)) {
lockProvider.setLocked(block, false)
event.player.sendMessage(plugin.messages["unlock-successful"])
removeKey(character, block)
event.player.inventory.addItem(lockProvider.lockItem)
event.player.updateInventory()
} else {
event.player.sendMessage(plugin.messages["unlock-invalid-no-key"])
}
} else {
event.player.sendMessage(plugin.messages["unlock-invalid-not-locked"])
}
lockProvider.setUnclaiming(minecraftProfile, false)
event.isCancelled = true
} else if (lockProvider.isGettingKey(minecraftProfile)) {
if (block == null) {
event.player.sendMessage(plugin.messages["get-key-invalid-not-locked"])
} else {
for (item in event.player.inventory.addItem(lockProvider.getKeyFor(block)).values) {
event.player.world.dropItem(event.player.location, item)
}
event.player.updateInventory()
event.player.sendMessage(plugin.messages["get-key-successful"])
}
lockProvider.setGettingKey(minecraftProfile, false)
event.isCancelled = true
} else {
if (block != null) {
if (hasKey(character, block)) return
if (!hasKey(character, block)) {
event.isCancelled = true
event.player.sendMessage(plugin.messages["block-locked", mapOf(
Pair("block", block.type.toString().toLowerCase().replace('_', ' '))
)])
}
}
}
} else {
event.isCancelled = true
}
} else {
event.isCancelled = true
}
}
}
fun hasKey(character: RPKCharacter, block: Block): Boolean {
val lockProvider = plugin.core.serviceManager.getServiceProvider(RPKLockProvider::class)
val keyringProvider = plugin.core.serviceManager.getServiceProvider(RPKKeyringProvider::class)
val minecraftProfile = character.minecraftProfile
if (minecraftProfile != null) {
val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID)
val bukkitPlayer = offlineBukkitPlayer.player
if (bukkitPlayer != null) {
val inventory = bukkitPlayer.inventory
repeat(keyringProvider.getKeyring(character)
.filter { it.isSimilar(lockProvider.getKeyFor(block)) }.size) { return true }
repeat(inventory.contents
.filter { it != null }
.filter { it.isSimilar(lockProvider.getKeyFor(block)) }.size) { return true }
}
}
return false
}
fun removeKey(character: RPKCharacter, block: Block) {
val lockProvider = plugin.core.serviceManager.getServiceProvider(RPKLockProvider::class)
val keyringProvider = plugin.core.serviceManager.getServiceProvider(RPKKeyringProvider::class)
val keyring = keyringProvider.getKeyring(character)
val iterator = keyring.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
if (key.isSimilar(lockProvider.getKeyFor(block))) {
if (key.amount > 1) {
key.amount = key.amount - 1
} else {
iterator.remove()
}
return
}
}
keyringProvider.setKeyring(character, keyring)
val minecraftProfile = character.minecraftProfile
if (minecraftProfile != null) {
val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID)
val bukkitPlayer = offlineBukkitPlayer.player
if (bukkitPlayer != null) {
val inventory = bukkitPlayer.inventory
val inventoryContents = inventory.contents
for (key in inventoryContents) {
if (key.isSimilar(lockProvider.getKeyFor(block))) {
val oneKey = ItemStack(key)
oneKey.amount = 1
inventory.removeItem(oneKey)
return
}
}
}
}
}
}
| apache-2.0 | e0467c258126e2f462ad78be1fc08b96 | 51.27044 | 127 | 0.530983 | 5.676913 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/第一章/BinarySearch.kt | 1 | 577 | package 算法.第一章
fun main(args: Array<String>) {
println("->" + BinarySearch.rank(10, intArrayOf(0, 6, 10, 90, 240)))
}
/**
* 题目:在有序数组中快速找到一个 整数,并返回他数组中的位置
*/
object BinarySearch {
fun rank(key: Int, arr: IntArray): Int {
var lo = 0
var high = arr.size - 1
while (lo <= high) {
val mid = (high - lo) / 2
if (key < arr[mid]) high = mid - 1
else if (key > arr[mid]) lo = mid + 1
else return mid
}
return -1
}
} | epl-1.0 | d05dd09d471df5ff44bacc45edf35b74 | 22.272727 | 72 | 0.497065 | 3.005882 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/IsSetLogLevel.kt | 1 | 1340 | package com.gmail.blueboxware.libgdxplugin.utils
import com.intellij.psi.PsiClass
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
fun isSetLogLevel(clazz: PsiClass, methodName: String): Boolean {
val applicationClass = "com.badlogic.gdx.Application"
val loggerClass = "com.badlogic.gdx.utils.Logger"
if (clazz.qualifiedName == applicationClass) return methodName == "setLogLevel"
if (clazz.qualifiedName == loggerClass) return methodName == "setLevel"
for (superClass in clazz.supers.flatMap { it.supers.toList() }) {
if (superClass.qualifiedName == applicationClass) {
return methodName == "setLogLevel"
} else if (superClass.qualifiedName == loggerClass) {
return methodName == "setLevel"
}
}
return false
}
| apache-2.0 | 440f37e080b5ba229da97bd14bbcbcd7 | 32.5 | 83 | 0.71194 | 4.364821 | false | false | false | false |
ibinti/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/optimizeTipsImages.kt | 11 | 1515 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.intellij.build.images
import com.intellij.openapi.application.PathManager
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.serialization.JpsSerializationManager
import java.io.File
fun main(args: Array<String>) {
val homePath = PathManager.getHomePath()
val home = File(homePath)
val project = JpsSerializationManager.getInstance().loadModel(homePath, null).project
val optimizer = ImageSizeOptimizer(home)
project.modules.forEach { module ->
module.sourceRoots.forEach { root ->
val imagesDir = File(root.file, "tips/images")
if (JavaModuleSourceRootTypes.PRODUCTION.contains(root.rootType) && imagesDir.isDirectory) {
val images = optimizer.optimizeImages(imagesDir)
println("Processed root ${root.file} with $images images")
}
}
}
optimizer.printStats()
println()
println("Done")
} | apache-2.0 | 7d4cfee5e2f72b89463a9711df21a0c0 | 35.095238 | 98 | 0.745875 | 4.196676 | false | false | false | false |
antoniolg/Kotlin-for-Android-Developers | app/src/main/java/com/antonioleiva/weatherapp/domain/datasource/ForecastProvider.kt | 1 | 1126 | package com.antonioleiva.weatherapp.domain.datasource
import com.antonioleiva.weatherapp.data.db.ForecastDb
import com.antonioleiva.weatherapp.data.server.ForecastServer
import com.antonioleiva.weatherapp.domain.model.Forecast
import com.antonioleiva.weatherapp.domain.model.ForecastList
import com.antonioleiva.weatherapp.extensions.firstResult
class ForecastProvider(private val sources: List<ForecastDataSource> = ForecastProvider.SOURCES) {
companion object {
const val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
val SOURCES by lazy { listOf(ForecastDb(), ForecastServer()) }
}
fun requestByZipCode(zipCode: Long, days: Int): ForecastList = requestToSources {
val res = it.requestForecastByZipCode(zipCode, todayTimeSpan())
if (res != null && res.size >= days) res else null
}
fun requestForecast(id: Long): Forecast = requestToSources { it.requestDayForecast(id) }
private fun todayTimeSpan() = System.currentTimeMillis() / DAY_IN_MILLIS * DAY_IN_MILLIS
private fun <T : Any> requestToSources(f: (ForecastDataSource) -> T?): T = sources.firstResult { f(it) }
} | apache-2.0 | 68ced7bf0b4c783bece4b89007d22bc6 | 40.740741 | 108 | 0.743339 | 4.124542 | false | false | false | false |
tmarsteel/kotlin-prolog | stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/lists/sort__2.kt | 1 | 827 | package com.github.prologdb.runtime.stdlib.lists
import com.github.prologdb.runtime.stdlib.nativeRule
import com.github.prologdb.runtime.term.PrologList
import com.github.prologdb.runtime.term.Term
val BuiltinSort2 = nativeRule("sort", 2) { args, context ->
val inputUnsorted = args.getTyped<PrologList>(0)
val inputSorted = args[1]
val inputElementsSorted = inputUnsorted.elements.sorted()
val inputElementsSortedUnique = mutableListOf<Term>()
inputElementsSorted.forEach { notUniqueTerm ->
if (inputElementsSortedUnique.none { it.compareTo(notUniqueTerm) == 0 }) {
inputElementsSortedUnique.add(notUniqueTerm)
}
}
val sorted = PrologList(inputElementsSortedUnique, inputUnsorted.tail)
return@nativeRule sorted.unify(inputSorted, context.randomVariableScope)
}
| mit | 5ffd9acd92c15572138440b02b12f5ee | 36.590909 | 82 | 0.754534 | 4.053922 | false | false | false | false |
facebook/fresco | vito/view/src/main/java/com/facebook/fresco/vito/view/impl/VitoViewImpl2.kt | 2 | 6291 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.view.impl
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.View.OnAttachStateChangeListener
import android.widget.ImageView
import androidx.core.view.ViewCompat
import com.facebook.common.internal.Supplier
import com.facebook.common.internal.Suppliers
import com.facebook.drawee.drawable.VisibilityCallback
import com.facebook.fresco.vito.core.FrescoDrawableInterface
import com.facebook.fresco.vito.core.VitoImageRequest
import com.facebook.fresco.vito.listener.ImageListener
import com.facebook.fresco.vito.options.ImageOptions
import com.facebook.fresco.vito.provider.FrescoVitoProvider
import com.facebook.fresco.vito.source.ImageSource
/** Vito View implementation */
object VitoViewImpl2 {
@JvmStatic var useVisibilityCallbacks: Supplier<Boolean> = Suppliers.BOOLEAN_TRUE
@JvmStatic var useSimpleFetchLogic: Supplier<Boolean> = Suppliers.BOOLEAN_FALSE
private val onAttachStateChangeListenerCallback: OnAttachStateChangeListener =
object : OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View) {
getDrawable(view)?.apply {
imagePerfListener.onImageMount(this)
maybeFetchImage(this)
}
}
override fun onViewDetachedFromWindow(view: View) {
getDrawable(view)?.apply {
imagePerfListener.onImageUnmount(this)
FrescoVitoProvider.getController().release(this)
}
}
}
@JvmStatic
fun show(
imageSource: ImageSource,
imageOptions: ImageOptions,
callerContext: Any?,
imageListener: ImageListener?,
target: View
) {
show(
FrescoVitoProvider.getImagePipeline()
.createImageRequest(target.resources, imageSource, imageOptions),
callerContext,
imageListener,
target)
}
@JvmStatic
fun show(
imageRequest: VitoImageRequest,
callerContext: Any?,
imageListener: ImageListener?,
target: View
) {
val frescoDrawable = ensureDrawableSet(target)
// The Drawable might be re-purposed before being cleaned up, so we release if necessary.
val oldImageRequest = frescoDrawable.imageRequest
if (oldImageRequest != null && oldImageRequest != imageRequest) {
FrescoVitoProvider.getController().releaseImmediately(frescoDrawable)
}
frescoDrawable.refetchRunnable = Runnable {
FrescoVitoProvider.getController()
.fetch(frescoDrawable, imageRequest, callerContext, null, imageListener, null, null)
}
if (useSimpleFetchLogic.get()) {
frescoDrawable.imagePerfListener.onImageMount(frescoDrawable)
maybeFetchImage(frescoDrawable)
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// If the view is already attached to the window, immediately fetch the image.
// Otherwise, the fetch will be submitted later when then View is attached.
if (target.isAttachedToWindow) {
frescoDrawable.imagePerfListener.onImageMount(frescoDrawable)
maybeFetchImage(frescoDrawable)
}
} else {
// Before Kitkat we don't have a good way to know.
// Normally we expect the view to be already attached, thus we always fetch the image.
frescoDrawable.imagePerfListener.onImageMount(frescoDrawable)
maybeFetchImage(frescoDrawable)
}
}
// `addOnAttachStateChangeListener` is not idempotent
target.removeOnAttachStateChangeListener(onAttachStateChangeListenerCallback)
target.addOnAttachStateChangeListener(onAttachStateChangeListenerCallback)
}
@JvmStatic
fun release(target: View) {
getDrawable(target)?.apply {
imagePerfListener.onImageUnmount(this)
FrescoVitoProvider.getController().releaseImmediately(this)
refetchRunnable = null
}
}
private fun maybeFetchImage(drawable: FrescoDrawableInterface) {
drawable.refetchRunnable?.run()
}
/**
* Ensure that a [FrescoDrawableInterface] is set for the given View target
*
* @param target the target to use
* @return The drawable to use for the given target
*/
private fun ensureDrawableSet(target: View): FrescoDrawableInterface {
return when (target) {
is ImageView ->
when (val current = target.drawable) {
is FrescoDrawableInterface -> current
else ->
createDrawable().also {
// Force the Drawable to adjust its bounds to match the hosting ImageView's
// bounds, since Fresco has custom scale types that are separate from ImageView's
// scale type.
// Without this, the Drawable would not respect the given Fresco ScaleType,
// effectively resulting in CENTER_INSIDE.
target.scaleType = ImageView.ScaleType.FIT_XY
target.setImageDrawable(it as Drawable)
}
}
else ->
when (val current = target.background) {
is FrescoDrawableInterface -> current
else -> createDrawable().also { ViewCompat.setBackground(target, it as Drawable) }
}
}
}
private fun getDrawable(view: View): FrescoDrawableInterface? {
return (if (view is ImageView) view.drawable else view.background) as? FrescoDrawableInterface
}
private fun createDrawable(): FrescoDrawableInterface {
val frescoDrawable: FrescoDrawableInterface =
FrescoVitoProvider.getController().createDrawable()
if (useVisibilityCallbacks.get()) {
frescoDrawable.setVisibilityCallback(
object : VisibilityCallback {
override fun onVisibilityChange(visible: Boolean) {
if (!visible) {
FrescoVitoProvider.getController().release(frescoDrawable)
} else {
maybeFetchImage(frescoDrawable)
}
}
override fun onDraw() {
// NOP
}
})
}
return frescoDrawable
}
}
| mit | b33e8da1264136e216bf4f7f2b278ef7 | 35.364162 | 99 | 0.685106 | 4.984945 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/sync/HexagonMovieSync.kt | 1 | 10305 | package com.battlelancer.seriesguide.sync
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import android.content.OperationApplicationException
import android.text.TextUtils
import androidx.preference.PreferenceManager
import com.battlelancer.seriesguide.backend.HexagonTools
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.provider.SeriesGuideContract
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.movies.tools.MovieTools
import com.battlelancer.seriesguide.util.DBUtils
import com.battlelancer.seriesguide.util.Errors
import com.google.api.client.util.DateTime
import com.uwetrottmann.androidutils.AndroidUtils
import com.uwetrottmann.seriesguide.backend.movies.model.Movie
import com.uwetrottmann.seriesguide.backend.movies.model.MovieList
import timber.log.Timber
import java.io.IOException
import java.util.ArrayList
internal class HexagonMovieSync(
private val context: Context,
private val hexagonTools: HexagonTools
) {
/**
* Downloads movies from hexagon, updates existing movies with new properties, removes
* movies that are neither in collection or watchlist or watched.
*
* Adds movie tmdb ids of new movies to the respective collection, watchlist or watched set.
*/
fun download(
newCollectionMovies: MutableSet<Int>,
newWatchlistMovies: MutableSet<Int>,
newWatchedMoviesToPlays: MutableMap<Int, Int>,
hasMergedMovies: Boolean
): Boolean {
var movies: List<Movie>?
var hasMoreMovies = true
var cursor: String? = null
val currentTime = System.currentTimeMillis()
val lastSyncTime = DateTime(HexagonSettings.getLastMoviesSyncTime(context))
val localMovies = MovieTools.getMovieTmdbIdsAsSet(context)
if (localMovies == null) {
Timber.e("download: querying for local movies failed.")
return false
}
if (hasMergedMovies) {
Timber.d("download: movies changed since %s", lastSyncTime)
} else {
Timber.d("download: all movies")
}
var updatedCount = 0
var removedCount = 0
while (hasMoreMovies) {
// abort if connection is lost
if (!AndroidUtils.isNetworkConnected(context)) {
Timber.e("download: no network connection")
return false
}
try {
// get service each time to check if auth was removed
val moviesService = hexagonTools.moviesService ?: return false
val request = moviesService.get() // use default server limit
if (hasMergedMovies) {
request.updatedSince = lastSyncTime
}
if (!TextUtils.isEmpty(cursor)) {
request.cursor = cursor
}
val response = request.execute()
if (response == null) {
// nothing more to do
Timber.d("download: response was null, done here")
break
}
movies = response.movies
if (response.cursor != null) {
cursor = response.cursor
} else {
hasMoreMovies = false
}
} catch (e: IOException) {
Errors.logAndReportHexagon("get movies", e)
return false
} catch (e: IllegalArgumentException) {
// Note: JSON parser may throw IllegalArgumentException.
Errors.logAndReportHexagon("get movies", e)
return false
}
if (movies == null || movies.isEmpty()) {
// nothing more to do
break
}
val batch = ArrayList<ContentProviderOperation>()
for (movie in movies) {
if (localMovies.contains(movie.tmdbId)) {
// movie is in database
if (movie.isInCollection == false
&& movie.isInWatchlist == false
&& movie.isWatched == false) {
// if no longer in watchlist, collection or watched: remove movie
// note: this is backwards compatible with watched movies downloaded
// by trakt as those will have a null watched flag on Cloud
batch.add(
ContentProviderOperation.newDelete(
SeriesGuideContract.Movies.buildMovieUri(movie.tmdbId)
).build()
)
removedCount++
} else {
// update collection, watchlist and watched flags and plays
val values = ContentValues().apply {
putIfNotNull(
movie.isInCollection,
SeriesGuideContract.Movies.IN_COLLECTION
)
putIfNotNull(
movie.isInWatchlist,
SeriesGuideContract.Movies.IN_WATCHLIST
)
putIfNotNull(
movie.isWatched,
SeriesGuideContract.Movies.WATCHED
)
movie.isWatched?.let {
if (it) {
// Watched.
// Note: plays may be null for legacy data. Protect against invalid data.
if (movie.plays != null && movie.plays >= 1) {
put(SeriesGuideContract.Movies.PLAYS, movie.plays)
} else {
put(SeriesGuideContract.Movies.PLAYS, 1)
}
} else {
// Not watched.
put(SeriesGuideContract.Movies.PLAYS, 0)
}
}
}
batch.add(
ContentProviderOperation.newUpdate(
SeriesGuideContract.Movies.buildMovieUri(movie.tmdbId)
).withValues(values).build()
)
updatedCount++
}
} else {
// schedule movie to be added
if (movie.isInCollection == true) {
newCollectionMovies.add(movie.tmdbId)
}
if (movie.isInWatchlist == true) {
newWatchlistMovies.add(movie.tmdbId)
}
if (movie.isWatched == true) {
// Note: plays may be null for legacy data. Protect against invalid data.
val plays = if (movie.plays != null && movie.plays >= 1) {
movie.plays
} else {
1
}
newWatchedMoviesToPlays[movie.tmdbId] = plays
}
}
}
try {
DBUtils.applyInSmallBatches(context, batch)
} catch (e: OperationApplicationException) {
Timber.e(e, "download: applying movie updates failed")
return false
}
}
Timber.d("download: updated %d and removed %d movies", updatedCount, removedCount)
// set new last sync time
if (hasMergedMovies) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putLong(HexagonSettings.KEY_LAST_SYNC_MOVIES, currentTime)
.apply()
}
return true
}
private fun ContentValues.putIfNotNull(value: Boolean?, key: String) {
if (value != null) {
put(key, if (value) 1 else 0)
}
}
/**
* Uploads all local movies to Hexagon.
*/
fun uploadAll(): Boolean {
Timber.d("uploadAll: uploading all movies")
val movies = buildMovieList()
if (movies.isEmpty()) {
// nothing to do
Timber.d("uploadAll: no movies to upload")
return true
}
// Upload in small batches
val wrapper = MovieList()
while (movies.isNotEmpty()) {
wrapper.movies = ArrayList()
while (movies.isNotEmpty() && wrapper.movies.size < MAX_BATCH_SIZE) {
wrapper.movies.add(movies.removeFirst())
}
try {
// get service each time to check if auth was removed
val moviesService = hexagonTools.moviesService ?: return false
moviesService.save(wrapper).execute()
} catch (e: IOException) {
Errors.logAndReportHexagon("save movies", e)
return false
}
}
return true
}
private fun buildMovieList(): MutableList<Movie> {
val movies = ArrayList<Movie>()
// query for movies in lists or that are watched
val moviesInListsOrWatched = SgRoomDatabase.getInstance(context)
.movieHelper()
.getMoviesOnListsOrWatched()
for (movie in moviesInListsOrWatched) {
val movieToUpload = Movie()
movieToUpload.tmdbId = movie.tmdbId
movieToUpload.isInCollection = movie.inCollection
movieToUpload.isInWatchlist = movie.inWatchlist
movieToUpload.isWatched = movie.watched
movieToUpload.plays = movie.plays
movies.add(movieToUpload)
}
return movies
}
companion object {
private const val MAX_BATCH_SIZE = 500
}
}
| apache-2.0 | 950fd934bc2dd21a0b2ddbc365078a27 | 37.451493 | 109 | 0.517225 | 5.851789 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.