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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToOrdinaryStringLiteralIntention.kt | 3 | 4349 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ToOrdinaryStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
KotlinBundle.lazyMessage("to.ordinary.string.literal")
), LowPriorityAction {
companion object {
private val TRIM_INDENT_FUNCTIONS = listOf(FqName("kotlin.text.trimIndent"), FqName("kotlin.text.trimMargin"))
}
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
return element.text.startsWith("\"\"\"")
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val startOffset = element.startOffset
val endOffset = element.endOffset
val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset
val entries = element.entries
val trimIndentCall = getTrimIndentCall(element, entries)
val text = buildString {
append("\"")
if (trimIndentCall != null) {
append(trimIndentCall.stringTemplateText)
} else {
entries.joinTo(buffer = this, separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape() else it.text
}
}
append("\"")
}
val replaced = (trimIndentCall?.qualifiedExpression ?: element).replaced(KtPsiFactory(element).createExpression(text))
val offset = when {
currentOffset - startOffset < 2 -> startOffset
endOffset - currentOffset < 2 -> replaced.endOffset
else -> maxOf(currentOffset - 2, replaced.startOffset)
}
editor?.caretModel?.moveToOffset(offset)
}
private fun String.escape(escapeLineSeparators: Boolean = true): String {
var text = this
text = text.replace("\\", "\\\\")
text = text.replace("\"", "\\\"")
return if (escapeLineSeparators) text.escapeLineSeparators() else text
}
private fun String.escapeLineSeparators(): String {
return StringUtil.convertLineSeparators(this, "\\n")
}
private fun getTrimIndentCall(
element: KtStringTemplateExpression,
entries: Array<KtStringTemplateEntry>
): TrimIndentCall? {
val qualifiedExpression = element.getQualifiedExpressionForReceiver()?.takeIf {
it.callExpression?.isCalling(TRIM_INDENT_FUNCTIONS) == true
} ?: return null
val marginPrefix = if (qualifiedExpression.calleeName == "trimMargin") {
when (val arg = qualifiedExpression.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()) {
null -> "|"
is KtStringTemplateExpression -> arg.entries.singleOrNull()?.takeIf { it is KtLiteralStringTemplateEntry }?.text
else -> null
} ?: return null
} else {
null
}
val stringTemplateText = entries
.joinToString(separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape(escapeLineSeparators = false) else it.text
}
.let { if (marginPrefix != null) it.trimMargin(marginPrefix) else it.trimIndent() }
.escapeLineSeparators()
return TrimIndentCall(qualifiedExpression, stringTemplateText)
}
private data class TrimIndentCall(
val qualifiedExpression: KtQualifiedExpression,
val stringTemplateText: String
)
}
| apache-2.0 | 858b038c9d13ddbc80267ea8fea3c3b1 | 41.637255 | 158 | 0.682686 | 5.41594 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowStandaloneDiffFromLogActionProvider.kt | 4 | 1330 | // 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.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
class ShowStandaloneDiffFromLogActionProvider : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(VcsLogInternalDataKeys.MAIN_UI) != null && e.getData(ChangesBrowserBase.DATA_KEY) == null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
val project = e.project
val logUi = e.getData(VcsLogInternalDataKeys.MAIN_UI)
if (project == null || logUi == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = logUi.changesBrowser.canShowDiff()
}
override fun actionPerformed(e: AnActionEvent) {
ChangesBrowserBase.showStandaloneDiff(e.project!!, e.getRequiredData(VcsLogInternalDataKeys.MAIN_UI).changesBrowser)
}
} | apache-2.0 | 69da5433ab817507ba94f784ad872e4a | 39.333333 | 120 | 0.780451 | 4.586207 | false | false | false | false |
GunoH/intellij-community | platform/analysis-api/src/com/intellij/openapi/fileEditor/FileEditorComposite.kt | 2 | 1291 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.fileEditor
import com.intellij.openapi.util.Pair
import org.jetbrains.annotations.ApiStatus.Internal
interface FileEditorComposite {
companion object {
@Internal
val EMPTY: FileEditorComposite = object : FileEditorComposite {
override val allEditors: List<FileEditor>
get() = emptyList()
override val allProviders: List<FileEditorProvider>
get() = emptyList()
override val isPreview: Boolean
get() = false
}
fun fromPair(pair: Pair<Array<FileEditor>, Array<FileEditorProvider>>): FileEditorComposite {
return object : FileEditorComposite {
override val allEditors: List<FileEditor>
get() = pair.getFirst().asList()
override val allProviders: List<FileEditorProvider>
get() = pair.getSecond().asList()
override val isPreview: Boolean
get() = false
}
}
}
val allEditors: List<FileEditor>
val allProviders: List<FileEditorProvider>
val isPreview: Boolean
@Internal
fun retrofit(): Pair<Array<FileEditor>, Array<FileEditorProvider>> = Pair(allEditors.toTypedArray(), allProviders.toTypedArray())
}
| apache-2.0 | 4c463fd187beadaa92b50bf0bce324e1 | 33.891892 | 131 | 0.702556 | 4.677536 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/namespacePackages/PyNamespacePackageRootProvider.kt | 3 | 3678 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.namespacePackages
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.actions.ContentEntryEditingAction
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.ui.JBColor
import com.intellij.util.containers.MultiMap
import com.jetbrains.python.PyBundle
import com.jetbrains.python.module.PyContentEntriesEditor
import com.jetbrains.python.module.PyRootTypeProvider
import java.awt.Color
import javax.swing.Icon
import javax.swing.JTree
class PyNamespacePackageRootProvider: PyRootTypeProvider() {
private val myNamespacePackages = MultiMap<ContentEntry, VirtualFilePointer>()
init {
if (!Registry.`is`("python.explicit.namespace.packages")) {
throw ExtensionNotApplicableException.create()
}
}
override fun reset(disposable: Disposable, editor: PyContentEntriesEditor, module: Module) {
myNamespacePackages.clear()
val namespacePackages = PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles
for (namespacePackage in namespacePackages) {
val contentEntry = findContentEntryForFile(namespacePackage, editor) ?: continue
val pointer = VirtualFilePointerManager.getInstance().create(namespacePackage, disposable, DUMMY_LISTENER)
myNamespacePackages.putValue(contentEntry, pointer)
}
}
override fun apply(module: Module) {
val instance = PyNamespacePackagesService.getInstance(module)
val currentNamespacePackages = getCurrentNamespacePackages()
if (!Comparing.haveEqualElements(instance.namespacePackageFoldersVirtualFiles, currentNamespacePackages)) {
instance.namespacePackageFoldersVirtualFiles = currentNamespacePackages
PyNamespacePackagesStatisticsCollector.logApplyInNamespacePackageRootProvider()
}
}
override fun isModified(module: Module): Boolean =
!Comparing.haveEqualElements(PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles,
getCurrentNamespacePackages())
override fun getRoots(): MultiMap<ContentEntry, VirtualFilePointer> = myNamespacePackages
override fun getIcon(): Icon {
return AllIcons.Nodes.Package
}
override fun getName(): String {
return PyBundle.message("python.namespace.packages.name")
}
override fun getDescription(): String {
return PyBundle.message("python.namespace.packages.description")
}
override fun getRootsGroupColor(): Color {
return EASTERN_BLUE
}
override fun createRootEntryEditingAction(tree: JTree?,
disposable: Disposable?,
editor: PyContentEntriesEditor?,
model: ModifiableRootModel?): ContentEntryEditingAction {
return RootEntryEditingAction(tree, disposable, editor, model)
}
private fun getCurrentNamespacePackages(): List<VirtualFile> = myNamespacePackages.values().mapNotNull { it.file }
companion object {
private val EASTERN_BLUE: Color = JBColor(0x29A5AD, 0x29A5AD)
}
} | apache-2.0 | b3318455992afddfad6e0b314d32bde6 | 41.287356 | 120 | 0.771071 | 5.194915 | false | false | false | false |
asedunov/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInspection/Java9AccessCanBeTightenedTest.kt | 1 | 2812 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInspection
import com.intellij.codeInspection.java19modules.Java9ModuleEntryPoint
import com.intellij.codeInspection.visibility.VisibilityInspection
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
class Java9AccessCanBeTightenedTest : LightCodeInsightFixtureTestCase() {
override fun getTestDataPath() = PathManagerEx.getTestDataPath() + "/inspection/java9AccessCanBeTightened/"
override fun getProjectDescriptor(): LightProjectDescriptor = JAVA_9
private lateinit var inspection: VisibilityInspection
override fun setUp() {
super.setUp()
inspection = createGlobalTool()
myFixture.enableInspections(inspection.sharedLocalInspectionTool!!)
}
fun testPublicClass() = doTestClass()
fun testPublicClassOff() = doTestClass()
fun testExportedPackage() = doTestClass()
fun testExportedPackageOff() = doTestClass()
fun testDeclaredService() = doTestService()
fun testDeclaredServiceOff() = doTestService()
fun testUsedService() = doTestService()
fun testUsedServiceOff() = doTestService()
private fun doTestClass() = doTest("Public")
private fun doTestService() = doTest("Service")
private fun doTest(className: String) {
val testName = getTestName(true)
val enabled = !testName.endsWith("Off")
inspection.setEntryPointEnabled(Java9ModuleEntryPoint.ID, enabled)
addModuleInfo(testDataPath + testName)
myFixture.configureByFiles("$testName/foo/bar/$className.java")
myFixture.checkHighlighting()
}
private fun addModuleInfo(path: String) {
val sourceFile = FileUtil.findFirstThatExist("$path/module-info.java")
val text = String(FileUtil.loadFileText(sourceFile!!))
val moduleInfo = myFixture.configureByText("module-info.java", text)
myFixture.allowTreeAccessForFile(moduleInfo.virtualFile)
}
private fun createGlobalTool() = VisibilityInspection().apply {
SUGGEST_PRIVATE_FOR_INNERS = true
SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES = true
SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS = true
}
} | apache-2.0 | 940644b581c78a3bd0008051c6193528 | 35.064103 | 109 | 0.771693 | 4.542811 | false | true | false | false |
ktorio/ktor | ktor-utils/posix/src/io/ktor/util/collections/ConcurrentMapNative.kt | 1 | 2548 | // ktlint-disable filename
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util.collections
import kotlinx.atomicfu.locks.*
/**
* Ktor concurrent map implementation. Please do not use it.
*/
public actual class ConcurrentMap<Key, Value> public actual constructor(
initialCapacity: Int
) : MutableMap<Key, Value> {
private val delegate = LinkedHashMap<Key, Value>(initialCapacity)
private val lock = SynchronizedObject()
/**
* Computes [block] and inserts result in map. The [block] will be evaluated at most once.
*/
public actual fun computeIfAbsent(key: Key, block: () -> Value): Value = synchronized(lock) {
if (delegate.containsKey(key)) return delegate[key]!!
val value = block()
delegate[key] = value
return value
}
override val size: Int
get() = delegate.size
override fun containsKey(key: Key): Boolean = synchronized(lock) { delegate.containsKey(key) }
override fun containsValue(value: Value): Boolean = synchronized(lock) { delegate.containsValue(value) }
override fun get(key: Key): Value? = synchronized(lock) { delegate[key] }
override fun isEmpty(): Boolean = delegate.isEmpty()
override val entries: MutableSet<MutableMap.MutableEntry<Key, Value>>
get() = synchronized(lock) { delegate.entries }
override val keys: MutableSet<Key>
get() = synchronized(lock) { delegate.keys }
override val values: MutableCollection<Value>
get() = synchronized(lock) { delegate.values }
override fun clear() {
synchronized(lock) {
delegate.clear()
}
}
override fun put(key: Key, value: Value): Value? = synchronized(lock) { delegate.put(key, value) }
override fun putAll(from: Map<out Key, Value>) {
synchronized(lock) {
delegate.putAll(from)
}
}
override fun remove(key: Key): Value? = synchronized(lock) { delegate.remove(key) }
public actual fun remove(key: Key, value: Value): Boolean = synchronized(lock) {
if (delegate[key] != value) return false
delegate.remove(key)
return true
}
override fun hashCode(): Int = synchronized(lock) { delegate.hashCode() }
override fun equals(other: Any?): Boolean = synchronized(lock) {
if (other !is Map<*, *>) return false
return other == delegate
}
override fun toString(): String = "ConcurrentMapJs by $delegate"
}
| apache-2.0 | 265615563c195c3867f72c2ff3c30d1f | 31.253165 | 119 | 0.656201 | 4.304054 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opus/src/templates/kotlin/opus/templates/OpusFile.kt | 4 | 85102 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opus.templates
import opus.*
import org.lwjgl.generator.*
val OpusFile = "OpusFile".nativeClass(Module.OPUS, prefix = "OP", prefixMethod = "opus_", binding = OPUS_BINDING_DELEGATE) {
documentation =
"""
<h3>Introduction</h3>
This is the documentation for the <b>libopusfile</b> C API.
The libopusfile package provides a convenient high-level API for decoding and basic manipulation of all Ogg Opus audio streams. libopusfile is
implemented as a layer on top of Xiph.Org's reference ${url("https://www.xiph.org/ogg/doc/libogg/reference.html", "libogg")} and
${url("https://opus-codec.org/docs/opus_api-1.3.1/", "libopus")} libraries.
libopusfile provides several sets of built-in routines for file/stream access, and may also use custom stream I/O routines provided by the embedded
environment. There are built-in I/O routines provided for ANSI-compliant {@code stdio} ({@code FILE *}), memory buffers, and URLs (including
{@code file:} URLs, plus optionally {@code http:} and {@code https:} URLs).
<h3>Organization</h3>
The main API is divided into several sections:
${ul(
"stream_open_close",
"stream_info",
"stream_decoding",
"stream_seeking"
)}
Several additional sections are not tied to the main API.
${ul(
"stream_callbacks",
"header_info",
"error_codes"
)}
<h3>Overview</h3>
The libopusfile API always decodes files to 48 kHz. The original sample rate is not preserved by the lossy compression, though it is stored in the
header to allow you to resample to it after decoding (the libopusfile API does not currently provide a resampler, but the
${url("https://www.speex.org/docs/manual/speex-manual/node7.html\\#SECTION00760000000000000000", "the Speex resampler")} is a good choice if you need
one). In general, if you are playing back the audio, you should leave it at 48 kHz, provided your audio hardware supports it. When decoding to a file,
it may be worth resampling back to the original sample rate, so as not to surprise users who might not expect the sample rate to change after encoding
to Opus and decoding.
Opus files can contain anywhere from 1 to 255 channels of audio. The channel mappings for up to 8 channels are the same as the
${url("https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html\\#x1-810004.3.9", "Vorbis mappings")}. A special stereo API can convert everything to 2
channels, making it simple to support multichannel files in an application which only has stereo output. Although the libopusfile ABI provides support
for the theoretical maximum number of channels, the current implementation does not support files with more than 8 channels, as they do not have
well-defined channel mappings.
Like all Ogg files, Opus files may be "chained". That is, multiple Opus files may be combined into a single, longer file just by concatenating the
original files. This is commonly done in internet radio streaming, as it allows the title and artist to be updated each time the song changes, since
each link in the chain includes its own set of metadata.
libopusfile fully supports chained files. It will decode the first Opus stream found in each link of a chained file (ignoring any other streams that
might be concurrently multiplexed with it, such as a video stream).
The channel count can also change between links. If your application is not prepared to deal with this, it can use the stereo API to ensure the audio
from all links will always get decoded into a common format. Since libopusfile always decodes to 48 kHz, you do not have to worry about the sample rate
changing between links (as was possible with Vorbis). This makes application support for chained files with libopusfile very easy.
"""
EnumConstant(
"Error codes.",
"FALSE".enum("A request did not succeed.", "-1"),
"EOF".enum("Currently not used externally.", "-2"),
"HOLE".enum("There was a hole in the page sequence numbers (e.g., a page was corrupt or missing).", "-3"),
"EREAD".enum("An underlying read, seek, or tell operation failed when it should have succeeded.", "-128"),
"EFAULT".enum(
"A #NULL pointer was passed where one was unexpected, or an internal memory allocation failed, or an internal library error was encountered.",
"-129"
),
"EIMPL".enum("The stream used a feature that is not implemented, such as an unsupported channel family.", "-130"),
"EINVAL".enum("One or more parameters to a function were invalid.", "-131"),
"ENOTFORMAT".enum(
"""
A purported Ogg Opus stream did not begin with an Ogg page, a purported header packet did not start with one of the required strings, "OpusHead" or
"OpusTags", or a link in a chained file was encountered that did not contain any logical Opus streams.
""",
"-132"
),
"EBADHEADER".enum("A required header packet was not properly formatted, contained illegal values, or was missing altogether.", "-133"),
"EVERSION".enum("The ID header contained an unrecognized version number", "-134"),
"ENOTAUDIO".enum("Currently not used at all.", "-135"),
"EBADPACKET".enum(
"""
An audio packet failed to decode properly. This is usually caused by a multistream Ogg packet where the durations of the individual Opus packets
contained in it are not all the same.
""",
"-136"
),
"EBADLINK".enum(
"""
We failed to find data we had seen before, or the bitstream structure was sufficiently malformed that seeking to the target destination was
impossible.
""",
"-137"
),
"ENOSEEK".enum("An operation that requires seeking was requested on an unseekable stream.", "-138"),
"EBADTIMESTAMP".enum("The first or last granule position of a link failed basic validity checks.", "-139")
)
IntConstant("", "OPUS_CHANNEL_COUNT_MAX".."255").noPrefix()
EnumConstant(
"Picture tag image formats.",
"PIC_FORMAT_UNKNOWN".enum("The MIME type was not recognized, or the image data did not match the declared MIME type.", "-1"),
"PIC_FORMAT_URL".enum("The MIME type indicates the image data is really a URL.", "0"),
"PIC_FORMAT_JPEG".enum("The image is a JPEG.", "1"),
"PIC_FORMAT_PNG".enum("The image is a PNG.", "2"),
"PIC_FORMAT_GIF".enum("The image is a GIF.", "3")
)
IntConstant(
"These are the raw numbers used to define the request codes. They should not be used directly.",
"SSL_SKIP_CERTIFICATE_CHECK_REQUEST".."6464",
"HTTP_PROXY_HOST_REQUEST".."6528",
"HTTP_PROXY_PORT_REQUEST".."6592",
"HTTP_PROXY_USER_REQUEST".."6656",
"HTTP_PROXY_PASS_REQUEST".."6720",
"GET_SERVER_INFO_REQUEST".."6784"
)
IntConstant(
"Indicates that the decoding callback should produce signed 16-bit native-endian output samples.",
"DEC_FORMAT_SHORT".."7008"
)
IntConstant(
"Indicates that the decoding callback should produce 32-bit native-endian float samples.",
"DEC_FORMAT_FLOAT".."7040"
)
IntConstant(
"Indicates that the decoding callback did not decode anything, and that libopusfile should decode normally instead.",
"DEC_USE_DEFAULT".."6720"
)
IntConstant(
"""
Gain offset type that indicates that the provided offset is relative to the header gain.
This is the default.
""",
"HEADER_GAIN".."0"
)
IntConstant(
"Gain offset type that indicates that the provided offset is relative to the {@code R128_ALBUM_GAIN} value (if any), in addition to the header gain.",
"ALBUM_GAIN".."3007"
)
IntConstant(
"Gain offset type that indicates that the provided offset is relative to the {@code R128_TRACK_GAIN} value (if any), in addition to the header gain.",
"TRACK_GAIN".."3008"
)
IntConstant(
"Gain offset type that indicates that the provided offset should be used as the gain directly, without applying any the header or track gains.",
"ABSOLUTE_GAIN".."3009"
)
int(
"head_parse",
"Parses the contents of the ID header packet of an Ogg Opus stream.",
OpusHead.p(
"_head",
"""
returns the contents of the parsed packet. The contents of this structure are untouched on error. This may be #NULL to merely test the header for
validity.
"""
),
unsigned_char.const.p("_data", "the contents of the ID header packet"),
AutoSize("_data")..size_t("_len", "the number of bytes of data in the ID header packet"),
returnDoc =
"""
0 on success or a negative value on error:
${ul(
"#ENOTFORMAT If the data does not start with the \"OpusHead\" string.",
"#EVERSION If the version field signaled a version this library does not know how to parse.",
"#EIMPL If the channel mapping family was 255, which general purpose players should not attempt to play.",
"""
#EBADHEADER If the contents of the packet otherwise violate the Ogg Opus specification:
${ul(
"Insufficient data",
"Too much data for the known minor versions",
"An unrecognized channel mapping family",
"Zero channels or too many channels",
"Zero coded streams",
"Too many coupled streams, or",
"An invalid channel mapping index"
)}
"""
)}
"""
)
ogg_int64_t(
"granule_sample",
"""
Converts a granule position to a sample offset for a given Ogg Opus stream.
The sample offset is simply {@code _gp-_head->pre_skip}. Granule position values smaller than ##OpusHead{@code ::pre_skip} correspond to audio that
should never be played, and thus have no associated sample offset. This function returns {@code -1} for such values. This function also correctly
handles extremely large granule positions, which may have wrapped around to a negative number when stored in a signed {@code ogg_int64_t} value.
""",
OpusHead.const.p("_head", "the {@code OpusHead} information from the ID header of the stream"),
ogg_int64_t("_gp", "the granule position to convert"),
returnDoc =
"""
the sample offset associated with the given granule position (counting at a 48 kHz sampling rate), or the special value {@code -1} on error (i.e., the
granule position was smaller than the pre-skip amount)
"""
)
int(
"tags_parse",
"Parses the contents of the 'comment' header packet of an Ogg Opus stream.",
nullable..OpusTags.p(
"_tags",
"""
an uninitialized {@code OpusTags} structure. This returns the contents of the parsed packet. The contents of this structure are untouched on error.
This may be #NULL to merely test the header for validity.
"""
),
unsigned_char.const.p("_data", "the contents of the 'comment' header packet"),
AutoSize("_data")..size_t("_len", "the number of bytes of data in the 'info' header packet"),
returnDoc =
"""
${ul(
"{@code 0}: Success",
"#ENOTFORMAT If the data does not start with the \"OpusTags\" string",
"#EBADHEADER If the contents of the packet otherwise violate the Ogg Opus specification",
"#EFAULT If there wasn't enough memory to store the tags"
)}
"""
)
int(
"tags_copy",
"Performs a deep copy of an {@code OpusTags} structure.",
OpusTags.p("_dst", "the {@code OpusTags} structure to copy into. If this function fails, the contents of this structure remain untouched."),
OpusTags.const.p("_src", "the {@code OpusTags} structure to copy from"),
returnDoc =
"""
${ul(
"{@code 0}: Success",
"#EFAULT If there wasn't enough memory to copy the tags"
)}
"""
)
void(
"tags_init",
"Initializes an {@code OpusTags} structure. This should be called on a freshly allocated {@code OpusTags} structure before attempting to use it.",
OpusTags.p("_tags", "the {@code OpusTags} structure to initialize")
)
int(
"tags_add",
"""
Add a (tag, value) pair to an initialized {@code OpusTags} structure.
${note("""
Neither {@code opus_tags_add()} nor #tags_add_comment() support values containing embedded {@code NUL}s, although the bitstream format does support
them. To add such tags, you will need to manipulate the {@code OpusTags} structure directly.
""")}
""",
OpusTags.p("_tags", "the {@code OpusTags} structure to add the (tag, value) pair to"),
charASCII.const.p("_tag", "a {@code NUL}-terminated, case-insensitive, ASCII string containing the tag to add (without an {@code '='} character)"),
charUTF8.const.p("_value", "a {@code NUL}-terminated UTF-8 containing the corresponding value"),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"#EFAULT An internal memory allocation failed"
)}
"""
)
int(
"tags_add_comment",
"""
Add a comment to an initialized {@code OpusTags} structure.
${note("""
Neither {@code opus_tags_add_comment()} nor #tags_add() support comments containing embedded {@code NUL}s, although the bitstream format does support
them. To add such tags, you will need to manipulate the {@code OpusTags} structure directly.
""")}
""",
OpusTags.p("_tags", "the {@code OpusTags} structure to add the comment to"),
charUTF8.const.p("_comment", "a {@code NUL}-terminated UTF-8 string containing the comment in {@code \"TAG=value\"} form"),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"#EFAULT An internal memory allocation failed"
)}
"""
)
int(
"tags_set_binary_suffix",
"Replace the binary suffix data at the end of the packet (if any).",
OpusTags.p("_tags", "an initialized {@code OpusTags} structure"),
nullable..unsigned_char.const.p(
"_data",
"""
a buffer of binary data to append after the encoded user comments. The least significant bit of the first byte of this data must be set (to ensure
the data is preserved by other editors).
"""
),
AutoSize("_data")..int("_len", "the number of bytes of binary data to append. This may be zero to remove any existing binary suffix data."),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"""
#EINVAL {@code _len} was negative, or {@code _len} was positive but {@code _data} was #NULL or the least significant bit of the first byte was not
set
""",
"#EFAULT An internal memory allocation failed"
)}
"""
)
charUTF8.const.p(
"tags_query",
"Look up a comment value by its tag.",
OpusTags.const.p("_tags", "an initialized {@code OpusTags} structure"),
charASCII.const.p("_tag", "the tag to look up"),
int(
"_count",
"""
the instance of the tag.
The same tag can appear multiple times, each with a distinct value, so an index is required to retrieve them all. The order in which these values
appear is significant and should be preserved. Use #tags_query_count() to get the legal range for the {@code _count} parameter.
"""
),
returnDoc =
"""
a pointer to the queried tag's value.
This points directly to data in the {@code OpusTags} structure. It should not be modified or freed by the application, and modifications to the
structure may invalidate the pointer. #NULL if no matching tag is found.
"""
)
int(
"tags_query_count",
"""
Look up the number of instances of a tag.
Call this first when querying for a specific tag and then iterate over the number of instances with separate calls to #tags_query() to retrieve all the
values for that tag in order.
""",
OpusTags.const.p("_tags", "an initialized {@code OpusTags} structure"),
charASCII.const.p("_tag", "the tag to look up"),
returnDoc = "the number of instances of this particular tag"
)
unsigned_char.const.p(
"tags_get_binary_suffix",
"Retrieve the binary suffix data at the end of the packet (if any).",
OpusTags.const.p("_tags", "an initialized {@code OpusTags} structure"),
AutoSizeResult..Check(1)..int.p("_len", "returns the number of bytes of binary suffix data returned"),
returnDoc = "a pointer to the binary suffix data, or #NULL if none was present"
)
int(
"tags_get_album_gain",
"""
Get the album gain from an {@code R128_ALBUM_GAIN} tag, if one was specified. This searches for the first {@code R128_ALBUM_GAIN} tag with a valid
signed, 16-bit decimal integer value and returns the value. This routine is exposed merely for convenience for applications which wish to do something
special with the album gain (i.e., display it). If you simply wish to apply the album gain instead of the header gain, you can use
#op_set_gain_offset() with an #ALBUM_GAIN type and no offset.
""",
OpusTags.const.p("_tags", "an initialized {@code OpusTags} structure"),
Check(1)..int.p(
"_gain_q8",
"""
the album gain, in {@code 1/256ths} of a dB. This will lie in the range {@code [-32768,32767]}, and should be applied in <em>addition</em> to the
header gain. On error, no value is returned, and the previous contents remain unchanged.
"""
),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"#FALSE There was no album gain available in the given tags"
)}
"""
)
int(
"tags_get_track_gain",
"""
Get the track gain from an {@code R128_TRACK_GAIN} tag, if one was specified.
This searches for the first {@code R128_TRACK_GAIN} tag with a valid signed, 16-bit decimal integer value and returns the value. This routine is
exposed merely for convenience for applications which wish to do something special with the track gain (i.e., display it). If you simply wish to apply
the track gain instead of the header gain, you can use #op_set_gain_offset() with an #TRACK_GAIN type and no offset.
""",
OpusTags.const.p("_tags", "an initialized {@code OpusTags} structure"),
Check(1)..int.p(
"_gain_q8",
"""
the track gain, in {@code 1/256ths} of a dB. This will lie in the range {@code [-32768,32767]}, and should be applied in <em>addition</em> to the
header gain. On error, no value is returned, and the previous contents remain unchanged.
"""
),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"#FALSE There was no track gain available in the given tags"
)}
"""
)
void(
"tags_clear",
"""
Clears the {@code OpusTags} structure.
This should be called on an {@code OpusTags} structure after it is no longer needed. It will free all memory used by the structure members.
""",
OpusTags.p("_tags", "the {@code OpusTags} structure to clear")
)
int(
"tagcompare",
"Check if {@code _comment} is an instance of a {@code _tag_name} tag.",
charASCII.const.p(
"_tag_name",
"a {@code NUL}-terminated, case-insensitive, ASCII string containing the name of the tag to check for (without the terminating {@code '='} character)"
),
charUTF8.const.p("_comment", "the comment string to check"),
returnDoc =
"""
an integer less than, equal to, or greater than zero if {@code _comment} is found respectively, to be less than, to match, or be greater than a
{@code "tag=value"} string whose tag matches {@code _tag_name}
"""
)
int(
"tagncompare",
"""
Check if {@code _comment} is an instance of a {@code _tag_name} tag.
This version is slightly more efficient than #tagcompare() if the length of the tag name is already known (e.g., because it is a constant).
""",
charASCII.const.p(
"_tag_name",
"a case-insensitive ASCII string containing the name of the tag to check for (without the terminating {@code '='} character)"
),
AutoSize("_tag_name")..int("_tag_len", "the number of characters in the tag name. This must be non-negative."),
charUTF8.const.p("_comment", "the comment string to check"),
returnDoc =
"""
an integer less than, equal to, or greater than zero if {@code _comment} is found respectively, to be less than, to match, or be greater than a
{@code "tag=value"} string whose tag matches the first {@code _tag_len} characters of {@code _tag_name}
"""
)
int(
"picture_tag_parse",
"""
Parse a single {@code METADATA_BLOCK_PICTURE} tag.
This decodes the BASE64-encoded content of the tag and returns a structure with the MIME type, description, image parameters (if known), and the
compressed image data. If the MIME type indicates the presence of an image format we recognize (JPEG, PNG, or GIF) and the actual image data contains
the magic signature associated with that format, then the ##OpusPictureTag{@code ::format} field will be set to the corresponding format. This is
provided as a convenience to avoid requiring applications to parse the MIME type and/or do their own format detection for the commonly used formats. In
this case, we also attempt to extract the image parameters directly from the image data (overriding any that were present in the tag, which the
specification says applications are not meant to rely on). The application must still provide its own support for actually decoding the image data and,
if applicable, retrieving that data from URLs.
""",
OpusPictureTag.p(
"_pic",
"""
returns the parsed picture data.
No sanitation is done on the type, MIME type, or description fields, so these might return invalid values. The contents of this structure are left
unmodified on failure.
"""
),
charASCII.const.p(
"_tag",
"""
the {@code METADATA_BLOCK_PICTURE} tag contents. The leading {@code "METADATA_BLOCK_PICTURE="} portion is optional, to allow the function to be
used on either directly on the values in ##OpusTags{@code ::user_comments} or on the return value of #tags_query().
"""
),
returnDoc =
"""
0 on success, or a negative value on failure:
${ul(
"#ENOTFORMAT The METADATA_BLOCK_PICTURE contents were not valid",
"#EFAULT There was not enough memory to store the picture tag contents"
)}
"""
)
void(
"picture_tag_init",
"""
Initializes an {@code OpusPictureTag} structure. This should be called on a freshly allocated {@code OpusPictureTag} structure before attempting to use
it.
""",
OpusPictureTag.p("_pic", "the {@code OpusPictureTag} structure to initialize")
)
void(
"picture_tag_clear",
"""
Clears the {@code OpusPictureTag} structure.
This should be called on an {@code OpusPictureTag} structure after it is no longer needed. It will free all memory used by the structure members.
""",
OpusPictureTag.p("_pic", "the {@code OpusPictureTag} structure to clear")
)
/*void(
"server_info_init",
"""
Initializes an {@code OpusServerInfo} structure.
All fields are set as if the corresponding header was not available.
""",
OpusServerInfo.p("_info", "the {@code OpusServerInfo} structure to initialize")
)
void(
"server_info_clear",
"""
Clears the {@code OpusServerInfo} structure.
This should be called on an {@code OpusServerInfo} structure after it is no longer needed. It will free all memory used by the structure members.
""",
OpusServerInfo.p("_info", "the {@code OpusServerInfo} structure to clear")
)*/
opaque_p(
"op_fopen",
"""
Opens a stream with {@code fopen()} and fills in a set of callbacks that can be used to access it.
This is useful to avoid writing your own portable 64-bit seeking wrappers, and also avoids cross-module linking issues on Windows, where a
{@code FILE *} must be accessed by routines defined in the same module that opened it.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this file. If there is an error opening the file, nothing will be filled in here."),
charUTF8.const.p(
"_path",
"""
the path to the file to open. On Windows, this string must be UTF-8 (to allow access to files whose names cannot be represented in the current MBCS
code page). All other systems use the native character encoding.
"""
),
charASCII.const.p("_mode", "the mode to open the file in"),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)
opaque_p(
"op_fdopen",
"""
Opens a stream with {@code fdopen()} and fills in a set of callbacks that can be used to access it.
This is useful to avoid writing your own portable 64-bit seeking wrappers, and also avoids cross-module linking issues on Windows, where a
{@code FILE *} must be accessed by routines defined in the same module that opened it.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this file. If there is an error opening the file, nothing will be filled in here."),
int("_fd", "the file descriptor to open"),
charASCII.const.p("_mode", "the mode to open the file in"),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)
opaque_p(
"op_freopen",
"""
Opens a stream with {@code freopen()} and fills in a set of callbacks that can be used to access it.
This is useful to avoid writing your own portable 64-bit seeking wrappers, and also avoids cross-module linking issues on Windows, where a
{@code FILE *} must be accessed by routines defined in the same module that opened it.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this file. If there is an error opening the file, nothing will be filled in here."),
charUTF8.const.p(
"_path",
"""
the path to the file to open. On Windows, this string must be UTF-8 (to allow access to files whose names cannot be represented in the current MBCS
code page). All other systems use the native character encoding.
"""
),
charASCII.const.p("_mode", "the mode to open the file in"),
opaque_p("_stream", "a stream previously returned by #op_fopen(), #op_fdopen(), or #op_freopen()"),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)
opaque_p(
"op_mem_stream_create",
"""
Creates a stream that reads from the given block of memory.
This block of memory must contain the complete stream to decode. This is useful for caching small streams (e.g., sound effects) in RAM.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this stream. If there is an error creating the stream, nothing will be filled in here."),
unsigned_char.const.p("_data", "the block of memory to read from"),
AutoSize("_data")..size_t("_size", "the size of the block of memory"),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)
/*opaque_p(
"op_url_stream_vcreate",
"""
Creates a stream that reads from the given URL.
This function behaves identically to #op_url_stream_create(), except that it takes a va_list instead of a variable number of arguments. It does not call
the {@code va_end} macro, and because it invokes the {@code va_arg} macro, the value of {@code _ap} is undefined after the call.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this stream. If there is an error creating the stream, nothing will be filled in here."),
charUTF8.const.p(
"_url",
"""
the URL to read from.
Currently only the {@code file :}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled
at compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
va_list("_ap", "a list of the \"optional flags\" to use. This is a variable-length list of options terminated with #NULL."),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)
opaque_p(
"op_url_stream_create",
"""
Creates a stream that reads from the given URL.
<b>LWJGL note</b>: This is a vararg function that should be called with {@link Functions\#op_url_stream_create op_url_stream_create} via the libffi
bindings.
""",
OpusFileCallbacks.p("_cb", "the callbacks to use for this stream. If there is an error creating the stream, nothing will be filled in here."),
charUTF8.const.p(
"_url",
"""
the URL to read from.
Currently only the {@code file:}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled at
compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
returnDoc = "a stream handle to use with the callbacks, or #NULL on error",
noPrefix = true
)*/
int(
"op_test",
"""
Test to see if this is an Opus stream.
For good results, you will need at least 57 bytes (for a pure Opus-only stream). Something like 512 bytes will give more reliable results for
multiplexed streams. This function is meant to be a quick-rejection filter. Its purpose is not to guarantee that a stream is a valid Opus stream, but
to ensure that it looks enough like Opus that it isn't going to be recognized as some other format (except possibly an Opus stream that is also
multiplexed with other codecs, such as video).
""",
nullable..OpusHead.p(
"_head",
"""
the parsed ID header contents. You may pass #NULL if you do not need this information. If the function fails, the contents of this structure remain
untouched.
"""
),
unsigned_char.const.p("_initial_data", "an initial buffer of data from the start of the stream"),
AutoSize("_initial_data")..size_t("_initial_bytes", "the number of bytes in {@code _initial_data}"),
returnDoc =
"""
0 if the data appears to be Opus, or a negative value on error.
${ul(
"#FALSE There was not enough data to tell if this was an Opus stream or not",
"#EFAULT An internal memory allocation failed",
"#EIMPL The stream used a feature that is not implemented, such as an unsupported channel family",
"#ENOTFORMAT If the data did not contain a recognizable ID header for an Opus stream",
"#EVERSION If the version field signaled a version this library does not know how to parse",
"#EBADHEADER The ID header was not properly formatted or contained illegal values"
)}
""",
noPrefix = true
)
OggOpusFile.p(
"op_open_file",
"Open a stream from the given file path.",
charUTF8.const.p("_path", "the path to the file to open"),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. The failure code will be #EFAULT if the file could not be opened, or one of the other
failure codes from #op_open_callbacks() otherwise.
"""
),
returnDoc = "a freshly opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
OggOpusFile.p(
"op_open_memory",
"Open a stream from a memory buffer.",
unsigned_char.const.p("_data", "the memory buffer to open"),
AutoSize("_data")..size_t("_size", "the number of bytes in the buffer"),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
returnDoc = "a freshly opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
/*OggOpusFile.p(
"op_vopen_url",
"""
Open a stream from a URL.
This function behaves identically to #op_open_url(), except that it takes a {@code va_list} instead of a variable number of arguments. It does not call
the {@code va_end} macro, and because it invokes the {@code va_arg} macro, the value of {@code _ap} is undefined after the call.
""",
charUTF8.const.p(
"_url",
"""
the URL to open.
Currently only the {@code file:}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled at
compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
va_list("_ap", "a list of the \"optional flags\" to use. This is a variable-length list of options terminated with #NULL."),
returnDoc = "a freshly opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
OggOpusFile.p(
"op_open_url",
"""
Open a stream from a URL.
<b>LWJGL note</b>: This is a vararg function that should be called with {@link Functions\#op_open_url op_open_url} via the libffi bindings.
""",
charUTF8.const.p(
"_url",
"""
the URL to open.
Currently only the {@code file:}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled at
compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
returnDoc = "a freshly opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)*/
OggOpusFile.p(
"op_open_callbacks",
"Open a stream using the given set of callbacks to access it.",
opaque_p(
"_stream",
"the stream to read from (e.g., a {@code FILE *}). This value will be passed verbatim as the first argument to all of the callbacks."
),
OpusFileCallbacks.const.p(
"_cb",
"""
the callbacks with which to access the stream.
{@code "read()"} must be implemented. {@code "seek()"} and {@code "tell()"} may be #NULL, or may always return {@code -1} to indicate a stream is
unseekable, but if {@code "seek()"} is implemented and succeeds on a particular stream, then {@code "tell()"} must also. {@code "close()"} may be
#NULL, but if it is not, it will be called when the {@code OggOpusFile} is destroyed by #op_free(). It will not be called if
{@code op_open_callbacks()} fails with an error.
"""
),
unsigned_char.const.p(
"_initial_data",
"""
an initial buffer of data from the start of the stream.
Applications can read some number of bytes from the start of the stream to help identify this as an Opus stream, and then provide them here to
allow the stream to be opened, even if it is unseekable.
"""
),
AutoSize("_initial_data")..size_t(
"_initial_bytes",
"""
the number of bytes in {@code _initial_data}.
If the stream is seekable, its current position (as reported by {@code "tell()"} at the start of this function) must be equal to
{@code _initial_bytes}. Otherwise, seeking to absolute positions will generate inconsistent results.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. The failure code will be one of:
${ul(
"""
#EREAD An underlying read, seek, or tell operation failed when it should have succeeded, or we failed to find data in the stream we had seen before
""",
"#EFAULT There was a memory allocation failure, or an internal library error",
"#EIMPL The stream used a feature that is not implemented, such as an unsupported channel family",
"""
#EINVAL {@code "seek()"} was implemented and succeeded on this source, but {@code "tell()"} did not, or the starting position indicator was not
equal to {@code _initial_bytes}
""",
"#ENOTFORMAT The stream contained a link that did not have any logical Opus streams in it",
"#EBADHEADER A required header packet was not properly formatted, contained illegal values, or was missing altogether",
"#EVERSION An ID header contained an unrecognized version number",
"#EBADLINK We failed to find data we had seen before after seeking",
"#EBADTIMESTAMP The first or last timestamp in a link failed basic validity checks"
)}
"""
),
returnDoc =
"""
a freshly opened {@code OggOpusFile}, or #NULL on error.
libopusfile does <em>not</em> take ownership of the stream if the call fails. The calling application is responsible for closing the stream if this
call returns an error.
""",
noPrefix = true
)
OggOpusFile.p(
"op_test_file",
"Partially open a stream from the given file path.",
charUTF8.const.p("_path", "the path to the file to open"),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. The failure code will be #EFAULT if the file could not be opened, or one of the other
failure codes from #op_open_callbacks() otherwise.
"""
),
returnDoc = "a partially opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
OggOpusFile.p(
"op_test_memory",
"Partially open a stream from a memory buffer.",
unsigned_char.const.p("_data", "the memory buffer to open"),
AutoSize("_data")..size_t("_size", "the number of bytes in the buffer"),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
returnDoc = "a partially opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
/*OggOpusFile.p(
"op_vtest_url",
"""
Partially open a stream from a URL.
This function behaves identically to #op_test_url(), except that it takes a {@code va_list} instead of a variable number of arguments. It does not call
the {@code va_end} macro, and because it invokes the {@code va_arg} macro, the value of {@code _ap} is undefined after the call.
""",
charUTF8.const.p(
"_url",
"""
the URL to open.
Currently only the {@code file:}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled at
compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
va_list("_ap", "a list of the {@code \"optional flags\"} to use. This is a variable-length list of options terminated with #NULL."),
returnDoc = "a partially opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)
OggOpusFile.p(
"op_test_url",
"""
Partially open a stream from a URL.
<b>LWJGL note</b>: This is a vararg function that should be called with {@link Functions\#op_test_url op_test_url} via the libffi bindings.
""",
charUTF8.const.p(
"_url",
"""
the URL to open.
Currently only the {@code file:}, {@code http:}, and {@code https:} schemes are supported. Both {@code http:} and {@code https:} may be disabled at
compile time, in which case opening such URLs will always fail. Currently this only supports URIs. IRIs should be converted to UTF-8 and
URL-escaped, with internationalized domain names encoded in punycode, before passing them to this function.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
returnDoc = "a partially opened {@code OggOpusFile}, or #NULL on error",
noPrefix = true
)*/
OggOpusFile.p(
"op_test_callbacks",
"""
Partially open a stream using the given set of callbacks to access it.
This tests for Opusness and loads the headers for the first link. It does not seek (although it tests for seekability). You can query a partially open
stream for the few pieces of basic information returned by #op_serialno(), #op_channel_count(), #op_head(), and #op_tags() (but only for the first
link). You may also determine if it is seekable via a call to #op_seekable(). You cannot read audio from the stream, seek, get the size or duration,
get information from links other than the first one, or even get the total number of links until you finish opening the stream with #op_test_open(). If
you do not need to do any of these things, you can dispose of it with #op_free() instead.
This function is provided mostly to simplify porting existing code that used libvorbisfile. For new code, you are likely better off using #op_test()
instead, which is less resource-intensive, requires less data to succeed, and imposes a hard limit on the amount of data it examines (important for
unseekable streams, where all such data must be buffered until you are sure of the stream type).
""",
opaque_p(
"_stream",
"the stream to read from (e.g., a {@code FILE *}). This value will be passed verbatim as the first argument to all of the callbacks."
),
OpusFileCallbacks.const.p(
"_cb",
"""
the callbacks with which to access the stream.
{@code "read()"} must be implemented. {@code "seek()"} and {@code "tell()"} may be #NULL, or may always return {@code -1} to indicate a stream is
unseekable, but if {@code "seek()"} is implemented and succeeds on a particular stream, then {@code "tell()"} must also. {@code "close()"} may be
#NULL, but if it is not, it will be called when the {@code OggOpusFile} is destroyed by #op_free(). It will not be called if #op_open_callbacks()
fails with an error.
"""
),
unsigned_char.const.p(
"_initial_data",
"""
an initial buffer of data from the start of the stream.
Applications can read some number of bytes from the start of the stream to help identify this as an Opus stream, and then provide them here to
allow the stream to be tested more thoroughly, even if it is unseekable.
"""
),
AutoSize("_initial_data")..size_t(
"_initial_bytes",
"""
the number of bytes in {@code _initial_data}.
If the stream is seekable, its current position (as reported by {@code "tell()"} at the start of this function) must be equal to
{@code _initial_bytes}. Otherwise, seeking to absolute positions will generate inconsistent results.
"""
),
Check(1)..nullable..int.p(
"_error",
"""
returns 0 on success, or a failure code on error.
You may pass in #NULL if you don't want the failure code. See #op_open_callbacks() for a full list of failure codes.
"""
),
returnDoc =
"""
a partially opened {@code OggOpusFile}, or #NULL on error.
libopusfile does <em>not</em> take ownership of the stream if the call fails. The calling application is responsible for closing the stream if this
call returns an error.
""",
noPrefix = true
)
int(
"op_test_open",
"""
Finish opening a stream partially opened with #op_test_callbacks() or one of the associated convenience functions.
If this function fails, you are still responsible for freeing the {@code OggOpusFile} with #op_free().
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} to finish opening"),
returnDoc =
"""
0 on success, or a negative value on error:
${ul(
"#EREAD An underlying read, seek, or tell operation failed when it should have succeeded",
"#EFAULT There was a memory allocation failure, or an internal library error",
"#EIMPL The stream used a feature that is not implemented, such as an unsupported channel family",
"#EINVAL The stream was not partially opened with #op_test_callbacks() or one of the associated convenience functions",
"#ENOTFORMAT The stream contained a link that did not have any logical Opus streams in it",
"#EBADHEADER A required header packet was not properly formatted, contained illegal values, or was missing altogether",
"#EVERSION An ID header contained an unrecognized version number",
"#EBADLINK We failed to find data we had seen before after seeking",
"#EBADTIMESTAMP The first or last timestamp in a link failed basic validity checks"
)}
""",
noPrefix = true
)
void(
"op_free",
"Release all memory used by an {@code OggOpusFile}.",
OggOpusFile.p("_of", "the {@code OggOpusFile} to free"),
noPrefix = true
)
intb(
"op_seekable",
"""
Returns whether or not the stream being read is seekable.
This is true if
${ol(
"The {@code \"seek()\"} and {@code \"tell()\"} callbacks are both non-#NULL",
"The {@code \"seek()\"} callback was successfully executed at least once, and",
"The {@code \"tell()\"} callback was successfully able to report the position indicator afterwards"
)}
This function may be called on partially-opened streams.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} whose seekable status is to be returned"),
returnDoc = "a non-zero value if seekable, and 0 if unseekable",
noPrefix = true
)
int(
"op_link_count",
"""
Returns the number of links in this chained stream.
This function may be called on partially-opened streams, but it will always return 1. The actual number of links is not known until the stream is fully
opened.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the link count"),
returnDoc =
"""
for fully-open seekable streams, this returns the total number of links in the whole stream, which will be at least 1. For partially-open or unseekable
streams, this always returns 1.
""",
noPrefix = true
)
opus_uint32(
"op_serialno",
"""
Get the serial number of the given link in a (possibly-chained) Ogg Opus stream.
This function may be called on partially-opened streams, but it will always return the serial number of the Opus stream in the first link.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the serial number"),
int("_li", "the index of the link whose serial number should be retrieved. Use a negative number to get the serial number of the current link."),
returnDoc =
"""
the serial number of the given link.
If {@code _li} is greater than the total number of links, this returns the serial number of the last link. If the stream is not seekable, this always
returns the serial number of the current link.
""",
noPrefix = true
)
int(
"op_channel_count",
"""
Get the channel count of the given link in a (possibly-chained) Ogg Opus stream.
This is equivalent to {@code op_head(_of,_li)->channel_count}, but is provided for convenience. This function may be called on partially-opened
streams, but it will always return the channel count of the Opus stream in the first link.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the channel count"),
int("_li", "the index of the link whose channel count should be retrieved. Use a negative number to get the channel count of the current link."),
returnDoc =
"""
the channel count of the given link.
If {@code _li} is greater than the total number of links, this returns the channel count of the last link. If the stream is not seekable, this always
returns the channel count of the current link.
""",
noPrefix = true
)
long_long(
"op_raw_total",
"""
Get the total (compressed) size of the stream, or of an individual link in a (possibly-chained) Ogg Opus stream, including all headers and Ogg muxing
overhead.
Warning: If the Opus stream (or link) is concurrently multiplexed with other logical streams (e.g., video), this returns the size of the entire stream
(or link), not just the number of bytes in the first logical Opus stream. Returning the latter would require scanning the entire file.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the compressed size"),
int("_li", "the index of the link whose compressed size should be computed. Use a negative number to get the compressed size of the entire stream."),
returnDoc =
"""
the compressed size of the entire stream if {@code _li} is negative, the compressed size of link {@code _li} if it is non-negative, or a negative value
on error.
The compressed size of the entire stream may be smaller than that of the underlying stream if trailing garbage was detected in the file.
#EINVAL The stream is not seekable (so we can't know the length),{@code #}_li wasn't less than the total number of links in the stream, or the stream
was only partially open.
""",
noPrefix = true
)
ogg_int64_t(
"op_pcm_total",
"""
Get the total PCM length (number of samples at 48 kHz) of the stream, or of an individual link in a (possibly-chained) Ogg Opus stream.
Users looking for {@code op_time_total()} should use {@code op_pcm_total()} instead. Because timestamps in Opus are fixed at 48 kHz, there is no need for a
separate function to convert this to seconds (and leaving it out avoids introducing floating point to the API, for those that wish to avoid it).
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the PCM offset"),
int("_li", "the index of the link whose PCM length should be computed. Use a negative number to get the PCM length of the entire stream."),
returnDoc =
"""
the PCM length of the entire stream if {@code _li} is negative, the PCM length of link {@code _li} if it is non-negative, or a negative value on error.
#EINVAL The stream is not seekable (so we can't know the length), {@code _li} wasn't less than the total number of links in the stream, or the stream
was only partially open.
""",
noPrefix = true
)
OpusHead.const.p(
"op_head",
"""
Get the ID header information for the given link in a (possibly chained) Ogg Opus stream.
This function may be called on partially-opened streams, but it will always return the ID header information of the Opus stream in the first link.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the ID header information"),
int(
"_li",
"""
the index of the link whose ID header information should be retrieved. Use a negative number to get the ID header information of the current link.
For an unseekable stream, {@code _li} is ignored, and the ID header information for the current link is always returned, if available.
"""
),
returnDoc = "the contents of the ID header for the given link",
noPrefix = true
)
OpusTags.const.p(
"op_tags",
"""
Get the comment header information for the given link in a (possibly chained) Ogg Opus stream.
This function may be called on partially-opened streams, but it will always return the tags from the Opus stream in the first link.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the comment header information"),
int(
"_li",
"""
the index of the link whose comment header information should be retrieved. Use a negative number to get the comment header information of the
current link. For an unseekable stream, {@code _li} is ignored, and the comment header information for the current link is always returned, if
available.
"""
),
returnDoc =
"the contents of the comment header for the given link, or #NULL if this is an unseekable stream that encountered an invalid link",
noPrefix = true
)
int(
"op_current_link",
"""
Retrieve the index of the current link.
This is the link that produced the data most recently read by #op_read_float() or its associated functions, or, after a seek, the link that the seek
target landed in. Reading more data may advance the link index (even on the first read after a seek).
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the current link index"),
returnDoc =
"""
the index of the current link on success, or a negative value on failure.
For seekable streams, this is a number between 0 (inclusive) and the value returned by #op_link_count() (exclusive). For unseekable streams, this value
starts at 0 and increments by one each time a new link is encountered (even though {@code op_link_count()} always returns 1).
#EINVAL The stream was only partially open.
""",
noPrefix = true
)
opus_int32(
"op_bitrate",
"""
Computes the bitrate of the stream, or of an individual link in a (possibly-chained) Ogg Opus stream.
The stream must be seekable to compute the bitrate. For unseekable streams, use #op_bitrate_instant() to get periodic estimates.
Warning: If the Opus stream (or link) is concurrently multiplexed with other logical streams (e.g., video), this uses the size of the entire stream (or
link) to compute the bitrate, not just the number of bytes in the first logical Opus stream. Returning the latter requires scanning the entire file,
but this may be done by decoding the whole file and calling {@code op_bitrate_instant()} once at the end. Install a trivial decoding callback with
#op_set_decode_callback() if you wish to skip actual decoding during this process.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the bitrate"),
int("_li", "the index of the link whose bitrate should be computed. Use a negative number to get the bitrate of the whole stream."),
returnDoc =
"""
the bitrate on success, or a negative value on error.
#EINVAL The stream was only partially open, the stream was not seekable, or {@code _li} was larger than the number of links.
""",
noPrefix = true
)
opus_int32(
"op_bitrate_instant",
"""
Compute the instantaneous bitrate, measured as the ratio of bits to playable samples decoded since
${ol(
"the last call to {@code op_bitrate_instant()},",
"the last seek, or",
"the start of playback, whichever was most recent.",
marker = 'a'
)}
This will spike somewhat after a seek or at the start/end of a chain boundary, as pre-skip, pre-roll, and end-trimming causes samples to be decoded but
not played.
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} from which to retrieve the bitrate"),
returnDoc =
"""
the bitrate, in bits per second, or a negative value on error:
${ul(
"#FALSE No data has been decoded since any of the events described above",
"#EINVAL The stream was only partially open"
)}
""",
noPrefix = true
)
long_long(
"op_raw_tell",
"Obtain the current value of the position indicator for {@code _of}.",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the position indicator"),
returnDoc = "the byte position that is currently being read from. #EINVAL The stream was only partially open.",
noPrefix = true
)
ogg_int64_t(
"op_pcm_tell",
"""
Obtain the PCM offset of the next sample to be read.
If the stream is not properly timestamped, this might not increment by the proper amount between reads, or even return monotonically increasing values.
""",
OggOpusFile.const.p("_of", "the {@code OggOpusFile} from which to retrieve the PCM offset"),
returnDoc = "the PCM offset of the next sample to be read. #EINVAL The stream was only partially open.",
noPrefix = true
)
int(
"op_raw_seek",
"""
Seek to a byte offset relative to the <b>compressed</b> data.
This also scans packets to update the PCM cursor. It will cross a logical bitstream boundary, but only if it can't get any packets out of the tail of
the link to which it seeks.
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} in which to seek"),
long_long("_byte_offset", "the byte position to seek to. This must be between 0 and {@code op_raw_total(_of, -1)} (inclusive)."),
returnDoc =
"""
0 on success, or a negative error code on failure:
${ul(
"#EREAD The underlying seek operation failed",
"#EINVAL The stream was only partially open, or the target was outside the valid range for the stream",
"#ENOSEEK This stream is not seekable",
"#EBADLINK Failed to initialize a decoder for a stream for an unknown reason"
)}
""",
noPrefix = true
)
int(
"op_pcm_seek",
"Seek to the specified PCM offset, such that decoding will begin at exactly the requested position.",
OggOpusFile.p("_of", "the {@code OggOpusFile} in which to seek"),
ogg_int64_t("_pcm_offset", "the PCM offset to seek to. This is in samples at 48 kHz relative to the start of the stream."),
returnDoc =
"""
0 on success, or a negative value on error:
${ul(
"#EREAD An underlying read or seek operation failed",
"#EINVAL The stream was only partially open, or the target was outside the valid range for the stream",
"#ENOSEEK This stream is not seekable",
"""
#EBADLINK We failed to find data we had seen before, or the bitstream structure was sufficiently malformed that seeking to the target destination
was impossible
"""
)}
""",
noPrefix = true
)
void(
"op_set_decode_callback",
"""
Sets the packet decode callback function.
If set, this is called once for each packet that needs to be decoded. This can be used by advanced applications to do additional processing on the
compressed or uncompressed data. For example, an application might save the final entropy coder state for debugging and testing purposes, or it might
apply additional filters before the downmixing, dithering, or soft-clipping performed by {@code libopusfile}, so long as these filters do not introduce
any latency.
A call to this function is no guarantee that the audio will eventually be delivered to the application. libopusfile may discard some or all of the
decoded audio data (i.e., at the beginning or end of a link, or after a seek), however the callback is still required to provide all of it.
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} on which to set the decode callback"),
op_decode_cb_func("_decode_cb", "the callback function to call. This may be #NULL to disable calling the callback."),
opaque_p("_ctx", "the application-provided context pointer to pass to the callback on each call"),
noPrefix = true
)
int(
"op_set_gain_offset",
"""
Sets the gain to be used for decoded output.
By default, the gain in the header is applied with no additional offset. The total gain (including header gain and/or track gain, if applicable, and
this offset), will be clamped to {@code [-32768,32767]/256} dB. This is more than enough to saturate or underflow 16-bit PCM.
${note("""
The new gain will not be applied to any already buffered, decoded output. This means you cannot change it sample-by-sample, as at best it
will be updated packet-by-packet. It is meant for setting a target volume level, rather than applying smooth fades, etc.
""")}
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} on which to set the gain offset"),
int("_gain_type", "", "#HEADER_GAIN, #ALBUM_GAIN, #TRACK_GAIN #ABSOLUTE_GAIN"),
opus_int32("_gain_offset_q8", "the gain offset to apply, in {@code 1/256ths} of a dB"),
returnDoc = "0 on success or a negative value on error. #EINVAL The {@code _gain_type} was unrecognized.",
noPrefix = true
)
void(
"op_set_dither_enabled",
"""
Sets whether or not dithering is enabled for 16-bit decoding.
By default, when libopusfile is compiled to use floating-point internally, calling #op_read() or #op_read_stereo() will first decode to float, and then
convert to fixed-point using noise-shaping dithering. This flag can be used to disable that dithering. When the application uses #op_read_float() or
#op_read_float_stereo(), or when the library has been compiled to decode directly to fixed point, this flag has no effect.
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} on which to enable or disable dithering"),
intb("_enabled", "a non-zero value to enable dithering, or 0 to disable it"),
noPrefix = true
)
int(
"op_read",
"""
Reads more samples from the stream.
${note("""
Although {@code _buf_size} must indicate the total number of values that can be stored in {@code _pcm}, the return value is the number of samples
<em>per channel</em>. This is done because
${ol(
"""
The channel count cannot be known a priori (reading more samples might advance us into the next link, with a different channel count), so
{@code _buf_size} cannot also be in units of samples per channel
""",
"Returning the samples per channel matches the libopus API as closely as we're able",
"""
Returning the total number of values instead of samples per channel would mean the caller would need a division to compute the samples per channel,
and might worry about the possibility of getting back samples for some channels and not others, and
""",
"""
This approach is relatively fool-proof: if an application passes too small a value to {@code _buf_size}, they will simply get fewer samples back,
and if they assume the return value is the total number of values, then they will simply read too few (rather than reading too many and going off
the end of the buffer)
"""
)}
""")}
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} from which to read"),
opus_int16.p(
"_pcm",
"""
a buffer in which to store the output PCM samples, as signed native-endian 16-bit values at 48 kHz with a nominal range of {@code [-32768,32767)}.
Multiple channels are interleaved using the ${url("https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html\\#x1-810004.3.9", "Vorbis channel ordering")}.
This must have room for at least {@code _buf_size} values.
"""
),
AutoSize("_pcm")..int(
"_buf_size",
"""
the number of values that can be stored in {@code _pcm}.
It is recommended that this be large enough for at least 120 ms of data at 48 kHz per channel (5760 values per channel). Smaller buffers will
simply return less data, possibly consuming more memory to buffer the data internally. libopusfile may return less data than requested. If so,
there is no guarantee that the remaining data in {@code _pcm} will be unmodified.
"""
),
Check(1)..nullable..int.p(
"_li",
"""
the index of the link this data was decoded from.
You may pass #NULL if you do not need this information. If this function fails (returning a negative value), this parameter is left unset.
"""
),
returnDoc =
"""
the number of samples read per channel on success, or a negative value on failure.
The channel count can be retrieved on success by calling {@code op_head(_of,*_li)}. The number of samples returned may be 0 if the buffer was too small
to store even a single sample for all channels, or if end-of-file was reached. The list of possible failure codes follows. Most of them can only be
returned by unseekable, chained streams that encounter a new link.
${ul(
"#HOLE There was a hole in the data, and some samples may have been skipped. Call this function again to continue decoding past the hole",
"#EREAD An underlying read operation failed. This may signal a truncation attack from an {@code https:} source",
"#EFAULT An internal memory allocation failed",
"#EIMPL An unseekable stream encountered a new link that used a feature that is not implemented, such as an unsupported channel family",
"#EINVAL The stream was only partially open",
"#ENOTFORMAT An unseekable stream encountered a new link that did not have any logical Opus streams in it",
"""
#EBADHEADER An unseekable stream encountered a new link with a required header packet that was not properly formatted, contained illegal values, or
was missing altogether
""",
"#EVERSION An unseekable stream encountered a new link with an ID header that contained an unrecognized version number",
"#EBADPACKET Failed to properly decode the next packet",
"#EBADLINK We failed to find data we had seen before",
"#EBADTIMESTAMP An unseekable stream encountered a new link with a starting timestamp that failed basic validity checks"
)}
""",
noPrefix = true
)
int(
"op_read_float",
"""
Reads more samples from the stream.
${note("""
Although {@code _buf_size} must indicate the total number of values that can be stored in {@code _pcm}, the return value is the number of samples
<em>per channel</em>.
${ol(
"""
The channel count cannot be known a priori (reading more samples might advance us into the next link, with a different channel count), so
{@code _buf_size} cannot also be in units of samples per channel,
""",
"Returning the samples per channel matches the libopus API as closely as we're able,",
"""
Returning the total number of values instead of samples per channel would mean the caller would need a division to compute the samples per channel,
and might worry about the possibility of getting back samples for some channels and not others, and
""",
"""
This approach is relatively fool-proof: if an application passes too small a value to {@code _buf_size}, they will simply get fewer samples back,
and if they assume the return value is the total number of values, then they will simply read too few (rather than reading too many and going off
the end of the buffer).
"""
)}
""")}
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} from which to read"),
float.p(
"_pcm",
"""
a buffer in which to store the output PCM samples as signed floats at 48 kHz with a nominal range of {@code [-1.0,1.0]}.
Multiple channels are interleaved using the ${url("https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html\\#x1-810004.3.9", "Vorbis channel ordering")}.
This must have room for at least {@code _buf_size} floats.
"""
),
AutoSize("_pcm")..int(
"_buf_size",
"""
the number of floats that can be stored in {@code _pcm}.
It is recommended that this be large enough for at least 120 ms of data at 48 kHz per channel (5760 samples per channel). Smaller buffers will
simply return less data, possibly consuming more memory to buffer the data internally. If less than {@code _buf_size} values are returned,
libopusfile makes no guarantee that the remaining data in {@code _pcm} will be unmodified.
"""
),
Check(1)..nullable..int.p(
"_li",
"""
the index of the link this data was decoded from.
You may pass #NULL if you do not need this information. If this function fails (returning a negative value), this parameter is left unset.
"""
),
returnDoc =
"""
the number of samples read per channel on success, or a negative value on failure.
The channel count can be retrieved on success by calling {@code op_head(_of,*_li)}. The number of samples returned may be 0 if the buffer was too small
to store even a single sample for all channels, or if end-of-file was reached. The list of possible failure codes follows. Most of them can only be
returned by unseekable, chained streams that encounter a new link.
${ul(
"#HOLE There was a hole in the data, and some samples may have been skipped. Call this function again to continue decoding past the hole",
"#EREAD An underlying read operation failed. This may signal a truncation attack from an {@code https:} source",
"#EFAULT An internal memory allocation failed",
"#EIMPL An unseekable stream encountered a new link that used a feature that is not implemented, such as an unsupported channel family",
"#EINVAL The stream was only partially open",
"#ENOTFORMAT An unseekable stream encountered a new link that did not have any logical Opus streams in it",
"""
#EBADHEADER An unseekable stream encountered a new link with a required header packet that was not properly formatted, contained illegal values, or
was missing altogether
""",
"#EVERSION An unseekable stream encountered a new link with an ID header that contained an unrecognized version number",
"#EBADPACKET Failed to properly decode the next packet",
"#EBADLINK We failed to find data we had seen before",
"#EBADTIMESTAMP An unseekable stream encountered a new link with a starting timestamp that failed basic validity checks"
)}
""",
noPrefix = true
)
int(
"op_read_stereo",
"""
Reads more samples from the stream and downmixes to stereo, if necessary.
This function is intended for simple players that want a uniform output format, even if the channel count changes between links in a chained stream.
${note("""
{@code _buf_size} indicates the total number of values that can be stored in {@code _pcm}, while the return value is the number of samples <em>per
channel</em>, even though the channel count is known, for consistency with #op_read().
""")}
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} from which to read"),
opus_int16.p(
"_pcm",
"""
a buffer in which to store the output PCM samples, as signed native-endian 16-bit values at 48 kHz with a nominal range of {@code [-32768,32767)}.
The left and right channels are interleaved in the buffer. This must have room for at least {@code _buf_size} values.
"""
),
AutoSize("_pcm")..int(
"_buf_size",
"""
the number of values that can be stored in {@code _pcm}.
It is recommended that this be large enough for at least 120 ms of data at 48 kHz per channel (11520 values total). Smaller buffers will simply
return less data, possibly consuming more memory to buffer the data internally. If less than {@code _buf_size} values are returned, libopusfile
makes no guarantee that the remaining data in {@code _pcm} will be unmodified.
"""
),
returnDoc =
"""
the number of samples read per channel on success, or a negative value on failure.
The number of samples returned may be 0 if the buffer was too small to store even a single sample for both channels, or if end-of-file was reached.
The list of possible failure codes follows. Most of them can only be returned by unseekable, chained streams that encounter a new link.
${ul(
"#HOLE There was a hole in the data, and some samples may have been skipped. Call this function again to continue decoding past the hole",
"#EREAD An underlying read operation failed. This may signal a truncation attack from an {@code https:} source",
"#EFAULT An internal memory allocation failed",
"#EIMPL An unseekable stream encountered a new link that used a feature that is not implemented, such as an unsupported channel family",
"#EINVAL The stream was only partially open",
"#ENOTFORMAT An unseekable stream encountered a new link that did not have any logical Opus streams in it",
"""
#EBADHEADER An unseekable stream encountered a new link with a required header packet that was not properly formatted, contained illegal values, or
was missing altogether
""",
"#EVERSION An unseekable stream encountered a new link with an ID header that contained an unrecognized version number",
"#EBADPACKET Failed to properly decode the next packet",
"#EBADLINK We failed to find data we had seen before",
"#EBADTIMESTAMP An unseekable stream encountered a new link with a starting timestamp that failed basic validity checks"
)}
""",
noPrefix = true
)
int(
"op_read_float_stereo",
"""
Reads more samples from the stream and downmixes to stereo, if necessary.
This function is intended for simple players that want a uniform output format, even if the channel count changes between links in a chained stream.
${note("""
{@code _buf_size} indicates the total number of values that can be stored in {@code _pcm}, while the return value is the number of samples <em>per
channel</em>, even though the channel count is known, for consistency with #op_read_float().
""")}
""",
OggOpusFile.p("_of", "the {@code OggOpusFile} from which to read"),
float.p(
"_pcm",
"""
a buffer in which to store the output PCM samples, as signed floats at 48 kHz with a nominal range of {@code [-1.0,1.0]}.
The left and right channels are interleaved in the buffer. This must have room for at least {@code _buf_size} values.
"""
),
AutoSize("_pcm")..int(
"_buf_size",
"""
the number of values that can be stored in {@code _pcm}.
It is recommended that this be large enough for at least 120 ms of data at 48 kHz per channel (11520 values total). Smaller buffers will simply
return less data, possibly consuming more memory to buffer the data internally. If less than {@code _buf_size} values are returned, libopusfile
makes no guarantee that the remaining data in {@code _pcm} will be unmodified.
"""
),
returnDoc =
"""
the number of samples read per channel on success, or a negative value on failure.
The number of samples returned may be 0 if the buffer was too small to store even a single sample for both channels, or if end-of-file was reached. The
list of possible failure codes follows. Most of them can only be returned by unseekable, chained streams that encounter a new link.
${ul(
"#HOLE There was a hole in the data, and some samples may have been skipped. Call this function again to continue decoding past the hole",
"#EREAD An underlying read operation failed. This may signal a truncation attack from an {@code https:} source",
"#EFAULT An internal memory allocation failed",
"#EIMPL An unseekable stream encountered a new link that used a feature that is not implemented, such as an unsupported channel family",
"#EINVAL The stream was only partially open",
"#ENOTFORMAT An unseekable stream encountered a new link that that did not have any logical Opus streams in it",
"""
#EBADHEADER An unseekable stream encountered a new link with a required header packet that was not properly formatted, contained illegal values, or
was missing altogether
""",
"#EVERSION An unseekable stream encountered a new link with an ID header that contained an unrecognized version number",
"#EBADPACKET Failed to properly decode the next packet",
"#EBADLINK We failed to find data we had seen before",
"#EBADTIMESTAMP An unseekable stream encountered a new link with a starting timestamp that failed basic validity checks"
)}
""",
noPrefix = true
)
}
| bsd-3-clause | a6acbba4e34a645be766b57e94739212 | 45.125745 | 163 | 0.616637 | 4.55237 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/utils/transition/LeakFreeSupportSharedElementCallback.kt | 1 | 4179 | package com.ashish.movieguide.utils.transition
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.RectF
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.SharedElementCallback
import android.view.View
import android.widget.ImageView
abstract class LeakFreeSupportSharedElementCallback : SharedElementCallback() {
companion object {
private const val BUNDLE_SNAPSHOT_BITMAP = "BUNDLE_SNAPSHOT_BITMAP"
private const val BUNDLE_SNAPSHOT_IMAGE_SCALETYPE = "BUNDLE_SNAPSHOT_IMAGE_SCALETYPE"
private const val BUNDLE_SNAPSHOT_IMAGE_MATRIX = "BUNDLE_SNAPSHOT_IMAGE_MATRIX"
private const val BUNDLE_SNAPSHOT_TYPE = "BUNDLE_SNAPSHOT_TYPE"
private const val BUNDLE_SNAPSHOT_TYPE_IMAGE_VIEW = "BUNDLE_SNAPSHOT_TYPE"
}
private var tempMatrix: Matrix? = null
override fun onCaptureSharedElementSnapshot(sharedElement: View, viewToGlobalMatrix: Matrix,
screenBounds: RectF): Parcelable {
if (sharedElement is ImageView) {
val imageView = sharedElement
val drawable = imageView.drawable
val bg = imageView.background
if (drawable != null && (bg == null || bg.alpha == 0)) {
val bitmap = TransitionUtils.createDrawableBitmap(drawable)
if (bitmap != null) {
val bundle = Bundle()
bundle.putParcelable(BUNDLE_SNAPSHOT_BITMAP, bitmap)
bundle.putString(BUNDLE_SNAPSHOT_IMAGE_SCALETYPE, imageView.scaleType.toString())
if (imageView.scaleType == ImageView.ScaleType.MATRIX) {
val matrix = imageView.imageMatrix
val values = FloatArray(9)
matrix.getValues(values)
bundle.putFloatArray(BUNDLE_SNAPSHOT_IMAGE_MATRIX, values)
}
bundle.putString(BUNDLE_SNAPSHOT_TYPE, BUNDLE_SNAPSHOT_TYPE_IMAGE_VIEW)
return bundle
}
}
}
if (tempMatrix == null) {
tempMatrix = Matrix(viewToGlobalMatrix)
} else {
tempMatrix!!.set(viewToGlobalMatrix)
}
val bundle = Bundle()
val bitmap = TransitionUtils.createViewBitmap(sharedElement, tempMatrix!!, screenBounds)
bundle.putParcelable(BUNDLE_SNAPSHOT_BITMAP, bitmap)
return bundle
}
override fun onCreateSnapshotView(context: Context?, snapshot: Parcelable?): View? {
var view: View? = null
if (snapshot is Bundle) {
val bundle = snapshot
var bitmap = bundle.getParcelable<Bitmap>(BUNDLE_SNAPSHOT_BITMAP)
if (bitmap == null) {
bundle.clear()
return null
}
// Curiously, this is required to have the bitmap be GCed almost immediately after transition ends
// otherwise, garbage-collectable mem will still build up quickly
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false)
if (bitmap == null) {
return null
}
if (BUNDLE_SNAPSHOT_TYPE_IMAGE_VIEW == snapshot.getString(BUNDLE_SNAPSHOT_TYPE)) {
val imageView = ImageView(context)
view = imageView
imageView.setImageBitmap(bitmap)
imageView.scaleType = ImageView.ScaleType.valueOf(bundle.getString(BUNDLE_SNAPSHOT_IMAGE_SCALETYPE))
if (imageView.scaleType == ImageView.ScaleType.MATRIX) {
val values = bundle.getFloatArray(BUNDLE_SNAPSHOT_IMAGE_MATRIX)
val matrix = Matrix()
matrix.setValues(values)
imageView.imageMatrix = matrix
}
} else {
view = View(context)
view.background = BitmapDrawable(context!!.resources, bitmap)
}
bundle.clear()
}
return view
}
} | apache-2.0 | 6fc44c41aafdd5698f7443dc5cecbe57 | 38.065421 | 116 | 0.602776 | 5.165637 | false | false | false | false |
google/glance-experimental-tools | appwidget-host/src/main/java/com/google/android/glance/appwidget/host/AppWidgetSizeUtils.kt | 1 | 4967 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glance.appwidget.host
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.SizeF
import android.util.TypedValue
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import kotlin.math.min
fun DpSize.toSizeF(): SizeF = SizeF(width.value, height.value)
fun Dp.toPixels(context: Context) = toPixels(context.resources.displayMetrics)
fun Dp.toPixels(displayMetrics: DisplayMetrics) =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, displayMetrics).toInt()
internal fun Int.pixelsToDp(context: Context) = pixelsToDp(context.resources.displayMetrics)
internal fun Int.pixelsToDp(displayMetrics: DisplayMetrics) = (this / displayMetrics.density).dp
fun AppWidgetProviderInfo.getTargetSize(context: Context): DpSize = DpSize(
minWidth.pixelsToDp(context),
minHeight.pixelsToDp(context)
)
fun AppWidgetProviderInfo.getMaxSize(context: Context): DpSize =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && maxResizeWidth > 0) {
DpSize(
maxResizeWidth.pixelsToDp(context),
maxResizeHeight.pixelsToDp(context)
)
} else {
DpSize(Int.MAX_VALUE.dp, Int.MAX_VALUE.dp)
}
fun AppWidgetProviderInfo.getMinSize(context: Context): DpSize = DpSize(
width = minResizeWidth.pixelsToDp(context),
height = minResizeHeight.pixelsToDp(context)
)
fun AppWidgetProviderInfo.getSingleSize(context: Context): DpSize {
val minWidth = min(
minWidth,
if (resizeMode and AppWidgetProviderInfo.RESIZE_HORIZONTAL != 0) {
minResizeWidth
} else {
Int.MAX_VALUE
}
)
val minHeight = min(
minHeight,
if (resizeMode and AppWidgetProviderInfo.RESIZE_VERTICAL != 0) {
minResizeHeight
} else {
Int.MAX_VALUE
}
)
return DpSize(
minWidth.pixelsToDp(context),
minHeight.pixelsToDp(context)
)
}
val Context.appwidgetBackgroundRadius: Dp
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val size = resources.getDimensionPixelSize(
android.R.dimen.system_app_widget_background_radius
)
(size / resources.displayMetrics.density).dp
} else {
16.dp
}
val Context.appwidgetBackgroundRadiusPixels: Float
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
resources.getDimensionPixelSize(
android.R.dimen.system_app_widget_background_radius
).toFloat()
} else {
(16 * resources.displayMetrics.density)
}
fun AppWidgetProviderInfo.toSizeExtras(context: Context, availableSize: DpSize): Bundle {
return Bundle().apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
putInt(
AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,
minResizeWidth
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT,
minResizeHeight
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,
maxResizeWidth
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT,
maxResizeHeight
)
putParcelableArrayList(
AppWidgetManager.OPTION_APPWIDGET_SIZES,
arrayListOf(availableSize.toSizeF())
)
} else {
// TODO to check how this affects the different glance SizeModes
putInt(
AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,
availableSize.width.toPixels(context)
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT,
availableSize.height.toPixels(context)
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,
availableSize.width.toPixels(context)
)
putInt(
AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT,
availableSize.height.toPixels(context)
)
}
}
}
| apache-2.0 | 0f55edef8912001095d8452480fb9f4e | 32.560811 | 96 | 0.653715 | 4.474775 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/MenuItem.kt | 1 | 4003 | package tripleklay.ui
import euklid.f.Dimension
import klay.scene.Pointer
import react.Closeable
import react.SignalView
import react.Value
import kotlin.reflect.KClass
/**
* An item in a menu. This overrides clicking with a two phase click behavior: clicking an
* unselected menu item selects it; clicking a selected menu item triggers it.
*/
class MenuItem
/**
* Creates a new menu item with the given label and icon.
*/
constructor(label: String, icon: Icon? = null) : TextWidget<MenuItem>(), Togglable<MenuItem> {
/** Modes of text display. */
enum class ShowText {
ALWAYS, NEVER, WHEN_ACTIVE
}
/** The text shown. */
val text = Value<String?>(null)
/** The icon shown. */
val icon = Value<Icon?>(null)
init {
this.text.update(label)
this.text.connect(textDidChange())
// update after connect so we trigger iconDidChange, in case our icon is a not-ready-image
this.icon.connect(iconDidChange())
this.icon.update(icon)
}
/**
* Sets the text display mode for this menu item.
*/
fun showText(value: ShowText): MenuItem {
_showText = value
invalidate()
return this
}
/**
* Sets the menu item to show its text when the item is selected
*/
fun hideTextWhenInactive(): MenuItem {
return showText(ShowText.WHEN_ACTIVE)
}
/**
* Sets the menu item to only use an icon and no tex. This is useful for layouts that show the
* text of the selected item in a central location.
*/
fun hideText(): MenuItem {
return showText(ShowText.NEVER)
}
/**
* Sets the preferred size of the menu item.
*/
fun setPreferredSize(wid: Float, hei: Float): MenuItem {
_localPreferredSize.setSize(wid, hei)
invalidate()
return this
}
/**
* Gets the signal that dispatches when a menu item is triggered. Most callers will just
* connect to [Menu.itemTriggered].
*/
fun triggered(): SignalView<MenuItem> {
return toToggle().clicked
}
// from Togglable and Clickable
override fun selected(): Value<Boolean> {
return toToggle().selected
}
override fun clicked(): SignalView<MenuItem> {
return toToggle().clicked
}
override fun click() {
toToggle().click()
}
internal fun trigger() {
toToggle().click()
}
internal fun setRelay(relay: Closeable) {
_relay.close()
_relay = relay
}
private fun toToggle(): Behavior.Toggle<MenuItem> {
return _behave as Behavior.Toggle<MenuItem>
}
override val styleClass: KClass<*>
get() = MenuItem::class
override fun icon(): Icon? {
return icon.get()
}
override fun createBehavior(): Behavior<MenuItem>? {
return object : Behavior.Toggle<MenuItem>(this) {
override fun onStart(iact: Pointer.Interaction) {}
override fun onDrag(iact: Pointer.Interaction) {}
override fun onEnd(iact: Pointer.Interaction) {}
override fun onClick(iact: Pointer.Interaction) {
click()
}
}
}
override fun text(): String? {
when (_showText) {
MenuItem.ShowText.NEVER -> return ""
MenuItem.ShowText.WHEN_ACTIVE -> return if (isSelected) text.get() else ""
MenuItem.ShowText.ALWAYS -> return text.get()
}
}
override fun createLayoutData(hintX: Float, hintY: Float): LayoutData {
return SizableLayoutData(super.createLayoutData(hintX, hintY), _localPreferredSize)
}
private var _relay = Closeable.Util.NOOP
/** Size override. */
// TODO(cdi) clarify if we really cannot use the property Element#_preferredSize
private val _localPreferredSize = Dimension(0f, 0f)
/** Text display mode. */
internal var _showText = ShowText.ALWAYS
}
/**
* Creates a new menu item with the given label.
*/
| apache-2.0 | 9aa2143dc0763081519e75fe8cd5c7b0 | 26.606897 | 98 | 0.621534 | 4.308934 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/newLocation/stepper/settings/LocationSettingsFragmentView.kt | 1 | 4386 | package soutvoid.com.DsrWeatherApp.ui.screen.newLocation.stepper.settings
import android.graphics.Point
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.agna.ferro.mvp.component.ScreenComponent
import com.stepstone.stepper.Step
import com.stepstone.stepper.VerificationError
import kotlinx.android.synthetic.main.fragment_location_settings.*
import soutvoid.com.DsrWeatherApp.R
import soutvoid.com.DsrWeatherApp.ui.base.activity.BasePresenter
import javax.inject.Inject
import soutvoid.com.DsrWeatherApp.domain.location.SavedLocation
import soutvoid.com.DsrWeatherApp.ui.base.fragment.BaseFragmentView
import soutvoid.com.DsrWeatherApp.ui.screen.editLocation.EditLocationActivityView
import soutvoid.com.DsrWeatherApp.ui.screen.newLocation.NewLocationActivityView
import soutvoid.com.DsrWeatherApp.ui.util.getDefaultPreferences
class LocationSettingsFragmentView : BaseFragmentView(), Step {
companion object {
const val NAME_KEY = "name"
const val LATITUDE_KEY = "latitude"
const val LONGITUDE_KEY = "longitude"
const val FAVORITE_KEY = "favorite"
const val FORECAST_KEY = "forecast"
const val ID_KEY = "id"
fun newInstance(): LocationSettingsFragmentView {
val locationSettingsView = LocationSettingsFragmentView()
return locationSettingsView
}
}
@Inject
lateinit var presenter: LocationSettingsFragmentPresenter
override fun getPresenter(): BasePresenter<*> = presenter
override fun getName(): String = "LocationSettings"
override fun createScreenComponent(): ScreenComponent<*> {
return DaggerLocationSettingsFragmentComponent.builder()
.appComponent(getAppComponent())
.fragmentModule(getFragmentModule())
.build()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater?.inflate(R.layout.fragment_location_settings, container, false)
return rootView
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initCheckButton()
fillInitData()
}
private fun fillInitData() {
location_settings_name.setText(context.getDefaultPreferences().getString(NAME_KEY, ""))
location_settings_favorite.isChecked = context.getDefaultPreferences().getBoolean(FAVORITE_KEY, false)
location_settings_show_forecast.isChecked = context.getDefaultPreferences().getBoolean(FORECAST_KEY, false)
}
private fun initCheckButton() {
location_settings_check.setOnClickListener { presenter.checkPressed() }
}
private fun eraseSharedPreferencesRecords() {
context.getDefaultPreferences().edit()
.remove(ID_KEY)
.remove(FAVORITE_KEY)
.remove(FORECAST_KEY)
.commit()
}
override fun onSelected() {
fillInitData()
}
override fun verifyStep(): VerificationError? {
presenter.checkPressed()
return null
}
override fun onError(error: VerificationError) {
}
fun getData(): SavedLocation {
val id = context.getDefaultPreferences().getInt(ID_KEY, 0)
val location = SavedLocation(
location_settings_name.text.toString(),
context.getDefaultPreferences().getFloat(LONGITUDE_KEY, 0f).toDouble(),
context.getDefaultPreferences().getFloat(LATITUDE_KEY, 0f).toDouble(),
location_settings_favorite.isChecked,
location_settings_show_forecast.isChecked
)
if (id != 0) location.id = id
return location
}
fun returnToHome() {
(activity as? NewLocationActivityView)?.returnToHome(getCheckBtnCoords())
(activity as? EditLocationActivityView)?.returnToHome(getCheckBtnCoords())
}
override fun onPause() {
eraseSharedPreferencesRecords()
super.onPause()
}
fun getCheckBtnCoords(): Point {
return Point(
location_settings_check.left + location_settings_check.measuredWidth / 2,
location_settings_check.top + location_settings_check.measuredHeight / 2
)
}
} | apache-2.0 | 7cb8628909b34d085331dea3e4bd0c39 | 35.256198 | 117 | 0.694254 | 4.90604 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/ast/ASTNodeBuilder.kt | 2 | 2175 | package org.intellij.markdown.ast
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.impl.ListCompositeNode
import org.intellij.markdown.ast.impl.ListItemCompositeNode
import java.util.ArrayList
public open class ASTNodeBuilder(protected val text: CharSequence) {
public open fun createLeafNodes(type: IElementType, startOffset: Int, endOffset: Int): List<ASTNode> {
if (type == MarkdownTokenTypes.WHITE_SPACE) {
val result = ArrayList<ASTNode>()
var lastEol = startOffset
while (lastEol < endOffset) {
val nextEol = indexOfSubSeq(text, lastEol, endOffset, '\n')
if (nextEol == -1) {
break
}
if (nextEol > lastEol) {
result.add(LeafASTNode(MarkdownTokenTypes.WHITE_SPACE, lastEol, nextEol))
}
result.add(LeafASTNode(MarkdownTokenTypes.EOL, nextEol, nextEol + 1))
lastEol = nextEol + 1
}
if (endOffset > lastEol) {
result.add(LeafASTNode(MarkdownTokenTypes.WHITE_SPACE, lastEol, endOffset))
}
return result
}
return listOf(LeafASTNode(type, startOffset, endOffset))
}
public open fun createCompositeNode(type: IElementType, children: List<ASTNode>): CompositeASTNode {
when (type) {
MarkdownElementTypes.UNORDERED_LIST,
MarkdownElementTypes.ORDERED_LIST -> {
return ListCompositeNode(type, children)
}
MarkdownElementTypes.LIST_ITEM -> {
return ListItemCompositeNode(children)
}
else -> {
return CompositeASTNode(type, children)
}
}
}
companion object {
fun indexOfSubSeq(s: CharSequence, from: Int, to: Int, c: Char): Int {
for (i in from..to - 1) {
if (s[i] == c) {
return i
}
}
return -1
}
}
} | apache-2.0 | 22aaf29f2f04093e18bff5b32ea59efd | 34.672131 | 106 | 0.576552 | 4.865772 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/lang/language.kt | 1 | 786 | package me.serce.solidity.lang
import com.intellij.lang.Language
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import me.serce.solidity.ide.SolidityIcons
import java.nio.charset.StandardCharsets.UTF_8
object SolidityLanguage : Language("Solidity", "text/solidity") {
override fun isCaseSensitive() = true
}
object SolidityFileType : LanguageFileType(SolidityLanguage) {
object DEFAULTS {
const val DESCRIPTION = "Solidity file"
}
override fun getName() = DEFAULTS.DESCRIPTION
override fun getDescription() = DEFAULTS.DESCRIPTION
override fun getDefaultExtension() = "sol"
override fun getIcon() = SolidityIcons.FILE_ICON
override fun getCharset(file: VirtualFile, content: ByteArray): String = UTF_8.name()
}
| mit | 325c16775caf0f91c2a7170dec08a0af | 33.173913 | 87 | 0.784987 | 4.318681 | false | false | false | false |
xmartlabs/Android-Base-Project | core/src/main/java/com/xmartlabs/bigbang/core/repository/CoreSessionRepository.kt | 1 | 1537 | package com.xmartlabs.bigbang.core.repository
import android.content.SharedPreferences
import androidx.annotation.CheckResult
import com.xmartlabs.bigbang.core.model.SessionType
/**
* Controller that manages the Session of the Application.
*
* The Session will be stored via the [SharedPreferencesSource].
*/
abstract class CoreSessionRepository(private val sharedPreferencesSource: SharedPreferencesSource) {
companion object {
private val PREFERENCES_KEY_SESSION = "session"
}
abstract fun getSessionType(): Class<out SessionType>
/**
* Retrieves the current stored [SessionType], if it exists.
*
* @return the current [SessionType], or `null` if none exists
*/
open val abstractSession
get() = sharedPreferencesSource.getEntity(PREFERENCES_KEY_SESSION, getSessionType())
/**
* Returns whether the [SessionType] information is present on the device.
*
* @return whether or not the [SessionType] information exists
*/
open val isSessionAlive
@CheckResult
get() = sharedPreferencesSource.hasEntity(PREFERENCES_KEY_SESSION)
/**
* Stores the `session` into the [SharedPreferences].
*
* @param session the `S` object to be stored
* *
* @param <S> the [SessionType] object to be stored
* */
open fun <S : SessionType> saveSession(session: S) =
sharedPreferencesSource.saveEntity(PREFERENCES_KEY_SESSION, session)
/** Deletes the session information */
open fun deleteSession() = sharedPreferencesSource.deleteEntity(PREFERENCES_KEY_SESSION)
}
| apache-2.0 | d79a8bb3110ead49c575bc1c6058cfc4 | 31.020833 | 100 | 0.7365 | 4.455072 | false | false | false | false |
seratch/jslack | slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/PlainTextInputElementBuilder.kt | 1 | 3294 | package com.slack.api.model.kotlin_extension.block.element
import com.slack.api.model.block.composition.PlainTextObject
import com.slack.api.model.block.element.PlainTextInputElement
import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder
import com.slack.api.model.kotlin_extension.block.Builder
@BlockLayoutBuilder
class PlainTextInputElementBuilder : Builder<PlainTextInputElement> {
private var actionId: String? = null
private var placeholder: PlainTextObject? = null
private var initialValue: String? = null
private var multiline: Boolean = false
private var minLength: Int? = null
private var maxLength: Int? = null
/**
* An identifier for the input value when the parent modal is submitted. You can use this when you receive a
* view_submission payload to identify the value of the input element. Should be unique among all other action_ids
* used elsewhere by your app. Maximum length for this field is 255 characters.*
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun actionId(id: String) {
actionId = id
}
/**
* Adds a plain text object to the placeholder field.
*
* The placeholder text shown in the plain-text input. Maximum length for the text in this field is 150 characters.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun placeholder(text: String, emoji: Boolean? = null) {
placeholder = PlainTextObject(text, emoji)
}
/**
* The initial value in the plain-text input when it is loaded.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun initialValue(value: String) {
initialValue = value
}
/**
* Indicates whether the input will be a single line (false) or a larger textarea (true). Defaults to false.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun multiline(isMultiline: Boolean) {
multiline = isMultiline
}
/**
* The minimum length of input that the user must provide. If the user provides less, they will receive an error. Maximum value is 3000.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun minLength(length: Int) {
minLength = length
}
/**
* The maximum length of input that the user can provide. If the user provides more, they will receive an error.
*
* @see <a href="https://api.slack.com/reference/block-kit/block-elements#input">Plain text input documentation</a>
*/
fun maxLength(length: Int) {
maxLength = length
}
override fun build(): PlainTextInputElement {
return PlainTextInputElement.builder()
.actionId(actionId)
.placeholder(placeholder)
.initialValue(initialValue)
.multiline(multiline)
.minLength(minLength)
.maxLength(maxLength)
.build()
}
} | mit | 20086c7a089a5dc64b2bb3f150c8c409 | 37.764706 | 140 | 0.669702 | 4.283485 | false | false | false | false |
ranmocy/rCaltrain | android/app/src/main/java/me/ranmocy/rcaltrain/HomeActivity.kt | 1 | 8268 | package me.ranmocy.rcaltrain
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ListView
import android.widget.RadioGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.google.firebase.analytics.FirebaseAnalytics
import me.ranmocy.rcaltrain.database.ScheduleDao
import me.ranmocy.rcaltrain.models.ScheduleResult
import me.ranmocy.rcaltrain.ui.ResultsListAdapter
import me.ranmocy.rcaltrain.ui.ScheduleViewModel
import me.ranmocy.rcaltrain.ui.StationListAdapter
class HomeActivity : AppCompatActivity(), View.OnClickListener {
companion object {
private const val TAG = "HomeActivity"
}
private val scheduleViewModel: ScheduleViewModel by lazy { ViewModelProviders.of(this).get(ScheduleViewModel::class.java) }
private val resultsAdapter: ResultsListAdapter by lazy { ResultsListAdapter(this) }
private val stationsAdapter: StationListAdapter by lazy { StationListAdapter(this) }
private val preferences: Preferences by lazy { Preferences(this) }
private val departureView: TextView by lazy { findViewById<TextView>(R.id.input_departure) }
private val arrivalView: TextView by lazy { findViewById<TextView>(R.id.input_arrival) }
private val scheduleGroup: RadioGroup by lazy { findViewById<RadioGroup>(R.id.schedule_group) }
private val nextTrainView: TextView by lazy { findViewById<TextView>(R.id.next_train) }
private val firebaseAnalytics: FirebaseAnalytics by lazy { FirebaseAnalytics.getInstance(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// Setup result view
val resultsView = findViewById<ListView>(R.id.results)
resultsView.adapter = resultsAdapter
// TODO: check saved station name, invalid it if it's not in our list.
departureView.text = preferences.lastDepartureStationName
arrivalView.text = preferences.lastDestinationStationName
when (preferences.lastScheduleType) {
ScheduleDao.ServiceType.SERVICE_NOW -> scheduleGroup.check(R.id.btn_now)
ScheduleDao.ServiceType.SERVICE_WEEKDAY -> scheduleGroup.check(R.id.btn_week)
ScheduleDao.ServiceType.SERVICE_SATURDAY -> scheduleGroup.check(R.id.btn_sat)
ScheduleDao.ServiceType.SERVICE_SUNDAY -> scheduleGroup.check(R.id.btn_sun)
}
scheduleViewModel.getStations(this).observe(this, Observer { stationNames ->
stationsAdapter.setData(stationNames ?: ArrayList<String>())
})
scheduleViewModel.results.observe(this, Observer { results ->
updateUI(results ?: ArrayList<ScheduleResult>())
})
// Init schedule
reschedule()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_home, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
override fun onClick(v: View) {
Log.v(TAG, "onClick:" + v)
when (v.id) {
R.id.input_departure -> {
showStationSelector(true)
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.clickDepartureEvent)
return
}
R.id.input_arrival -> {
showStationSelector(false)
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.clickArrivalEvent)
return
}
R.id.switch_btn -> {
val departureViewText = departureView.text
val arrivalViewText = arrivalView.text
departureView.text = arrivalViewText
arrivalView.text = departureViewText
preferences.lastDepartureStationName = departureViewText.toString()
preferences.lastDestinationStationName = arrivalViewText.toString()
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.clickSwitchEvent)
}
R.id.btn_now -> {
preferences.lastScheduleType = ScheduleDao.ServiceType.SERVICE_NOW
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.getClickScheduleEvent(ScheduleDao.ServiceType.SERVICE_NOW))
}
R.id.btn_week -> {
preferences.lastScheduleType = ScheduleDao.ServiceType.SERVICE_WEEKDAY
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.getClickScheduleEvent(ScheduleDao.ServiceType.SERVICE_WEEKDAY))
}
R.id.btn_sat -> {
preferences.lastScheduleType = ScheduleDao.ServiceType.SERVICE_SATURDAY
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.getClickScheduleEvent(ScheduleDao.ServiceType.SERVICE_SATURDAY))
}
R.id.btn_sun -> {
preferences.lastScheduleType = ScheduleDao.ServiceType.SERVICE_SUNDAY
firebaseAnalytics.logEvent(Events.EVENT_ON_CLICK, Events.getClickScheduleEvent(ScheduleDao.ServiceType.SERVICE_SUNDAY))
}
R.id.schedule_group -> {
Log.v(TAG, "schedule_group")
return
}
else -> return
}
reschedule()
}
private fun showStationSelector(isDeparture: Boolean) {
AlertDialog.Builder(this)
.setAdapter(stationsAdapter) { dialog, which ->
val stationName = stationsAdapter.getData()[which]
if (isDeparture) {
preferences.lastDepartureStationName = stationName
departureView.text = stationName
} else {
preferences.lastDestinationStationName = stationName
arrivalView.text = stationName
}
dialog.dismiss()
reschedule()
}
.setCancelable(false)
.show()
}
private fun reschedule() {
val departure = departureView.text.toString()
val destination = arrivalView.text.toString()
// reschedule, update results data
@ScheduleDao.ServiceType val scheduleType: Int
when (scheduleGroup.checkedRadioButtonId) {
-1 -> {
Log.v(TAG, "No schedule selected, skip.")
return
}
R.id.btn_now -> scheduleType = ScheduleDao.ServiceType.SERVICE_NOW
R.id.btn_week -> scheduleType = ScheduleDao.ServiceType.SERVICE_WEEKDAY
R.id.btn_sat -> scheduleType = ScheduleDao.ServiceType.SERVICE_SATURDAY
R.id.btn_sun -> scheduleType = ScheduleDao.ServiceType.SERVICE_SUNDAY
else -> throw RuntimeException("Unexpected schedule selection:" + scheduleGroup.checkedRadioButtonId)
}
firebaseAnalytics.logEvent(
Events.EVENT_SCHEDULE,
Events.getScheduleEvent(departure, destination, scheduleType))
scheduleViewModel.updateQuery(this, departure, destination, scheduleType)
}
private fun updateUI(results: List<ScheduleResult>) {
resultsAdapter.setData(results)
if (scheduleGroup.checkedRadioButtonId == R.id.btn_now) {
nextTrainView.text = resultsAdapter.nextTime
nextTrainView.visibility = View.VISIBLE
} else {
nextTrainView.visibility = View.GONE
}
}
}
| mit | 87eccaba5fcdef59ce2f5cca9a1aacb6 | 42.746032 | 137 | 0.652758 | 4.866392 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/action/GenerateOverwriteAction.kt | 1 | 4611 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.findMethods
import com.demonwav.mcdev.platform.mixin.util.findSource
import com.demonwav.mcdev.util.MinecraftFileTemplateGroupFactory.Companion.MIXIN_OVERWRITE_FALLBACK
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiGenerationInfo
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.util.MemberChooser
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.codeStyle.CodeStyleManager
class GenerateOverwriteAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val methods = (findMethods(psiClass) ?: return)
.map(::PsiMethodMember).toTypedArray()
if (methods.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No methods to overwrite have been found")
return
}
val chooser = MemberChooser<PsiMethodMember>(methods, false, true, project)
chooser.title = "Select Methods to Overwrite"
chooser.setCopyJavadocVisible(false)
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
val requiredMembers = LinkedHashSet<PsiMember>()
runWriteAction {
val newMethods = elements.map {
val method = it.element.findSource()
val sourceClass = method.containingClass
val codeBlock = method.body
val newMethod: PsiMethod
if (sourceClass != null && codeBlock != null) {
// Source of method is available
// Collect all references to potential @Shadow members
requiredMembers.addAll(collectRequiredMembers(codeBlock, sourceClass))
}
// Create temporary (dummy) method
var tmpMethod =
JavaPsiFacade.getElementFactory(project).createMethod(method.name, method.returnType!!, psiClass)
// Replace temporary method with a copy of the original method
tmpMethod = tmpMethod.replace(method) as PsiMethod
// Remove Javadocs
OverrideImplementUtil.deleteDocComment(tmpMethod)
// Reformat the code with the project settings
newMethod = CodeStyleManager.getInstance(project).reformat(tmpMethod) as PsiMethod
if (codeBlock == null) {
// Generate fallback method body if source is not available
OverrideImplementUtil.setupMethodBody(
newMethod, method, psiClass,
FileTemplateManager.getInstance(project).getCodeTemplate(MIXIN_OVERWRITE_FALLBACK)
)
}
// TODO: Automatically add Javadoc comment for @Overwrite? - yes please
// Add @Overwrite annotation
newMethod.modifierList.addAnnotation(MixinConstants.Annotations.OVERWRITE)
PsiGenerationInfo(newMethod)
}
// Insert new methods
GenerateMembersUtil.insertMembersAtOffset(file, offset, newMethods)
// Select first element in editor
.first().positionCaret(editor, true)
}
// Generate needed shadows
val newShadows = createShadowMembers(project, psiClass, filterNewShadows(requiredMembers, psiClass))
disableAnnotationWrapping(project) {
runWriteAction {
// Insert shadows
insertShadows(psiClass, newShadows)
}
}
}
}
| mit | a249c3e3dbe4d2e256872dfcd99ad0fc | 38.75 | 117 | 0.670354 | 5.3 | false | false | false | false |
HelmMobile/KotlinCleanArchitecture | app/src/main/java/cat/helm/basearchitecture/ui/detail/DetailActivity.kt | 1 | 1262 | package cat.helm.basearchitecture.ui.detail
import android.content.Context
import android.content.Intent
import android.widget.TextView
import cat.helm.basearchitecture.R
import cat.helm.basearchitecture.model.TvShow
import cat.helm.basearchitecture.ui.base.BaseActivity
import cat.helm.basearchitecture.ui.bind
import kotlinx.android.synthetic.main.activity_detail.*
import org.jetbrains.anko.find
import javax.inject.Inject
class DetailActivity : BaseActivity(), DetailView {
companion object {
val TV_SHOW_ID: String = "tvShowId"
fun getIntent(id: Int, context: Context): Intent {
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(TV_SHOW_ID, id)
return intent
}
}
@Inject lateinit var presenter: DetailPresenter
override fun onRequestLayout(): Int = R.layout.activity_detail
override fun onViewLoaded() {
val id = intent.extras.getInt(TV_SHOW_ID)
presenter.onStart(id)
}
override fun showTvShow(tvShow: TvShow) {
with(tvShow) {
descritpion.text = description
detailImage.bind(getString(R.string.baseImageUrl)+tvShow.image)
find<TextView>(R.id.title).text = name
}
}
}
| apache-2.0 | e7c77acf40928bb4da7cc6c301315aa2 | 29.780488 | 75 | 0.696513 | 4.031949 | false | false | false | false |
dyoung81/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/pokemon/CatchablePokemon.kt | 1 | 3558 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.pokemon
import POGOProtos.Data.Capture.CaptureProbabilityOuterClass.CaptureProbability
import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId
import com.pokegoapi.api.inventory.ItemBag
import com.pokegoapi.api.inventory.Pokeball
import com.pokegoapi.api.map.pokemon.CatchResult
import com.pokegoapi.api.map.pokemon.CatchablePokemon
import ink.abb.pogo.scraper.util.Log
/**
* Extension function to make the code more readable in the CatchOneNearbyPokemon task
*/
fun CatchablePokemon.catch(normalizedHitPosition: Double = 1.0,
normalizedReticleSize: Double = 1.95 + Math.random() * 0.05,
spinModifier: Double = 0.85 + Math.random() * 0.15,
ballType: Pokeball? = Pokeball.POKEBALL, amount: Int = -1): CatchResult? {
return this.catchPokemon(normalizedHitPosition, normalizedReticleSize, spinModifier, ballType, amount)
}
// unfortunately necessary because of the shitty `Pokeball` class...
val itemToPokeball = mapOf(
Pair(ItemId.ITEM_POKE_BALL, Pokeball.POKEBALL),
Pair(ItemId.ITEM_GREAT_BALL, Pokeball.GREATBALL),
Pair(ItemId.ITEM_ULTRA_BALL, Pokeball.ULTRABALL),
Pair(ItemId.ITEM_MASTER_BALL, Pokeball.MASTERBALL)
)
fun CatchablePokemon.catch(captureProbability: CaptureProbability, itemBag: ItemBag, desiredCatchProbability: Double): CatchResult? {
val ballTypes = captureProbability.pokeballTypeList
val probabilities = captureProbability.captureProbabilityList
var ball: ItemId? = null
var needCurve = false
var needRazzBerry = false
var highestAvailable: ItemId? = null
for ((index, ballType) in ballTypes.withIndex()) {
val probability = probabilities.get(index)
val ballAmount = itemBag.getItem(ballType).count
if (ballAmount == 0) {
continue;
} else {
highestAvailable = ballType
}
if (probability >= desiredCatchProbability - 0.2) {
ball = ballType
break
} else if (probability >= desiredCatchProbability - 0.1) {
ball = ballType
needCurve = true
break
} else if (probability >= desiredCatchProbability - 0.2) {
ball = ballType
needCurve = true
needRazzBerry = true
break
}
}
if (highestAvailable == null) {
Log.red("No balls available")
return null
}
if (ball == null) {
ball = highestAvailable
needCurve = true
needRazzBerry = true
}
var logMessage = "Using ${ball.name}"
val razzBerryCount = itemBag.getItem(ItemId.ITEM_RAZZ_BERRY).count
if (razzBerryCount > 0 && needRazzBerry) {
logMessage += "; Using Razz Berry"
useItem(ItemId.ITEM_RAZZ_BERRY)
}
if (needCurve) {
logMessage += "; Using curve"
}
Log.yellow(logMessage)
return catch(
normalizedHitPosition = 1.0,
normalizedReticleSize = 1.95 + Math.random() * 0.05,
spinModifier = if (needCurve) 0.85 + Math.random() * 0.15 else Math.random() * 0.10,
ballType = itemToPokeball.get(ball)
)
}
| gpl-3.0 | 8def5332826cdde4eab6d0440090a6e0 | 36.452632 | 133 | 0.65964 | 4.024887 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/fileType/HaskellFileType.kt | 1 | 931 | package org.jetbrains.haskell.fileType
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.haskell.HaskellLanguage
import org.jetbrains.haskell.icons.HaskellIcons
import javax.swing.*
class HaskellFileType : LanguageFileType(HaskellLanguage.INSTANCE) {
private var myIcon: Icon = HaskellIcons.DEFAULT
override fun getName(): String =
"Haskell file"
override fun getDescription(): String =
"Haskell file"
override fun getDefaultExtension(): String =
DEFAULT_EXTENSION
override fun getIcon(): Icon =
myIcon
override fun getCharset(file: VirtualFile, content: ByteArray): String =
"UTF-8"
companion object {
@JvmField val INSTANCE: HaskellFileType = HaskellFileType()
val DEFAULT_EXTENSION: String = "hs"
}
}
| apache-2.0 | d57ed1504432006b7911a086b44d2bf6 | 27.212121 | 76 | 0.711063 | 4.823834 | false | false | false | false |
JetBrains/intellij-community | platform/object-serializer/src/BeanBinding.kt | 1 | 11052 | // 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.serialization
import com.amazon.ion.IonReader
import com.amazon.ion.IonType
import com.amazon.ion.system.IonReaderBuilder
import it.unimi.dsi.fastutil.objects.Object2IntMap
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.lang.reflect.Type
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaConstructor
private val structReaderBuilder by lazy {
IonReaderBuilder.standard().immutable()
}
private const val ID_FIELD_NAME = "@id"
internal class BeanBinding(beanClass: Class<*>) : BaseBeanBinding(beanClass), Binding {
private lateinit var bindings: Array<Binding>
private lateinit var nameToBindingIndex: Object2IntMap<String>
private lateinit var properties: List<MutableAccessor>
private val propertyMapping: Lazy<NonDefaultConstructorInfo?> = lazy {
computeNonDefaultConstructorInfo(beanClass)
}
// type parameters for bean binding doesn't play any role, should be the only binding for such class
override fun createCacheKey(aClass: Class<*>?, type: Type) = aClass!!
override fun init(originalType: Type, context: BindingInitializationContext) {
val list = context.propertyCollector.collect(beanClass)
properties = list
val nameToBindingIndex = Object2IntOpenHashMap<String>(list.size)
nameToBindingIndex.defaultReturnValue(-1)
bindings = Array(list.size) { index ->
val accessor = list.get(index)
val binding = context.bindingProducer.getNestedBinding(accessor)
nameToBindingIndex.put(accessor.name, index)
binding
}
this.nameToBindingIndex = nameToBindingIndex
if (context.isResolveConstructorOnInit) {
try {
resolveConstructor()
}
catch (e: NoSuchMethodException) {
propertyMapping.value
}
}
}
override fun serialize(obj: Any, context: WriteContext) {
val writer = context.writer
val objectIdWriter = context.objectIdWriter
if (objectIdWriter != null) {
val alreadySerializedReference = objectIdWriter.getId(obj)
if (alreadySerializedReference != -1) {
writer.writeInt(alreadySerializedReference.toLong())
return
}
}
writer.stepIn(IonType.STRUCT)
if (objectIdWriter != null) {
// id as field because annotation supports only string, but it is not efficient
writer.setFieldName(ID_FIELD_NAME)
writer.writeInt(objectIdWriter.registerObject(obj).toLong())
}
val bindings = bindings
val properties = properties
@Suppress("ReplaceManualRangeWithIndicesCalls")
for (i in 0 until bindings.size) {
val property = properties[i]
val binding = bindings[i]
try {
binding.serialize(obj, property, context)
}
catch (e: Exception) {
throw SerializationException("Cannot serialize property (property=$property, binding=$binding, beanClass=${beanClass.name})", e)
}
}
writer.stepOut()
}
private fun createUsingCustomConstructor(context: ReadContext, hostObject: Any?): Any {
var constructorInfo = propertyMapping.value
if (constructorInfo == null) {
constructorInfo = context.configuration.resolvePropertyMapping?.invoke(beanClass)
?: getPropertyMappingIfDataClass()
?: throw SerializationException("Please annotate non-default constructor with PropertyMapping (beanClass=${beanClass.name})")
}
val names = constructorInfo.names
val initArgs = arrayOfNulls<Any?>(names.size)
/**
* Applies [body] to `context.reader` and makes a copy of the structure being read if the second pass will be required
* to handle properties which are not deserialized by invoking the constructor.
*/
fun doReadAndMakeCopyIfSecondPassIsNeeded(body: (reader: IonReader) -> Unit): BufferExposingByteArrayOutputStream? {
return if (bindings.size > names.size) {
val out = context.allocateByteArrayOutputStream()
// ionType is already checked - so, struct is expected
binaryWriterBuilder.newWriter(out).use { it.writeValue(context.reader) }
structReaderBuilder.build(out.internalBuffer, 0, out.size()).use { reader ->
reader.next()
body(reader)
}
out
}
else {
body(context.reader)
null
}
}
// we cannot read all field values before creating instance because some field value can reference to parent - our instance,
// so, first, create instance, and only then read rest of fields
var id = -1
val out = doReadAndMakeCopyIfSecondPassIsNeeded { reader ->
val subReadContext = context.createSubContext(reader)
readStruct(reader) { fieldName, type ->
if (type == IonType.NULL) {
return@readStruct
}
if (type == IonType.INT && fieldName == ID_FIELD_NAME) {
id = reader.intValue()
return@readStruct
}
val argIndex = names.indexOf(fieldName)
if (argIndex == -1) {
return@readStruct
}
val bindingIndex = nameToBindingIndex.getInt(fieldName)
if (bindingIndex == -1) {
LOG.error("Cannot find binding (fieldName=$fieldName, valueType=${reader.type}, beanClass=${beanClass.name}")
return@readStruct
}
val binding = bindings.get(bindingIndex)
try {
initArgs[argIndex] = binding.deserialize(subReadContext, hostObject)
}
catch (e: Exception) {
throw SerializationException("Cannot deserialize parameter value (fieldName=$fieldName, binding=$binding, valueType=${reader.type}, beanClass=${beanClass.name})", e)
}
}
}
var instance = try {
constructorInfo.constructor.newInstance(*initArgs)
}
catch (e: Exception) {
throw SerializationException("Cannot create instance (beanClass=${beanClass.name}, initArgs=${initArgs.joinToString()})", e)
}
// must be called after creation because child properties can reference object
context.configuration.beanConstructed?.let {
instance = it(instance)
}
if (id != -1) {
context.objectIdReader.registerObject(instance, id)
}
if (out != null) {
structReaderBuilder.build(out.internalBuffer, 0, out.size()).use { reader ->
reader.next()
readIntoObject(instance, context.createSubContext(reader), checkId = false /* already registered */) { !names.contains(it) }
}
}
return instance
}
private fun getPropertyMappingIfDataClass(): NonDefaultConstructorInfo? {
try {
// primaryConstructor will be null for Java
// parameter names are available only via kotlin reflection, not via java reflection
val kFunction = beanClass.kotlin.primaryConstructor ?: return null
try {
kFunction.isAccessible = true
}
catch (ignored: SecurityException) {
}
val names = kFunction.parameters.mapNotNull { it.name }
if (names.isEmpty()) {
return null
}
return NonDefaultConstructorInfo(names, kFunction.javaConstructor!!)
}
catch (e: Exception) {
LOG.error(e)
}
return null
}
override fun deserialize(context: ReadContext, hostObject: Any?): Any {
val reader = context.reader
val ionType = reader.type
if (ionType == IonType.INT) {
// reference
return context.objectIdReader.getObject(reader.intValue())
}
else if (ionType != IonType.STRUCT) {
var stringValue = ""
if (ionType == IonType.SYMBOL || ionType == IonType.STRING) {
stringValue = reader.stringValue()
}
throw SerializationException("Expected STRUCT, but got $ionType (stringValue=$stringValue)")
}
if (propertyMapping.isInitialized()) {
return createUsingCustomConstructor(context, hostObject)
}
val instance = try {
resolveConstructor().newInstance()
}
catch (e: SecurityException) {
beanClass.newInstance()
}
catch (e: NoSuchMethodException) {
return createUsingCustomConstructor(context, hostObject)
}
readIntoObject(instance, context)
return context.configuration.beanConstructed?.let { it(instance) } ?: instance
}
private fun readIntoObject(instance: Any, context: ReadContext, checkId: Boolean = true, filter: ((fieldName: String) -> Boolean)? = null) {
val nameToBindingIndex = nameToBindingIndex
val bindings = bindings
val accessors = properties
val reader = context.reader
readStruct(reader) { fieldName, type ->
if (type == IonType.INT && fieldName == ID_FIELD_NAME) {
// check flag checkId only here, to ensure that @id is not reported as unknown field
if (checkId) {
val id = reader.intValue()
context.objectIdReader.registerObject(instance, id)
}
return@readStruct
}
if (filter != null && !filter(fieldName)) {
return@readStruct
}
val bindingIndex = nameToBindingIndex.getInt(fieldName)
// ignore unknown field
if (bindingIndex == -1) {
context.errors.unknownFields.add(ReadError("Unknown field (fieldName=$fieldName, beanClass=${beanClass.name})"))
return@readStruct
}
val binding = bindings.get(bindingIndex)
try {
binding.deserialize(instance, accessors.get(bindingIndex), context)
}
catch (e: SerializationException) {
throw e
}
catch (e: Exception) {
throw SerializationException("Cannot deserialize field value (field=$fieldName, binding=$binding, valueType=${reader.type}, beanClass=${beanClass.name})", e)
}
}
}
}
private inline fun readStruct(reader: IonReader, read: (fieldName: String, type: IonType) -> Unit) {
reader.stepIn()
while (true) {
val type = reader.next() ?: break
val fieldName = reader.fieldName
if (fieldName == null) {
throw IllegalStateException("No valid current value or the current value is not a field of a struct.")
}
read(fieldName, type)
}
reader.stepOut()
}
private fun computeNonDefaultConstructorInfo(beanClass: Class<*>): NonDefaultConstructorInfo? {
for (constructor in beanClass.declaredConstructors) {
val annotation = constructor.getAnnotation(PropertyMapping::class.java) ?: continue
try {
constructor.isAccessible = true
}
catch (ignore: SecurityException) {
}
if (constructor.parameterCount != annotation.value.size) {
throw SerializationException("PropertyMapping annotation specifies ${annotation.value.size} parameters, " +
"but constructor of ${beanClass.name} accepts ${constructor.parameterCount}")
}
return NonDefaultConstructorInfo(annotation.value.toList(), constructor)
}
return null
} | apache-2.0 | aa5528ba94acd38ec4c91615c517a794 | 34.426282 | 175 | 0.678067 | 4.624268 | false | false | false | false |
littleGnAl/Accounting | app/src/main/java/com/littlegnal/accounting/ui/summary/SummaryChart.kt | 1 | 10358 | /*
* Copyright (C) 2017 littlegnal
*
* 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.littlegnal.accounting.ui.summary
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import com.littlegnal.accounting.R
import com.littlegnal.accounting.base.util.ChangeDetected
import com.littlegnal.accounting.base.util.colorRes
import com.littlegnal.accounting.base.util.dip
import com.littlegnal.accounting.base.util.sp
import io.reactivex.subjects.PublishSubject
import java.util.Date
/**
* 汇总曲线控件
*/
class SummaryChart : View {
private var months: List<Pair<String, Date>>? = null
private var max: Float = -1.0f
private var min: Float = -1.0f
private var points: List<Pair<Int, Float>>? = null
set(value) {
field = value
max = value?.maxBy { it.second }?.second ?: -1.0f
min = value?.minBy { it.second }?.second ?: -1.0f
}
private var selectedIndex: Int = -1
private var values: List<String>? = null
var summaryChartData by ChangeDetected(SummaryChartData()) {
months = it.months
points = it.points
values = it.values
selectedIndex = it.selectedIndex
postInvalidate()
}
private val DOT_RADIUS = dip(3)
private val SELECTED_DOT_RADIUS = dip(6)
private val textBounds: Rect by lazy { Rect() }
private val linePaint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
.apply {
color = context.colorRes(R.color.colorAccent)
strokeWidth = dip(2).toFloat()
style = Paint.Style.STROKE
}
}
private val monthsPaint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
.apply {
textSize = sp(14).toFloat()
color = context.colorRes(R.color.defaultTextColor)
}
}
private val valueTipsTextPaint by lazy {
Paint(monthsPaint).apply {
color = context.colorRes(R.color.colorAccent)
}
}
private val valueTipsPaint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
.apply {
color = 0xfff3f3f3.toInt()
style = Paint.Style.FILL
}
}
private val dotPaint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
.apply {
style = Paint.Style.FILL
color = context.colorRes(R.color.colorAccent)
}
}
private var activePointerId: Int = -1
private var lastDownX: Float = -1.0f
private var lastDownY: Float = -1.0f
private var touchSlop: Int = -1
private var isMoved: Boolean = false
private val TOUCH_RADIUS = dip(20)
private val curvePath: Path by lazy { Path() }
private val trianglePath: Path by lazy { Path() }
private val valueTipsRectF: RectF by lazy { RectF() }
private val monthClickedPublisher: PublishSubject<Date> = PublishSubject.create()
constructor(context: Context?) : this(context, null)
constructor(
context: Context?,
attrs: AttributeSet?
) : this(context, attrs, 0)
constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int
) :
super(context, attrs, defStyleAttr) {
touchSlop = ViewConfiguration.get(context)
.scaledTouchSlop
}
override fun onDraw(canvas: Canvas?) {
drawCurveLine(canvas)
drawDotsAndTips(canvas)
drawMonths(canvas)
}
/**
* 只用 *40%* 的高度画曲线, 上下留出 *30%* 的间隔
* @see getYByValue
*/
private fun drawCurveLine(canvas: Canvas?) {
points?.let {
if (it.isEmpty()) return
var preX: Float
var preY: Float
var curX: Float
var curY: Float
val firstPoint = it[0]
curX = getXByIndex(firstPoint.first)
curY = getYByValue(firstPoint.second)
curvePath.moveTo(curX, curY)
for (pair in it) {
preX = curX
preY = curY
curX = getXByIndex(pair.first)
curY = getYByValue(pair.second)
val cpx: Float = preX + (curX - preX) / 2.0f
curvePath.cubicTo(cpx, preY, cpx, curY, curX, curY)
}
canvas?.drawPath(curvePath, linePaint)
}
}
private fun drawDotsAndTips(canvas: Canvas?) {
points?.apply {
val triangleHeight = dip(5)
val triangleWidth = dip(10)
val triangleDotMargin = dip(6)
val rectRadius = dip(5).toFloat()
for ((index, pair) in this.withIndex()) {
val valueIndex = pair.first
val x = getXByIndex(valueIndex)
val y = getYByValue(pair.second)
if (valueIndex == selectedIndex) {
canvas?.drawCircle(x, y, SELECTED_DOT_RADIUS.toFloat(), dotPaint)
} else {
canvas?.drawCircle(x, y, DOT_RADIUS.toFloat(), dotPaint)
}
values?.get(index)
?.apply {
val valueWidth = getTextWith(this, valueTipsTextPaint)
val valueHeight = getTextHeight(this, valueTipsTextPaint)
if (valueIndex == selectedIndex) {
trianglePath.reset()
trianglePath.moveTo(x, y - triangleDotMargin - SELECTED_DOT_RADIUS / 2.0f)
trianglePath.lineTo(
x - triangleWidth / 2.0f,
y - triangleDotMargin - triangleHeight - SELECTED_DOT_RADIUS / 2.0f
)
trianglePath.lineTo(
x + triangleWidth / 2.0f,
y - triangleDotMargin - triangleHeight - SELECTED_DOT_RADIUS / 2.0f
)
val rectWidth = valueWidth + dip(6) * 2.0f
val rectHeight = valueHeight + dip(6) * 2.0f
valueTipsRectF.setEmpty()
valueTipsRectF.left = x - rectWidth / 2.0f
valueTipsRectF.right = valueTipsRectF.left + rectWidth
valueTipsRectF.bottom = y - triangleDotMargin - triangleHeight -
SELECTED_DOT_RADIUS / 2.0f
valueTipsRectF.top = valueTipsRectF.bottom - rectHeight
trianglePath.addRoundRect(valueTipsRectF, rectRadius, rectRadius, Path.Direction.CW)
canvas?.drawPath(trianglePath, valueTipsPaint)
valueTipsTextPaint.color = context.colorRes(R.color.colorAccent)
canvas?.drawText(
this,
valueTipsRectF.centerX() - valueWidth / 2.0f,
valueTipsRectF.centerY() + valueHeight / 2.0f,
valueTipsTextPaint
)
} else {
valueTipsTextPaint.color = context.colorRes(R.color.defaultTextColor)
canvas?.drawText(
this,
x - valueWidth / 2.0f,
y - triangleDotMargin - DOT_RADIUS / 2.0f,
valueTipsTextPaint
)
}
}
}
}
}
/**
* 底部留*40dp*画日期
*/
private fun drawMonths(canvas: Canvas?) {
months?.apply {
for ((index, value) in this.withIndex()) {
val month: String = value.first
val x = getXByIndex(index) - getTextWith(month, monthsPaint) / 2.0f
val y = height - dip(40) / 2.0f + getTextHeight(month, monthsPaint) / 2.0f
canvas?.drawText(month, x, y, monthsPaint)
}
}
}
private fun getXByIndex(index: Int): Float {
val itemSpacing = getItemSpacing()
return itemSpacing * index + itemSpacing / 2.0f
}
private fun getItemSpacing() = (width / months?.size!!).toFloat()
private fun getYByValue(value: Float): Float {
return if (max == -1.0f || min == -1.0f) {
0.0f
} else if (max == min) {
(height - dip(40)) / 2.0f
} else {
val drawingHeight = height - dip(40)
val availableDrawingHeight = drawingHeight * 0.4f
drawingHeight - (drawingHeight * 0.3f) -
(availableDrawingHeight / (max - min)) * (value - min)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.actionMasked) {
MotionEvent.ACTION_DOWN -> {
activePointerId = event.getPointerId(0)
lastDownX = event.x
lastDownY = event.y
}
MotionEvent.ACTION_MOVE -> {
val deltaX = lastDownX - event.getX(activePointerId)
val deltaY = lastDownY - event.getY(activePointerId)
if (Math.abs(deltaX) > touchSlop || Math.abs(deltaY) > touchSlop) {
isMoved = true
}
}
MotionEvent.ACTION_UP -> {
if (!isMoved) {
val itemSpacing = getItemSpacing()
val x = event.x
val y = event.y
val index: Int = (x / getItemSpacing()).toInt()
points?.filter { it.first == index }
?.take(1)
?.forEach {
val valueX = index * itemSpacing + itemSpacing / 2.0f
if (Math.abs(x - valueX) <= TOUCH_RADIUS / 2.0f &&
Math.abs(y - getYByValue(it.second)) <= TOUCH_RADIUS / 2.0f
) {
months?.get(index)
?.apply {
selectedIndex = index
postInvalidate()
monthClickedPublisher.onNext(this.second)
}
}
}
}
isMoved = false
}
}
return true
}
private fun getTextWith(
text: String,
paint: Paint
): Float =
paint.measureText(text, 0, text.length)
private fun getTextHeight(
text: String,
paint: Paint
): Int {
textBounds.setEmpty()
paint.getTextBounds(text, 0, text.length, textBounds)
return textBounds.height()
}
fun getMonthClickedObservable() = monthClickedPublisher
}
| apache-2.0 | 2a7a14c9f387ad93547088170a9820b6 | 28.953488 | 100 | 0.600932 | 4.04237 | false | false | false | false |
exercism/xkotlin | exercises/practice/perfect-numbers/.meta/src/reference/kotlin/NaturalNumber.kt | 1 | 508 |
enum class Classification {
DEFICIENT, PERFECT, ABUNDANT
}
fun classify(naturalNumber: Int): Classification {
require(naturalNumber > 0) { "$naturalNumber is not a natural number" }
val aliquotSum = naturalNumber.aliquotSum()
return when {
aliquotSum == naturalNumber -> Classification.PERFECT
aliquotSum > naturalNumber -> Classification.ABUNDANT
else -> Classification.DEFICIENT
}
}
fun Int.aliquotSum(): Int = (1 until this).filter { this % it == 0 }.sum()
| mit | e7646f8d247e7a6681ead77b743df90f | 28.882353 | 75 | 0.685039 | 3.937984 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListComponent.kt | 2 | 10793 | // 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 org.jetbrains.plugins.github.pullrequest.ui.toolwindow
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.newui.VerticalLayout
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.ui.*
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.ListUiUtil
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.codereview.OpenReviewButton
import com.intellij.util.ui.codereview.OpenReviewButtonViewModel
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.pullrequest.data.GHListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext
import org.jetbrains.plugins.github.pullrequest.data.GHPRListUpdatesChecker
import org.jetbrains.plugins.github.pullrequest.data.GHPRSearchQuery
import org.jetbrains.plugins.github.pullrequest.search.GHPRSearchCompletionProvider
import org.jetbrains.plugins.github.pullrequest.search.GHPRSearchQueryHolder
import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler
import org.jetbrains.plugins.github.ui.component.GHHandledErrorPanelModel
import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel
import org.jetbrains.plugins.github.ui.util.BoundedRangeModelThresholdListener
import org.jetbrains.plugins.github.ui.util.SingleValueModel
import java.awt.FlowLayout
import java.awt.event.ActionListener
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.ListSelectionModel
internal object GHPRListComponent {
fun create(project: Project,
dataContext: GHPRDataContext,
disposable: Disposable): JComponent {
val actionManager = ActionManager.getInstance()
val listLoader = dataContext.listLoader
val listModel = CollectionListModel(listLoader.loadedData)
listLoader.addDataListener(disposable, object : GHListLoader.ListDataListener {
override fun onDataAdded(startIdx: Int) {
val loadedData = listLoader.loadedData
listModel.add(loadedData.subList(startIdx, loadedData.size))
}
override fun onDataUpdated(idx: Int) = listModel.setElementAt(listLoader.loadedData[idx], idx)
override fun onDataRemoved(data: Any) {
(data as? GHPullRequestShort)?.let { listModel.remove(it) }
}
override fun onAllDataRemoved() = listModel.removeAll()
})
val list = object : JBList<GHPullRequestShort>(listModel) {
override fun getToolTipText(event: MouseEvent): String? {
val childComponent = ListUtil.getDeepestRendererChildComponentAt(this, event.point)
if (childComponent !is JComponent) return null
return childComponent.toolTipText
}
}.apply {
setExpandableItemsEnabled(false)
emptyText.clear()
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
}.also {
ScrollingUtil.installActions(it)
ListUtil.installAutoSelectOnMouseMove(it)
ListUiUtil.Selection.installSelectionOnFocus(it)
ListUiUtil.Selection.installSelectionOnRightClick(it)
DataManager.registerDataProvider(it) { dataId ->
if (GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId)) it.selectedValue else null
}
PopupHandler.installSelectionListPopup(it,
actionManager.getAction("Github.PullRequest.ToolWindow.List.Popup") as ActionGroup,
ActionPlaces.UNKNOWN, actionManager)
val shortcuts = CompositeShortcutSet(CommonShortcuts.ENTER, CommonShortcuts.DOUBLE_CLICK_1)
EmptyAction.registerWithShortcutSet("Github.PullRequest.Show", shortcuts, it)
ListSpeedSearch(it) { item -> item.title }
}
val openButtonViewModel = OpenReviewButtonViewModel()
OpenReviewButton.installOpenButtonListeners(list, openButtonViewModel) {
ActionManager.getInstance().getAction("Github.PullRequest.Show")
}
val renderer = GHPRListCellRenderer(dataContext.avatarIconsProvider, openButtonViewModel)
list.cellRenderer = renderer
UIUtil.putClientProperty(list, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer))
val searchQueryHolder = dataContext.searchHolder
val searchStringModel = SingleValueModel(searchQueryHolder.queryString)
searchQueryHolder.addQueryChangeListener(disposable) {
if (searchStringModel.value != searchQueryHolder.queryString)
searchStringModel.value = searchQueryHolder.queryString
}
searchStringModel.addValueChangedListener {
searchQueryHolder.queryString = searchStringModel.value
}
ListEmptyTextController(listLoader, searchQueryHolder, list.emptyText, disposable)
val searchCompletionProvider = GHPRSearchCompletionProvider(project, dataContext.repositoryDataService)
val pullRequestUiSettings = GithubPullRequestsProjectUISettings.getInstance(project)
val search = GHPRSearchPanel.create(project, searchStringModel, searchCompletionProvider, pullRequestUiSettings).apply {
border = IdeBorderFactory.createBorder(SideBorder.BOTTOM)
}
val outdatedStatePanel = JPanel(FlowLayout(FlowLayout.LEFT, JBUIScale.scale(5), 0)).apply {
background = UIUtil.getPanelBackground()
border = JBUI.Borders.empty(4, 0)
add(JLabel(GithubBundle.message("pull.request.list.outdated")))
add(ActionLink(GithubBundle.message("pull.request.list.refresh")) {
listLoader.reset()
})
isVisible = false
}
OutdatedPanelController(listLoader, dataContext.listUpdatesChecker, outdatedStatePanel, disposable)
val errorHandler = GHApiLoadingErrorHandler(project, dataContext.securityService.account) {
listLoader.reset()
}
val errorModel = GHHandledErrorPanelModel(GithubBundle.message("pull.request.list.cannot.load"), errorHandler).apply {
error = listLoader.error
}
listLoader.addErrorChangeListener(disposable) {
errorModel.error = listLoader.error
}
val errorPane = GHHtmlErrorPanel.create(errorModel)
val controlsPanel = JPanel(VerticalLayout(0)).apply {
isOpaque = false
add(search, VerticalLayout.FILL_HORIZONTAL)
add(outdatedStatePanel, VerticalLayout.FILL_HORIZONTAL)
add(errorPane, VerticalLayout.FILL_HORIZONTAL)
}
val listLoaderPanel = createListLoaderPanel(listLoader, list, disposable)
return JBUI.Panels.simplePanel(listLoaderPanel).addToTop(controlsPanel).andTransparent().also {
DataManager.registerDataProvider(it) { dataId ->
if (GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId)) {
if (list.isSelectionEmpty) null else list.selectedValue
}
else null
}
actionManager.getAction("Github.PullRequest.List.Reload").registerCustomShortcutSet(it, disposable)
}
}
private fun createListLoaderPanel(loader: GHListLoader<*>, list: JBList<GHPullRequestShort>, disposable: Disposable): JComponent {
val scrollPane = ScrollPaneFactory.createScrollPane(list, true).apply {
isOpaque = false
viewport.isOpaque = false
verticalScrollBar.apply {
isOpaque = true
UIUtil.putClientProperty(this, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, false)
}
BoundedRangeModelThresholdListener.install(verticalScrollBar) {
if (loader.canLoadMore()) loader.loadMore()
}
}
loader.addDataListener(disposable, object : GHListLoader.ListDataListener {
override fun onAllDataRemoved() {
if (scrollPane.isShowing) loader.loadMore()
}
})
val progressStripe = ProgressStripe(scrollPane, disposable,
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
if (loader.loading) startLoadingImmediately() else stopLoading()
}
loader.addLoadingStateChangeListener(disposable) {
if (loader.loading) progressStripe.startLoading() else progressStripe.stopLoading()
}
return progressStripe
}
private class ListEmptyTextController(private val listLoader: GHListLoader<*>,
private val searchHolder: GHPRSearchQueryHolder,
private val emptyText: StatusText,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
searchHolder.addQueryChangeListener(listenersDisposable, ::update)
}
private fun update() {
emptyText.clear()
if (listLoader.loading || listLoader.error != null) return
if (searchHolder.query != GHPRSearchQuery.DEFAULT) {
emptyText.appendText(GithubBundle.message("pull.request.list.no.matches"))
.appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters"), SimpleTextAttributes.LINK_ATTRIBUTES,
ActionListener {
searchHolder.query = GHPRSearchQuery.DEFAULT
})
}
else {
emptyText.appendText(GithubBundle.message("pull.request.list.nothing.loaded"))
.appendSecondaryText(GithubBundle.message("pull.request.list.refresh"), SimpleTextAttributes.LINK_ATTRIBUTES, ActionListener {
listLoader.reset()
})
}
}
}
private class OutdatedPanelController(private val listLoader: GHListLoader<*>,
private val listChecker: GHPRListUpdatesChecker,
private val panel: JPanel,
listenersDisposable: Disposable) {
init {
listLoader.addLoadingStateChangeListener(listenersDisposable, ::update)
listLoader.addErrorChangeListener(listenersDisposable, ::update)
listChecker.addOutdatedStateChangeListener(listenersDisposable, ::update)
}
private fun update() {
panel.isVisible = listChecker.outdated && (!listLoader.loading && listLoader.error == null)
}
}
}
| apache-2.0 | 7876a4590f7258a4f4b72f35b1e64dec | 44.348739 | 140 | 0.734365 | 4.973733 | false | false | false | false |
allotria/intellij-community | build/tasks/test/org/jetbrains/intellij/build/io/ZipTest.kt | 1 | 4614 | // 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 org.jetbrains.intellij.build.io
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.util.zip.ImmutableZipFile
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.configuration.ConfigurationProvider
import org.junit.Rule
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.zip.ZipEntry
import kotlin.random.Random
@Suppress("UsePropertyAccessSyntax")
class ZipTest {
@JvmField
@Rule
val tempDir = TemporaryDirectory()
@Test
fun `interrupt thread`() {
val (list, archiveFile) = createLargeArchive(128)
val zipFile = ImmutableZipFile.load(archiveFile)
val executor = Executors.newWorkStealingPool(4)
// force init of AssertJ to avoid ClosedByInterruptException on reading FileLoader index
ConfigurationProvider.CONFIGURATION_PROVIDER
for (i in 0..100) {
executor.execute {
val ioThread = runInThread {
while (!Thread.currentThread().isInterrupted()) {
for (name in list) {
assertThat(zipFile.getEntry(name)).isNotNull()
}
}
}
// once in a while, the IO thread is stopped
Thread.sleep(50)
ioThread.interrupt()
Thread.sleep(10)
ioThread.join()
}
}
executor.shutdown()
executor.awaitTermination(4, TimeUnit.MINUTES)
}
@Test
fun `do not compress jars and images`() {
val random = Random(42)
val dir = tempDir.newPath("/dir")
Files.createDirectories(dir)
val fileDescriptors = listOf(Entry("lib.jar", true), Entry("lib.zip", true), Entry("image.png", true), Entry("scalable-image.svg", true), Entry("readme.txt", true))
for (entry in fileDescriptors) {
Files.write(dir.resolve(entry.path), random.nextBytes(1024))
}
val archiveFile = tempDir.newPath("/archive.zip")
zip(archiveFile, mapOf(dir to ""))
val zipFile = ImmutableZipFile.load(archiveFile)
for (entry in fileDescriptors) {
assertThat(zipFile.getEntry(entry.path).method)
.describedAs(entry.path)
.isEqualTo(if (entry.isCompressed) ZipEntry.DEFLATED else ZipEntry.STORED)
}
}
@Test
fun `read zip file with more than 65K entries`() {
val (list, archiveFile) = createLargeArchive(Short.MAX_VALUE * 2)
val zipFile = ImmutableZipFile.load(archiveFile)
for (name in list) {
assertThat(zipFile.getEntry(name)).isNotNull()
}
}
private fun createLargeArchive(size: Int): Pair<MutableList<String>, Path> {
val random = Random(42)
val dir = tempDir.newPath("/dir")
Files.createDirectories(dir)
val list = mutableListOf<String>()
for (i in 0..size) {
val name = "entry-item${random.nextInt()}-$i"
list.add(name)
Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128)))
}
val archiveFile = tempDir.newPath("/archive.zip")
zip(archiveFile, mapOf(dir to ""))
return Pair(list, archiveFile)
}
@Test
fun `custom prefix`() {
val random = Random(42)
val dir = tempDir.newPath("/dir")
Files.createDirectories(dir)
val list = mutableListOf<String>()
for (i in 0..10) {
val name = "entry-item${random.nextInt()}-$i"
list.add(name)
Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128)))
}
val archiveFile = tempDir.newPath("/archive.zip")
zip(archiveFile, mapOf(dir to "test"))
val zipFile = ImmutableZipFile.load(archiveFile)
for (name in list) {
assertThat(zipFile.getEntry("test/$name")).isNotNull()
}
}
@Test
fun `small file`() {
val dir = tempDir.newPath("/dir")
val file = dir.resolve("samples/nested_dir/__init__.py")
Files.createDirectories(file.parent)
Files.writeString(file, "\n")
val archiveFile = tempDir.newPath("/archive.zip")
zip(archiveFile, mapOf(dir to ""))
val zipFile = ImmutableZipFile.load(archiveFile)
for (name in zipFile.entries) {
val entry = zipFile.getEntry("samples/nested_dir/__init__.py")
assertThat(entry).isNotNull()
assertThat(String(entry.getData(zipFile), Charsets.UTF_8)).isEqualTo("\n")
}
}
}
private class Entry(val path: String, val isCompressed: Boolean)
private fun runInThread(block: () -> Unit): Thread {
val thread = Thread(block, "test interrupt")
thread.isDaemon = true
thread.start()
return thread
}
| apache-2.0 | 1e7cb082277874b91d455ed904bb7439 | 30.387755 | 168 | 0.67707 | 4.008688 | false | true | false | false |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/Collision.kt | 1 | 294 | package com.thedeadpixelsociety.ld34
object Collision {
const val PLAYER: Int = 0x0001
const val WALL: Int = 0x0002
const val COIN: Int = 0x0004
const val GOAL: Int = 0x0008
const val HAZARD: Int = 0x0010
const val ALL: Int = PLAYER or WALL or COIN or GOAL or HAZARD
}
| mit | f3d31c66119bbb409fbbf6f1e701c7d2 | 28.4 | 65 | 0.690476 | 3.230769 | false | false | false | false |
square/okio | okio/src/nativeMain/kotlin/okio/FileSource.kt | 1 | 2544 | /*
* Copyright (C) 2020 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 okio
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import okio.Buffer.UnsafeCursor
import platform.posix.FILE
import platform.posix.errno
import platform.posix.fclose
import platform.posix.feof
import platform.posix.ferror
/** Reads the bytes of a file as a source. */
internal class FileSource(
private val file: CPointer<FILE>
) : Source {
private val unsafeCursor = UnsafeCursor()
private var closed = false
override fun read(
sink: Buffer,
byteCount: Long
): Long {
require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
check(!closed) { "closed" }
val sinkInitialSize = sink.size
// Request a writable segment in `sink`. We request at least 1024 bytes, unless the request is
// for smaller than that, in which case we request only that many bytes.
val cursor = sink.readAndWriteUnsafe(unsafeCursor)
val addedCapacityCount = cursor.expandBuffer(minByteCount = minOf(byteCount, 1024L).toInt())
// Now that we have a writable segment, figure out how many bytes to read. This is the smaller
// of the user's requested byte count, and the segment's writable capacity.
val attemptCount = minOf(byteCount, addedCapacityCount)
// Copy bytes from the file to the segment.
val bytesRead = cursor.data!!.usePinned { pinned ->
variantFread(pinned.addressOf(cursor.start), attemptCount.toUInt(), file).toLong()
}
// Remove new capacity that was added but not used.
cursor.resizeBuffer(sinkInitialSize + bytesRead)
cursor.close()
return when {
bytesRead == attemptCount -> bytesRead
feof(file) != 0 -> if (bytesRead == 0L) -1L else bytesRead
ferror(file) != 0 -> throw errnoToIOException(errno)
else -> bytesRead
}
}
override fun timeout(): Timeout = Timeout.NONE
override fun close() {
if (closed) return
closed = true
fclose(file)
}
}
| apache-2.0 | 379b899ae9eb76e5741949e6ffa57a4d | 32.473684 | 98 | 0.712264 | 4.163666 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkUpdateNotification.kt | 1 | 8649 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
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.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.NlsContexts.NotificationContent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.io.systemIndependentPath
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
private val LOG = logger<JdkUpdateNotification>()
/**
* There are the following possibilities for a given JDK:
* - we have no notification (this object must be tracked)
* - we show update suggestion
* - the JDK update is running
* - a error notification is shown
*
* This class keeps track of all such possibilities
*
* The [whenComplete] callback is executed when we reach the final state, which is:
* - the error notification is dismissed
* - the update notification is dismissed (or rejected)
* - the JDK update is completed
*/
class JdkUpdateNotification(val jdk: Sdk,
val oldItem: JdkItem,
val newItem: JdkItem,
private val whenComplete: (JdkUpdateNotification) -> Unit
) {
private val lock = ReentrantLock()
private val jdkVersion = jdk.versionString
private val jdkHome = jdk.homePath
private val openProjectsSnapshot = ProjectManager.getInstance().openProjects.map { it.locationHash }.toSortedSet()
private var myIsTerminated = false
private var myIsUpdateRunning = false
/**
* Can be either suggestion or error notification
*/
private var myPendingNotification : Notification? = null
private fun Notification.bindNextNotificationAndShow() {
bindNextNotification(this)
notify(null)
}
private fun bindNextNotification(notification: Notification) {
lock.withLock {
myPendingNotification?.expire()
notification.whenExpired {
lock.withLock {
if (myPendingNotification === notification) {
myPendingNotification = null
}
}
}
myPendingNotification = notification
}
}
fun tryReplaceWithNewerNotification(other: JdkUpdateNotification? = null): Boolean = lock.withLock {
//nothing to do if update is already running
if (myIsUpdateRunning) return false
//the pending notification is the same as before
if (other != null && isSameNotification(other)) return false
myPendingNotification?.expire()
myPendingNotification = null
reachTerminalState()
return true
}
private fun isSameNotification(other: JdkUpdateNotification): Boolean {
if (this.jdkVersion != other.jdkVersion) return false
if (this.jdkHome != other.jdkHome) return false
if (this.newItem != other.newItem) return false
//a new open project may also have a update notification, that is not shown there
if (!this.openProjectsSnapshot.containsAll(other.openProjectsSnapshot)) return false
return true
}
/**
* The state-machine reached it's end
*/
private fun reachTerminalState(): Unit = lock.withLock {
if (myIsTerminated) return
myIsTerminated = true
whenComplete(this)
}
fun isTerminated() = lock.withLock { myIsTerminated }
private fun updateJdkAction(@NotificationContent message: String) = InstallUpdateNotification(message)
inner class InstallUpdateNotification(@NotificationContent message: String) : NotificationAction(message) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
lock.withLock {
if (myIsUpdateRunning) return
myIsUpdateRunning = true
}
updateJdk(e.project)
notification.expire()
}
}
private fun rejectJdkAction() = RejectUpdateNotification()
inner class RejectUpdateNotification : NotificationAction(ProjectBundle.message("notification.link.jdk.update.skip")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
service<JdkUpdaterState>().blockVersion(jdk, newItem)
notification.expire()
reachTerminalState()
}
}
fun showNotificationIfAbsent() : Unit = lock.withLock {
if (myPendingNotification != null || myIsUpdateRunning || myIsTerminated) return
val title = ProjectBundle.message("notification.title.jdk.update.found")
val message = ProjectBundle.message("notification.text.jdk.update.found",
jdk.name,
newItem.fullPresentationText,
oldItem.versionPresentationText)
NotificationGroupManager.getInstance().getNotificationGroup("JDK Update")
.createNotification(title, message, NotificationType.INFORMATION)
.setImportant(true)
.addAction(updateJdkAction(ProjectBundle.message("notification.link.jdk.update.apply")))
.addAction(rejectJdkAction())
.bindNextNotificationAndShow()
}
private fun showUpdateErrorNotification(feedItem: JdkItem) : Unit = lock.withLock {
NotificationGroupManager.getInstance().getNotificationGroup("JDK Update Error")
.createNotification(type = NotificationType.ERROR)
.setTitle(ProjectBundle.message("progress.title.updating.jdk.0.to.1", jdk.name, feedItem.fullPresentationText))
.setContent(ProjectBundle.message("progress.title.updating.jdk.failed", feedItem.fullPresentationText))
.addAction(updateJdkAction(ProjectBundle.message("notification.link.jdk.update.retry")))
.addAction(rejectJdkAction())
.bindNextNotificationAndShow()
}
private fun updateJdk(project: Project?) {
val title = ProjectBundle.message("progress.title.updating.jdk.0.to.1", jdk.name, newItem.fullPresentationText)
ProgressManager.getInstance().run(
object : Task.Backgroundable(null /*progress should be global*/, title, true, ALWAYS_BACKGROUND) {
override fun run(indicator: ProgressIndicator) {
val newJdkHome = try {
val installer = JdkInstaller.getInstance()
val request = installer.prepareJdkInstallation(newItem, installer.defaultInstallDir(newItem))
installer.installJdk(request, indicator, project)
//make sure VFS sees the files and sets up the JDK correctly
indicator.text = ProjectBundle.message("progress.text.updating.jdk.setting.up")
VfsUtil.markDirtyAndRefresh(false, true, true, request.installDir.toFile())
request.javaHome
}
catch (t: Throwable) {
if (t is ControlFlowException) {
reachTerminalState()
throw t
}
LOG.warn("Failed to update $jdk to $newItem. ${t.message}", t)
showUpdateErrorNotification(newItem)
lock.withLock { myIsUpdateRunning = false }
return
}
invokeLater {
try {
runWriteAction {
jdk.sdkModificator.apply {
removeAllRoots()
homePath = newJdkHome.systemIndependentPath
versionString = newItem.versionString
}.commitChanges()
(jdk.sdkType as? SdkType)?.setupSdkPaths(jdk)
reachTerminalState()
}
}
catch (t: Throwable) {
if (t is ControlFlowException) {
reachTerminalState()
throw t
}
LOG.warn("Failed to apply downloaded JDK update for $jdk from $newItem at $newJdkHome. ${t.message}", t)
showUpdateErrorNotification(newItem)
lock.withLock { myIsUpdateRunning = false }
}
}
}
}
)
}
}
| apache-2.0 | eb7c6128e25d06d33fe2424d29ab0687 | 37.611607 | 140 | 0.695919 | 4.985014 | false | false | false | false |
DeflatedPickle/Quiver | spritesheetviewer/src/main/kotlin/com/deflatedpickle/spritesheetviewer/SpriteSheetViewer.kt | 1 | 1417 | /* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.spritesheetviewer
import com.deflatedpickle.quiver.Quiver
import com.deflatedpickle.quiver.filepanel.api.Viewer
import java.io.File
import java.lang.Integer.max
import java.lang.Integer.min
import javax.imageio.ImageIO
import javax.swing.JScrollPane
object SpriteSheetViewer : Viewer<File> {
var index = 0
set(value) {
field = min(max(value, 0), maxIndex)
SpriteSheetViewerPlugin.validateButtons()
}
var maxIndex = 0
override fun refresh(with: File) {
val image = ImageIO.read(with)
if (image.width == Quiver.resolution) {
SpriteSheetComponent.image = image.getSubimage(0, index * Quiver.resolution, Quiver.resolution, Quiver.resolution)
maxIndex = (image.height / Quiver.resolution) - 1
SpriteSheetViewerPlugin.indexLabel.text = "${index + 1}/${maxIndex + 1}"
SpriteSheetViewerPlugin.validateButtons()
} else {
SpriteSheetComponent.image = image
}
SpriteSheetComponent.repaint()
}
override fun getComponent() = SpriteSheetComponent
override fun getScroller() = JScrollPane(getComponent())
override fun getToolBars() = Viewer.ToolBarPosition(
north = SpriteSheetViewerPlugin.mediaToolbar,
south = SpriteSheetViewerPlugin.toolbar
)
}
| mit | b9a1a30d969053a6d4b5a89e39d8101b | 32.738095 | 126 | 0.688073 | 4.400621 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesDiffHelperImpl.kt | 1 | 4945 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.changes
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.ComparisonUtil
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.openapi.diff.impl.patch.PatchReader
import com.intellij.openapi.vcs.changes.Change
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewThread
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupportImpl
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewThreadMapping
import org.jetbrains.plugins.github.pullrequest.data.GHPRChangeDiffData
import org.jetbrains.plugins.github.pullrequest.data.GHPRChangesProvider
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataProvider
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewService
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewServiceAdapter
import org.jetbrains.plugins.github.util.GHPatchHunkUtil
class GHPRChangesDiffHelperImpl(private val reviewService: GHPRReviewService,
private val avatarIconsProviderFactory: CachingGithubAvatarIconsProvider.Factory,
private val currentUser: GHUser)
: GHPRChangesDiffHelper {
private var dataProvider: GHPRDataProvider? = null
private var changesProvider: GHPRChangesProvider? = null
override fun setUp(dataProvider: GHPRDataProvider, changesProvider: GHPRChangesProvider) {
this.dataProvider = dataProvider
this.changesProvider = changesProvider
}
override fun reset() {
dataProvider = null
changesProvider = null
}
override fun getReviewSupport(change: Change): GHPRDiffReviewSupport? {
val reviewService = dataProvider?.let { GHPRReviewServiceAdapter.create(reviewService, it) } ?: return null
return changesProvider?.let { provider ->
val diffData = provider.findChangeDiffData(change) ?: return null
val createReviewCommentHelper = GHPRCreateDiffCommentParametersHelper(diffData.commitSha, diffData.filePath, diffData.linesMapper)
return GHPRDiffReviewSupportImpl(reviewService, diffData.diffRanges,
{ mapThread(diffData, it) },
createReviewCommentHelper,
avatarIconsProviderFactory, currentUser)
}
}
private fun mapThread(diffData: GHPRChangeDiffData, thread: GHPullRequestReviewThread): GHPRDiffReviewThreadMapping? {
val originalCommitSha = thread.originalCommit?.oid ?: return null
if (!diffData.contains(originalCommitSha, thread.path)) return null
val (side, line) = when (diffData) {
is GHPRChangeDiffData.Cumulative -> thread.position?.let { diffData.linesMapper.findFileLocation(it) } ?: return null
is GHPRChangeDiffData.Commit -> {
val patchReader = PatchReader(GHPatchHunkUtil.createPatchFromHunk(thread.path, thread.diffHunk))
patchReader.readTextPatches()
val patchHunk = patchReader.textPatches[0].hunks.lastOrNull() ?: return null
val position = GHPatchHunkUtil.getHunkLinesCount(patchHunk) - 1
val (unmappedSide, unmappedLine) = GHPatchHunkUtil.findSideFileLineFromHunkLineIndex(patchHunk, position) ?: return null
diffData.mapPosition(originalCommitSha, unmappedSide, unmappedLine) ?: return null
}
}
return GHPRDiffReviewThreadMapping(side, line, thread)
}
override fun getDiffComputer(change: Change): DiffUserDataKeysEx.DiffComputer? {
val diffRanges = changesProvider?.findChangeDiffData(change)?.diffRangesWithoutContext ?: return null
return DiffUserDataKeysEx.DiffComputer { text1, text2, policy, innerChanges, indicator ->
val comparisonManager = ComparisonManagerImpl.getInstanceImpl()
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
if (!ComparisonUtil.isValidRanges(text1, text2, lineOffsets1, lineOffsets2, diffRanges)) {
error("Invalid diff line ranges for change $change")
}
val iterable = DiffIterableUtil.create(diffRanges, lineOffsets1.lineCount, lineOffsets2.lineCount)
DiffIterableUtil.iterateAll(iterable).map {
comparisonManager.compareLinesInner(it.first, text1, text2, lineOffsets1, lineOffsets2, policy, innerChanges,
indicator)
}.flatten()
}
}
} | apache-2.0 | f5dd487e27bc9b9855638450da5157e9 | 52.76087 | 140 | 0.762386 | 4.718511 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/python/sdk/add/PyAddNewVirtualEnvPanel.kt | 1 | 5950 | // 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.jetbrains.python.sdk.add
import com.intellij.execution.ExecutionException
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.ui.FormBuilder
import com.jetbrains.python.PyBundle
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.sdk.*
import icons.PythonIcons
import org.jetbrains.annotations.SystemIndependent
import java.awt.BorderLayout
import javax.swing.Icon
import javax.swing.event.DocumentEvent
/**
* @author vlan
*/
class PyAddNewVirtualEnvPanel(private val project: Project?,
private val module: Module?,
private val existingSdks: List<Sdk>,
newProjectPath: String?,
private val context: UserDataHolder) : PyAddNewEnvPanel() {
override val envName: String = "Virtualenv"
override var newProjectPath: String? = newProjectPath
set(value) {
field = value
pathField.text = FileUtil.toSystemDependentName(PySdkSettings.instance.getPreferredVirtualEnvBasePath(projectBasePath))
}
val path: String
get() = pathField.text.trim()
override val panelName: String = "New environment"
override val icon: Icon = PythonIcons.Python.Virtualenv
private val baseSdkField = PySdkPathChoosingComboBox().apply {
val preferredSdkPath = PySdkSettings.instance.preferredVirtualEnvBaseSdk
val detectedPreferredSdk = items.find { it.homePath == preferredSdkPath }
selectedSdk = when {
detectedPreferredSdk != null -> detectedPreferredSdk
preferredSdkPath != null -> PyDetectedSdk(preferredSdkPath).apply {
childComponent.insertItemAt(this, 0)
}
else -> items.getOrNull(0)
}
}
private val pathField = TextFieldWithBrowseButton().apply {
text = FileUtil.toSystemDependentName(PySdkSettings.instance.getPreferredVirtualEnvBasePath(projectBasePath))
addBrowseFolderListener(PyBundle.message("python.sdk.select.location.for.virtualenv.title"), null, project,
FileChooserDescriptorFactory.createSingleFolderDescriptor())
}
private val inheritSitePackagesField = JBCheckBox("Inherit global site-packages")
private val makeSharedField = JBCheckBox(PyBundle.message("available.to.all.projects"))
init {
layout = BorderLayout()
val formPanel = FormBuilder.createFormBuilder()
.addLabeledComponent("Location:", pathField)
.addLabeledComponent(PyBundle.message("base.interpreter"), baseSdkField)
.addComponent(inheritSitePackagesField)
.addComponent(makeSharedField)
.panel
add(formPanel, BorderLayout.NORTH)
addInterpretersAsync(baseSdkField) {
findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: getSdksToInstall()
}
}
override fun validateAll(): List<ValidationInfo> =
listOfNotNull(validateEnvironmentDirectoryLocation(pathField),
validateSdkComboBox(baseSdkField, this))
override fun getOrCreateSdk(): Sdk? {
val root = pathField.text
val baseSdk = baseSdkField.selectedSdk
.let { if (it is PySdkToInstall) it.install(module) { detectSystemWideSdks(module, existingSdks, context) } else it }
if (baseSdk == null) return null
val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.creating.virtualenv.title"), false) {
override fun compute(indicator: ProgressIndicator): String {
indicator.isIndeterminate = true
val packageManager = PyPackageManager.getInstance(baseSdk)
return packageManager.createVirtualEnv(root, inheritSitePackagesField.isSelected)
}
}
val shared = makeSharedField.isSelected
val associatedPath = if (!shared) projectBasePath else null
val sdk = createSdkByGenerateTask(task, existingSdks, baseSdk, associatedPath, null) ?: return null
if (!shared) {
sdk.associateWithModule(module, newProjectPath)
}
moduleToExcludeSdkFrom(root, project)?.excludeInnerVirtualEnv(sdk)
with(PySdkSettings.instance) {
setPreferredVirtualEnvBasePath(FileUtil.toSystemIndependentName(pathField.text), projectBasePath)
preferredVirtualEnvBaseSdk = baseSdk.homePath
}
return sdk
}
override fun addChangeListener(listener: Runnable) {
pathField.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
listener.run()
}
})
baseSdkField.childComponent.addItemListener { listener.run() }
}
private fun moduleToExcludeSdkFrom(path: String, project: Project?): Module? {
val possibleProjects = if (project != null) listOf(project) else ProjectManager.getInstance().openProjects.asList()
val rootFile = StandardFileSystems.local().refreshAndFindFileByPath(path) ?: return null
return possibleProjects
.asSequence()
.map { ModuleUtil.findModuleForFile(rootFile, it) }
.filterNotNull()
.firstOrNull()
}
private val projectBasePath: @SystemIndependent String?
get() = newProjectPath ?: module?.basePath ?: project?.basePath
}
| apache-2.0 | adff0a98870e1c7babae4127958cdc64 | 42.75 | 143 | 0.746891 | 4.913295 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Email.kt | 1 | 4115 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.notifications.email.EmailMessage
import slatekit.notifications.email.EmailService
import slatekit.notifications.email.SendGrid
//</doc:import_required>
//<doc:import_examples>
import slatekit.common.templates.Template
import slatekit.common.templates.TemplatePart
import slatekit.common.templates.Templates
import slatekit.results.Try
import slatekit.common.conf.Config
import slatekit.common.info.ApiLogin
import slatekit.common.io.Uris
import slatekit.common.types.Vars
import slatekit.common.ext.env
import slatekit.results.builders.Tries
import kotlinx.coroutines.runBlocking
import slatekit.common.ext.orElse
//</doc:import_examples>
class Example_Email : Command("auth") {
override fun execute(request: CommandRequest): Try<Any> {
//<doc:setup>
// Setup 1: Getting Api key/login info from config
// Load the config file from slatekit directory in user_home directory
// e.g. {user_home}/slatekit/conf/sms.conf
// NOTE: It is safer/more secure to store config files there.
val conf = Config.of("~/.slatekit/conf/email.conf")
val apiKey1 = conf.apiLogin("email")
// Setup 2: Get the api key either through conf or explicitly
val apiKey2 = ApiLogin("17181234567", "ABC1234567", "password", "dev", "sendgrid-email")
// Setup 3a: Setup the email service ( basic ) with api key
val apiKey = apiKey1 ?: apiKey2
val emailService1 = SendGrid(apiKey.key, apiKey.pass, apiKey.account)
// Setup 3b: Setup the sms service with support for templates
val templates = Templates.build(
templates = listOf(
Template("email_welcome", Uris.readText("~/slatekit/templates/email_welcome.txt") ?: ""),
Template("email_pass", """
Hi @{user.name},
<p>
Your code for @{app.name} is @{app.code}.
</p>
Regards,
@{app.from}
@{app.tagline}
""".trimIndent())
),
subs = listOf(
"app.name" to { s: TemplatePart -> "My App" },
"app.from" to { s: TemplatePart -> "My App Team" },
"app.tagline" to { s:TemplatePart -> "My App tagline" }
)
)
val emailService2 = SendGrid(apiKey.key, apiKey.pass, apiKey.account, templates)
val email: EmailService = emailService2
//</doc:setup>
//<doc:examples>
runBlocking {
// Sample email ( loaded from environment variable for test/example purposes )
val toAddress = "SLATEKIT_EXAMPLE_EMAIL".env().orElse("[email protected]")
// Use case 1: Send a confirmation code to the U.S. to verify a users phone number.
val result1 = email.send(toAddress, "Welcome to MyApp.com 1", "showWelcome!", false)
// Use case 2: Send using a constructed message object
email.sendSync(EmailMessage(toAddress, "Welcome to MyApp.com 2", "showWelcome!", false))
// Use case 3: Send message using one of the setup templates
val result2 = email.sendTemplate("email_welcome", toAddress, "Welcome to MyApp.com 3", true,
Vars(listOf(
"app.confirmUrl" to "https://www.myapp.com/confirm?abc=123",
"user.name" to "user1",
"user.email" to "[email protected]",
"app.code" to "ABC123"
)))
}
//</doc:examples>
return Tries.success("Ok")
}
}
| apache-2.0 | 6b0ca9620e32cb678d6dec849835b86c | 37.101852 | 113 | 0.598299 | 4.304393 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/smap/newsmap/mappingInSubInlineLambdaSameFileInline.kt | 2 | 741 | // NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun test(s: () -> Unit) {
val z = 1;
s()
val x = 1;
}
// FILE: 2.kt
import test.*
inline fun test2(s: () -> String): String {
val z = 1;
val res = s()
return res
}
fun box(): String {
var result = "fail"
test {
{
result = test2 {
"OK"
}
}()
}
return result
}
// FILE: 1.smap
// FILE: 2.smap
SMAP
2.kt
Kotlin
*S Kotlin
*F
+ 1 2.kt
_2Kt
+ 2 1.kt
test/_1Kt
*L
1#1,26:1
6#2,4:27
*E
*S KotlinDebug
*F
+ 1 2.kt
_2Kt
*L
14#1,4:27
*E
SMAP
2.kt
Kotlin
*S Kotlin
*F
+ 1 2.kt
_2Kt$box$1$1
+ 2 2.kt
_2Kt
*L
1#1,26:1
6#2,3:27
*E
*S KotlinDebug
*F
+ 1 2.kt
_2Kt$box$1$1
*L
16#1,3:27
*E | apache-2.0 | 452a5886c5d6e6a735b59269e85253b2 | 8.275 | 43 | 0.497976 | 2.179412 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/diagnostics/functions/tailRecursion/returnInCatch.kt | 2 | 416 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND_WITHOUT_CHECK: JS
<!NO_TAIL_CALLS_FOUND!>tailrec fun test(counter : Int) : Int<!> {
if (counter == 0) return 0
try {
throw Exception()
} catch (e : Exception) {
return <!TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED!>test<!>(counter - 1)
}
}
fun box() : String = if (test(3) == 0) "OK" else "FAIL" | apache-2.0 | 7f30dfbec8d3cb4806ad9e7ccfc073c5 | 28.785714 | 77 | 0.612981 | 3.301587 | false | true | false | false |
micabytes/lib_game | src/main/java/com/micabytes/Game.kt | 2 | 1156 | package com.micabytes
import android.app.Activity
import android.app.Application
import com.micabytes.app.BaseActivityCallback
import com.micabytes.util.CrashReportingTree
import timber.log.Timber
//import com.squareup.leakcanary.LeakCanary
/* The Game Application */
class Game : Application() {
init {
instance = this
}
val mFTActivityLifecycleCallbacks = BaseActivityCallback()
override fun onCreate() {
super.onCreate()
/*
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
*/
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else {
Timber.plant(CrashReportingTree())
}
registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks)
}
companion object {
@JvmStatic
lateinit var instance: Game
private set
val currentActivity: Activity
get() = instance.mFTActivityLifecycleCallbacks.currentActivity!!
var world: WorldInterface? = null
var data: DataInterface? = null
}
}
| apache-2.0 | 93c1e3a5ff126a9a28b8ef32259ec01f | 23.083333 | 70 | 0.711073 | 4.64257 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-foundation/src/androidAndroidTest/kotlin/androidx/wear/compose/foundation/SpyModifier.kt | 3 | 5547 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.foundation
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.Placeable
import org.junit.Assert
/**
* Class used to capture information regarding measure/layout.
* This is used through CurvedModifier.spy, and captures information on that point in the modifier
* chain.
* This is also the single point of access to the internals of CurvedLayout, so tests are easier to
* refactor if we change something there.
*/
internal data class CapturedInfo(
// Counters
var measuresCount: Int = 0,
var layoutsCount: Int = 0,
var drawCount: Int = 0
) {
// Captured information
var lastLayoutInfo: CurvedLayoutInfo? = null
var parentOuterRadius: Float = 0f
var parentThickness: Float = 0f
var parentStartAngleRadians: Float = 0f
var parentSweepRadians: Float = 0f
fun reset() {
measuresCount = 0
layoutsCount = 0
drawCount = 0
lastLayoutInfo = null
parentOuterRadius = 0f
parentThickness = 0f
parentStartAngleRadians = 0f
parentSweepRadians = 0f
}
}
internal const val FINE_FLOAT_TOLERANCE = 0.001f
internal fun CapturedInfo.checkDimensions(
expectedAngleDegrees: Float? = null,
expectedThicknessPx: Float? = null
) {
if (expectedAngleDegrees != null) {
Assert.assertEquals(
expectedAngleDegrees,
lastLayoutInfo!!.sweepRadians.toDegrees(),
FINE_FLOAT_TOLERANCE
)
}
if (expectedThicknessPx != null) {
Assert.assertEquals(
expectedThicknessPx,
lastLayoutInfo!!.thickness,
FINE_FLOAT_TOLERANCE
)
}
}
internal fun CapturedInfo.checkParentDimensions(
expectedAngleDegrees: Float? = null,
expectedThicknessPx: Float? = null,
) {
if (expectedAngleDegrees != null) {
Assert.assertEquals(
expectedAngleDegrees,
parentSweepRadians.toDegrees(),
FINE_FLOAT_TOLERANCE
)
}
if (expectedThicknessPx != null) {
Assert.assertEquals(
expectedThicknessPx,
parentThickness,
FINE_FLOAT_TOLERANCE
)
}
}
internal fun CapturedInfo.checkPositionOnParent(
expectedAngularPositionDegrees: Float,
expectedRadialPositionPx: Float
) {
Assert.assertEquals(
expectedAngularPositionDegrees,
(lastLayoutInfo!!.startAngleRadians - parentStartAngleRadians).toDegrees(),
FINE_FLOAT_TOLERANCE
)
Assert.assertEquals(
expectedRadialPositionPx,
parentOuterRadius - lastLayoutInfo!!.outerRadius,
FINE_FLOAT_TOLERANCE
)
}
internal fun CapturedInfo.checkPositionRelativeTo(
target: CapturedInfo,
expectedAngularPositionDegrees: Float,
expectedRadialPositionPx: Float
) {
Assert.assertEquals(
expectedAngularPositionDegrees,
lastLayoutInfo!!.startAngleRadians - target.lastLayoutInfo!!.startAngleRadians,
FINE_FLOAT_TOLERANCE
)
Assert.assertEquals(
expectedRadialPositionPx,
target.lastLayoutInfo!!.outerRadius - lastLayoutInfo!!.outerRadius,
FINE_FLOAT_TOLERANCE
)
}
internal fun CurvedModifier.spy(capturedInfo: CapturedInfo) =
this.then { wrapped -> SpyCurvedChildWrapper(capturedInfo, wrapped) }
internal class SpyCurvedChildWrapper(private val capturedInfo: CapturedInfo, wrapped: CurvedChild) :
BaseCurvedChildWrapper(wrapped) {
override fun CurvedMeasureScope.initializeMeasure(measurables: Iterator<Measurable>) =
with(wrapped) {
capturedInfo.measuresCount++
initializeMeasure(measurables)
}
override fun doRadialPosition(
parentOuterRadius: Float,
parentThickness: Float,
): PartialLayoutInfo {
capturedInfo.parentOuterRadius = parentOuterRadius
capturedInfo.parentThickness = parentThickness
return wrapped.radialPosition(
parentOuterRadius,
parentThickness,
)
}
override fun doAngularPosition(
parentStartAngleRadians: Float,
parentSweepRadians: Float,
centerOffset: Offset
): Float {
capturedInfo.parentStartAngleRadians = parentStartAngleRadians
capturedInfo.parentSweepRadians = parentSweepRadians
return wrapped.angularPosition(
parentStartAngleRadians,
parentSweepRadians,
centerOffset
)
}
override fun (Placeable.PlacementScope).placeIfNeeded() = with(wrapped) {
capturedInfo.lastLayoutInfo = layoutInfo
capturedInfo.layoutsCount++
placeIfNeeded()
}
override fun DrawScope.draw() = with(wrapped) {
capturedInfo.lastLayoutInfo = layoutInfo
capturedInfo.drawCount++
draw()
}
}
| apache-2.0 | c7dd4f6909633844d71cce603d5fe51b | 29.646409 | 100 | 0.687218 | 4.661345 | false | false | false | false |
AndroidX/androidx | camera/camera-camera2-pipe-integration/src/androidTest/java/androidx/camera/camera2/pipe/testing/VerifyResultListener.kt | 3 | 3772 | /*
* 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.testing
import android.hardware.camera2.CaptureFailure
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.FrameInfo
import androidx.camera.camera2.pipe.FrameNumber
import androidx.camera.camera2.pipe.Request
import androidx.camera.camera2.pipe.RequestMetadata
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeout
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
class VerifyResultListener(capturesCount: Int) : Request.Listener {
private val captureRequests = mutableListOf<RequestMetadata>()
private val captureResults = mutableListOf<FrameInfo>()
private val waitingCount = atomic(capturesCount)
private val failureException =
TimeoutException("Test doesn't complete after waiting for $capturesCount frames.")
@Volatile private var startReceiving = false
@Volatile private var _verifyBlock: (
captureRequest: RequestMetadata,
captureResult: FrameInfo
) -> Boolean = { _, _ -> false }
private val signal = CompletableDeferred<Unit>()
override fun onAborted(request: Request) {
if (!startReceiving) {
return
}
if (waitingCount.decrementAndGet() < 0) {
signal.completeExceptionally(failureException)
return
}
}
override fun onComplete(
requestMetadata: RequestMetadata,
frameNumber: FrameNumber,
result: FrameInfo
) {
if (!startReceiving) {
return
}
captureRequests.add(requestMetadata)
captureResults.add(result)
if (waitingCount.decrementAndGet() < 0) {
signal.completeExceptionally(failureException)
return
}
if (_verifyBlock(requestMetadata, result)) {
signal.complete(Unit)
}
}
override fun onFailed(
requestMetadata: RequestMetadata,
frameNumber: FrameNumber,
captureFailure: CaptureFailure
) {
if (!startReceiving) {
return
}
if (waitingCount.decrementAndGet() < 0) {
signal.completeExceptionally(failureException)
return
}
}
suspend fun verify(
verifyBlock: (
captureRequest: RequestMetadata,
captureResult: FrameInfo
) -> Boolean = { _, _ -> false },
timeout: Long = TimeUnit.SECONDS.toMillis(5),
) {
withTimeout(timeout) {
_verifyBlock = verifyBlock
startReceiving = true
signal.await()
}
}
suspend fun verifyAllResults(
verifyBlock: (
captureRequests: List<RequestMetadata>,
captureResults: List<FrameInfo>
) -> Unit,
timeout: Long = TimeUnit.SECONDS.toMillis(5),
) {
withTimeout(timeout) {
startReceiving = true
signal.join()
verifyBlock(captureRequests, captureResults)
}
}
} | apache-2.0 | d076016375446347b0e867befd90b97a | 31.247863 | 94 | 0.661188 | 4.905072 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/DslMembersCompletion.kt | 6 | 2440 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.completion.PrefixMatcher
import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.ReceiverType
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.psiUtil.collectAnnotationEntriesFromStubOrPsi
class DslMembersCompletion(
private val prefixMatcher: PrefixMatcher,
private val elementFactory: LookupElementFactory,
receiverTypes: List<ReceiverType>?,
private val collector: LookupElementsCollector,
private val indicesHelper: KotlinIndicesHelper,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>
) {
/**
* It is stated that `two implicit receivers of the same DSL are not accessible in the same scope`,
* that's why we need only the last one of the receivers to provide the completion (see [DslMarker]).
*
* When the last receiver is not a part of DSL, [nearestReceiverMarkers] will be empty, and dsl
* members would not be suggested in the autocompletion (see KT-30996).
*/
private val nearestReceiver = receiverTypes?.lastOrNull()
private val nearestReceiverMarkers = nearestReceiver?.takeIf { it.implicit }?.extractDslMarkers().orEmpty()
fun completeDslFunctions() {
if (nearestReceiver == null || nearestReceiverMarkers.isEmpty()) return
val receiverMarkersShortNames = nearestReceiverMarkers.map { it.shortName() }.distinct()
val extensionDescriptors = indicesHelper.getCallableTopLevelExtensions(
nameFilter = { prefixMatcher.prefixMatches(it) },
declarationFilter = {
(it as KtModifierListOwner).modifierList?.collectAnnotationEntriesFromStubOrPsi()
?.any { it.shortName in receiverMarkersShortNames }
?: false
},
callTypeAndReceiver = callTypeAndReceiver,
receiverTypes = listOf(nearestReceiver.type)
)
extensionDescriptors.forEach {
collector.addDescriptorElements(it, elementFactory, notImported = true, withReceiverCast = false, prohibitDuplicates = true)
}
collector.flushToResultSet()
}
}
| apache-2.0 | 9fa4494b1a33e8921de9d02c4f31f757 | 46.843137 | 158 | 0.728689 | 5.147679 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/psiUtils.kt | 2 | 6554 | // 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.nj2k
import com.intellij.codeInsight.generation.GenerateEqualsHelper.getEqualsSignature
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.j2k.ClassKind
import org.jetbrains.kotlin.j2k.ReferenceSearcher
import org.jetbrains.kotlin.j2k.isNullLiteral
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
//copied from old j2k
fun canKeepEqEq(left: PsiExpression, right: PsiExpression?): Boolean {
if (left.isNullLiteral() || (right?.isNullLiteral() == true)) return true
when (val type = left.type) {
is PsiPrimitiveType, is PsiArrayType -> return true
is PsiClassType -> {
if (right?.type is PsiPrimitiveType) return true
val psiClass = type.resolve() ?: return false
if (!psiClass.hasModifierProperty(PsiModifier.FINAL)) return false
if (psiClass.isEnum) return true
val equalsSignature = getEqualsSignature(left.project, GlobalSearchScope.allScope(left.project))
val equalsMethod = MethodSignatureUtil.findMethodBySignature(psiClass, equalsSignature, true)
if (equalsMethod != null && equalsMethod.containingClass?.qualifiedName != CommonClassNames.JAVA_LANG_OBJECT) return false
return true
}
else -> return false
}
}
internal fun PsiMember.visibility(
referenceSearcher: ReferenceSearcher,
assignNonCodeElements: ((JKFormattingOwner, PsiElement) -> Unit)?
): JKVisibilityModifierElement =
modifierList?.children?.mapNotNull { child ->
if (child !is PsiKeyword) return@mapNotNull null
when (child.text) {
PsiModifier.PACKAGE_LOCAL -> Visibility.INTERNAL
PsiModifier.PRIVATE -> Visibility.PRIVATE
PsiModifier.PROTECTED -> handleProtectedVisibility(referenceSearcher)
PsiModifier.PUBLIC -> Visibility.PUBLIC
else -> null
}?.let {
JKVisibilityModifierElement(it)
}?.also { modifier ->
assignNonCodeElements?.also { it(modifier, child) }
}
}?.firstOrNull() ?: JKVisibilityModifierElement(Visibility.INTERNAL)
fun PsiMember.modality(assignNonCodeElements: ((JKFormattingOwner, PsiElement) -> Unit)?) =
modifierList?.children?.mapNotNull { child ->
if (child !is PsiKeyword) return@mapNotNull null
when (child.text) {
PsiModifier.FINAL -> Modality.FINAL
PsiModifier.ABSTRACT -> Modality.ABSTRACT
else -> null
}?.let {
JKModalityModifierElement(it)
}?.also { modifier ->
assignNonCodeElements?.let { it(modifier, child) }
}
}?.firstOrNull() ?: JKModalityModifierElement(Modality.OPEN)
fun JvmClassKind.toJk() = when (this) {
JvmClassKind.CLASS -> JKClass.ClassKind.CLASS
JvmClassKind.INTERFACE -> JKClass.ClassKind.INTERFACE
JvmClassKind.ANNOTATION -> JKClass.ClassKind.ANNOTATION
JvmClassKind.ENUM -> JKClass.ClassKind.ENUM
}
private fun PsiMember.handleProtectedVisibility(referenceSearcher: ReferenceSearcher): Visibility {
val originalClass = containingClass ?: return Visibility.PROTECTED
// Search for usages only in Java because java-protected member cannot be used in Kotlin from same package
val usages = referenceSearcher.findUsagesForExternalCodeProcessing(this, searchJava = true, searchKotlin = false)
return if (usages.any { !allowProtected(it.element, this, originalClass) })
Visibility.PUBLIC
else Visibility.PROTECTED
}
private fun allowProtected(element: PsiElement, member: PsiMember, originalClass: PsiClass): Boolean {
if (element.parent is PsiNewExpression && member is PsiMethod && member.isConstructor) {
// calls to for protected constructors are allowed only within same class or as super calls
return element.parentsWithSelf.contains(originalClass)
}
return element.parentsWithSelf.filterIsInstance<PsiClass>().any { accessContainingClass ->
if (!InheritanceUtil.isInheritorOrSelf(accessContainingClass, originalClass, true)) return@any false
if (element !is PsiReferenceExpression) return@any true
val qualifierExpression = element.qualifierExpression ?: return@any true
// super.foo is allowed if 'foo' is protected
if (qualifierExpression is PsiSuperExpression) return@any true
val receiverType = qualifierExpression.type ?: return@any true
val resolvedClass = PsiUtil.resolveGenericsClassInType(receiverType).element ?: return@any true
// receiver type should be subtype of containing class
InheritanceUtil.isInheritorOrSelf(resolvedClass, accessContainingClass, true)
}
}
fun PsiClass.classKind(): JKClass.ClassKind =
when {
isAnnotationType -> JKClass.ClassKind.ANNOTATION
isEnum -> JKClass.ClassKind.ENUM
isInterface -> JKClass.ClassKind.INTERFACE
else -> JKClass.ClassKind.CLASS
}
val KtDeclaration.fqNameWithoutCompanions
get() = generateSequence(this) { it.containingClassOrObject }
.filter { it.safeAs<KtObjectDeclaration>()?.isCompanion() != true && it.name != null }
.toList()
.foldRight(containingKtFile.packageFqName) { container, acc -> acc.child(Name.identifier(container.name!!)) }
internal fun <T> runUndoTransparentActionInEdt(inWriteAction: Boolean, action: () -> T): T {
var result: T? = null
ApplicationManager.getApplication().invokeAndWait {
CommandProcessor.getInstance().runUndoTransparentAction {
result = when {
inWriteAction -> runWriteAction(action)
else -> action()
}
}
}
return result!!
} | apache-2.0 | acd408a8f5fe43285e5efc63a493b46d | 41.019231 | 158 | 0.719103 | 5.006875 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/flippedSideEffect.kt | 13 | 190 | // PROBLEM: none
var x = 42
// Should be converted into arg in --x..++x (41..42) but initial check is arg <= ++x (43) && --x (42) <= arg
fun foo(arg: Int) = <caret>arg <= ++x && --x <= arg | apache-2.0 | 23d205f2db7a5ea93eee930744d5f098 | 30.833333 | 108 | 0.542105 | 2.753623 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/utils/GroupSerialization.kt | 1 | 5728 | package com.habitrpg.android.habitica.utils
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.inventory.QuestRageStrike
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Group
import io.realm.Realm
import io.realm.RealmList
import java.lang.reflect.Type
class GroupSerialization : JsonDeserializer<Group>, JsonSerializer<Group> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Group {
val group = Group()
val obj = json.asJsonObject
group.id = obj.get("_id").asString
group.name = obj.get("name").asString
if (obj.has("description") && !obj.get("description").isJsonNull) {
group.description = obj.get("description").asString
}
if (obj.has("summary") && !obj.get("summary").isJsonNull) {
group.summary = obj.get("summary").asString
}
if (obj.has("leaderMessage") && !obj.get("leaderMessage").isJsonNull) {
group.leaderMessage = obj.get("leaderMessage").asString
}
if (obj.has("privacy")) {
group.privacy = obj.get("privacy").asString
}
if (obj.has("memberCount")) {
group.memberCount = obj.get("memberCount").asInt
}
if (obj.has("balance")) {
group.balance = obj.get("balance").asDouble
}
if (obj.has("logo") && !obj.get("logo").isJsonNull) {
group.logo = obj.get("logo").asString
}
if (obj.has("type")) {
group.type = obj.get("type").asString
}
if (obj.has("leader")) {
if (obj.get("leader").isJsonPrimitive) {
group.leaderID = obj.get("leader").asString
} else {
val leader = obj.get("leader").asJsonObject
group.leaderID = leader.get("_id").asString
if (leader.has("profile") && !leader.get("profile").isJsonNull) {
if (leader.get("profile").asJsonObject.has("name")) {
group.leaderName = leader.get("profile").asJsonObject.get("name").asString
}
}
}
}
if (obj.has("quest")) {
group.quest = context.deserialize(obj.get("quest"), object : TypeToken<Quest>() {}.type)
group.quest?.id = group.id
val questObject = obj.getAsJsonObject("quest")
if (questObject.has("members")) {
val members = obj.getAsJsonObject("quest").getAsJsonObject("members")
val realm = Realm.getDefaultInstance()
val dbMembers = realm.copyFromRealm(realm.where(Member::class.java).equalTo("party.id", group.id).findAll())
realm.close()
dbMembers.forEach { member ->
if (members.has(member.id)) {
val value = members.get(member.id)
if (value.isJsonNull) {
member.participatesInQuest = null
} else {
member.participatesInQuest = value.asBoolean
}
} else {
member.participatesInQuest = null
}
members.remove(member.id)
}
members.entrySet().forEach { (key, value) ->
val member = Member()
member.id = key
if (!value.isJsonNull) {
member.participatesInQuest = value.asBoolean
}
dbMembers.add(member)
}
val newMembers = RealmList<Member>()
newMembers.addAll(dbMembers)
group.quest?.participants = newMembers
}
if (questObject.has("extra") && questObject["extra"].asJsonObject.has("worldDmg")) {
val worldDamageObject = questObject.getAsJsonObject("extra").getAsJsonObject("worldDmg")
worldDamageObject.entrySet().forEach { (key, value) ->
val rageStrike = QuestRageStrike(key, value.asBoolean)
group.quest?.addRageStrike(rageStrike)
}
}
}
if (obj.has("leaderOnly")) {
val leaderOnly = obj.getAsJsonObject("leaderOnly")
if (leaderOnly.has("challenges")) {
group.leaderOnlyChallenges = leaderOnly.get("challenges").asBoolean
}
if (leaderOnly.has("getGems")) {
group.leaderOnlyGetGems = leaderOnly.get("getGems").asBoolean
}
}
return group
}
override fun serialize(src: Group, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val obj = JsonObject()
obj.addProperty("name", src.name)
obj.addProperty("description", src.description)
obj.addProperty("summary", src.summary)
obj.addProperty("logo", src.logo)
obj.addProperty("type", src.type)
obj.addProperty("type", src.type)
obj.addProperty("leader", src.leaderID)
val leaderOnly = JsonObject()
leaderOnly.addProperty("challenges", src.leaderOnlyChallenges)
leaderOnly.addProperty("getGems", src.leaderOnlyGetGems)
obj.add("leaderOnly", leaderOnly)
return obj
}
}
| gpl-3.0 | 8b639a3721ba7602fd500b2488243cc1 | 42.75 | 124 | 0.544518 | 4.789298 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/Ec2.kt | 1 | 23678 | package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.ec2.model.*
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.CloudFormation
import uy.kohesive.iac.model.aws.cloudformation.resources.EC2
import uy.kohesive.iac.model.aws.helpers.RunSingleEC2InstanceRequest
// TODO: RequestSpotInstancesRequest can also result RunInstancesRequest, also mind the 'AvailabilityZone' property
class Ec2InstancePropertiesBuilder : ResourcePropertiesBuilder<RunSingleEC2InstanceRequest> {
override val requestClazz = RunSingleEC2InstanceRequest::class
// TODO: SsmAssociations?
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as RunSingleEC2InstanceRequest).originalRequest.let {
val placementRequest = relatedObjects.filterIsInstance<ModifyInstancePlacementRequest>().lastOrNull()
EC2.Instance(
Affinity = placementRequest?.affinity,
BlockDeviceMappings = it.blockDeviceMappings?.map {
EC2.Instance.MappingProperty(
DeviceName = it.deviceName,
NoDevice = it.noDevice?.let { emptyMap<String, String>() },
VirtualName = it.virtualName,
Ebs = it.ebs?.let {
EC2.Instance.MappingProperty.AmazonElasticBlockStoreProperty(
DeleteOnTermination = it.deleteOnTermination?.toString(),
VolumeType = it.volumeType,
VolumeSize = it.volumeSize?.toString(),
Iops = it.iops?.toString(),
SnapshotId = it.snapshotId,
Encrypted = it.encrypted?.toString()
)
}
)
},
InstanceType = it.instanceType,
PrivateIpAddress = it.privateIpAddress,
SecurityGroupIds = it.securityGroupIds,
IamInstanceProfile = it.iamInstanceProfile?.let {
it.arn ?: it.name
},
ImageId = it.imageId,
AdditionalInfo = it.additionalInfo,
DisableApiTermination = it.disableApiTermination?.toString(),
EbsOptimized = it.ebsOptimized?.toString(),
InstanceInitiatedShutdownBehavior = it.instanceInitiatedShutdownBehavior,
Ipv6AddressCount = it.ipv6AddressCount?.toString(),
Ipv6Addresses = it.ipv6Addresses?.map {
EC2.NetworkInterface.Ipv6AddressProperty(
Ipv6Address = it.ipv6Address
)
},
HostId = placementRequest?.hostId,
KernelId = it.kernelId,
KeyName = it.keyName,
Monitoring = it.monitoring?.toString(),
NetworkInterfaces = it.networkInterfaces?.map {
EC2.Instance.EmbeddedProperty(
AssociatePublicIpAddress = it.associatePublicIpAddress?.toString(),
Ipv6Addresses = it.ipv6Addresses?.map {
EC2.NetworkInterface.Ipv6AddressProperty(
Ipv6Address = it.ipv6Address
)
},
Ipv6AddressCount = it.ipv6AddressCount?.toString(),
PrivateIpAddress = it.privateIpAddress,
DeleteOnTermination = it.deleteOnTermination?.toString(),
Description = it.description,
DeviceIndex = it.deviceIndex.toString(),
GroupSet = it.groups,
NetworkInterfaceId = it.networkInterfaceId,
PrivateIpAddresses = it.privateIpAddresses?.map {
EC2.NetworkInterface.PrivateIPSpecificationProperty(
PrivateIpAddress = it.privateIpAddress,
Primary = it.primary.toString()
)
},
SecondaryPrivateIpAddressCount = it.secondaryPrivateIpAddressCount?.toString(),
SubnetId = it.subnetId
)
},
SubnetId = it.subnetId,
PlacementGroupName = it.placement?.groupName,
RamdiskId = it.ramdiskId,
Tenancy = placementRequest?.tenancy,
SecurityGroups = it.securityGroups,
SourceDestCheck = relatedObjects.filterIsInstance<ModifyInstanceAttributeRequest>().lastOrNull()?.sourceDestCheck?.toString(),
Volumes = relatedObjects.filterIsInstance<AttachVolumeRequest>().map {
EC2.Instance.MountPointProperty(
Device = it.device,
VolumeId = it.volumeId
)
},
UserData = it.userData,
Tags = relatedObjects.getTags()
)
}
}
class Ec2HostPropertiesBuilder : ResourcePropertiesBuilder<AllocateHostsRequest> {
override val requestClazz = AllocateHostsRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as AllocateHostsRequest).let {
EC2.Host(
AutoPlacement = it.autoPlacement,
InstanceType = it.instanceType,
AvailabilityZone = it.availabilityZone
)
}
}
class Ec2EIPPropertiesBuilder : ResourcePropertiesBuilder<AllocateAddressRequest> {
override val requestClazz = AllocateAddressRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as AllocateAddressRequest).let {
EC2.EIP(
Domain = it.domain,
InstanceId = relatedObjects.filterIsInstance<AssociateAddressRequest>().firstOrNull()?.instanceId
)
}
}
class Ec2SecurityGroupPropertiesBuilder : ResourcePropertiesBuilder<CreateSecurityGroupRequest> {
override val requestClazz = CreateSecurityGroupRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateSecurityGroupRequest).let {
EC2.SecurityGroup(
GroupDescription = it.description,
SecurityGroupIngress = relatedObjects.filterIsInstance<AuthorizeSecurityGroupIngressRequest>().flatMap { request ->
(listOf(request.ipPermissionFromBody()) + request.ipPermissions).filterNotNull()
}.flatMap { rule ->
(rule.ipv6Ranges.map { it.cidrIpv6 } + rule.ipv4Ranges.map { it.cidrIp }).map {
rule to it
}
}.map { ruleToCidrPair ->
EC2.SecurityGroup.RuleProperty(
CidrIp = ruleToCidrPair.second,
IpProtocol = ruleToCidrPair.first.ipProtocol,
FromPort = ruleToCidrPair.first.fromPort?.toString(),
ToPort = ruleToCidrPair.first.toPort?.toString()
)
},
SecurityGroupEgress = relatedObjects.filterIsInstance<AuthorizeSecurityGroupEgressRequest>().flatMap { request ->
(listOf(request.ipPermissionFromBody()) + request.ipPermissions).filterNotNull()
}.flatMap { rule ->
(rule.ipv6Ranges.map { it.cidrIpv6 } + rule.ipv4Ranges.map { it.cidrIp }).map {
rule to it
}
}.map { ruleToCidrPair ->
EC2.SecurityGroup.RuleProperty(
CidrIp = ruleToCidrPair.second,
IpProtocol = ruleToCidrPair.first.ipProtocol,
FromPort = ruleToCidrPair.first.fromPort?.toString(),
ToPort = ruleToCidrPair.first.toPort?.toString()
)
},
VpcId = request.vpcId,
Tags = relatedObjects.getTags()
)
}
}
class EC2CustomerGatewayResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateCustomerGatewayRequest> {
override val requestClazz = CreateCustomerGatewayRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateCustomerGatewayRequest).let {
EC2.CustomerGateway(
BgpAsn = request.bgpAsn.toString(),
IpAddress = request.publicIp,
Type = request.type,
Tags = relatedObjects.getTags()
)
}
}
class EC2DHCPOptionsResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateDhcpOptionsRequest> {
override val requestClazz = CreateDhcpOptionsRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateDhcpOptionsRequest).let {
fun getOptionValues(optionName: String): List<String>?
= request.dhcpConfigurations.firstOrNull { it.key == optionName }?.values
EC2.DHCPOptions(
DomainName = getOptionValues("domain-name")?.firstOrNull(),
DomainNameServers = getOptionValues("domain-name-servers"),
NetbiosNameServers = getOptionValues("netbios-name-servers"),
NetbiosNodeType = getOptionValues("netbios-node-type"),
NtpServers = getOptionValues("ntp-servers"),
Tags = relatedObjects.getTags()
)
}
}
class EC2FlowLogResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateFlowLogsRequest> {
override val requestClazz = CreateFlowLogsRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateFlowLogsRequest).let {
EC2.FlowLog(
ResourceId = request.resourceIds.first(),
DeliverLogsPermissionArn = request.deliverLogsPermissionArn,
LogGroupName = request.logGroupName,
ResourceType = request.resourceType,
TrafficType = request.trafficType
)
}
}
class EC2InternetGatewayResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateInternetGatewayRequest> {
override val requestClazz = CreateInternetGatewayRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateInternetGatewayRequest).let {
EC2.InternetGateway(
Tags = relatedObjects.getTags()
)
}
}
class EC2NatGatewayResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateNatGatewayRequest> {
override val requestClazz = CreateNatGatewayRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateNatGatewayRequest).let {
EC2.NatGateway(
AllocationId = request.allocationId,
SubnetId = request.subnetId
)
}
}
class EC2NetworkAclResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateNetworkAclRequest> {
override val requestClazz = CreateNetworkAclRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateNetworkAclRequest).let {
EC2.NetworkAcl(
VpcId = request.vpcId,
Tags = relatedObjects.getTags()
)
}
}
class EC2NetworkAclEntryResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateNetworkAclEntryRequest> {
override val requestClazz = CreateNetworkAclEntryRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateNetworkAclEntryRequest).let {
EC2.NetworkAclEntry(
CidrBlock = request.cidrBlock,
Egress = request.egress?.toString(),
Ipv6CidrBlock = request.ipv6CidrBlock,
NetworkAclId = request.networkAclId,
PortRange = request.portRange?.let {
EC2.NetworkAclEntry.PortRangeProperty(
From = it.from?.toString(),
To = it.to?.toString()
)
},
Protocol = request.protocol,
RuleAction = request.ruleAction,
RuleNumber = request.ruleNumber.toString(),
Icmp = request.icmpTypeCode?.let {
EC2.NetworkAclEntry.IcmpProperty(
Code = it.code?.toString(),
Type = it.type?.toString()
)
}
)
}
}
class EC2NetworkInterfaceResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateNetworkInterfaceRequest> {
override val requestClazz = CreateNetworkInterfaceRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateNetworkInterfaceRequest).let {
EC2.NetworkInterface(
Description = request.description,
GroupSet = request.groups,
Ipv6AddressCount = request.ipv6AddressCount?.toString(),
Ipv6Addresses = request.ipv6Addresses?.map {
EC2.NetworkInterface.Ipv6AddressProperty(
Ipv6Address = it.ipv6Address
)
},
PrivateIpAddress = request.privateIpAddress,
PrivateIpAddresses = request.privateIpAddresses?.map {
EC2.NetworkInterface.PrivateIPSpecificationProperty(
PrivateIpAddress = it.privateIpAddress,
Primary = (it.primary ?: false).toString()
)
},
SecondaryPrivateIpAddressCount = request.secondaryPrivateIpAddressCount?.toString(),
SubnetId = request.subnetId,
Tags = relatedObjects.getTags(),
SourceDestCheck = relatedObjects.filterIsInstance<ModifyNetworkInterfaceAttributeRequest>().lastOrNull()?.let {
it.isSourceDestCheck?.toString()
}
)
}
}
class EC2PlacementGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreatePlacementGroupRequest> {
override val requestClazz = CreatePlacementGroupRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreatePlacementGroupRequest).let {
EC2.PlacementGroup(
Strategy = request.strategy
)
}
}
class EC2RouteResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateRouteRequest> {
override val requestClazz = CreateRouteRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateRouteRequest).let {
EC2.Route(
DestinationCidrBlock = request.destinationCidrBlock,
DestinationIpv6CidrBlock = request.destinationIpv6CidrBlock,
GatewayId = request.gatewayId,
InstanceId = request.instanceId,
NatGatewayId = request.natGatewayId,
NetworkInterfaceId = request.networkInterfaceId,
RouteTableId = request.routeTableId,
VpcPeeringConnectionId = request.vpcPeeringConnectionId
)
}
}
class EC2RouteTableResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateRouteTableRequest> {
override val requestClazz = CreateRouteTableRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateRouteTableRequest).let {
EC2.RouteTable(
VpcId = request.vpcId,
Tags = relatedObjects.getTags()
)
}
}
class EC2SubnetResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateSubnetRequest> {
override val requestClazz = CreateSubnetRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateSubnetRequest).let {
EC2.Subnet(
AvailabilityZone = request.availabilityZone,
CidrBlock = request.cidrBlock,
VpcId = request.vpcId,
MapPublicIpOnLaunch = relatedObjects.filterIsInstance<ModifySubnetAttributeRequest>().lastOrNull()?.mapPublicIpOnLaunch?.toString(),
Tags = relatedObjects.getTags()
)
}
}
class EC2VPCResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpcRequest> {
override val requestClazz = CreateVpcRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpcRequest).let {
val modifyRequest = relatedObjects.filterIsInstance<ModifyVpcAttributeRequest>().lastOrNull()
EC2.VPC(
CidrBlock = request.cidrBlock,
InstanceTenancy = request.instanceTenancy,
EnableDnsHostnames = modifyRequest?.enableDnsHostnames?.toString(),
EnableDnsSupport = modifyRequest?.enableDnsSupport?.toString(),
Tags = relatedObjects.getTags()
)
}
}
class EC2VPCEndpointResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpcEndpointRequest> {
override val requestClazz = CreateVpcEndpointRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpcEndpointRequest).let {
EC2.VPCEndpoint(
PolicyDocument = request.policyDocument,
RouteTableIds = request.routeTableIds,
ServiceName = request.serviceName,
VpcId = request.vpcId
)
}
}
class EC2VPCPeeringConnectionResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpcPeeringConnectionRequest> {
override val requestClazz = CreateVpcPeeringConnectionRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpcPeeringConnectionRequest).let {
EC2.VPCPeeringConnection(
PeerVpcId = request.peerVpcId,
VpcId = request.vpcId,
Tags = relatedObjects.getTags()
)
}
}
class EC2VPNConnectionResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpnConnectionRequest> {
override val requestClazz = CreateVpnConnectionRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpnConnectionRequest).let {
EC2.VPNConnection(
CustomerGatewayId = request.customerGatewayId,
Type = request.type,
VpnGatewayId = request.vpnGatewayId,
StaticRoutesOnly = request.options?.staticRoutesOnly?.toString(),
Tags = relatedObjects.getTags()
)
}
}
class EC2VPNConnectionRouteResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpnConnectionRouteRequest> {
override val requestClazz = CreateVpnConnectionRouteRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpnConnectionRouteRequest).let {
EC2.VPNConnectionRoute(
DestinationCidrBlock = request.destinationCidrBlock,
VpnConnectionId = request.vpnConnectionId
)
}
}
class EC2VPNGatewayResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVpnGatewayRequest> {
override val requestClazz = CreateVpnGatewayRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVpnGatewayRequest).let {
EC2.VPNGateway(
Type = request.type,
Tags = relatedObjects.getTags()
)
}
}
class EC2VolumeResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateVolumeRequest> {
override val requestClazz = CreateVolumeRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateVolumeRequest).let {
EC2.Volume(
AvailabilityZone = request.availabilityZone,
AutoEnableIO = relatedObjects.filterIsInstance<ModifyVolumeAttributeRequest>().lastOrNull()?.autoEnableIO?.toString(),
Encrypted = request.encrypted?.toString(),
Iops = request.iops?.toString(),
KmsKeyId = request.kmsKeyId,
Size = request.size?.toString(),
SnapshotId = request.snapshotId,
VolumeType = request.volumeType,
Tags = request.tagSpecifications?.flatMap { it.tags }?.map {
CloudFormation.ResourceTag(
Key = it.key,
Value = it.value
)
}
)
}
}
private fun AuthorizeSecurityGroupIngressRequest.ipPermissionFromBody()
= if (ipPermissions.isEmpty()) {
IpPermission()
.withIpv4Ranges(this.cidrIp?.let { IpRange().withCidrIp(it) })
.withToPort(this.toPort)
.withFromPort(this.fromPort)
.withIpProtocol(this.ipProtocol)
} else {
null
}
private fun AuthorizeSecurityGroupEgressRequest.ipPermissionFromBody()
= if (ipPermissions.isEmpty()) {
IpPermission()
.withIpv4Ranges(this.cidrIp?.let { IpRange().withCidrIp(it) })
.withToPort(this.toPort)
.withFromPort(this.fromPort)
.withIpProtocol(this.ipProtocol)
} else {
null
}
private fun List<Any>.getTags() = filterIsInstance<CreateTagsRequest>().flatMap { it.tags }.map {
CloudFormation.ResourceTag(
Key = it.key,
Value = it.value
)
}
| mit | 20f637832f1726ec97309f1b00c8544c | 42.525735 | 148 | 0.59342 | 5.516775 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/LastModifiedFiles.kt | 1 | 4482 | // 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.scripting.gradle
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.FileAttribute
import org.jetbrains.kotlin.idea.KotlinPluginInternalApi
import org.jetbrains.kotlin.idea.core.script.scriptingErrorLog
import org.jetbrains.kotlin.idea.core.util.readNullable
import org.jetbrains.kotlin.idea.core.util.readStringList
import org.jetbrains.kotlin.idea.core.util.writeNullable
import org.jetbrains.kotlin.idea.core.util.writeStringList
import java.io.DataInputStream
import java.io.DataOutput
import java.io.DataOutputStream
/**
* Optimized collection for storing last modified files with ability to
* get time of last modified file expect given one ([lastModifiedTimeStampExcept]).
*
* This is required since Gradle scripts configurations should be updated on
* each other script changes (but not on the given script changes itself).
*
* Actually works by storing two last timestamps with the set of files modified at this times.
*/
class LastModifiedFiles(
private var last: SimultaneouslyChangedFiles = SimultaneouslyChangedFiles(),
private var previous: SimultaneouslyChangedFiles = SimultaneouslyChangedFiles()
) {
init {
previous.fileIds.removeAll(last.fileIds)
if (previous.fileIds.isEmpty()) previous = SimultaneouslyChangedFiles()
}
class SimultaneouslyChangedFiles(
val ts: Long = Long.MIN_VALUE,
val fileIds: MutableSet<String> = mutableSetOf()
) {
override fun toString(): String {
return "SimultaneouslyChangedFiles(ts=$ts, fileIds=$fileIds)"
}
}
@Synchronized
fun fileChanged(ts: Long, fileId: String) {
when {
ts > last.ts -> {
val prevPrev = previous
previous = last
previous.fileIds.remove(fileId)
if (previous.fileIds.isEmpty()) previous = prevPrev
last = SimultaneouslyChangedFiles(ts, hashSetOf(fileId))
}
ts == last.ts -> last.fileIds.add(fileId)
ts == previous.ts -> previous.fileIds.add(fileId)
}
}
@Synchronized
fun lastModifiedTimeStampExcept(fileId: String): Long = when {
last.fileIds.size == 1 && last.fileIds.contains(fileId) -> previous.ts
else -> last.ts
}
override fun toString(): String {
return "LastModifiedFiles(last=$last, previous=$previous)"
}
companion object {
private val fileAttribute = FileAttribute("last-modified-files", 1, false)
fun read(buildRoot: VirtualFile): LastModifiedFiles? {
try {
return fileAttribute.readAttribute(buildRoot)?.use {
readLastModifiedFiles(it)
}
} catch (e: Exception) {
scriptingErrorLog("Cannot read data for buildRoot=$buildRoot from file attributes", e)
return null
}
}
@KotlinPluginInternalApi
fun readLastModifiedFiles(it: DataInputStream) = it.readNullable {
LastModifiedFiles(readSCF(it), readSCF(it))
}
fun write(buildRoot: VirtualFile, data: LastModifiedFiles?) {
try {
fileAttribute.writeAttribute(buildRoot).use {
writeLastModifiedFiles(it, data)
}
} catch (e: Exception) {
scriptingErrorLog("Cannot store data=$data for buildRoot=$buildRoot to file attributes", e)
fileAttribute.writeAttribute(buildRoot).use {
writeLastModifiedFiles(it, null)
}
}
}
@KotlinPluginInternalApi
fun writeLastModifiedFiles(it: DataOutputStream, data: LastModifiedFiles?) {
it.writeNullable(data) { data ->
writeSCF(data.last)
writeSCF(data.previous)
}
}
fun remove(buildRoot: VirtualFile) {
write(buildRoot, null)
}
private fun readSCF(it: DataInputStream) = SimultaneouslyChangedFiles(it.readLong(), it.readStringList().toMutableSet())
private fun DataOutput.writeSCF(last: SimultaneouslyChangedFiles) {
writeLong(last.ts)
writeStringList(last.fileIds.toList())
}
}
} | apache-2.0 | 503382c1cf75c94d94b824777e472498 | 36.049587 | 158 | 0.647033 | 4.688285 | false | false | false | false |
LateNightProductions/CardKeeper | app/src/main/java/com/awscherb/cardkeeper/ui/create/CreateViewModel.kt | 1 | 1731 | package com.awscherb.cardkeeper.ui.create
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.awscherb.cardkeeper.data.model.ScannedCode
import com.awscherb.cardkeeper.data.service.ScannedCodeService
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
class CreateViewModel(
private val scannedCodeService: ScannedCodeService
) : ViewModel() {
val title = MutableLiveData<String>()
val text = MutableLiveData<String>()
val format = MutableLiveData<CreateType>()
val saveResult = MutableLiveData<SaveResult>()
fun save() {
val titleValue = title.value
val textValue = text.value
val formatValue = format.value
when {
titleValue.isNullOrEmpty() -> saveResult.postValue(InvalidTitle)
textValue.isNullOrEmpty() -> saveResult.postValue(InvalidText)
formatValue == null -> saveResult.postValue(InvalidFormat)
else -> {
val scannedCode = ScannedCode(
title = titleValue,
text = textValue,
format = formatValue.format
)
scannedCodeService.addScannedCode(scannedCode)
.onEach {
saveResult.postValue(
SaveSuccess(it.id)
)
}.launchIn(viewModelScope)
}
}
}
}
sealed class SaveResult
object InvalidTitle : SaveResult()
object InvalidText : SaveResult()
object InvalidFormat : SaveResult()
data class SaveSuccess(val codeId: Int) : SaveResult()
| apache-2.0 | 38cdf86acc112c87603d82bbf4678c2a | 29.910714 | 76 | 0.642403 | 5.046647 | false | false | false | false |
siosio/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenSetupProjectTest.kt | 1 | 3961 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.importing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTest
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTestCase
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import junit.framework.TestCase
import org.jetbrains.idea.maven.MavenImportingTestCase
import org.jetbrains.idea.maven.MavenMultiVersionImportingTestCase
import org.jetbrains.idea.maven.MavenTestCase
import org.jetbrains.idea.maven.importing.xml.MavenBuildFileBuilder
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.idea.maven.project.actions.AddFileAsMavenProjectAction
import org.jetbrains.idea.maven.project.actions.AddManagedFilesAction
import org.jetbrains.idea.maven.utils.MavenUtil.SYSTEM_ID
import org.junit.Test
class MavenSetupProjectTest : ExternalSystemSetupProjectTest, MavenImportingTestCase() {
override fun getSystemId(): ProjectSystemId = SYSTEM_ID
override fun assertModules(project: Project, vararg projectInfo: ExternalSystemSetupProjectTestCase.ProjectInfo) {
waitForImportCompletion(project)
super<ExternalSystemSetupProjectTest>.assertModules(project, *projectInfo)
}
@Test
fun `test settings are not reset`() {
val projectInfo = generateProject("A")
val linkedProjectInfo = generateProject("L")
waitForImport {
openProjectFrom(projectInfo.projectFile)
}.use {
assertModules(it, projectInfo)
MavenWorkspaceSettingsComponent.getInstance(it).settings.getGeneralSettings().isWorkOffline = true
waitForImport {
attachProject(it, linkedProjectInfo.projectFile)
}
assertModules(it, projectInfo, linkedProjectInfo)
TestCase.assertTrue(MavenWorkspaceSettingsComponent.getInstance (it).settings.getGeneralSettings().isWorkOffline)
}
}
override fun generateProject(id: String): ExternalSystemSetupProjectTestCase.ProjectInfo {
val name = "${System.currentTimeMillis()}-$id"
createProjectSubFile("$name-external-module/pom.xml", MavenBuildFileBuilder("$name-external-module").generate())
createProjectSubFile("$name-project/$name-module/pom.xml", MavenBuildFileBuilder("$name-module").generate())
val buildScript = MavenBuildFileBuilder("$name-project")
.withPomPackaging()
.withModule("$name-module")
.withModule("../$name-external-module")
.generate()
val projectFile = createProjectSubFile("$name-project/pom.xml", buildScript)
return ExternalSystemSetupProjectTestCase.ProjectInfo(projectFile, "$name-project", "$name-module", "$name-external-module")
}
override fun attachProject(project: Project, projectFile: VirtualFile) {
AddManagedFilesAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
}
override fun attachProjectFromScript(project: Project, projectFile: VirtualFile) {
AddFileAsMavenProjectAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
}
override fun <R> waitForImport(action: () -> R): R = action()
private fun waitForImportCompletion(project: Project) {
NonBlockingReadActionImpl.waitForAsyncTaskCompletion()
val projectManager = MavenProjectsManager.getInstance(project)
projectManager.initForTests()
ApplicationManager.getApplication().invokeAndWait {
projectManager.waitForResolvingCompletion()
projectManager.performScheduledImportInTests()
}
}
} | apache-2.0 | 8948485425eeca9dc13cab1b8366d750 | 46.73494 | 140 | 0.797526 | 4.878079 | false | true | false | false |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/httpserver/KtorApplicationModule.kt | 1 | 11632 | package info.dvkr.screenstream.mjpeg.httpserver
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.mjpeg.HttpServerException
import info.dvkr.screenstream.mjpeg.randomString
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.utils.io.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.*
import java.io.IOException
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
internal fun Application.appModule(
httpServerFiles: HttpServerFiles,
clientData: ClientData,
mjpegSharedFlow: SharedFlow<ByteArray>,
lastJPEG: AtomicReference<ByteArray>,
blockedJPEG: ByteArray,
stopDeferred: AtomicReference<CompletableDeferred<Unit>?>,
sendEvent: (HttpServer.Event) -> Unit
) {
val crlf = "\r\n".toByteArray()
val jpegBaseHeader = "Content-Type: image/jpeg\r\nContent-Length: ".toByteArray()
val multipartBoundary = randomString(20)
val contentType = ContentType.parse("multipart/x-mixed-replace; boundary=$multipartBoundary")
val jpegBoundary = "--$multipartBoundary\r\n".toByteArray()
suspend fun writeMJPEGFrame(channel: ByteWriteChannel, jpeg: ByteArray): Int {
if (channel.isClosedForWrite) return 0
channel.writeFully(jpegBaseHeader, 0, jpegBaseHeader.size)
val jpegSizeText = jpeg.size.toString().toByteArray()
channel.writeFully(jpegSizeText, 0, jpegSizeText.size)
channel.writeFully(crlf, 0, crlf.size)
channel.writeFully(crlf, 0, crlf.size)
channel.writeFully(jpeg, 0, jpeg.size)
channel.writeFully(crlf, 0, crlf.size)
channel.writeFully(jpegBoundary, 0, jpegBoundary.size)
channel.flush()
return jpegBaseHeader.size + jpegSizeText.size + crlf.size * 3 + jpeg.size + jpegBoundary.size
}
environment.monitor.subscribe(ApplicationStarted) {
XLog.i(getLog("monitor", "KtorApplicationStarted: ${hashCode()}"))
}
environment.monitor.subscribe(ApplicationStopped) {
XLog.i(getLog("monitor", "KtorApplicationStopped: ${hashCode()}"))
it.environment.parentCoroutineContext.cancel()
clientData.clearStatistics()
stopDeferred.getAndSet(null)?.complete(Unit)
}
install(DefaultHeaders) { header(HttpHeaders.CacheControl, "no-cache") }
install(CORS) {
allowHeader(HttpHeaders.AccessControlAllowOrigin)
anyHost()
}
install(StatusPages) {
status(HttpStatusCode.NotFound) { call, _ ->
call.respondRedirect(HttpServerFiles.ROOT_ADDRESS, permanent = true)
}
status(HttpStatusCode.Forbidden) { call, _ ->
call.respondRedirect(HttpServerFiles.CLIENT_BLOCKED_ADDRESS)
}
status(HttpStatusCode.Unauthorized) { call, _ ->
call.respondRedirect(HttpServerFiles.PIN_REQUEST_ADDRESS)
}
exception<Throwable> { call, cause ->
if (cause is IOException) return@exception
if (cause is CancellationException) return@exception
if (cause is IllegalArgumentException) return@exception
XLog.e([email protected]("exception<Throwable>", cause.toString()))
XLog.e([email protected]("exception"), cause)
sendEvent(HttpServer.Event.Error(HttpServerException))
call.respond(HttpStatusCode.InternalServerError)
}
}
routing {
route(HttpServerFiles.ROOT_ADDRESS) {
handle {
if (clientData.enablePin.not()) {
call.respondText(httpServerFiles.indexHtml, ContentType.Text.Html)
} else {
val ipAddress: InetSocketAddress? = ClientAddressWorkAround.getInetSocketAddress(call.request)
val fallbackHost = call.request.local.remoteHost
val clientId = ClientData.getId(ipAddress, fallbackHost)
if (clientData.isAddressBlocked(ipAddress, fallbackHost)) {
call.respond(HttpStatusCode.Forbidden)
} else {
if (clientData.isClientAuthorized(clientId)) {
call.respondText(httpServerFiles.indexHtml, ContentType.Text.Html)
} else {
call.respond(HttpStatusCode.Unauthorized)
}
}
}
}
get(HttpServerFiles.PIN_REQUEST_ADDRESS) {
if (clientData.enablePin.not()) {
call.respond(HttpStatusCode.NotFound)
} else {
val ipAddress: InetSocketAddress? = ClientAddressWorkAround.getInetSocketAddress(call.request)
val fallbackHost = call.request.local.remoteHost
val clientId = ClientData.getId(ipAddress, fallbackHost)
if (clientData.isAddressBlocked(ipAddress, fallbackHost)) {
call.respond(HttpStatusCode.Forbidden)
} else {
clientData.onConnected(clientId, ipAddress, fallbackHost)
when (call.request.queryParameters[HttpServerFiles.PIN_PARAMETER]) {
httpServerFiles.pin -> {
clientData.onPinCheck(clientId, true)
call.respondText(httpServerFiles.indexHtml, ContentType.Text.Html)
}
null -> {
call.respondText(httpServerFiles.pinRequestHtml, ContentType.Text.Html)
}
else -> {
clientData.onPinCheck(clientId, false)
if (clientData.isClientBlocked(clientId)) {
call.respond(HttpStatusCode.Forbidden)
} else {
call.respondText(httpServerFiles.pinRequestErrorHtml, ContentType.Text.Html)
}
}
}
}
}
}
get(HttpServerFiles.CLIENT_BLOCKED_ADDRESS) {
if (clientData.enablePin && clientData.blockAddress) {
call.respondText(httpServerFiles.addressBlockedHtml, ContentType.Text.Html)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
get(httpServerFiles.streamAddress) {
val ipAddress: InetSocketAddress? = ClientAddressWorkAround.getInetSocketAddress(call.request)
val fallbackHost = call.request.local.remoteHost
val clientId = ClientData.getId(ipAddress, fallbackHost)
if (clientData.isClientAllowed(clientId, ipAddress, fallbackHost).not()) {
call.respond(HttpStatusCode.NotFound)
return@get
}
call.respond(object : OutgoingContent.WriteChannelContent() {
override val status: HttpStatusCode = HttpStatusCode.OK
override val contentType: ContentType = contentType
override suspend fun writeTo(channel: ByteWriteChannel) {
val emmitCounter = AtomicLong(0L)
val collectCounter = AtomicLong(0L)
mjpegSharedFlow
.onStart {
XLog.d([email protected]("onStart", "Client: $clientId"))
clientData.onConnected(clientId, ipAddress, fallbackHost)
channel.writeFully(jpegBoundary, 0, jpegBoundary.size)
val totalSize = writeMJPEGFrame(channel, lastJPEG.get())
clientData.onNextBytes(clientId, totalSize)
}
.onCompletion {
XLog.d([email protected]("onCompletion", "Client: $clientId"))
clientData.onDisconnected(clientId)
}
.map { Pair(emmitCounter.incrementAndGet(), it) }
.conflate()
.onEach { (emmitCounter, jpeg) ->
if (channel.isClosedForWrite) {
XLog.d([email protected]("onEach", "IsClosedForWrite: Client: $clientId"))
coroutineContext.cancel()
return@onEach
}
if (emmitCounter - collectCounter.incrementAndGet() >= 5) {
XLog.i([email protected]("onEach", "Slow connection. Client: $clientId"))
collectCounter.set(emmitCounter)
clientData.onSlowConnection(clientId)
}
val totalSize = if (clientData.isClientAllowed(clientId, ipAddress, fallbackHost)) {
writeMJPEGFrame(channel, jpeg)
} else {
writeMJPEGFrame(channel, blockedJPEG)
}
clientData.onNextBytes(clientId, totalSize)
}
.catch { /* Empty intentionally */ }
.collect()
}
})
}
get(httpServerFiles.jpegFallbackAddress) {
val ipAddress: InetSocketAddress? = ClientAddressWorkAround.getInetSocketAddress(call.request)
if (clientData.isAddressBlocked(ipAddress, call.request.local.remoteHost)) {
call.respondBytes(blockedJPEG, ContentType.Image.JPEG)
} else {
call.respondBytes(lastJPEG.get(), ContentType.Image.JPEG)
}
}
get(HttpServerFiles.START_STOP_ADDRESS) {
if (httpServerFiles.htmlEnableButtons && clientData.enablePin.not())
sendEvent(HttpServer.Event.Action.StartStopRequest)
call.respondText("")
}
get(HttpServerFiles.FAVICON_PNG) {
call.respondBytes(httpServerFiles.faviconPng, ContentType.Image.PNG)
}
get(HttpServerFiles.LOGO_PNG) {
call.respondBytes(httpServerFiles.logoPng, ContentType.Image.PNG)
}
get(HttpServerFiles.FULLSCREEN_ON_PNG) {
call.respondBytes(httpServerFiles.fullscreenOnPng, ContentType.Image.PNG)
}
get(HttpServerFiles.FULLSCREEN_OFF_PNG) {
call.respondBytes(httpServerFiles.fullscreenOffPng, ContentType.Image.PNG)
}
get(HttpServerFiles.START_STOP_PNG) {
call.respondBytes(httpServerFiles.startStopPng, ContentType.Image.PNG)
}
}
}
} | mit | 4164e972825bd20b855f523e2cca380c | 44.799213 | 116 | 0.563876 | 5.345588 | false | false | false | false |
androidx/androidx | viewpager2/integration-tests/testapp/src/main/java/androidx/viewpager2/integration/testapp/cards/Card.kt | 4 | 2118 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.viewpager2.integration.testapp.cards
import android.os.Bundle
import androidx.core.text.BidiFormatter
/**
* Playing card
*/
class Card private constructor(val suit: String, val value: String) {
val cornerLabel: String
get() = value + "\n" + suit
/** Use in conjunction with [Card.fromBundle] */
fun toBundle(): Bundle {
val args = Bundle(1)
args.putStringArray(ARGS_BUNDLE, arrayOf(suit, value))
return args
}
override fun toString(): String {
val bidi = BidiFormatter.getInstance()
if (!bidi.isRtlContext) {
return bidi.unicodeWrap("$value $suit")
} else {
return bidi.unicodeWrap("$suit $value")
}
}
companion object {
internal val ARGS_BUNDLE = Card::class.java.name + ":Bundle"
val SUITS = setOf("♣" /* clubs*/, "♦" /* diamonds*/, "♥" /* hearts*/, "♠" /*spades*/)
val VALUES = setOf("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")
val DECK = SUITS.flatMap { suit ->
VALUES.map { value -> Card(suit, value) }
}
fun List<Card>.find(value: String, suit: String): Card? {
return find { it.value == value && it.suit == suit }
}
/** Use in conjunction with [Card.toBundle] */
fun fromBundle(bundle: Bundle): Card {
val spec = bundle.getStringArray(ARGS_BUNDLE)
return Card(spec!![0], spec[1])
}
}
}
| apache-2.0 | 9f3fbef112ac60e5885baec2808441d8 | 31.461538 | 93 | 0.606635 | 3.87156 | false | false | false | false |
robfletcher/keiko | keiko-mem/src/test/kotlin/com/netflix/spinnaker/q/memory/InMemoryQueueTest.kt | 1 | 1529 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.q.memory
import com.netflix.spinnaker.q.DeadMessageCallback
import com.netflix.spinnaker.q.QueueTest
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.MonitorableQueueTest
import com.netflix.spinnaker.q.metrics.QueueEvent
import org.funktionale.partials.invoke
import java.time.Clock
object InMemoryQueueTest : QueueTest<InMemoryQueue>(createQueue(p3 = null))
object InMemoryMonitorableQueueTest : MonitorableQueueTest<InMemoryQueue>(
createQueue,
InMemoryQueue::retry
)
private val createQueue = { clock: Clock,
deadLetterCallback: DeadMessageCallback,
publisher: EventPublisher? ->
InMemoryQueue(
clock = clock,
deadMessageHandlers = listOf(deadLetterCallback),
publisher = publisher ?: (object : EventPublisher {
override fun publishEvent(event: QueueEvent) {}
})
)
}
| apache-2.0 | 36e07a75fb53078cde68b64683d3f191 | 33.75 | 75 | 0.744931 | 4.247222 | false | true | false | false |
androidx/androidx | wear/watchface/watchface/src/main/java/androidx/wear/watchface/WatchFace.kt | 3 | 48596 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface
import android.annotation.SuppressLint
import android.app.Activity
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.support.wearable.watchface.SharedMemoryImage
import android.support.wearable.watchface.WatchFaceStyle
import android.view.Gravity
import android.view.Surface
import android.view.Surface.FRAME_RATE_COMPATIBILITY_DEFAULT
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.annotation.UiThread
import androidx.annotation.VisibleForTesting
import androidx.wear.watchface.complications.SystemDataSources
import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.toApiComplicationData
import androidx.wear.watchface.control.data.ComplicationRenderParams
import androidx.wear.watchface.control.data.HeadlessWatchFaceInstanceParams
import androidx.wear.watchface.control.data.WatchFaceRenderParams
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyle
import androidx.wear.watchface.style.UserStyleData
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.WatchFaceLayer
import androidx.wear.watchface.utility.TraceEvent
import java.lang.Long.min
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.security.InvalidParameterException
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import kotlin.math.max
// Human reaction time is limited to ~100ms.
private const val MIN_PERCEPTIBLE_DELAY_MILLIS = 100
// Zero is a special value meaning we will accept the system's choice for the
// display frame rate, which is the default behavior if this function isn't called.
private const val SYSTEM_DECIDES_FRAME_RATE = 0f
/**
* The type of watch face, whether it's digital or analog. This influences the time displayed for
* remote previews.
*
* @hide
*/
@IntDef(
value = [
WatchFaceType.DIGITAL,
WatchFaceType.ANALOG
]
)
public annotation class WatchFaceType {
public companion object {
/* The WatchFace has an analog time display. */
public const val ANALOG: Int = 0
/* The WatchFace has a digital time display. */
public const val DIGITAL: Int = 1
}
}
/**
* The return value of [WatchFaceService.createWatchFace] which brings together rendering, styling,
* complicationSlots and state observers.
*
* @param watchFaceType The type of watch face, whether it's digital or analog. Used to determine
* the default time for editor preview screenshots.
* @param renderer The [Renderer] for this WatchFace.
*/
public class WatchFace(
@WatchFaceType public var watchFaceType: Int,
public val renderer: Renderer
) {
internal var tapListener: TapListener? = null
internal var complicationDeniedDialogIntent: Intent? = null
internal var complicationRationaleDialogIntent: Intent? = null
public companion object {
/** Returns whether [LegacyWatchFaceOverlayStyle] is supported on this device. */
@JvmStatic
public fun isLegacyWatchFaceOverlayStyleSupported(): Boolean = Build.VERSION.SDK_INT <= 27
private val componentNameToEditorDelegate = HashMap<ComponentName, EditorDelegate>()
private var pendingComponentName: ComponentName? = null
private var pendingEditorDelegateCB: CompletableDeferred<EditorDelegate>? = null
/** @hide */
@JvmStatic
@UiThread
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun registerEditorDelegate(
componentName: ComponentName,
editorDelegate: EditorDelegate
) {
componentNameToEditorDelegate[componentName] = editorDelegate
if (componentName == pendingComponentName) {
pendingEditorDelegateCB?.complete(editorDelegate)
} else {
pendingEditorDelegateCB?.completeExceptionally(
IllegalStateException(
"Expected $pendingComponentName to be created but got $componentName"
)
)
}
pendingComponentName = null
pendingEditorDelegateCB = null
}
internal fun unregisterEditorDelegate(componentName: ComponentName) {
componentNameToEditorDelegate.remove(componentName)
}
/** @hide */
@JvmStatic
@UiThread
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@VisibleForTesting
public fun clearAllEditorDelegates() {
componentNameToEditorDelegate.clear()
}
/**
* For use by on watch face editors.
* @hide
*/
@JvmStatic
@UiThread
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun getOrCreateEditorDelegate(
componentName: ComponentName
): CompletableDeferred<EditorDelegate> {
componentNameToEditorDelegate[componentName]?.let {
return CompletableDeferred(it)
}
// There's no pre-existing watch face. We expect Home/SysUI to switch the watchface soon
// so record a pending request...
pendingComponentName = componentName
pendingEditorDelegateCB = CompletableDeferred()
return pendingEditorDelegateCB!!
}
/**
* For use by on watch face editors.
* @hide
*/
@SuppressLint("NewApi")
@JvmStatic
@UiThread
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public suspend fun createHeadlessSessionDelegate(
componentName: ComponentName,
params: HeadlessWatchFaceInstanceParams,
context: Context
): EditorDelegate {
// Attempt to construct the class for the specified watchFaceName, failing if it either
// doesn't exist or isn't a [WatchFaceService].
val watchFaceServiceClass =
Class.forName(componentName.className) ?: throw IllegalArgumentException(
"Can't create ${componentName.className}"
)
if (!WatchFaceService::class.java.isAssignableFrom(WatchFaceService::class.java)) {
throw IllegalArgumentException(
"${componentName.className} is not a WatchFaceService"
)
} else {
val watchFaceService =
watchFaceServiceClass.getConstructor().newInstance() as WatchFaceService
watchFaceService.setContext(context)
val engine = watchFaceService.createHeadlessEngine() as
WatchFaceService.EngineWrapper
engine.createHeadlessInstance(params)
return engine.deferredWatchFaceImpl.await().WFEditorDelegate()
}
}
}
/**
* Delegate used by on watch face editors.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public interface EditorDelegate {
/** The [WatchFace]'s [UserStyleSchema]. */
public val userStyleSchema: UserStyleSchema
/** The watch face's [UserStyle]. */
public var userStyle: UserStyle
/** The [WatchFace]'s [ComplicationSlotsManager]. */
public val complicationSlotsManager: ComplicationSlotsManager
/** The [WatchFace]'s screen bounds [Rect]. */
public val screenBounds: Rect
/** Th reference [Instant] for previews. */
public val previewReferenceInstant: Instant
/** The [Handler] for the background thread. */
public val backgroundThreadHandler: Handler
/** [Intent] to launch the complication permission denied dialog. */
public val complicationDeniedDialogIntent: Intent?
/** [Intent] to launch the complication permission request rationale dialog. */
public val complicationRationaleDialogIntent: Intent?
/**
* Renders the watchface to a [Bitmap] with the [CurrentUserStyleRepository]'s [UserStyle].
*/
public fun renderWatchFaceToBitmap(
renderParameters: RenderParameters,
instant: Instant,
slotIdToComplicationData: Map<Int, ComplicationData>?
): Bitmap
/** Signals that the activity is going away and resources should be released. */
public fun onDestroy()
/** Sets a callback to observe an y changes to [ComplicationSlot.configExtras]. */
public fun setComplicationSlotConfigExtrasChangeCallback(
callback: ComplicationSlotConfigExtrasChangeCallback?
)
}
/**
* Used to inform EditorSession about changes to [ComplicationSlot.configExtras].
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public interface ComplicationSlotConfigExtrasChangeCallback {
public fun onComplicationSlotConfigExtrasChanged()
}
/** Listens for taps on the watchface. */
public interface TapListener {
/**
* Called whenever the user taps on the watchface.
*
* The watch face receives three different types of touch events:
* - [TapType.DOWN] when the user puts the finger down on the touchscreen
* - [TapType.UP] when the user lifts the finger from the touchscreen
* - [TapType.CANCEL] when the system detects that the user is performing a gesture other
* than a tap
*
* Note that the watch face is only given tap events, i.e., events where the user puts
* the finger down on the screen and then lifts it at the position. If the user performs any
* other type of gesture while their finger in on the touchscreen, the watch face will be
* receive a cancel, as all other gestures are reserved by the system.
*
* Therefore, a [TapType.DOWN] event and the successive [TapType.UP] event are guaranteed
* to be close enough to be considered a tap according to the value returned by
* [android.view.ViewConfiguration.getScaledTouchSlop].
*
* If the watch face receives a [TapType.CANCEL] event, it should not trigger any action, as
* the system is already processing the gesture.
*
* @param tapType The type of touch event sent to the watch face
* @param tapEvent The received [TapEvent]
* @param complicationSlot The [ComplicationSlot] tapped if any or `null` otherwise
*/
@UiThread
public fun onTapEvent(
@TapType tapType: Int,
tapEvent: TapEvent,
complicationSlot: ComplicationSlot?
)
}
/**
* Legacy Wear 2.0 watch face styling. These settings will be ignored on Wear 3.0 devices.
*
* @param viewProtectionMode The view protection mode bit field, must be a combination of zero
* or more of [WatchFaceStyle.PROTECT_STATUS_BAR], [WatchFaceStyle.PROTECT_HOTWORD_INDICATOR],
* [WatchFaceStyle.PROTECT_WHOLE_SCREEN].
* @param statusBarGravity Controls the position of status icons (battery state, lack of
* connection) on the screen. This must be any combination of horizontal Gravity constant:
* ([Gravity.LEFT], [Gravity.CENTER_HORIZONTAL], [Gravity.RIGHT]) and vertical Gravity
* constants ([Gravity.TOP], [Gravity.CENTER_VERTICAL], [Gravity.BOTTOM]), e.g.
* `[Gravity.LEFT] | [Gravity.BOTTOM]`. On circular screens, only the vertical gravity is
* respected.
* @param tapEventsAccepted Controls whether this watch face accepts tap events. Watchfaces
* that set this `true` are indicating they are prepared to receive [TapType.DOWN],
* [TapType.CANCEL], and [TapType.UP] events.
* @param accentColor The accent color which will be used when drawing the unread notification
* indicator. Default color is white.
* @throws IllegalArgumentException if [viewProtectionMode] has an unexpected value
*/
public class LegacyWatchFaceOverlayStyle @JvmOverloads constructor(
public val viewProtectionMode: Int,
public val statusBarGravity: Int,
@get:JvmName("isTapEventsAccepted")
public val tapEventsAccepted: Boolean,
@ColorInt public val accentColor: Int = WatchFaceStyle.DEFAULT_ACCENT_COLOR
) {
init {
if (viewProtectionMode < 0 ||
viewProtectionMode >
WatchFaceStyle.PROTECT_STATUS_BAR + WatchFaceStyle.PROTECT_HOTWORD_INDICATOR +
WatchFaceStyle.PROTECT_WHOLE_SCREEN
) {
throw IllegalArgumentException(
"View protection must be combination " +
"PROTECT_STATUS_BAR, PROTECT_HOTWORD_INDICATOR or PROTECT_WHOLE_SCREEN"
)
}
}
}
/** The legacy [LegacyWatchFaceOverlayStyle] which only affects Wear 2.0 devices. */
public var legacyWatchFaceStyle: LegacyWatchFaceOverlayStyle = LegacyWatchFaceOverlayStyle(
0,
0,
true
)
private set
/**
* Sets the legacy [LegacyWatchFaceOverlayStyle] which only affects Wear 2.0 devices.
*/
public fun setLegacyWatchFaceStyle(
legacyWatchFaceStyle: LegacyWatchFaceOverlayStyle
): WatchFace = apply {
this.legacyWatchFaceStyle = legacyWatchFaceStyle
}
/**
* This class allows the watch face to configure the status overlay which is rendered by the
* system on top of the watch face. These settings are applicable from Wear 3.0 and will be
* ignored on earlier devices.
*/
public class OverlayStyle(
/**
* The background color of the status indicator tray. This can be any color, including
* [Color.TRANSPARENT]. If this is `null` then the system default will be used.
*/
val backgroundColor: Color?,
/**
* The background color of items rendered in the status indicator tray. If not `null` then
* this must be either [Color.BLACK] or [Color.WHITE]. If this is `null` then the system
* default will be used.
*/
val foregroundColor: Color?
) {
public constructor() : this(null, null)
init {
require(
foregroundColor == null ||
foregroundColor.toArgb() == Color.BLACK ||
foregroundColor.toArgb() == Color.WHITE
) {
"foregroundColor must be one of null, Color.BLACK or Color.WHITE"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as OverlayStyle
if (backgroundColor != other.backgroundColor) return false
if (foregroundColor != other.foregroundColor) return false
return true
}
override fun hashCode(): Int {
var result = backgroundColor?.hashCode() ?: 0
result = 31 * result + (foregroundColor?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "OverlayStyle(backgroundColor=$backgroundColor, " +
"foregroundColor=$foregroundColor)"
}
@UiThread
internal fun dump(writer: IndentingPrintWriter) {
writer.println("OverlayStyle:")
writer.increaseIndent()
writer.println("backgroundColor=$backgroundColor")
writer.println("foregroundColor=$foregroundColor")
writer.decreaseIndent()
}
}
/** The [OverlayStyle] which affects Wear 3.0 devices and beyond. */
public var overlayStyle: OverlayStyle = OverlayStyle()
private set
/**
* Sets the [OverlayStyle] which affects Wear 3.0 devices and beyond.
*/
public fun setOverlayStyle(
watchFaceOverlayStyle: OverlayStyle
): WatchFace = apply {
this.overlayStyle = watchFaceOverlayStyle
}
/**
* The [Instant] to use for preview rendering, or `null` if not set in which case the system
* chooses the Instant to use.
*/
public var overridePreviewReferenceInstant: Instant? = null
private set
/**
* Overrides the reference time for editor preview images.
*
* @param previewReferenceTimeMillis The UTC preview time in milliseconds since the epoch
*/
public fun setOverridePreviewReferenceInstant(previewReferenceTimeMillis: Instant): WatchFace =
apply { overridePreviewReferenceInstant = previewReferenceTimeMillis }
/**
* Sets an optional [TapListener] which if not `null` gets called on the ui thread whenever the
* user taps on the watchface.
*/
@SuppressWarnings("ExecutorRegistration")
public fun setTapListener(tapListener: TapListener?): WatchFace = apply {
this.tapListener = tapListener
}
/**
* Sets the [Intent] to launch an activity which explains the watch face needs permission to
* display complications. It is recommended the activity have a button which launches an intent
* with [Settings.ACTION_APPLICATION_DETAILS_SETTINGS] to allow the user to grant permissions if
* they wish.
*
* This [complicationDeniedDialogIntent] is launched when the user tries to configure a
* complication slot when the `com.google.android.wearable.permission.RECEIVE_COMPLICATION_DATA`
* permission has been denied. If the intent is not set or is `null` then no dialog will be
* displayed.
*/
public fun setComplicationDeniedDialogIntent(
complicationDeniedDialogIntent: Intent?
): WatchFace = apply {
this.complicationDeniedDialogIntent = complicationDeniedDialogIntent
}
/**
* Sets the [Intent] to launch an activity that explains the rational for the requesting the
* com.google.android.wearable.permission.RECEIVE_COMPLICATION_DATA` permission prior to
* requesting it, if [Activity.shouldShowRequestPermissionRationale] returns `true`.
*
* If the intent is not set or is `null` then no dialog will be displayed.
*/
public fun setComplicationRationaleDialogIntent(
complicationRationaleDialogIntent: Intent?
): WatchFace = apply {
this.complicationRationaleDialogIntent = complicationRationaleDialogIntent
}
}
internal class MockTime(var speed: Double, var minTime: Long, var maxTime: Long) {
/** Apply mock time adjustments. */
fun applyMockTime(timeMillis: Long): Long {
// This adjustment allows time to be sped up or slowed down and to wrap between two
// instants. This is useful when developing animations that occur infrequently (e.g.
// hourly).
val millis = (speed * (timeMillis - minTime).toDouble()).toLong()
val range = maxTime - minTime
var delta = millis % range
if (delta < 0) {
delta += range
}
return minTime + delta
}
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@SuppressLint("SyntheticAccessor")
public class WatchFaceImpl @UiThread constructor(
watchface: WatchFace,
private val watchFaceHostApi: WatchFaceHostApi,
private val watchState: WatchState,
internal val currentUserStyleRepository: CurrentUserStyleRepository,
@get:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
public var complicationSlotsManager: ComplicationSlotsManager,
internal val broadcastsObserver: BroadcastsObserver,
internal var broadcastsReceiver: BroadcastsReceiver?
) {
internal companion object {
internal const val NO_DEFAULT_DATA_SOURCE = SystemDataSources.NO_DATA_SOURCE
internal const val MOCK_TIME_INTENT = "androidx.wear.watchface.MockTime"
// For debug purposes we support speeding up or slowing down time, these pair of constants
// configure reading the mock time speed multiplier from a mock time intent.
internal const val EXTRA_MOCK_TIME_SPEED_MULTIPLIER =
"androidx.wear.watchface.extra.MOCK_TIME_SPEED_MULTIPLIER"
private const val MOCK_TIME_DEFAULT_SPEED_MULTIPLIER = 1.0f
// We support wrapping time between two instants, e.g. to loop an infrequent animation.
// These constants configure reading this from a mock time intent.
internal const val EXTRA_MOCK_TIME_WRAPPING_MIN_TIME =
"androidx.wear.watchface.extra.MOCK_TIME_WRAPPING_MIN_TIME"
private const val MOCK_TIME_WRAPPING_MIN_TIME_DEFAULT = -1L
internal const val EXTRA_MOCK_TIME_WRAPPING_MAX_TIME =
"androidx.wear.watchface.extra.MOCK_TIME_WRAPPING_MAX_TIME"
// Many devices will enter Time Only Mode to reduce power consumption when the battery is
// low, in which case only the system watch face will be displayed. On others there is a
// battery saver mode triggering at 5% battery using an SCR to draw the display. For these
// there's a gap of 10% battery (Intent.ACTION_BATTERY_LOW gets sent when < 15%) where we
// clamp the framerate to a maximum of 10fps to conserve power.
internal const val MAX_LOW_POWER_INTERACTIVE_UPDATE_RATE_MS = 100L
// Number of milliseconds before the target draw time for the delayed task to run and post a
// choreographer frame. This is necessary when rendering at less than 60 fps to make sure we
// post the choreographer frame in time to for us to render in the desired frame.
// NOTE this value must be less than 16 or we'll render too early.
internal const val POST_CHOREOGRAPHER_FRAME_MILLIS_BEFORE_DEADLINE = 10
}
private val defaultRenderParametersForDrawMode: HashMap<DrawMode, RenderParameters> =
hashMapOf(
DrawMode.AMBIENT to
RenderParameters(
DrawMode.AMBIENT,
WatchFaceLayer.ALL_WATCH_FACE_LAYERS,
null,
complicationSlotsManager.lastComplicationTapDownEvents
),
DrawMode.INTERACTIVE to
RenderParameters(
DrawMode.INTERACTIVE,
WatchFaceLayer.ALL_WATCH_FACE_LAYERS,
null,
complicationSlotsManager.lastComplicationTapDownEvents
),
DrawMode.LOW_BATTERY_INTERACTIVE to
RenderParameters(
DrawMode.LOW_BATTERY_INTERACTIVE,
WatchFaceLayer.ALL_WATCH_FACE_LAYERS,
null,
complicationSlotsManager.lastComplicationTapDownEvents
),
DrawMode.MUTE to
RenderParameters(
DrawMode.MUTE,
WatchFaceLayer.ALL_WATCH_FACE_LAYERS,
null,
complicationSlotsManager.lastComplicationTapDownEvents
),
)
internal val systemTimeProvider = watchFaceHostApi.systemTimeProvider
private val legacyWatchFaceStyle = watchface.legacyWatchFaceStyle
internal val renderer = watchface.renderer
private val tapListener = watchface.tapListener
internal var complicationDeniedDialogIntent =
watchface.complicationDeniedDialogIntent
internal var complicationRationaleDialogIntent =
watchface.complicationRationaleDialogIntent
internal var overlayStyle = watchface.overlayStyle
private var mockTime = MockTime(1.0, 0, Long.MAX_VALUE)
private var lastTappedComplicationId: Int? = null
// True if 'Do Not Disturb' mode is on.
private var muteMode = false
internal var lastDrawTimeMillis: Long = 0
internal var nextDrawTimeMillis: Long = 0
private val pendingUpdateTime: CancellableUniqueTask =
CancellableUniqueTask(watchFaceHostApi.getUiThreadHandler())
internal val componentName =
ComponentName(
watchFaceHostApi.getContext().packageName,
watchFaceHostApi.getContext().javaClass.name
)
internal fun getWatchFaceStyle() = WatchFaceStyle(
componentName,
legacyWatchFaceStyle.viewProtectionMode,
legacyWatchFaceStyle.statusBarGravity,
legacyWatchFaceStyle.accentColor,
false,
false,
legacyWatchFaceStyle.tapEventsAccepted
)
internal fun onActionTimeZoneChanged() {
renderer.invalidate()
}
internal fun onActionTimeChanged() {
// System time has changed hence next scheduled draw is invalid.
nextDrawTimeMillis = systemTimeProvider.getSystemTimeMillis()
renderer.invalidate()
}
internal fun onMockTime(intent: Intent) {
mockTime.speed = intent.getFloatExtra(
EXTRA_MOCK_TIME_SPEED_MULTIPLIER,
MOCK_TIME_DEFAULT_SPEED_MULTIPLIER
).toDouble()
mockTime.minTime = intent.getLongExtra(
EXTRA_MOCK_TIME_WRAPPING_MIN_TIME,
MOCK_TIME_WRAPPING_MIN_TIME_DEFAULT
)
// If MOCK_TIME_WRAPPING_MIN_TIME_DEFAULT is specified then use the current time.
if (mockTime.minTime == MOCK_TIME_WRAPPING_MIN_TIME_DEFAULT) {
mockTime.minTime = systemTimeProvider.getSystemTimeMillis()
}
mockTime.maxTime = intent.getLongExtra(EXTRA_MOCK_TIME_WRAPPING_MAX_TIME, Long.MAX_VALUE)
}
/** The reference [Instant] time for editor preview images in milliseconds since the epoch. */
public val previewReferenceInstant: Instant =
watchface.overridePreviewReferenceInstant ?: Instant.ofEpochMilli(
when (watchface.watchFaceType) {
WatchFaceType.ANALOG -> watchState.analogPreviewReferenceTimeMillis
WatchFaceType.DIGITAL -> watchState.digitalPreviewReferenceTimeMillis
else -> throw InvalidParameterException("Unrecognized watchFaceType")
}
)
internal var initComplete = false
private fun interruptionFilter(it: Int) {
// We are in mute mode in any of the following modes. The specific mode depends on the
// device's implementation of "Do Not Disturb".
val inMuteMode = it == NotificationManager.INTERRUPTION_FILTER_NONE ||
it == NotificationManager.INTERRUPTION_FILTER_PRIORITY ||
it == NotificationManager.INTERRUPTION_FILTER_ALARMS
if (muteMode != inMuteMode) {
muteMode = inMuteMode
watchFaceHostApi.invalidate()
}
}
internal fun onVisibility(isVisible: Boolean) {
TraceEvent("WatchFaceImpl.visibility").use {
if (isVisible) {
registerReceivers()
watchFaceHostApi.invalidate()
// It's not safe to draw until initComplete because the ComplicationSlotManager init
// may not have completed.
if (initComplete) {
onDraw()
}
scheduleDraw()
} else {
// We want to avoid a glimpse of a stale time when transitioning from hidden to
// visible, so we render two black frames to clear the buffers.
renderer.renderBlackFrame()
renderer.renderBlackFrame()
unregisterReceivers()
}
}
}
// Only installed if Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.R)
private fun batteryLowAndNotCharging(it: Boolean) {
// To save power we request a lower hardware display frame rate when the battery is low
// and not charging.
if (renderer.surfaceHolder.surface.isValid) {
SetFrameRateHelper.setFrameRate(
renderer.surfaceHolder.surface,
if (it) {
1000f / MAX_LOW_POWER_INTERACTIVE_UPDATE_RATE_MS.toFloat()
} else {
SYSTEM_DECIDES_FRAME_RATE
}
)
}
}
init {
renderer.watchFaceHostApi = watchFaceHostApi
if (renderer.additionalContentDescriptionLabels.isNotEmpty() ||
complicationSlotsManager.complicationSlots.isEmpty()
) {
watchFaceHostApi.updateContentDescriptionLabels()
}
if (!watchState.isHeadless) {
WatchFace.registerEditorDelegate(componentName, WFEditorDelegate())
registerReceivers()
}
val mainScope = CoroutineScope(Dispatchers.Main.immediate)
mainScope.launch {
watchState.isAmbient.collect {
TraceEvent("WatchFaceImpl.ambient").use {
// It's not safe to draw until initComplete because the ComplicationSlotManager
// init may not have completed.
if (initComplete) {
onDraw()
}
scheduleDraw()
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !watchState.isHeadless) {
mainScope.launch {
watchState.isBatteryLowAndNotCharging.collect {
if (it != null) {
batteryLowAndNotCharging(it)
}
}
}
}
mainScope.launch {
watchState.interruptionFilter.collect {
if (it != null) {
interruptionFilter(it)
}
}
}
}
internal fun invalidateIfNotAnimating() {
// Ensure we render a frame if the ComplicationSlot needs rendering, e.g. because it loaded
// an image. However if we're animating there's no need to trigger an extra invalidation.
if (!renderer.shouldAnimate() || computeDelayTillNextFrame(
nextDrawTimeMillis,
systemTimeProvider.getSystemTimeMillis(),
Instant.now()
) > MIN_PERCEPTIBLE_DELAY_MILLIS
) {
watchFaceHostApi.invalidate()
}
}
internal inner class WFEditorDelegate : WatchFace.EditorDelegate {
override val userStyleSchema
get() = currentUserStyleRepository.schema
override var userStyle: UserStyle
get() = currentUserStyleRepository.userStyle.value
set(value) {
currentUserStyleRepository.updateUserStyle(value)
}
override val complicationSlotsManager
get() = [email protected]
override val screenBounds
get() = renderer.screenBounds
override val previewReferenceInstant
get() = [email protected]
override val backgroundThreadHandler
get() = watchFaceHostApi.getBackgroundThreadHandler()
override val complicationDeniedDialogIntent
get() = watchFaceHostApi.getComplicationDeniedIntent()
override val complicationRationaleDialogIntent
get() = watchFaceHostApi.getComplicationRationaleIntent()
override fun renderWatchFaceToBitmap(
renderParameters: RenderParameters,
instant: Instant,
slotIdToComplicationData: Map<Int, ComplicationData>?
): Bitmap = TraceEvent("WFEditorDelegate.takeScreenshot").use {
val oldComplicationData =
complicationSlotsManager.complicationSlots.values.associateBy(
{ it.id },
{ it.renderer.getData() }
)
slotIdToComplicationData?.let {
for ((id, complicationData) in it) {
complicationSlotsManager.setComplicationDataUpdateSync(
id,
complicationData,
instant
)
}
}
val screenShot = renderer.takeScreenshot(
ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")),
renderParameters
)
slotIdToComplicationData?.let {
val now = getNow()
for ((id, complicationData) in oldComplicationData) {
complicationSlotsManager.setComplicationDataUpdateSync(
id,
complicationData,
now
)
}
}
return screenShot
}
override fun setComplicationSlotConfigExtrasChangeCallback(
callback: WatchFace.ComplicationSlotConfigExtrasChangeCallback?
) {
complicationSlotsManager.configExtrasChangeCallback = callback
}
override fun onDestroy(): Unit = TraceEvent("WFEditorDelegate.onDestroy").use {
if (watchState.isHeadless) {
[email protected]()
}
}
}
internal fun onDestroy() {
pendingUpdateTime.cancel()
renderer.onDestroyInternal()
if (!watchState.isHeadless) {
WatchFace.unregisterEditorDelegate(componentName)
}
unregisterReceivers()
}
@UiThread
private fun registerReceivers() {
// Looper can be null in some tests.
require(watchFaceHostApi.getUiThreadHandler().looper.isCurrentThread) {
"registerReceivers must be called the UiThread"
}
// There's no point registering BroadcastsReceiver for headless instances.
if (broadcastsReceiver == null && !watchState.isHeadless) {
broadcastsReceiver =
BroadcastsReceiver(watchFaceHostApi.getContext(), broadcastsObserver)
}
}
@UiThread
private fun unregisterReceivers() {
// Looper can be null in some tests.
require(watchFaceHostApi.getUiThreadHandler().looper.isCurrentThread) {
"unregisterReceivers must be called the UiThread"
}
broadcastsReceiver?.onDestroy()
broadcastsReceiver = null
}
private fun scheduleDraw() {
// Separate calls are issued to deliver the state of isAmbient and isVisible, so during init
// we might not yet know the state of both (which is required by the shouldAnimate logic).
if (!watchState.isAmbient.hasValue() || !watchState.isVisible.hasValue()) {
return
}
if (renderer.shouldAnimate()) {
pendingUpdateTime.postUnique {
watchFaceHostApi.invalidate()
}
}
}
/** Gets the [ZonedDateTime] from [systemTimeProvider] adjusted by the mock time controls. */
@UiThread
private fun getZonedDateTime() =
ZonedDateTime.ofInstant(getNow(), systemTimeProvider.getSystemTimeZoneId())
/** Returns the current system time as provied by [systemTimeProvider] as an [Instant]. */
private fun getNow() =
Instant.ofEpochMilli(mockTime.applyMockTime(systemTimeProvider.getSystemTimeMillis()))
/** @hide */
@UiThread
internal fun maybeUpdateDrawMode() {
var newDrawMode = if (watchState.isBatteryLowAndNotCharging.getValueOr(false)) {
DrawMode.LOW_BATTERY_INTERACTIVE
} else {
DrawMode.INTERACTIVE
}
// Watch faces may wish to run an animation while entering ambient mode and we let them
// defer entering ambient mode.
if (watchState.isAmbient.value!! && !renderer.shouldAnimate()) {
newDrawMode = DrawMode.AMBIENT
} else if (muteMode) {
newDrawMode = DrawMode.MUTE
}
if (renderer.renderParameters.drawMode != newDrawMode) {
renderer.renderParameters = defaultRenderParametersForDrawMode[newDrawMode]!!
}
}
@UiThread
fun onDraw() {
val startTime = getZonedDateTime()
val startInstant = startTime.toInstant()
val startTimeMillis = systemTimeProvider.getSystemTimeMillis()
maybeUpdateDrawMode()
complicationSlotsManager.selectComplicationDataForInstant(startInstant)
renderer.renderInternal(startTime)
lastDrawTimeMillis = startTimeMillis
if (renderer.shouldAnimate()) {
val currentTimeMillis = systemTimeProvider.getSystemTimeMillis()
var delay = computeDelayTillNextFrame(startTimeMillis, currentTimeMillis, Instant.now())
nextDrawTimeMillis = currentTimeMillis + delay
// We want to post our delayed task to post the choreographer frame a bit earlier than
// the deadline because if we post it too close to the deadline we'll miss it. If we're
// close to the deadline we post the choreographer frame immediately.
delay -= POST_CHOREOGRAPHER_FRAME_MILLIS_BEFORE_DEADLINE
if (delay <= 0) {
watchFaceHostApi.invalidate()
} else {
pendingUpdateTime.postDelayedUnique(delay) { watchFaceHostApi.invalidate() }
}
}
}
internal fun onSurfaceRedrawNeeded() {
maybeUpdateDrawMode()
renderer.renderInternal(getZonedDateTime())
}
/**
* @param startTimeMillis The SystemTime in milliseconds at which we started rendering
* @param currentTimeMillis The current SystemTime in milliseconds
* @param nowInstant The current [Instant].
*
* @hide
*/
@UiThread
internal fun computeDelayTillNextFrame(
startTimeMillis: Long,
currentTimeMillis: Long,
nowInstant: Instant
): Long {
// Limit update rate to conserve power when the battery is low and not charging.
val updateRateMillis =
if (watchState.isBatteryLowAndNotCharging.getValueOr(false)) {
max(
renderer.interactiveDrawModeUpdateDelayMillis,
MAX_LOW_POWER_INTERACTIVE_UPDATE_RATE_MS
)
} else {
renderer.interactiveDrawModeUpdateDelayMillis
}
var previousRequestedFrameTimeMillis = nextDrawTimeMillis
// Its possible for nextDrawTimeMillis to be in the past (it's initialized to 0) or the
// future (the user might have changed the system time) which we need to account for.
val earliestSensiblePreviousRequestedFrameTimeMillis = startTimeMillis - updateRateMillis
if (previousRequestedFrameTimeMillis < earliestSensiblePreviousRequestedFrameTimeMillis) {
previousRequestedFrameTimeMillis = startTimeMillis
}
if (previousRequestedFrameTimeMillis > startTimeMillis) {
previousRequestedFrameTimeMillis = startTimeMillis
}
// If the delay is long then round to the beginning of the next period.
var nextFrameTimeMillis = if (updateRateMillis >= 500) {
val nextUnroundedTime = previousRequestedFrameTimeMillis + updateRateMillis
val delay = updateRateMillis - (nextUnroundedTime % updateRateMillis)
previousRequestedFrameTimeMillis + delay
} else {
previousRequestedFrameTimeMillis + updateRateMillis
}
// If updateRateMillis is a multiple of 1 minute then align rendering to the beginning of
// the minute.
if ((updateRateMillis % 60000) == 0L) {
nextFrameTimeMillis += (60000 - (nextFrameTimeMillis % 60000)) % 60000
}
var delayMillis = nextFrameTimeMillis - currentTimeMillis
// Check if we need to render a frame sooner to support scheduled complication updates, e.g.
// the stop watch complication.
val nextComplicationChange = complicationSlotsManager.getNextChangeInstant(nowInstant)
if (nextComplicationChange != Instant.MAX) {
val nextComplicationChangeDelayMillis =
max(0, nextComplicationChange.toEpochMilli() - nowInstant.toEpochMilli())
delayMillis = min(delayMillis, nextComplicationChangeDelayMillis)
}
return delayMillis
}
/**
* Called when a tap or touch related event occurs. Detects taps on [ComplicationSlot]s and
* triggers the associated action.
*
* @param tapType The [TapType] of the event
* @param tapEvent The received [TapEvent]
*/
@UiThread
internal fun onTapCommand(@TapType tapType: Int, tapEvent: TapEvent) {
val tappedComplication =
complicationSlotsManager.getComplicationSlotAt(tapEvent.xPos, tapEvent.yPos)
tapListener?.onTapEvent(tapType, tapEvent, tappedComplication)
if (tappedComplication == null) {
lastTappedComplicationId = null
return
}
when (tapType) {
TapType.UP -> {
if (tappedComplication.id != lastTappedComplicationId &&
lastTappedComplicationId != null
) {
// The UP event belongs to a different complication then the DOWN event,
// do not consider this a tap on either of them.
lastTappedComplicationId = null
return
}
complicationSlotsManager.onComplicationSlotSingleTapped(tappedComplication.id)
watchFaceHostApi.invalidate()
lastTappedComplicationId = null
}
TapType.DOWN -> {
complicationSlotsManager.onTapDown(tappedComplication.id, tapEvent)
lastTappedComplicationId = tappedComplication.id
}
else -> lastTappedComplicationId = null
}
}
@UiThread
@RequiresApi(27)
internal fun renderWatchFaceToBitmap(
params: WatchFaceRenderParams
): Bundle = TraceEvent("WatchFaceImpl.renderWatchFaceToBitmap").use {
val oldStyle = currentUserStyleRepository.userStyle.value
val instant = Instant.ofEpochMilli(params.calendarTimeMillis)
params.userStyle?.let {
currentUserStyleRepository.updateUserStyle(
UserStyle(UserStyleData(it), currentUserStyleRepository.schema)
)
}
val oldComplicationData =
complicationSlotsManager.complicationSlots.values.associateBy(
{ it.id },
{ it.renderer.getData() }
)
params.idAndComplicationDatumWireFormats?.let {
for (idAndData in it) {
complicationSlotsManager.setComplicationDataUpdateSync(
idAndData.id, idAndData.complicationData.toApiComplicationData(), instant
)
}
}
val bitmap = renderer.takeScreenshot(
ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")),
RenderParameters(params.renderParametersWireFormat)
)
// Restore previous style & complicationSlots if required.
if (params.userStyle != null) {
currentUserStyleRepository.updateUserStyle(oldStyle)
}
if (params.idAndComplicationDatumWireFormats != null) {
val now = getNow()
for ((id, complicationData) in oldComplicationData) {
complicationSlotsManager.setComplicationDataUpdateSync(id, complicationData, now)
}
}
return SharedMemoryImage.ashmemWriteImageBundle(bitmap)
}
@UiThread
@RequiresApi(27)
internal fun renderComplicationToBitmap(
params: ComplicationRenderParams
): Bundle? = TraceEvent("WatchFaceImpl.renderComplicationToBitmap").use {
val zonedDateTime = ZonedDateTime.ofInstant(
Instant.ofEpochMilli(params.calendarTimeMillis),
ZoneId.of("UTC")
)
return complicationSlotsManager[params.complicationSlotId]?.let {
val oldStyle = currentUserStyleRepository.userStyle.value
val instant = Instant.ofEpochMilli(params.calendarTimeMillis)
val newStyle = params.userStyle
if (newStyle != null) {
currentUserStyleRepository.updateUserStyle(
UserStyle(UserStyleData(newStyle), currentUserStyleRepository.schema)
)
}
val bounds = it.computeBounds(renderer.screenBounds)
val complicationBitmap =
Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888)
var prevData: ComplicationData? = null
val screenshotComplicationData = params.complicationData
if (screenshotComplicationData != null) {
prevData = it.renderer.getData()
complicationSlotsManager.setComplicationDataUpdateSync(
params.complicationSlotId,
screenshotComplicationData.toApiComplicationData(),
instant
)
}
it.renderer.render(
Canvas(complicationBitmap),
Rect(0, 0, bounds.width(), bounds.height()),
zonedDateTime,
RenderParameters(params.renderParametersWireFormat),
params.complicationSlotId
)
// Restore previous ComplicationData & style if required.
if (prevData != null) {
val now = getNow()
complicationSlotsManager.setComplicationDataUpdateSync(
params.complicationSlotId,
prevData,
now
)
}
if (newStyle != null) {
currentUserStyleRepository.updateUserStyle(oldStyle)
}
SharedMemoryImage.ashmemWriteImageBundle(complicationBitmap)
}
}
@UiThread
internal fun dump(writer: IndentingPrintWriter) {
writer.println("WatchFaceImpl ($componentName): ")
writer.increaseIndent()
writer.println("mockTime.maxTime=${mockTime.maxTime}")
writer.println("mockTime.minTime=${mockTime.minTime}")
writer.println("mockTime.speed=${mockTime.speed}")
writer.println("lastDrawTimeMillis=$lastDrawTimeMillis")
writer.println("nextDrawTimeMillis=$nextDrawTimeMillis")
writer.println("muteMode=$muteMode")
writer.println("pendingUpdateTime=${pendingUpdateTime.isPending()}")
writer.println("lastTappedComplicationId=$lastTappedComplicationId")
writer.println(
"currentUserStyleRepository.userStyle=${currentUserStyleRepository.userStyle.value}"
)
writer.println("currentUserStyleRepository.schema=${currentUserStyleRepository.schema}")
overlayStyle.dump(writer)
watchState.dump(writer)
complicationSlotsManager.dump(writer)
renderer.dumpInternal(writer)
writer.decreaseIndent()
}
}
internal class SetFrameRateHelper {
@RequiresApi(Build.VERSION_CODES.R)
companion object {
fun setFrameRate(surface: Surface, frameRate: Float) {
surface.setFrameRate(frameRate, FRAME_RATE_COMPATIBILITY_DEFAULT)
}
}
}
internal fun <Boolean> StateFlow<Boolean?>.getValueOr(default: Boolean): Boolean {
return if (hasValue()) {
value!!
} else {
default
}
}
internal fun <T> StateFlow<T>.hasValue(): Boolean = value != null
| apache-2.0 | 1d7f217760ce3ad3a7798b25fa96729b | 38.702614 | 100 | 0.646308 | 5.262725 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/IntroduceIndexMatcher.kt | 4 | 6171 | // 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.intentions.loopToCallChain.sequence
import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.AccessTarget
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.ReadValueInstruction
import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraverseInstructionResult
import org.jetbrains.kotlin.cfg.pseudocodeTraverser.traverseFollowingInstructions
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
/**
* Analyzes the rest of the loop and detects index variable manually incremented inside.
* So it does not produce any transformation in its result but adds an index variable.
*/
object IntroduceIndexMatcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = false // old index variable is still needed - cannot introduce another one
override val shouldUseInputVariables: Boolean
get() = false
override fun match(state: MatchingState): TransformationMatch.Sequence? {
for (statement in state.statements) {
val unaryExpressions = statement.collectDescendantsOfType<KtUnaryExpression>(
canGoInside = { it !is KtBlockExpression && it !is KtFunction }
)
for (unaryExpression in unaryExpressions) {
checkIndexCandidate(unaryExpression, state)?.let { return it }
}
}
return null
}
private fun checkIndexCandidate(incrementExpression: KtUnaryExpression, state: MatchingState): TransformationMatch.Sequence? {
val operand = incrementExpression.isPlusPlusOf() ?: return null
val variableInitialization = operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false)
?: return null
if ((variableInitialization.initializer as? KtConstantExpression)?.text != "0") return null
val variable = variableInitialization.variable
if (variable.countWriteUsages(state.outerLoop) > 1) return null // changed somewhere else
// variable should have no usages except in the initialization + currently matching part of the loop
//TODO: preform more precise analysis when variable can be used earlier or used later but value overwritten before that
if (variable.countUsages() != variable.countUsages(state.statements + variableInitialization.initializationStatement)) return null
val pseudocode = state.pseudocodeProvider()
val firstStatement = state.statements.first()
val firstInstruction = pseudocode.instructionForElement(firstStatement) ?: return null
val incrementInstruction = pseudocode.instructionForElement(incrementExpression) ?: return null
if (!isAlwaysReachedOrExitedLoop(firstInstruction, incrementInstruction, state.outerLoop, state.innerLoop)) return null
val variableDescriptor = variable.unsafeResolveToDescriptor() as VariableDescriptor
// index accessed inside loop after increment
if (isAccessedAfter(variableDescriptor, incrementInstruction, state.innerLoop)) return null
// if it is among statements then drop it, otherwise "index++" will be replaced with "index" by generateLambda()
val restStatements = state.statements - incrementExpression
val newState = state.copy(
statements = restStatements,
indexVariable = variable,
initializationStatementsToDelete = state.initializationStatementsToDelete + variableInitialization.initializationStatement,
incrementExpressions = state.incrementExpressions + incrementExpression
)
return TransformationMatch.Sequence(emptyList(), newState)
}
private fun isAlwaysReachedOrExitedLoop(
from: Instruction,
to: Instruction,
outerLoop: KtForExpression,
innerLoop: KtForExpression
): Boolean {
val visited = HashSet<Instruction>()
return traverseFollowingInstructions(from, visited) { instruction ->
val nextInstructionScope = instruction.blockScope.block
// we should either reach the target instruction or exit the outer loop on every branch
// (if we won't do this on some branch we will finally exit the inner loop and return false from traverseFollowingInstructions)
when {
instruction == to -> TraverseInstructionResult.SKIP
// we are out of the outer loop - it's ok
!outerLoop.isAncestor(nextInstructionScope, strict = false) -> TraverseInstructionResult.SKIP
// we exited or continued inner loop
!innerLoop.isAncestor(nextInstructionScope, strict = true) -> TraverseInstructionResult.HALT
else -> TraverseInstructionResult.CONTINUE
}
} && visited.contains(to)
}
private fun isAccessedAfter(variableDescriptor: VariableDescriptor, instruction: Instruction, loop: KtForExpression): Boolean {
return !traverseFollowingInstructions(instruction) {
when {
!loop.isAncestor(
it.blockScope.block,
strict = true
) -> TraverseInstructionResult.SKIP // we are outside the loop or going to the next iteration
it.isReadOfVariable(variableDescriptor) -> TraverseInstructionResult.HALT
else -> TraverseInstructionResult.CONTINUE
}
}
}
private fun Instruction.isReadOfVariable(descriptor: VariableDescriptor): Boolean {
return ((this as? ReadValueInstruction)?.target as? AccessTarget.Call)?.resolvedCall?.resultingDescriptor == descriptor
}
} | apache-2.0 | 5fa463a6d43129e7edf591e9fa479c25 | 53.140351 | 158 | 0.722087 | 5.544474 | false | false | false | false |
Firenox89/Shinobooru | app/src/main/java/com/github/firenox89/shinobooru/ui/thumbnail/ThumbnailActivity.kt | 1 | 6956 | package com.github.firenox89.shinobooru.ui.thumbnail
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import android.widget.AutoCompleteTextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import com.github.firenox89.shinobooru.R
import com.github.firenox89.shinobooru.settings.SettingsActivity
import com.github.firenox89.shinobooru.settings.SettingsManager
import com.github.firenox89.shinobooru.ui.base.BaseActivity
import com.github.firenox89.shinobooru.ui.post.PostPagerActivity
import com.github.firenox89.shinobooru.utility.Constants
import com.github.firenox89.shinobooru.utility.Constants.BOARD_INTENT_KEY
import com.github.firenox89.shinobooru.utility.Constants.POSITION_INTENT_KEY
import com.github.firenox89.shinobooru.utility.Constants.TAGS_INTENT_KEY
import com.google.android.material.navigation.NavigationView
import kotlinx.android.synthetic.main.activity_thumbnail.*
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import timber.log.Timber
class ThumbnailActivity : BaseActivity() {
private val settingsManager: SettingsManager by inject()
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private var recyclerAdapter: ThumbnailAdapter? = null
private val recyclerLayout = androidx.recyclerview.widget.StaggeredGridLayoutManager(4, androidx.recyclerview.widget.StaggeredGridLayoutManager.VERTICAL)
private lateinit var board: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_thumbnail)
setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp)
}
//setup the RecyclerView adapter
val tags = intent.getStringExtra(TAGS_INTENT_KEY) ?: ""
board = intent.getStringExtra(BOARD_INTENT_KEY) ?: SettingsActivity.currentBoardURL
setupDrawer(nav_view, drawer_layout, board)
swipeRefreshLayout.setOnRefreshListener {
lifecycleScope.launch {
dataSource.getPostLoader(board, tags).onRefresh()
swipeRefreshLayout.isRefreshing = false
}
}
title = "${board.replace("https://", "")} $tags"
Timber.i("board '$board' tags '$tags'")
lifecycleScope.launch {
recyclerAdapter = ThumbnailAdapter(lifecycleScope, dataSource.getPostLoader(board, tags)) { clickedPostId ->
//when an image was clicked start a new PostPagerActivity that starts on Post that was clicked
Timber.d("Click on post imageID")
val intent = Intent(this@ThumbnailActivity, PostPagerActivity::class.java)
intent.putExtra(BOARD_INTENT_KEY, board)
intent.putExtra(TAGS_INTENT_KEY, tags)
intent.putExtra(POSITION_INTENT_KEY, clickedPostId)
startActivityForResult(intent, 1)
}
recyclerAdapter?.subscribeLoader()
recyclerView.layoutManager = recyclerLayout
Timber.w("Set adapter")
recyclerView.adapter = recyclerAdapter
//update the number of posts per row of the recycler layout
updatePostPerRow()
}
}
override fun onResume() {
super.onResume()
//update the number of posts per row of the recycler layout
updatePostPerRow()
}
/**
* Updates the span count of the layout manager.
* If the given value is 1 the [RecyclerView] will display sample instead of preview images.
* @param value that should be used as spanCount
*/
private fun updatePostPerRow() {
val postsPerRow = settingsManager.postsPerRow
recyclerLayout.spanCount = postsPerRow
recyclerAdapter?.usePreview = postsPerRow != 1
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.thumbnail_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
drawer_layout.openDrawer(GravityCompat.START)
return true
}
R.id.search_tags -> {
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* Gets called when a [PostPagerActivity] returns.
* Scrolls the [RecyclerView] to the post position of the last view post of [PostPagerActivity].
*
* @param requestCode gets ignored
* @param resultCode gets ignored
* @param data if an Int value for position is stored there it will be used to scroll
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val post = data?.getIntExtra("position", -1)
if (post != null && post != -1)
recyclerView.scrollToPosition(post)
}
private fun setupDrawer(navigation: NavigationView, drawer: DrawerLayout, board: String) {
navigation.inflateHeaderView(R.layout.drawer_header).also { headerView ->
headerView.findViewById<AutoCompleteTextView>(R.id.tagSearchAutoCompletion).also { autoCompleteTextView ->
val autoCompleteAdapter = TagSearchAutoCompleteAdapter(board)
autoCompleteTextView.setAdapter(autoCompleteAdapter)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
openBoard(board, autoCompleteAdapter.getItem(position))
}
}
}
dataSource.getBoards().forEach {
navigation.menu.add(it)
}
navigation.setNavigationItemSelectedListener { item ->
when (item.title) {
"Settings" -> {
drawer.closeDrawers()
navigateToSettings()
}
"Sync" -> {
drawer.closeDrawers()
navigateToSync()
}
"Filemanager" -> {
drawer.closeDrawers()
if (board != Constants.FILE_LOADER_NAME) {
openBoard(Constants.FILE_LOADER_NAME)
}
}
else -> {
drawer.closeDrawers()
if (board != item.title.toString()) {
openBoard(item.title.toString())
}
}
}
true
}
}
}
| mit | d9ed87a30b48b582f30316c8afae1032 | 37.644444 | 157 | 0.64678 | 5.156412 | false | false | false | false |
siosio/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/RawPluginDescriptor.kt | 1 | 2473 | // 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.plugins
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.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
@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 content = PluginContentDescriptor.EMPTY
@JvmField internal var dependencies = ModuleDependenciesDescriptor.EMPTY
class ActionDescriptor(
@JvmField val name: String,
@JvmField val element: XmlElement,
@JvmField val resourceBundle: String?,
)
}
| apache-2.0 | 00c7f31fd2409d00c9b68676f19ed67e | 38.253968 | 140 | 0.781642 | 4.877712 | false | false | false | false |
rustamgaifullin/MP | app/src/main/kotlin/io/rg/mp/ui/spreadsheet/SpreadsheetViewModel.kt | 1 | 4926 | package io.rg.mp.ui.spreadsheet
import android.os.Bundle
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import io.rg.mp.drive.FolderService
import io.rg.mp.drive.SpreadsheetService
import io.rg.mp.drive.TransactionService
import io.rg.mp.drive.data.CreationResult
import io.rg.mp.persistence.dao.FailedSpreadsheetDao
import io.rg.mp.persistence.dao.SpreadsheetDao
import io.rg.mp.persistence.entity.FailedSpreadsheet
import io.rg.mp.ui.AbstractViewModel
import io.rg.mp.ui.CreatedSuccessfully
import io.rg.mp.ui.ListSpreadsheet
import io.rg.mp.ui.RenamedSuccessfully
import io.rg.mp.utils.getLocaleInstance
import java.text.SimpleDateFormat
import java.util.Date
class SpreadsheetViewModel(
private val spreadsheetDao: SpreadsheetDao,
private val folderService: FolderService,
private val transactionService: TransactionService,
private val spreadsheetService: SpreadsheetService,
private val failedSpreadsheetDao: FailedSpreadsheetDao) : AbstractViewModel() {
companion object {
const val DEFAULT_TEMPLATE_ID = "1Ydrns7Pv4mf17D4eZjLD_sNL78LPH0SC05Lt_U45JFk"
const val REQUEST_AUTHORIZATION_LOADING_SPREADSHEETS = 2001
const val REQUEST_AUTHORIZATION_NEW_SPREADSHEET = 2003
const val REQUEST_AUTHORIZATION_FOR_DELETE = 2005
const val REQUEST_DO_NOTHING = 2000000
const val SPREADSHEET_NAME = "spreadsheetName"
const val SPREADSHEET_ID = "spreadsheetId"
}
fun reloadData() {
reloadSpreadsheets()
downloadSpreadsheets()
}
private fun reloadSpreadsheets() {
val disposable = spreadsheetDao.allSorted()
.subscribeOn(Schedulers.io())
.subscribe {
subject.onNext(ListSpreadsheet(it))
}
compositeDisposable.add(disposable)
}
private fun downloadSpreadsheets() {
val disposable = spreadsheetService.list()
.subscribeOn(Schedulers.io())
.doOnSubscribe { progressSubject.onNext(1) }
.doFinally { progressSubject.onNext(-1) }
.subscribe(
{ (spreadsheetList) -> spreadsheetDao.updateData(spreadsheetList) },
{ handleErrors(it, REQUEST_AUTHORIZATION_LOADING_SPREADSHEETS) }
)
compositeDisposable.add(disposable)
}
fun createNewSpreadsheet(name: String, id: String) {
val disposable = folderService
.copy(id, name)
.doOnSuccess(temporaryInsertToFailed())
.flatMap{ transactionService.clearAllTransactions(it.id).toSingleDefault(it) }
.doOnSubscribe { progressSubject.onNext(1) }
.doFinally { progressSubject.onNext(-1) }
.subscribeOn(Schedulers.io())
.subscribe(
{
failedSpreadsheetDao.delete(it.id)
subject.onNext(CreatedSuccessfully(it.id))
},
{
handleErrors(it, REQUEST_AUTHORIZATION_NEW_SPREADSHEET)
}
)
compositeDisposable.add(disposable)
}
private fun temporaryInsertToFailed(): (CreationResult) -> Unit =
{ failedSpreadsheetDao.insert(FailedSpreadsheet(spreadsheetId = it.id)) }
fun deleteFailedSpreadsheets() {
val disposable = failedSpreadsheetDao.all()
.flatMapPublisher { Flowable.fromIterable(it) }
.subscribeOn(Schedulers.io())
.subscribe { failedSpreadsheet ->
spreadsheetService.deleteSpreadsheet(failedSpreadsheet.spreadsheetId)
.subscribe(
{
spreadsheetDao.delete(failedSpreadsheet.spreadsheetId)
failedSpreadsheetDao.delete(failedSpreadsheet.spreadsheetId)
},
{ handleErrors(it, REQUEST_AUTHORIZATION_FOR_DELETE) })
}
compositeDisposable.add(disposable)
}
fun createSpreadsheetName(): String {
val simpleDateFormat = SimpleDateFormat("LLLL YYYY", getLocaleInstance())
return simpleDateFormat.format(Date())
}
fun renameSpreadsheet(id: String, newName: String) {
val disposable = folderService.rename(id, newName)
.doOnSubscribe { progressSubject.onNext(1) }
.doFinally { progressSubject.onNext(-1) }
.subscribeOn(Schedulers.io())
.subscribe(
{ subject.onNext(RenamedSuccessfully) },
{ handleErrors(it, REQUEST_DO_NOTHING) }
)
compositeDisposable.add(disposable)
}
} | mit | eb763b7f41b7d1368525f917950004b4 | 39.719008 | 100 | 0.61084 | 4.805854 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/expression/KotlinWithIfExpressionSurrounder.kt | 4 | 2203 | // 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.codeInsight.surroundWith.expression
import com.intellij.codeInsight.CodeInsightUtilBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.utils.sure
class KotlinWithIfExpressionSurrounder(val withElse: Boolean) : KotlinExpressionSurrounder() {
override fun isApplicable(expression: KtExpression) =
super.isApplicable(expression) && (expression.analyze(BodyResolveMode.PARTIAL).getType(expression)?.isBoolean() ?: false)
override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange {
val factory = KtPsiFactory(project)
val replaceResult = expression.replace(
factory.createIf(
expression,
factory.createBlock("blockStubContentToBeRemovedLater"),
if (withElse) factory.createEmptyBody() else null
)
) as KtExpression
val ifExpression = KtPsiUtil.deparenthesizeOnce(replaceResult) as KtIfExpression
CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(ifExpression)
val firstStatementInThenRange = (ifExpression.then as? KtBlockExpression).sure {
"Then branch should exist and be a block expression"
}.statements.first().textRange
editor.document.deleteString(firstStatementInThenRange.startOffset, firstStatementInThenRange.endOffset)
return TextRange(firstStatementInThenRange.startOffset, firstStatementInThenRange.startOffset)
}
@NlsSafe
override fun getTemplateDescription() = "if (expr) { ... }" + (if (withElse) " else { ... }" else "")
}
| apache-2.0 | 60b204d13109d39d563801aac32b8b5e | 46.891304 | 158 | 0.758057 | 4.852423 | false | false | false | false |
jwren/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/FileSet.kt | 1 | 4105 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.function.BiPredicate
import java.util.stream.Collectors
class FileSet(private val root: Path) {
private val includePatterns: MutableMap<String, Regex> = mutableMapOf()
private val excludePatterns: MutableMap<String, Regex> = mutableMapOf()
private fun toRegex(pattern: String): Regex = pattern
.let { FileUtil.toSystemIndependentName(it) }
.let { FileUtil.convertAntToRegexp(it) }
.let { Regex(it) }
fun include(pattern: String): FileSet {
includePatterns[pattern] = toRegex(pattern)
return this
}
fun includeAll(): FileSet = include("**")
fun exclude(pattern: String): FileSet {
excludePatterns[pattern] = toRegex(pattern)
return this
}
fun copyToDir(targetDir: Path) {
for (path in enumerate()) {
val destination = targetDir.resolve(root.relativize(path))
LOG.debug("Copy: $path -> $destination ($this)")
Files.createDirectories(destination.parent)
Files.copy(path, destination, StandardCopyOption.COPY_ATTRIBUTES)
}
}
fun delete() {
for (path in enumerate()) {
LOG.debug("Delete: file $path ($this)")
Files.delete(path)
}
}
fun enumerate(): List<Path> = toPathListImpl(assertUnusedPatterns = true)
fun enumerateNoAssertUnusedPatterns(): List<Path> = toPathListImpl(assertUnusedPatterns = false)
private fun toPathListImpl(assertUnusedPatterns: Boolean): List<Path> {
if (includePatterns.isEmpty()) {
// Prevent accidental coding errors, do not remove
error("No include patterns in $this. Please add some or call includeAll()")
}
val usedIncludePatterns = mutableSetOf<String>()
val usedExcludePatterns = mutableSetOf<String>()
val result = Files.find(root, Int.MAX_VALUE, BiPredicate { path, attr ->
if (attr.isDirectory) {
return@BiPredicate false
}
val relative = root.relativize(path)
var included = false
for ((pattern, pathMatcher) in includePatterns) {
if (pathMatcher.matches(FileUtil.toSystemIndependentName(relative.toString()))) {
included = true
usedIncludePatterns.add(pattern)
}
}
if (!included) {
return@BiPredicate false
}
var excluded = false
for ((pattern, pathMatcher) in excludePatterns) {
if (pathMatcher.matches(FileUtil.toSystemIndependentName(relative.toString()))) {
excluded = true
usedExcludePatterns.add(pattern)
}
}
return@BiPredicate !excluded
}).use { stream ->
stream.collect(Collectors.toList())
}
val unusedIncludePatterns = includePatterns.keys - usedIncludePatterns
if (assertUnusedPatterns && unusedIncludePatterns.isNotEmpty()) {
// Prevent accidental coding errors, do not remove
error("The following include patterns were not matched while traversing $this:\n" + unusedIncludePatterns.joinToString("\n"))
}
val unusedExcludePatterns = excludePatterns.keys - usedExcludePatterns
if (assertUnusedPatterns && unusedExcludePatterns.isNotEmpty()) {
// Prevent accidental coding errors, do not remove
error("The following exclude patterns were not matched while traversing $this:\n" + unusedExcludePatterns.joinToString("\n"))
}
return result
}
fun isEmpty(): Boolean = enumerateNoAssertUnusedPatterns().isEmpty()
override fun toString() = "FileSet(" +
"root='$root', " +
"included=[${includePatterns.keys.sorted().joinToString(", ")}], " +
"excluded=[${excludePatterns.keys.sorted().joinToString(", ")}]" +
")"
companion object {
private val LOG = Logger.getInstance(FileSet::class.java)
}
}
| apache-2.0 | 81b8ce9d5e96b0f830327f755fb3f9e2 | 33.495798 | 131 | 0.675518 | 4.506037 | false | false | false | false |
Unic8/retroauth | retroauth/src/main/java/com/andretietz/retroauth/Retroauth.kt | 1 | 4648 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import java.util.LinkedList
import java.util.concurrent.Executor
/**
* This is the wrapper builder to create the [Retrofit] object.
*/
class Retroauth private constructor() {
class Builder<out OWNER_TYPE : Any, OWNER : Any, CREDENTIAL_TYPE : Any, CREDENTIAL : Any> @JvmOverloads constructor(
private val authenticator: Authenticator<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL>,
private val ownerManager: OwnerStorage<OWNER_TYPE, OWNER, CREDENTIAL_TYPE>,
private val credentialStorage: CredentialStorage<OWNER, CREDENTIAL_TYPE, CREDENTIAL>,
private val methodCache: MethodCache<OWNER_TYPE, CREDENTIAL_TYPE> = MethodCache.DefaultMethodCache()
) {
private val retrofitBuilder: Retrofit.Builder = Retrofit.Builder()
private val callAdapterFactories: MutableList<CallAdapter.Factory> = LinkedList()
private var okHttpClient: OkHttpClient? = null
private var executor: Executor? = null
/**
* [retrofit2.Retrofit.Builder.client]
*/
@Suppress("unused")
fun client(client: OkHttpClient): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.okHttpClient = client
return this
}
/**
* [retrofit2.Retrofit.Builder.baseUrl]
*/
@Suppress("unused")
fun baseUrl(baseUrl: HttpUrl): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.retrofitBuilder.baseUrl(baseUrl)
return this
}
/**
* [retrofit2.Retrofit.Builder.baseUrl]
*/
@Suppress("unused")
fun baseUrl(baseUrl: String): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.retrofitBuilder.baseUrl(baseUrl)
return this
}
/**
* [retrofit2.Retrofit.Builder.addConverterFactory]
*/
@Suppress("unused")
fun addConverterFactory(factory: Converter.Factory): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.retrofitBuilder.addConverterFactory(factory)
return this
}
/**
* [retrofit2.Retrofit.Builder.addCallAdapterFactory]
*/
@Suppress("unused")
fun addCallAdapterFactory(factory: CallAdapter.Factory): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.callAdapterFactories.add(factory)
return this
}
/**
* [retrofit2.Retrofit.Builder.callbackExecutor]
*/
@Suppress("unused")
fun callbackExecutor(executor: Executor): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.executor = executor
this.retrofitBuilder.callbackExecutor(executor)
return this
}
/**
* [retrofit2.Retrofit.Builder.validateEagerly]
*/
@Suppress("unused")
fun validateEagerly(validateEagerly: Boolean): Builder<OWNER_TYPE, OWNER, CREDENTIAL_TYPE, CREDENTIAL> {
this.retrofitBuilder.validateEagerly(validateEagerly)
return this
}
/**
* @return a [Retrofit] instance using the given parameter.
*/
fun build(): Retrofit {
// creating a custom calladapter to handle authentication
val callAdapter = RetroauthCallAdapterFactory(
authenticator,
methodCache)
// use this callAdapter to create the retrofit object
retrofitBuilder.addCallAdapterFactory(callAdapter)
callAdapterFactories.forEach { retrofitBuilder.addCallAdapterFactory(it) }
val builder = okHttpClient?.newBuilder() ?: OkHttpClient.Builder()
// create the okhttp interceptor to intercept requests
val interceptor = CredentialInterceptor(
authenticator,
ownerManager,
credentialStorage,
methodCache
)
// add it as the first interceptor to be used
builder.interceptors().add(interceptor)
// add the newly created okhttpclient as callFactory
this.retrofitBuilder.callFactory(builder.build())
// create the retrofit object
return this.retrofitBuilder.build()
}
}
}
| apache-2.0 | b8f68305336b7bd90d70877c7df260c4 | 31.503497 | 118 | 0.70525 | 4.574803 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/packaging/PyRequirementImpl.kt | 12 | 1338 | // 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.jetbrains.python.packaging
import com.jetbrains.python.packaging.requirement.PyRequirementVersionSpec
/**
* This class is not an API, consider using methods listed below.
*
* @see PyPackageManager.parseRequirement
* @see PyPackageManager.parseRequirements
*
* @see PyRequirementParser.fromText
* @see PyRequirementParser.fromLine
* @see PyRequirementParser.fromFile
*/
data class PyRequirementImpl(private val name: String,
private val versionSpecs: List<PyRequirementVersionSpec>,
private val installOptions: List<String>,
private val extras: String) : PyRequirement {
override fun getName(): String = name
override fun getExtras(): String = extras
override fun getVersionSpecs(): List<PyRequirementVersionSpec> = versionSpecs
override fun getInstallOptions(): List<String> = installOptions
override fun match(packages: Collection<PyPackage>): PyPackage? {
val normalizedName = name.replace('_', '-')
return packages.firstOrNull { `package` ->
normalizedName.equals(`package`.name, true)
&& versionSpecs.all { it.matches(`package`.version) }
}
}
}
| apache-2.0 | a1e0991e11efa4f0de02d99c6e13cb52 | 39.545455 | 140 | 0.709268 | 4.711268 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/test/util/ReferenceUtils.kt | 2 | 2125 | // 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.
@file:JvmName("ReferenceUtils")
package org.jetbrains.kotlin.test.util
import com.intellij.navigation.NavigationItem
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.plainContent
import org.junit.Assert
@JvmOverloads
fun PsiElement.renderAsGotoImplementation(renderModule: Boolean = false): String {
val navigationElement = navigationElement
if (navigationElement is KtObjectDeclaration && navigationElement.isCompanion()) {
//default presenter return null for companion object
val containingClass = PsiTreeUtil.getParentOfType(navigationElement, KtClass::class.java)!!
return "companion object of " + containingClass.renderAsGotoImplementation(renderModule)
}
if (navigationElement is KtStringTemplateExpression) {
return navigationElement.plainContent
}
Assert.assertTrue(navigationElement is NavigationItem)
val presentation = (navigationElement as NavigationItem).presentation
if (presentation == null) {
val elementText = text
return elementText ?: navigationElement.text
}
val presentableText = presentation.presentableText
var locationString = presentation.locationString
if (locationString == null && parent is PsiAnonymousClass) {
locationString = "<anonymous>"
}
if (renderModule) {
locationString = "[${navigationElement.module?.name ?: ""}] $locationString"
}
return if (locationString == null || navigationElement is PsiPackage)
presentableText!!
else
locationString + "." + presentableText// for PsiPackage, presentableText is FQ name of current package
} | apache-2.0 | 9171e700a11f90d878ed0e94b7de2e3f | 39.113208 | 158 | 0.761882 | 5.195599 | false | false | false | false |
mhshams/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/http/HttpServerFileUpload.kt | 2 | 1544 | package io.vertx.kotlin.core.http
import io.vertx.kotlin.core.buffer.Buffer
import io.vertx.kotlin.core.internal.KotlinHandler
import io.vertx.kotlin.core.streams.ReadStream
/**
*/
class HttpServerFileUpload(override val delegate: io.vertx.core.http.HttpServerFileUpload) : ReadStream<Buffer> {
override fun exceptionHandler(handler: (Throwable) -> Unit): HttpServerFileUpload {
this.delegate.exceptionHandler(handler)
return this
}
override fun handler(handler: (Buffer) -> Unit): HttpServerFileUpload {
this.delegate.handler(KotlinHandler(handler, { Buffer(it) }))
return this
}
override fun endHandler(endHandler: (Unit) -> Unit): HttpServerFileUpload {
delegate.endHandler(KotlinHandler(endHandler, {}))
return this
}
override fun pause(): HttpServerFileUpload {
this.delegate.pause()
return this
}
override fun resume(): HttpServerFileUpload {
this.delegate.resume()
return this
}
fun streamToFileSystem(filename: String): HttpServerFileUpload {
this.delegate.streamToFileSystem(filename)
return this
}
fun filename(): String = delegate.filename()
fun name(): String = delegate.name()
fun contentType(): String = delegate.contentType()
fun contentTransferEncoding(): String = delegate.contentTransferEncoding()
fun charset(): String = delegate.charset()
fun size(): Long = delegate.size()
fun isSizeAvailable(): Boolean = delegate.isSizeAvailable()
}
| apache-2.0 | 5f80595dedca76b01033fa0953f7def1 | 27.592593 | 113 | 0.692358 | 4.51462 | false | false | false | false |
sky-map-team/stardroid | app/src/main/java/com/google/android/stardroid/ephemeris/OrbitalElements.kt | 1 | 3238 | // Copyright 2008 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
//
// 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.stardroid.ephemeris
import android.util.Log
import com.google.android.stardroid.math.MathUtils.sin
import com.google.android.stardroid.math.MathUtils.cos
import com.google.android.stardroid.math.MathUtils.abs
import com.google.android.stardroid.math.MathUtils.sqrt
import com.google.android.stardroid.math.MathUtils.tan
import com.google.android.stardroid.math.mod2pi
import com.google.android.stardroid.util.MiscUtil
/**
* This class wraps the six parameters which define the path an object takes as
* it orbits the sun.
*
* The equations come from JPL's Solar System Dynamics site:
* http://ssd.jpl.nasa.gov/?planet_pos
*
* The original source for the calculations is based on the approximations described in:
* Van Flandern T. C., Pulkkinen, K. F. (1979): "Low-Precision Formulae for
* Planetary Positions", 1979, Astrophysical Journal Supplement Series, Vol. 41,
* pp. 391-411.
*
*
* @author Kevin Serafini
* @author Brent Bryan
*/
data class OrbitalElements(
val distance: Float, // Mean distance (AU)
val eccentricity: Float, // Eccentricity of orbit
val inclination: Float, // Inclination of orbit (AngleUtils.RADIANS)
val ascendingNode: Float, // Longitude of ascending node (AngleUtils.RADIANS)
val perihelion: Float, // Longitude of perihelion (AngleUtils.RADIANS)
val meanLongitude: Float // Mean longitude (AngleUtils.RADIANS)
) {
val anomaly: Float
get() = calculateTrueAnomaly(meanLongitude - perihelion, eccentricity)
private val TAG = MiscUtil.getTag(OrbitalElements::class.java)
// calculation error
// compute the true anomaly from mean anomaly using iteration
// m - mean anomaly in radians
// e - orbit eccentricity
// Return value is in radians.
private fun calculateTrueAnomaly(m: Float, e: Float): Float {
// initial approximation of eccentric anomaly
var e0 = m + e * sin(m) * (1.0f + e * cos(m))
var e1: Float
// iterate to improve accuracy
var counter = 0
do {
e1 = e0
e0 = e1 - (e1 - e * sin(e1) - m) / (1.0f - e * cos(e1))
if (counter++ > 100) {
Log.d(TAG, "Failed to converge! Exiting.")
Log.d(TAG, "e1 = $e1, e0 = $e0")
Log.d(TAG, "diff = " + abs(e0 - e1))
break
}
} while (abs(e0 - e1) > EPSILON)
// convert eccentric anomaly to true anomaly
val v = 2f * kotlin.math.atan(
sqrt((1 + e) / (1 - e))
* tan(0.5f * e0)
)
return mod2pi(v)
}
}
private const val EPSILON = 1.0e-6f
| apache-2.0 | 4b558ea8dc34beb336de2034ce80e98b | 36.218391 | 88 | 0.664917 | 3.523395 | false | false | false | false |
kun368/ACManager | src/main/java/com/zzkun/util/prob/PbDiffCalcer.kt | 1 | 1243 | package com.zzkun.util.prob
import com.zzkun.dao.ExtOjPbInfoRepo
import com.zzkun.dao.UserACPbRepo
import com.zzkun.model.OJType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
/**
* Created by Administrator on 2017/2/26 0026.
*/
@Component
open class PbDiffCalcer(
@Autowired private val extOjPbInfoRepo: ExtOjPbInfoRepo,
@Autowired private val userACPbRepo: UserACPbRepo) {
@Suppress("UNUSED_PARAMETER")
fun calcPbDiff(ojName: OJType, pbId: String, pbNum: String): Double {
// val info = extOjPbInfoRepo.findByOjNameAndPid(ojName, pbId)
// val weAC = userACPbRepo.countByOjNameAndOjPbId(ojName, pbNum)
// val res = (DEFAULT_MAX - log(1.0 + info.dacu)) / log(1.7 + weAC)
// println("${ojName},${pbId},${pbNum},${info.dacu},${info.ac},${weAC}")
// return res
return 1.0;
}
fun allPbDiff(): HashMap<String, Double> {
val res = HashMap<String, Double>()
val list = extOjPbInfoRepo.findAll()
list.forEach {
res["${it.num}@${it.ojName}"] = calcPbDiff(it.ojName, it.pid, it.num)
}
return res
}
} | gpl-3.0 | ed80b27c002412d7f6ae849a0dbbe757 | 32.583333 | 81 | 0.6428 | 3.271053 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/api/v1/SignInServlet.kt | 1 | 2754 | /*
* Copyright 2017 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.servlet.api.v1
import com.google.gson.Gson
import com.rpkit.core.web.RPKServlet
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_OK
import javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED
class SignInServlet(private val plugin: RPKPlayersBukkit): RPKServlet() {
override val url = "/api/v1/signin"
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
val gson = Gson()
val name = req.getParameter("name")
val password = req.getParameter("password")
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = profileProvider.getProfile(name)
if (profile != null) {
if (profile.checkPassword(password.toCharArray())) {
profileProvider.setActiveProfile(req, profile)
resp.contentType = "application/json"
resp.status = SC_OK
resp.writer.write(
gson.toJson(
mapOf(
Pair("message", "Success.")
)
)
)
} else {
resp.contentType = "application/json"
resp.status = SC_UNAUTHORIZED
resp.writer.write(
gson.toJson(
mapOf(
Pair("message", "Failure.")
)
)
)
}
} else {
resp.contentType = "application/json"
resp.status = SC_UNAUTHORIZED
resp.writer.write(
gson.toJson(
mapOf(
Pair("message", "Failure.")
)
)
)
}
}
} | apache-2.0 | 350b48f7da23e5812e232cadea3e9e1a | 35.25 | 102 | 0.561728 | 5.186441 | false | false | false | false |
CALlanoR/virtual_environments | medical_etls/part3/kotlin-users-service-api/src/main/kotlin/com/puj/admincenter/service/LoginService.kt | 2 | 4263 | package com.puj.admincenter.service
import com.puj.admincenter.domain.users.User
import com.puj.admincenter.dto.login.LoginDto
import com.puj.admincenter.dto.login.TokenDto
import com.puj.admincenter.repository.users.UserRepository
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.ResponseEntity
import org.springframework.http.HttpStatus
import org.springframework.security.crypto.bcrypt.BCrypt
import org.springframework.stereotype.Service
import java.util.stream.Collectors
import org.slf4j.LoggerFactory
import java.util.Calendar
import java.util.*
@Service
class LoginService(val userRepository: UserRepository) {
companion object {
val logger = LoggerFactory.getLogger(LoginService::class.java)!!
}
@Value(value = "\${jwt.secret}")
private val jwtSecret: String? = null
@Value(value = "\${jwt.expiration:5}")
private val jwtExpiration: Long = 5
fun login(loginDto: LoginDto): ResponseEntity<*> {
val user = userRepository.findUserByUserAndPassword(loginDto.username,
loginDto.password)
return if (user != null) {
logger.info("found user $user")
val jwtToken = getJWTToken(loginDto.username)
println("tokenJwt: $jwtToken")
val token = TokenDto(jwtToken,
user.id)
logger.info("Token $token for user $user generated")
ResponseEntity<TokenDto>(token,
HttpStatus.OK)
} else {
val message = "the user does not exist or is not enabled"
logger.error(message)
ResponseEntity<String>(message,
HttpStatus.NOT_FOUND)
}
}
fun getJWTToken(username:String): String {
val secretKey = "mySecretKey"
val grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")
val claims = Jwts.claims()
.setSubject(username)
claims.put("identity", username)
val token = Jwts.builder()
.setId("softtekJWT")
.setClaims(claims)
.claim("authorities",
grantedAuthorities.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList()))
.setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + 600000))
.signWith(SignatureAlgorithm.HS512,
secretKey.toByteArray()).compact()
return "Bearer " + token
}
}
// Note:
// RS256 vs HS256
// When creating clients and resources servers (APIs) in Auth0, two algorithms are supported for signing
// JSON Web Tokens (JWTs): RS256 and HS256. HS256 is the default for clients and RS256 is the default for APIs.
// When building applications, it is important to understand the differences between these two algorithms.
// To begin, HS256 generates a symmetric MAC and RS256 generates an asymmetric signature. Simply put HS256
// must share a secret with any client or API that wants to verify the JWT. Like any other symmetric algorithm,
// the same secret is used for both signing and verifying the JWT. This means there is no way to fully
// guarantee Auth0 generated the JWT as any client or API with the secret could generate a validly signed JWT.
// On the other hand, RS256 generates an asymmetric signature, which means a private key must be used to sign
// the JWT and a different public key must be used to verify the signature. Unlike symmetric algorithms,
// using RS256 offers assurances that Auth0 is the signer of a JWT since Auth0 is the only party with the
// private key.
// https://auth0.com/blog/navigating-rs256-and-jwks/ | apache-2.0 | 533dcfe9f654c1e61cff6d0dbb54fc0a | 44.361702 | 113 | 0.652592 | 4.554487 | false | false | false | false |
sonnytron/FitTrainerBasic | mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/database/WorkoutObject.kt | 1 | 1240 | package com.sonnyrodriguez.fittrainer.fittrainerbasic.database
import android.arch.persistence.room.*
import android.os.Parcel
import android.os.Parcelable
import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.LocalExerciseObject
@Entity(tableName = "workouts")
data class WorkoutObject(@ColumnInfo(name = "workout_title") var title: String,
@ColumnInfo(name = "exercise_meta_list") var exerciseMetaList: List<LocalExerciseObject>) : Parcelable {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true) var id: Long = 0
constructor(source: Parcel) : this(
source.readString(),
source.createTypedArrayList(LocalExerciseObject.CREATOR)
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(title)
writeTypedList(exerciseMetaList)
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<WorkoutObject> = object : Parcelable.Creator<WorkoutObject> {
override fun createFromParcel(source: Parcel): WorkoutObject = WorkoutObject(source)
override fun newArray(size: Int): Array<WorkoutObject?> = arrayOfNulls(size)
}
}
}
| apache-2.0 | ecfbf2480a626068697fff7370ba839b | 37.75 | 129 | 0.706452 | 4.575646 | false | false | false | false |
grote/Transportr | app/src/main/java/de/grobox/transportr/trips/BaseViewHolder.kt | 1 | 3356 | /*
* Transportr
*
* Copyright (c) 2013 - 2021 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.trips
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import de.grobox.transportr.R
import de.grobox.transportr.utils.DateUtils.formatDelay
import de.grobox.transportr.utils.DateUtils.formatTime
import de.schildbach.pte.dto.Position
import de.schildbach.pte.dto.Stop
import java.util.*
internal abstract class BaseViewHolder(v: View) : RecyclerView.ViewHolder(v) {
protected val context: Context = v.context
protected val fromTime: TextView = v.findViewById(R.id.fromTime)
protected val toTime: TextView = v.findViewById(R.id.toTime)
protected val fromDelay: TextView = v.findViewById(R.id.fromDelay)
protected val toDelay: TextView = v.findViewById(R.id.toDelay)
fun setArrivalTimes(timeView: TextView?, delayView: TextView, stop: Stop) {
if (stop.arrivalTime == null) return
val time = Date(stop.arrivalTime.time)
if (stop.isArrivalTimePredicted && stop.arrivalDelay != null) {
val delay = stop.arrivalDelay
time.time = time.time - delay
formatDelay(delayView.context, delay).let {
delayView.apply {
text = it.delay
setTextColor(it.color)
visibility = VISIBLE
}
}
} else {
delayView.visibility = GONE
}
timeView?.let { it.text = formatTime(context, time) }
}
fun setDepartureTimes(timeView: TextView?, delayView: TextView, stop: Stop) {
if (stop.departureTime == null) return
val time = Date(stop.departureTime.time)
if (stop.isDepartureTimePredicted && stop.departureDelay != null) {
val delay = stop.departureDelay
time.time = time.time - delay
formatDelay(delayView.context, delay).let {
delayView.apply {
text = it.delay
setTextColor(it.color)
visibility = VISIBLE
}
}
} else {
delayView.visibility = GONE
}
timeView?.let { it.text = formatTime(context, time) }
}
@SuppressLint("SetTextI18n")
protected fun TextView.addPlatform(position: Position?) {
if (position == null) return
text = "$text ${context.getString(R.string.platform, position.toString())}"
}
}
| gpl-3.0 | c02c28c34cc7f7b4b988108d8af0bf15 | 35.086022 | 83 | 0.654052 | 4.286079 | false | false | false | false |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/ui/CheckedImageView.kt | 1 | 3851 | package ru.ustimov.weather.ui
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import android.view.View
import android.widget.Checkable
import ru.ustimov.weather.R
class CheckedImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr), Checkable {
private companion object {
private val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked)
}
interface OnCheckedChangeListener {
fun onCheckedChanged(v: CheckedImageView, isChecked: Boolean)
}
private var checked = false
private var broadcasting = false
private var onCheckedChangeListener: OnCheckedChangeListener? = null
init {
isClickable = true
val a = context.obtainStyledAttributes(attrs, R.styleable.CheckedImageView, defStyleAttr, 0)
try {
val checked = a.getBoolean(R.styleable.CheckedImageView_android_checked, false)
this.checked = checked
} finally {
a.recycle()
}
}
fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
onCheckedChangeListener = listener
}
override fun setChecked(checked: Boolean) {
if (this.checked != checked) {
this.checked = checked
refreshDrawableState()
// Avoid infinite recursions if setChecked() is called from a listener
if (!broadcasting) {
broadcasting = true
onCheckedChangeListener?.onCheckedChanged(this, this.checked)
broadcasting = false
}
}
}
override fun isChecked() = this.checked
override fun toggle() {
isChecked = !this.checked
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (isChecked) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET)
}
return drawableState
}
override fun performClick(): Boolean {
/* When clicked, toggle the state */
toggle()
return super.performClick()
}
private class SavedState : View.BaseSavedState {
var checked: Boolean
internal constructor(superState: Parcelable, checked: Boolean) : super(superState) {
this.checked = checked
}
private constructor(src: Parcel) : super(src) {
checked = src.readInt() == 1
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeValue(if (checked) 1 else 0)
}
override fun toString(): String {
return ("CheckedImageView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " checked=" + checked + "}")
}
companion object {
@JvmStatic
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(src: Parcel) = SavedState(src)
override fun newArray(size: Int): Array<SavedState?> = arrayOfNulls(size)
}
}
}
public override fun onSaveInstanceState(): Parcelable {
// Force our ancestor class to save its state
val superState = super.onSaveInstanceState()
return SavedState(superState, isChecked)
}
public override fun onRestoreInstanceState(state: Parcelable) {
val ss = state as SavedState
super.onRestoreInstanceState(ss.getSuperState())
isChecked = ss.checked
requestLayout()
}
} | apache-2.0 | 870df3cedd9f93f723d0710f7c0dcadd | 28.181818 | 100 | 0.635419 | 5.239456 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/push/PushManager.kt | 2 | 13631 | package chat.rocket.android.push
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.Spanned
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY
import chat.rocket.android.R
import chat.rocket.android.server.domain.GetAccountInteractor
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.siteName
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.server.ui.changeServerIntent
import chat.rocket.common.model.RoomType
import chat.rocket.common.model.roomTypeOf
import com.squareup.moshi.Moshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
class PushManager @Inject constructor(
private val groupedPushes: GroupedPush,
private val notificationManager: NotificationManager,
private val moshi: Moshi,
private val getAccountInteractor: GetAccountInteractor,
private val getSettingsInteractor: GetSettingsInteractor,
private val context: Context,
private val serverInteractor: GetCurrentServerInteractor,
private val factory: RocketChatClientFactory
) {
private val random = Random()
fun registerPushNotificationToken(token: String) = GlobalScope.launch(Dispatchers.IO) {
serverInteractor.get()?.let { currentServer ->
registerPushNotificationToken(factory.get(currentServer), token)
}
}
/**
* Handles a receiving push by creating and displaying an appropriate notification based
* on the *data* param bundle received.
*/
fun handle(data: Bundle) = runBlocking {
val message = data["message"] as String?
val ejson = data["ejson"] as String?
val title = data["title"] as String?
val notId = data["notId"] as String? ?: random.nextInt().toString()
val image = data["image"] as String?
val style = data["style"] as String?
val summaryText = data["summaryText"] as String?
val count = data["count"] as String?
try {
if (title != null && message != null) {
val pushInfo = if (ejson != null) {
moshi.adapter<PushInfo>(PushInfo::class.java).fromJson(ejson)
} else {
null
}
val pushMessage = PushMessage(
title = title,
message = message,
info = pushInfo ?: PushInfo(
hostname = "",
roomId = "",
type = roomTypeOf(RoomType.CHANNEL),
name = "",
sender = null
),
image = image,
count = count,
notificationId = notId,
summaryText = summaryText,
style = style
)
showNotification(pushMessage)
Timber.d("Received push message: $pushMessage")
}
} catch (ex: Exception) {
Timber.e(ex, "Error parsing push message: $data")
}
}
@SuppressLint("NewApi")
fun showNotification(pushMessage: PushMessage) {
val notId = pushMessage.notificationId.toInt()
val host = pushMessage.info.host
createSingleNotification(pushMessage)?.let { notification ->
NotificationManagerCompat.from(context).notify(notId, notification)
if (!hasAccount(host)) {
Timber.d("Test or generic Push message: $pushMessage sent")
return
}
}
val groupTuple = getGroupForHost(host)
groupTuple.second.incrementAndGet()
val notIdListForHostname: MutableList<PushMessage>? =
groupedPushes.hostToPushMessageList[host]
if (notIdListForHostname == null) {
groupedPushes.hostToPushMessageList[host] = arrayListOf(pushMessage)
} else {
notIdListForHostname.add(0, pushMessage)
}
val pushMessageList = groupedPushes.hostToPushMessageList[host]
pushMessageList?.let {
if (pushMessageList.size > 1) {
val groupNotification = createGroupNotification(pushMessage)
groupNotification?.let {
NotificationManagerCompat.from(context)
.notify(groupTuple.first, groupNotification)
}
}
}
}
private fun hasAccount(host: String): Boolean {
return getAccountInteractor.get(host) != null
}
private fun getGroupForHost(host: String): TupleGroupIdMessageCount {
val size = groupedPushes.groupMap.size
var group = groupedPushes.groupMap[host]
if (group == null) {
group = TupleGroupIdMessageCount(size + 1, AtomicInteger(0))
groupedPushes.groupMap[host] = group
}
return group
}
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N)
private fun createGroupNotification(pushMessage: PushMessage): Notification? {
with(pushMessage) {
val host = info.host
val builder = createBaseNotificationBuilder(pushMessage, grouped = true)
.setGroupSummary(true)
if (style == null || style == "inbox") {
val pushMessageList = groupedPushes.hostToPushMessageList[host]
pushMessageList?.let {
val count = pushMessageList.filter {
it.title == title
}.size
builder.setContentTitle(getTitle(count, title))
val inbox = NotificationCompat.InboxStyle()
.setBigContentTitle(getTitle(count, title))
for (push in pushMessageList) {
inbox.addLine(push.message)
}
builder.setStyle(inbox)
}
} else {
val bigText = NotificationCompat.BigTextStyle()
.bigText(message.fromHtml())
.setBigContentTitle(title.fromHtml())
builder.setStyle(bigText)
}
return builder.build()
}
}
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.N)
private fun createSingleNotification(pushMessage: PushMessage): Notification? {
with(pushMessage) {
val host = info.host
val builder = createBaseNotificationBuilder(pushMessage).setGroupSummary(false)
if (style == null || "inbox" == style) {
val pushMessageList = groupedPushes.hostToPushMessageList[host]
if (pushMessageList != null) {
val userMessages = pushMessageList.filter {
it.notificationId == pushMessage.notificationId
}
val count = pushMessageList.filter {
it.title == title
}.size
builder.setContentTitle(getTitle(count, title))
if (count > 1) {
val inbox = NotificationCompat.InboxStyle()
inbox.setBigContentTitle(getTitle(count, title))
for (push in userMessages) {
inbox.addLine(push.message)
}
builder.setStyle(inbox)
} else {
val bigTextStyle = NotificationCompat.BigTextStyle()
.bigText(message.fromHtml())
builder.setStyle(bigTextStyle)
}
} else {
// We don't know which kind of push is this - maybe a test push, so just show it
val bigTextStyle = NotificationCompat.BigTextStyle()
.bigText(message.fromHtml())
builder.setStyle(bigTextStyle)
return builder.build()
}
} else {
val bigTextStyle = NotificationCompat.BigTextStyle().bigText(message.fromHtml())
builder.setStyle(bigTextStyle)
}
return builder.build()
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createBaseNotificationBuilder(
pushMessage: PushMessage,
grouped: Boolean = false
): NotificationCompat.Builder {
return with(pushMessage) {
val id = notificationId.toInt()
val host = info.host
val contentIntent = getContentIntent(context, id, pushMessage, grouped)
val deleteIntent = getDismissIntent(context, pushMessage)
val builder = NotificationCompat.Builder(context, host)
.setWhen(info.createdAt)
.setContentTitle(title.fromHtml())
.setContentText(message.fromHtml())
.setGroup(host)
.setDeleteIntent(deleteIntent)
.setContentIntent(contentIntent)
.setMessageNotification()
if (host.isEmpty()) {
builder.setContentIntent(deleteIntent)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId: String
val channelName: String
if (host.isEmpty()) {
channelName = "Test Notification"
channelId = "test-channel"
} else {
channelName = host
channelId = host
}
val channel =
NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channel.enableLights(false)
channel.enableVibration(true)
channel.setShowBadge(true)
notificationManager.createNotificationChannel(channel)
builder.setChannelId(channelId)
}
//TODO: Get Site_Name PublicSetting from cache
val subText = getSiteName(host)
if (subText.isNotEmpty()) {
builder.setSubText(subText)
}
return@with builder
}
}
private fun getSiteName(host: String): String {
val settings = getSettingsInteractor.get(host)
return settings.siteName() ?: "Rocket.Chat"
}
private fun getTitle(messageCount: Int, title: String): CharSequence {
return if (messageCount > 1) "($messageCount) ${title.fromHtml()}" else title.fromHtml()
}
private fun getDismissIntent(context: Context, pushMessage: PushMessage): PendingIntent {
val deleteIntent = Intent(context, DeleteReceiver::class.java)
.putExtra(EXTRA_NOT_ID, pushMessage.notificationId.toInt())
.putExtra(EXTRA_HOSTNAME, pushMessage.info.host)
return PendingIntent.getBroadcast(
context,
pushMessage.notificationId.toInt(),
deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
private fun getContentIntent(
context: Context,
notificationId: Int,
pushMessage: PushMessage,
grouped: Boolean = false
): PendingIntent {
val roomId = if (!grouped) pushMessage.info.roomId else null
val notificationIntent =
context.changeServerIntent(pushMessage.info.host, chatRoomId = roomId)
return PendingIntent.getActivity(
context,
random.nextInt(),
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
// CharSequence extensions
private fun CharSequence.fromHtml(): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this as String, FROM_HTML_MODE_LEGACY, null, null)
} else {
Html.fromHtml(this as String)
}
}
private fun NotificationCompat.Builder.setMessageNotification(): NotificationCompat.Builder {
val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val res = context.resources
val smallIcon = res.getIdentifier(
"rocket_chat_notification", "drawable", context.packageName
)
with(this) {
setAutoCancel(true)
setShowWhen(true)
color = ContextCompat.getColor(context, R.color.colorPrimary)
setDefaults(Notification.DEFAULT_ALL)
setSmallIcon(smallIcon)
setSound(alarmSound)
}
return this
}
}
const val EXTRA_NOT_ID = "chat.rocket.android.EXTRA_NOT_ID"
const val EXTRA_HOSTNAME = "chat.rocket.android.EXTRA_HOSTNAME" | mit | 0d73675e9d7a71032102812e2a9853d5 | 36.553719 | 100 | 0.595554 | 5.297707 | false | false | false | false |
UnderMybrella/Visi | src/main/kotlin/org/abimon/visi/io/ByteArrayIOStream.kt | 1 | 3426 | package org.abimon.visi.io
import org.abimon.visi.collections.get
import java.io.InputStream
import java.io.OutputStream
class ByteArrayIOStream {
private val buffer: MutableList<Byte> = ArrayList()
private var pos: Int = 0
val inputStream: InputStream =
object : InputStream() {
val io: ByteArrayIOStream = this@ByteArrayIOStream
override fun read(): Int = io.read()
override fun read(b: ByteArray): Int = io.read(b)
override fun read(b: ByteArray, off: Int, len: Int): Int = io.read(b, off, len)
override fun skip(n: Long): Long {
io.seekFromPos(n.toInt())
return n
}
override fun available(): Int = io.buffer.size - io.pos
override fun reset() {
io.pos = 0
}
}
val outputStream: OutputStream =
object : OutputStream() {
val io: ByteArrayIOStream = this@ByteArrayIOStream
override fun write(b: Int) = io.write(b.toByte())
override fun write(b: ByteArray) = io.write(b)
override fun write(b: ByteArray, off: Int, len: Int) = io.write(b, off, len)
}
val dataSource: DataSource =
object : DataSource {
val io: ByteArrayIOStream = this@ByteArrayIOStream
override val inputStream: InputStream
get() = io.inputStream
override val seekableInputStream: InputStream
get() = io.inputStream
override val location: String
get() = "ByteArrayIOStrea#dataSource ${io.hashCode()}"
override val data: ByteArray
get() = io.toByteArray()
override val size: Long
get() = buffer.size.toLong()
override fun pipe(out: OutputStream) = out.write(toByteArray())
}
val position: Int
get() = pos
val size: Int
get() = buffer.size
fun read(): Int = buffer[pos++, -1].toInt() and 0xFF
fun read(bytes: ByteArray): Int {
for (i in 0 until bytes.size) {
if (pos + i >= buffer.size || pos + i < 0)
return i
bytes[i] = buffer[pos++]
}
return bytes.size
}
fun read(bytes: ByteArray, off: Int, len: Int): Int {
for (i in 0 until len) {
if (pos + i >= buffer.size || i + off >= bytes.size || pos + i < 0)
return i
bytes[i + off] = buffer[pos++]
}
return len
}
fun write(byte: Byte) {
buffer.add(pos++, byte)
}
fun write(bytes: ByteArray) {
bytes.forEach { buffer.add(pos++, it) }
}
fun write(bytes: ByteArray, off: Int, len: Int) {
for(i in 0 until len) {
if(i + off >= bytes.size)
return
buffer.add(pos++, bytes[i + off])
}
}
fun seek(pos: Int) {
this.pos = pos
}
fun seekFromEnd(offset: Int) {
pos = buffer.size - offset - 1
}
fun seekFromPos(offset: Int) {
pos += offset
}
fun clear() {
buffer.clear()
}
fun toByteArray(): ByteArray = buffer.toByteArray()
fun writeTo(output: OutputStream) = output.write(toByteArray())
} | mit | e3ec61fca91aeeb3db7584ea5ca8a645 | 27.798319 | 95 | 0.511384 | 4.358779 | false | false | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/memory/DefaultNativeMemoryChunkPoolParams.kt | 1 | 2705 | /*
* 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.imagepipeline.memory
import android.util.SparseIntArray
import com.facebook.common.util.ByteConstants
/** Provides pool parameters ([PoolParams]) for [NativeMemoryChunkPool] */
object DefaultNativeMemoryChunkPoolParams {
/**
* Length of 'small' sized buckets. Bucket lengths for these buckets are larger because they're
* smaller in size
*/
private const val SMALL_BUCKET_LENGTH = 5
/** Bucket lengths for 'large' (> 256KB) buckets */
private const val LARGE_BUCKET_LENGTH = 2
@JvmStatic
fun get(): PoolParams {
val DEFAULT_BUCKETS = SparseIntArray()
DEFAULT_BUCKETS.put(1 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(2 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(4 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(8 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(16 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(32 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(64 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(128 * ByteConstants.KB, SMALL_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(256 * ByteConstants.KB, LARGE_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(512 * ByteConstants.KB, LARGE_BUCKET_LENGTH)
DEFAULT_BUCKETS.put(1_024 * ByteConstants.KB, LARGE_BUCKET_LENGTH)
return PoolParams(maxSizeSoftCap, maxSizeHardCap, DEFAULT_BUCKETS)
}
/**
* [NativeMemoryChunkPool] manages memory on the native heap, so we don't need as strict caps as
* we would if we were on the Dalvik heap. However, since native memory OOMs are significantly
* more problematic than Dalvik OOMs, we would like to stay conservative.
*/
private val maxSizeSoftCap: Int
get() {
val maxMemory = Math.min(Runtime.getRuntime().maxMemory(), Int.MAX_VALUE.toLong()).toInt()
return if (maxMemory < 16 * ByteConstants.MB) {
3 * ByteConstants.MB
} else if (maxMemory < 32 * ByteConstants.MB) {
6 * ByteConstants.MB
} else {
12 * ByteConstants.MB
}
}
/**
* We need a smaller cap for devices with less then 16 MB so that we don't run the risk of
* evicting other processes from the native heap.
*/
private val maxSizeHardCap: Int
get() {
val maxMemory = Math.min(Runtime.getRuntime().maxMemory(), Int.MAX_VALUE.toLong()).toInt()
return if (maxMemory < 16 * ByteConstants.MB) {
maxMemory / 2
} else {
maxMemory / 4 * 3
}
}
}
| mit | 92d65c6ba5f7eacd4093ba7eeb0a5892 | 36.569444 | 98 | 0.697967 | 3.715659 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/macrobenchmark-app/src/main/java/com/example/macrobenchmark/newmessage/NewMessage.kt | 2 | 24740 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.newmessage
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Send
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.MotionLayout
import androidx.constraintlayout.compose.MotionLayoutScope
import androidx.constraintlayout.compose.MotionScene
import androidx.constraintlayout.compose.Visibility
import com.example.macrobenchmark.testutils.components.TestableButton
// Copied from ComposeMail project
@Preview
@Composable
fun NewMotionMessagePreview() {
NewMotionMessageWithControls(useDsl = false)
}
@Preview
@Composable
fun NewMotionMessagePreviewWithDsl() {
NewMotionMessageWithControls(useDsl = true)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun NewMotionMessageWithControls(
useDsl: Boolean
) {
val initialLayout = NewMessageLayout.Full
val newMessageState = rememberNewMessageState(initialLayoutState = initialLayout)
val motionScene = if (useDsl) {
messageMotionSceneDsl(initialState = initialLayout)
} else {
messageMotionScene(initialState = initialLayout)
}
Column(Modifier.semantics { testTagsAsResourceId = true }) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
TestableButton(
onClick = newMessageState::setToFab,
text = "Fab"
)
TestableButton(
onClick = newMessageState::setToFull,
text = "Full"
)
TestableButton(
onClick = newMessageState::setToMini,
text = "Mini"
)
}
NewMessageButton(
modifier = Modifier.fillMaxSize(),
motionScene = motionScene,
state = newMessageState,
)
}
}
@Composable
private fun messageMotionSceneDsl(initialState: NewMessageLayout): MotionScene {
val startState = remember { initialState }
val endState = when (startState) {
NewMessageLayout.Fab -> NewMessageLayout.Full
NewMessageLayout.Mini -> NewMessageLayout.Fab
NewMessageLayout.Full -> NewMessageLayout.Fab
}
val primary = MaterialTheme.colors.primary
val primaryVariant = MaterialTheme.colors.primaryVariant
val onPrimary = MaterialTheme.colors.onPrimary
val surface = MaterialTheme.colors.surface
val onSurface = MaterialTheme.colors.onSurface
return MotionScene {
val box = createRefFor("box")
val minIcon = createRefFor("minIcon")
val editClose = createRefFor("editClose")
val title = createRefFor("title")
val content = createRefFor("content")
val fab = constraintSet(NewMessageLayout.Fab.name) {
constrain(box) {
width = Dimension.value(50.dp)
height = Dimension.value(50.dp)
end.linkTo(parent.end, 12.dp)
bottom.linkTo(parent.bottom, 12.dp)
customColor("background", primary)
}
constrain(minIcon) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
end.linkTo(editClose.start, 8.dp)
top.linkTo(editClose.top)
customColor("content", onPrimary)
}
constrain(editClose) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
centerTo(box)
customColor("content", onPrimary)
}
constrain(title) {
width = Dimension.fillToConstraints
top.linkTo(box.top)
bottom.linkTo(editClose.bottom)
start.linkTo(box.start, 8.dp)
end.linkTo(minIcon.start, 8.dp)
customColor("content", onPrimary)
visibility = Visibility.Gone
}
constrain(content) {
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
start.linkTo(box.start, 8.dp)
end.linkTo(box.end, 8.dp)
top.linkTo(editClose.bottom, 8.dp)
bottom.linkTo(box.bottom, 8.dp)
visibility = Visibility.Gone
}
}
val full = constraintSet(NewMessageLayout.Full.name) {
constrain(box) {
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
start.linkTo(parent.start, 12.dp)
end.linkTo(parent.end, 12.dp)
bottom.linkTo(parent.bottom, 12.dp)
top.linkTo(parent.top, 40.dp)
customColor("background", surface)
}
constrain(minIcon) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
end.linkTo(editClose.start, 8.dp)
top.linkTo(editClose.top)
customColor("content", onSurface)
}
constrain(editClose) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
end.linkTo(box.end, 4.dp)
top.linkTo(box.top, 4.dp)
customColor("content", onSurface)
}
constrain(title) {
width = Dimension.fillToConstraints
top.linkTo(box.top)
bottom.linkTo(editClose.bottom)
start.linkTo(box.start, 8.dp)
end.linkTo(minIcon.start, 8.dp)
customColor("content", onSurface)
}
constrain(content) {
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
start.linkTo(box.start, 8.dp)
end.linkTo(box.end, 8.dp)
top.linkTo(editClose.bottom, 8.dp)
bottom.linkTo(box.bottom, 8.dp)
}
}
val mini = constraintSet(NewMessageLayout.Mini.name) {
constrain(box) {
width = Dimension.value(220.dp)
height = Dimension.value(50.dp)
end.linkTo(parent.end, 12.dp)
bottom.linkTo(parent.bottom, 12.dp)
customColor("background", primaryVariant)
}
constrain(minIcon) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
end.linkTo(editClose.start, 8.dp)
top.linkTo(editClose.top)
rotationZ = 180f
customColor("content", onPrimary)
}
constrain(editClose) {
width = Dimension.value(40.dp)
height = Dimension.value(40.dp)
end.linkTo(box.end, 4.dp)
top.linkTo(box.top, 4.dp)
customColor("content", onPrimary)
}
constrain(title) {
width = Dimension.fillToConstraints
top.linkTo(box.top)
bottom.linkTo(editClose.bottom)
start.linkTo(box.start, 8.dp)
end.linkTo(minIcon.start, 8.dp)
customColor("content", onPrimary)
}
constrain(content) {
width = Dimension.fillToConstraints
start.linkTo(box.start, 8.dp)
end.linkTo(box.end, 8.dp)
top.linkTo(editClose.bottom, 8.dp)
bottom.linkTo(box.bottom, 8.dp)
visibility = Visibility.Gone
}
}
fun constraintSetFor(layoutState: NewMessageLayout) =
when (layoutState) {
NewMessageLayout.Full -> full
NewMessageLayout.Mini -> mini
NewMessageLayout.Fab -> fab
}
defaultTransition(
from = constraintSetFor(startState),
to = constraintSetFor(endState)
)
}
}
@Composable
private fun messageMotionScene(initialState: NewMessageLayout): MotionScene {
val startState = remember { initialState }
val endState = when (startState) {
NewMessageLayout.Fab -> NewMessageLayout.Full
NewMessageLayout.Mini -> NewMessageLayout.Fab
NewMessageLayout.Full -> NewMessageLayout.Fab
}
val startStateName = startState.name
val endStateName = endState.name
val primary = MaterialTheme.colors.primary.toHexString()
val primaryVariant = MaterialTheme.colors.primaryVariant.toHexString()
val onPrimary = MaterialTheme.colors.onPrimary.toHexString()
val surface = MaterialTheme.colors.surface.toHexString()
val onSurface = MaterialTheme.colors.onSurface.toHexString()
return MotionScene(
content =
"""
{
ConstraintSets: {
${NewMessageLayout.Fab.name}: {
box: {
width: 50, height: 50,
end: ['parent', 'end', 12],
bottom: ['parent', 'bottom', 12],
custom: {
background: '#$primary'
}
},
minIcon: {
width: 40, height: 40,
end: ['editClose', 'start', 8],
top: ['editClose', 'top', 0],
visibility: 'gone',
custom: {
content: '#$onPrimary'
}
},
editClose: {
width: 40, height: 40,
centerHorizontally: 'box',
centerVertically: 'box',
custom: {
content: '#$onPrimary'
}
},
title: {
width: 'spread',
top: ['box', 'top', 0],
bottom: ['editClose', 'bottom', 0],
start: ['box', 'start', 8],
end: ['minIcon', 'start', 8],
custom: {
content: '#$onPrimary'
}
visibility: 'gone'
},
content: {
width: 'spread', height: 'spread',
start: ['box', 'start', 8],
end: ['box', 'end', 8],
top: ['editClose', 'bottom', 8],
bottom: ['box', 'bottom', 8],
visibility: 'gone'
}
},
${NewMessageLayout.Full.name}: {
box: {
width: 'spread', height: 'spread',
start: ['parent', 'start', 12],
end: ['parent', 'end', 12],
bottom: ['parent', 'bottom', 12],
top: ['parent', 'top', 40],
custom: {
background: '#$surface'
}
},
minIcon: {
width: 40, height: 40,
end: ['editClose', 'start', 8],
top: ['editClose', 'top', 0],
custom: {
content: '#$onSurface'
}
},
editClose: {
width: 40, height: 40,
end: ['box', 'end', 4],
top: ['box', 'top', 4],
custom: {
content: '#$onSurface'
}
},
title: {
width: 'spread',
top: ['box', 'top', 0],
bottom: ['editClose', 'bottom', 0],
start: ['box', 'start', 8],
end: ['minIcon', 'start', 8],
custom: {
content: '#$onSurface'
}
},
content: {
width: 'spread', height: 'spread',
start: ['box', 'start', 8],
end: ['box', 'end', 8],
top: ['editClose', 'bottom', 8],
bottom: ['box', 'bottom', 8]
}
},
${NewMessageLayout.Mini.name}: {
box: {
width: 180, height: 50,
bottom: ['parent', 'bottom', 12],
end: ['parent', 'end', 12],
custom: {
background: '#$primaryVariant'
}
},
minIcon: {
width: 40, height: 40,
end: ['editClose', 'start', 8],
top: ['editClose', 'top', 0],
rotationZ: 180,
custom: {
content: '#$onPrimary'
}
},
editClose: {
width: 40, height: 40,
end: ['box', 'end', 4],
top: ['box', 'top', 4],
custom: {
content: '#$onPrimary'
}
},
title: {
width: 'spread',
top: ['box', 'top', 0],
bottom: ['editClose', 'bottom', 0],
start: ['box', 'start', 8],
end: ['minIcon', 'start', 8],
custom: {
content: '#$onPrimary'
}
},
content: {
width: 'spread', height: 'spread',
start: ['box', 'start', 8],
end: ['box', 'end', 8],
top: ['editClose', 'bottom', 8],
bottom: ['box', 'bottom', 8],
visibility: 'gone'
}
}
},
Transitions: {
default: {
from: '$startStateName',
to: '$endStateName'
}
}
}
"""
)
}
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun MotionLayoutScope.MotionMessageContent(
state: NewMessageState
) {
val currentState = state.currentState
val focusManager = LocalFocusManager.current
val dialogName = remember(currentState) {
when (currentState) {
NewMessageLayout.Mini -> "Draft"
else -> "Message"
}
}
Surface(
modifier = Modifier.layoutId("box"),
color = motionColor(id = "box", name = "background"),
elevation = 4.dp,
shape = RoundedCornerShape(8.dp)
) {}
ColorableIconButton(
modifier = Modifier.layoutId("editClose"),
imageVector = when (currentState) {
NewMessageLayout.Fab -> Icons.Default.Edit
else -> Icons.Default.Close
},
color = motionColor("editClose", "content"),
enabled = true
) {
when (currentState) {
NewMessageLayout.Fab -> state.setToFull()
else -> state.setToFab()
}
}
ColorableIconButton(
modifier = Modifier.layoutId("minIcon"),
imageVector = Icons.Default.KeyboardArrowDown,
color = motionColor("minIcon", "content"),
enabled = true
) {
when (currentState) {
NewMessageLayout.Full -> state.setToMini()
else -> state.setToFull()
}
}
CheapText(
text = dialogName,
modifier = Modifier.layoutId("title"),
color = motionColor("title", "content"),
style = MaterialTheme.typography.h6
)
MessageWidget(modifier = Modifier.layoutId("content"), onDelete = {
focusManager.clearFocus()
state.setToFab()
})
// MessageWidgetCol(
// modifier = Modifier
// .layoutId("content")
// .padding(start = 4.dp, end = 4.dp, bottom = 4.dp)
// )
}
@Composable
private fun NewMessageButton(
modifier: Modifier = Modifier,
motionScene: MotionScene,
state: NewMessageState
) {
val currentStateName = state.currentState.name
MotionLayout(
motionScene = motionScene,
animationSpec = tween(700),
constraintSetName = currentStateName,
modifier = modifier
) {
MotionMessageContent(state = state)
}
}
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun ColorableIconButton(
modifier: Modifier,
imageVector: ImageVector,
color: Color,
enabled: Boolean,
noinline onClick: () -> Unit
) {
Surface(
modifier = modifier,
color = Color.Transparent,
contentColor = color,
onClick = onClick,
enabled = enabled
) {
Icon(
imageVector = imageVector,
contentDescription = null,
modifier = Modifier.fillMaxSize()
)
}
}
// With column
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun MessageWidgetCol(modifier: Modifier) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
TextField(
modifier = Modifier.fillMaxWidth(),
value = "",
onValueChange = {},
placeholder = {
Text("Recipients")
}
)
TextField(
modifier = Modifier.fillMaxWidth(),
value = "",
onValueChange = {},
placeholder = {
Text("Subject")
}
)
TextField(
modifier = Modifier
.fillMaxWidth()
.weight(weight = 2.0f, fill = true),
value = "",
onValueChange = {},
placeholder = {
Text("Message")
}
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Button(onClick = { /*TODO*/ }) {
Row {
Text(text = "Send")
Spacer(modifier = Modifier.width(8.dp))
Icon(
imageVector = Icons.Default.Send,
contentDescription = "Send Mail",
)
}
}
Button(onClick = { /*TODO*/ }) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Delete Draft",
)
}
}
}
}
// With ConstraintLayout
@Preview
@Composable
private fun MessageWidgetPreview() {
MessageWidget(modifier = Modifier.fillMaxSize())
}
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun MessageWidget(
modifier: Modifier,
noinline onDelete: () -> Unit = {}
) {
val constraintSet = remember {
ConstraintSet(
"""
{
gl1: { type: 'hGuideline', end: 50 },
recipient: {
top: ['parent', 'top', 2],
width: 'spread',
centerHorizontally: 'parent',
},
subject: {
top: ['recipient', 'bottom', 8],
width: 'spread',
centerHorizontally: 'parent',
},
message: {
height: 'spread',
width: 'spread',
centerHorizontally: 'parent',
top: ['subject', 'bottom', 8],
bottom: ['gl1', 'bottom', 4],
},
delete: {
height: 'spread',
top: ['gl1', 'bottom', 0],
bottom: ['parent', 'bottom', 4],
start: ['parent', 'start', 0]
},
send: {
height: 'spread',
top: ['gl1', 'bottom', 0],
bottom: ['parent', 'bottom', 4],
end: ['parent', 'end', 0]
}
}
""".trimIndent()
)
}
ConstraintLayout(
modifier = modifier.padding(top = 4.dp, start = 8.dp, end = 8.dp, bottom = 0.dp),
constraintSet = constraintSet
) {
OutlinedTextField(
modifier = Modifier.layoutId("recipient"),
value = "",
onValueChange = {},
label = {
CheapText("To")
}
)
OutlinedTextField(
modifier = Modifier.layoutId("subject"),
value = "",
onValueChange = {},
label = {
CheapText("Subject")
}
)
OutlinedTextField(
modifier = Modifier
.layoutId("message")
.fillMaxHeight(),
value = "",
onValueChange = {},
label = {
CheapText("Message")
}
)
Button(
modifier = Modifier.layoutId("send"),
onClick = onDelete // TODO: Do something different for Send onClick
) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CheapText(text = "Send")
Icon(
imageVector = Icons.Default.Send,
contentDescription = "Send Mail",
)
}
}
Button(
modifier = Modifier.layoutId("delete"),
onClick = onDelete
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Delete Draft",
)
}
}
}
/**
* [Text] Composable constrained to one line for better animation performance.
*/
@Suppress("NOTHING_TO_INLINE")
@Composable
private inline fun CheapText(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
style: TextStyle = LocalTextStyle.current,
overflow: TextOverflow = TextOverflow.Clip
) {
Text(
text = text,
modifier = modifier,
color = color,
style = style,
maxLines = 1,
overflow = overflow,
)
}
private fun Color.toHexString() = toArgb().toUInt().toString(16) | apache-2.0 | 5aa90b34863f8e8d1c58f7e1d3b0ad2e | 31.769536 | 89 | 0.520251 | 4.896101 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/listener/InventoryClickListener.kt | 1 | 1749 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.locks.bukkit.listener
import com.rpkit.core.service.Services
import com.rpkit.locks.bukkit.RPKLocksBukkit
import com.rpkit.locks.bukkit.lock.RPKLockService
import org.bukkit.Material.AIR
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryClickEvent
class InventoryClickListener(private val plugin: RPKLocksBukkit) : Listener {
@EventHandler
fun onInventoryClick(event: InventoryClickEvent) {
if (!event.view.title.equals("Keyring", ignoreCase = true)) return
val currentItem = event.currentItem ?: return
event.isCancelled = true
val lockService = Services[RPKLockService::class.java]
if (lockService == null) {
event.whoClicked.sendMessage(plugin.messages.noLockService)
return
}
if (lockService.isKey(currentItem)) {
event.isCancelled = false
}
if (currentItem.type == AIR) {
event.isCancelled = false
}
if (event.isCancelled) {
event.whoClicked.sendMessage(plugin.messages.keyringInvalidItem)
}
}
} | apache-2.0 | 456bb65def4afc0d7c2fd0ee0f34c903 | 33.313725 | 77 | 0.705546 | 4.329208 | false | false | false | false |
belyaev-mikhail/kcheck | src/main/kotlin/ru/spbstu/kotlin/generate/combinators/KCheck.kt | 1 | 10389 | package ru.spbstu.kotlin.generate.combinators
import ru.spbstu.kotlin.generate.assume.AssumptionFailedException
import ru.spbstu.kotlin.typeclass.TypeClasses
import ru.spbstu.ktuples.*
import ru.spbstu.wheels.getOrElse
import ru.spbstu.wheels.tryEx
import java.util.concurrent.TimeoutException
import kotlin.reflect.KType
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.jvm.reflect
data class ForInputException(val data: Any?, val nested: Exception) :
Exception("forAll failed for input data: $data", nested)
inline fun<R> retrying(limit: Int = 50, appendable: Appendable = NullAppendable, body: () -> R): R {
var count = limit
while(--count != 0) {
try{ return body() }
catch (retry: AssumptionFailedException) {
appendable.appendln("Assumption failed, retrying")
continue
}
}
throw AssumptionFailedException()
}
@PublishedApi
internal fun <T> generate(
iterations: Int,
gen: Arbitrary<T>,
appendable: Appendable,
body: (T) -> Unit
): Pair<T, Exception>? = with(appendable) {
appendln("Generating...")
repeat(iterations) {
retrying(appendable = appendable) {
val value = gen.next()
appendln("Generated: $value")
try {
body(value)
} catch (assumption: AssumptionFailedException) {
throw assumption
} catch (ex: Exception) {
return value to ex
}
}
}
return null
}
@PublishedApi
internal fun <T> shrink(
iterations: Int,
shrinker: Shrinker<T>,
value: T,
ex: Exception,
appendable: Appendable,
body: (T) -> Unit
): Pair<T, Exception> = with(appendable) {
appendln("Shrinking $value...")
var current = value
var currentEx: Exception = ex
val tried = mutableSetOf<T>()
repeat(iterations) {
val nexts = shrinker.shrink(current)
for(v in nexts) {
if(v in tried) continue
tried.add(v)
appendln("Trying $v")
try {
body(v)
}
catch(assume: AssumptionFailedException) {}
// do not shrink on timeout
catch(timeout: TimeoutException) { return@with v to timeout }
catch(ex: Exception) {
current = v
currentEx = ex
break
}
}
}
return@with current to currentEx
}.also { appendable.appendln("Shrinking result: $it") }
object NullAppendable : Appendable {
override fun append(csq: CharSequence?): Appendable = this
override fun append(csq: CharSequence?, start: Int, end: Int): Appendable = this
override fun append(c: Char): Appendable = this
}
object NoShrinker : Shrinker<Any?>
object KCheck {
init {
Arbitrary.exportDefaults()
Shrinker.exportDefaults()
}
val arbitrary = Arbitrary::class
val shrinker = Shrinker::class
fun <T> getShrinker(type: KType) = tryEx { TypeClasses.get<Shrinker<*>>(type) as Shrinker<T> }
.getOrElse { NoShrinker as Shrinker<T> }
inline fun <reified T> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (T) -> Unit) {
val type = body.reflect()!!.parameters.first().type
val generator = TypeClasses.get<Arbitrary<*>>(type) as Arbitrary<T>
val shrinker = getShrinker<T>(type)
val (generated, ex) = generate(generationIterations, generator, appendable, body) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, body)
throw ForInputException(shrinked, ex2)
}
inline fun <reified A, reified B> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple2::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple2<A, B>>
val shrinker = getShrinker<Tuple2<A, B>>(tuple)
val tupleBody = { t: Tuple2<A, B> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
inline fun <reified A, reified B, reified C> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B, C) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple3::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple3<A, B, C>>
val shrinker = getShrinker<Tuple3<A, B, C>>(tuple)
val tupleBody = { t: Tuple3<A, B, C> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
inline fun <reified A, reified B, reified C, reified D> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B, C, D) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple4::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple4<A, B, C, D>>
val shrinker = getShrinker<Tuple4<A, B, C, D>>(tuple)
val tupleBody = { t: Tuple4<A, B, C, D> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
inline fun <reified A, reified B, reified C,
reified D, reified E> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B, C, D, E) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple5::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple5<A, B, C, D, E>>
val shrinker = getShrinker<Tuple5<A, B, C, D, E>>(tuple)
val tupleBody = { t: Tuple5<A, B, C, D, E> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
inline fun <reified A, reified B, reified C,
reified D, reified E, reified F> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B, C, D, E, F) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple5::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple6<A, B, C, D, E, F>>
val shrinker = getShrinker<Tuple6<A, B, C, D, E, F>>(tuple)
val tupleBody = { t: Tuple6<A, B, C, D, E, F> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
inline fun <reified A, reified B, reified C,
reified D, reified E, reified F, reified G> forAll(generationIterations: Int = 100,
shrinkingIterations: Int = 100,
appendable: Appendable = NullAppendable,
noinline body: (A, B, C, D, E, F, G) -> Unit) {
with(TypeClasses) {
val types = body.reflect()!!.parameters.map { it.type }
val tuple = Tuple5::class.createType(types.map { KTypeProjection.invariant(it) })
val generator = (arbitrary of tuple) as Arbitrary<Tuple7<A, B, C, D, E, F, G>>
val shrinker = getShrinker<Tuple7<A, B, C, D, E, F, G>>(tuple)
val tupleBody = { t: Tuple7<A, B, C, D, E, F, G> -> t.letAll(body) }
val (generated, ex) =
generate(generationIterations, generator, appendable, tupleBody) ?: return
val (shrinked, ex2) = shrink(shrinkingIterations, shrinker, generated, ex, appendable, tupleBody)
throw ForInputException(shrinked, ex2)
}
}
}
| mit | e08867e024e92a1db03513eb3a688d6e | 42.468619 | 109 | 0.562807 | 4.319751 | false | false | false | false |
android/user-interface-samples | CanonicalLayouts/supporting-panel-fragments/app/src/main/java/com/google/supporting/panel/fragments/SupportFragment.kt | 1 | 2245 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.supporting.panel.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import com.google.supporting.panel.fragments.databinding.FragmentSupportBinding
class SupportFragment : Fragment() {
private val viewModel : ContentViewModel by activityViewModels()
private var _binding: FragmentSupportBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSupportBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = SupportAdapter { newItem ->
viewModel.selectFromSupportingPanel(newItem)
}
binding.supportList.adapter = adapter
binding.supportList.layoutManager =
LinearLayoutManager(requireContext(), VERTICAL, false)
lifecycleScope.launchWhenStarted {
viewModel.supportingState.collect { items ->
adapter.updateItems(items)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | apache-2.0 | 1b3623842efdf2047710516e1f9cfc81 | 32.029412 | 79 | 0.72294 | 5 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/SAMExecutor.kt | 1 | 2527 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.gabrielaimageserver.data.SAMLogoRequest
import net.perfectdreams.gabrielaimageserver.data.URLImageData
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.declarations.BRMemesCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.gabrielaimageserver.handleExceptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
class SAMExecutor(loritta: LorittaBot, val client: GabrielaImageServerClient) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val type = string("type", BRMemesCommand.I18N_PREFIX.Sam.Options.Type) {
choice(BRMemesCommand.I18N_PREFIX.Sam.Options.Choice.Sam1, "1")
choice(BRMemesCommand.I18N_PREFIX.Sam.Options.Choice.Sam2, "2")
choice(BRMemesCommand.I18N_PREFIX.Sam.Options.Choice.Sam3, "3")
}
val imageReference = imageReferenceOrAttachment("image")
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage() // Defer message because image manipulation is kinda heavy
val type = args[options.type]
val imageReference = args[options.imageReference].get(context)!!
val result = client.handleExceptions(context) {
client.images.samLogo(
SAMLogoRequest(
URLImageData(imageReference.url),
when (type) {
"1" -> SAMLogoRequest.LogoType.SAM_1
"2" -> SAMLogoRequest.LogoType.SAM_2
"3" -> SAMLogoRequest.LogoType.SAM_3
else -> error("Unsupported Logo Type!")
}
)
)
}
context.sendMessage {
addFile("sam_logo.png", result.inputStream())
}
}
} | agpl-3.0 | 7ac822579a0037dee7a447228fd7ef23 | 48.568627 | 119 | 0.717847 | 4.859615 | false | false | false | false |
lzanita09/KotlinHackerNews | app/src/main/java/com/reindeercrafts/hackernews/data/ArticleRepository.kt | 1 | 2058 | package com.reindeercrafts.hackernews.data
import io.reactivex.Completable
import io.reactivex.Flowable
import java.util.*
class ArticleRepository(private val localSource: ArticleSource, private val remoteSource: ArticleSource) {
var cacheDirty = false
fun setArticleCacheDirty(dirty: Boolean) {
this.cacheDirty = dirty
}
fun getArticles(type: String, sortedByFunction: Comparator<Article>, localCallback: (List<Article>) -> Unit,
remoteCallback: (List<Article>?) -> Unit) {
localSource.getArticles(type, { articles ->
if (!articles.isEmpty()) {
localCallback(articles.sortedWith(sortedByFunction))
}
if (articles.isEmpty() || cacheDirty) {
remoteSource.getArticles(type, { remoteArticles ->
if (remoteArticles.isNotEmpty()) {
localSource.saveArticles(remoteArticles)
cacheDirty = false
remoteCallback(remoteArticles.sortedWith(sortedByFunction))
}
})
}
})
}
fun getArticle(id: String): Flowable<Article> {
return Flowable.just(id).flatMap {
val localArticle = localSource.getArticleSync(it)
if (localArticle != null) {
// Check local cache to see if it is there already.
Flowable.just(localArticle)
} else {
// Fetch from network and store in database.
val remoteArticle = remoteSource.getArticleSync(id)
if (remoteArticle != null) {
localSource.saveArticles(listOf(remoteArticle))
Flowable.just(remoteArticle)
} else {
Completable.complete().toFlowable()
}
}
}
}
fun trimArticles(callback: () -> Unit) {
localSource.getArticles(null, {
localSource.deleteArticles(it)
callback()
})
}
} | mit | af4c1fe27488db5b16c555c71c0851bb | 33.898305 | 112 | 0.560739 | 5.044118 | false | false | false | false |
LorittaBot/Loritta | web/embed-editor/embed-renderer/src/main/kotlin/net/perfectdreams/loritta/embededitor/generator/EmbedImageGenerator.kt | 1 | 930 | package net.perfectdreams.loritta.embededitor.generator
import kotlinx.html.*
import net.perfectdreams.loritta.embededitor.EmbedRenderer
import net.perfectdreams.loritta.embededitor.data.DiscordEmbed
import net.perfectdreams.loritta.embededitor.utils.*
object EmbedImageGenerator : GeneratorBase {
fun generate(m: EmbedRenderer, content: FlowContent, embed: DiscordEmbed, modifyTagCallback: MODIFY_TAG_CALLBACK? = null) {
val imageUrl = embed.image?.url
if (imageUrl != null) {
content.div {
modifyTagCallback?.invoke(this, this, MessageTagSection.EMBED_IMAGE_NOT_NULL, null)
img(src = m.parsePlaceholders(imageUrl)) {
style = "width: 100%;"
}
}
} else {
content.div {
modifyTagCallback?.invoke(this, this, MessageTagSection.EMBED_IMAGE_NULL, null)
}
}
}
} | agpl-3.0 | 9ed07379d46e8e3e2fa809632387ecd1 | 37.791667 | 127 | 0.644086 | 4.60396 | false | false | false | false |
JiangKlijna/leetcode-learning | kt/083 Remove Duplicates from Sorted List/RemoveDuplicatesfromSortedList.kt | 1 | 705 |
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class Solution {
fun deleteDuplicates(head: ListNode?): ListNode? {
var current = head ?: return head
var ln = head
while (ln != null) {
if (current.`val` < ln.`val`) {
current.next = ln
current = ln
}
ln = ln.next
}
if (current != null) current.next = null
return head
}
}
| mit | e29773551d19fa6617ec2a1b0c0531a8 | 26.115385 | 93 | 0.526241 | 3.730159 | false | false | false | false |
Haldir65/AndroidRepo | app/src/main/java/com/me/harris/androidanimations/_37_horizontal_scroll/PickerLayoutManager.kt | 1 | 2225 | package com.me.harris.androidanimations._37_horizontal_scroll
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
/**
* Created by Harris on 2017/6/12.
*/
class PickerLayoutManager(context: Context?, orientation: Int, reverseLayout: Boolean) : LinearLayoutManager(context, orientation, reverseLayout) {
private val scaleDownBy = 0.66f
private val scaleDownDistance = 0.9f
private val changeAlpha = true
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
val orientation = orientation
if (orientation == LinearLayoutManager.HORIZONTAL) {
val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
val mid = width / 2.0f
val unitScaleDownDist = scaleDownDistance * mid
for (i in 0..childCount - 1) {
val child = getChildAt(i)
val childMid = (getDecoratedLeft(child!!) + getDecoratedRight(child)) / 2.0f
val scale = 1.0f + -1 * scaleDownBy * Math.min(unitScaleDownDist, Math.abs(mid - childMid)) / unitScaleDownDist
child.scaleX = scale
child.scaleY = scale
if (changeAlpha) {
child.alpha = scale
}
}
return scrolled
} else
return 0
}
override fun onScrollStateChanged(state: Int) {
super.onScrollStateChanged(state)
if (state == 0) {
if (scrollListener != null) {
var selected = 0
var lastHeight = 0f
for (i in 0 until childCount) {
if (lastHeight < getChildAt(i)!!.scaleY) {
lastHeight = getChildAt(i)!!.scaleY
selected = i
}
}
(scrollListener as onScrollStopListener).selectedView(getChildAt(selected)!!)
}
}
}
private var scrollListener: onScrollStopListener? = null
interface onScrollStopListener {
fun selectedView(view: View)
}
} | apache-2.0 | 1635c8537257cc75493dfea0ce693db1 | 33.246154 | 147 | 0.593708 | 4.933481 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hil/psi/TypeCachedValueProvider.kt | 1 | 5208 | /*
* 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.intellij.plugins.hil.psi
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.intellij.plugins.hcl.terraform.config.model.Type
import org.intellij.plugins.hcl.terraform.config.model.TypeModelProvider
import org.intellij.plugins.hcl.terraform.config.model.Types
import org.intellij.plugins.hil.HILElementTypes
import org.intellij.plugins.hil.HILTypes.ILBinaryBooleanOnlyOperations
class TypeCachedValueProvider private constructor(private val e: ILExpression) : CachedValueProvider<Type?> {
companion object {
fun getType(e: ILExpression): Type? {
return CachedValuesManager.getCachedValue(e, TypeCachedValueProvider(e))
}
private val LOG = Logger.getInstance(TypeCachedValueProvider::class.java)
private fun doGetType(e: ILExpressionHolder): Type? {
val expression = e.ilExpression ?: return Types.Any
return getType(expression)
}
private fun doGetType(e: ILParenthesizedExpression): Type? {
val expression = e.ilExpression ?: return Types.Any
return getType(expression)
}
private fun doGetType(e: ILLiteralExpression): Type? {
// Don't use `ILLiteralExpression#getType` cause it would cause SO
return when {
e.doubleQuotedString != null -> Types.String
e.number != null -> Types.Number
"true".equals(e.text, true) -> Types.Boolean
"false".equals(e.text, true) -> Types.Boolean
else -> null
}
}
private fun doGetType(e: ILUnaryExpression): Type? {
val sign = e.operationSign
if (sign == HILElementTypes.OP_PLUS || sign == HILElementTypes.OP_MINUS) {
return Types.Number
} else if (sign == HILElementTypes.OP_NOT) {
return Types.Boolean
} else {
LOG.error("Unexpected operation sign of UnaryExpression: $sign", e.text)
return null
}
}
private fun doGetType(e: ILBinaryExpression): Type? {
val et = e.node.elementType
if (et == HILElementTypes.IL_BINARY_ADDITION_EXPRESSION || et == HILElementTypes.IL_BINARY_MULTIPLY_EXPRESSION) {
return Types.Number
} else if (et == HILElementTypes.IL_BINARY_RELATIONAL_EXPRESSION || et == HILElementTypes.IL_BINARY_EQUALITY_EXPRESSION) {
return Types.Boolean
} else if (et in ILBinaryBooleanOnlyOperations) {
return Types.Boolean
}
return null
}
private fun doGetType(e: ILConditionalExpression): Type? {
val first = e.then
val second = e.`else`
val l = first?.let { getType(it) }
val r = second?.let { getType(it) }
// There's some weird logic in HIL eval_test.go:
// > // false expression is type-converted to match true expression
// > // true expression is type-converted to match false expression if the true expression is string
if (l == r) return l
if (l == null) return r
if (r == null) return l
if (l == Types.Any || r == Types.Any) return Types.Any
if (l == Types.String) return r
return l
}
}
override fun compute(): CachedValueProvider.Result<Type?>? {
return when (e) {
is ILExpressionHolder -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
is ILParenthesizedExpression -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
is ILLiteralExpression -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
is ILUnaryExpression -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
is ILBinaryExpression -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
is ILConditionalExpression -> doGetType(e)?.let { CachedValueProvider.Result.create(it, e) }
// TODO: Implement via resolving/model :
is ILVariable -> null
is ILSelectExpression -> {
// For now return 'Any' to fix HILOperationTypesMismatchInspection
return CachedValueProvider.Result.create(Types.Any, e)
}
is ILMethodCallExpression -> {
val method = e.method?.name
if (method != null && e.callee === e.method) {
TypeModelProvider.getModel(e.project).getFunction(method)?.ret?.let { CachedValueProvider.Result.create(it, e.method) }
} else null
}
// Errors:
is ILParameterList -> {
LOG.error("#getType should not be called for ILParameterList", e.text)
return null
}
else -> {
LOG.error("Unexpected #getType call for ${e.javaClass.name}", e.text)
return null
}
}
}
} | apache-2.0 | f0296d25e790b70128aa9656d613b28d | 37.301471 | 129 | 0.677803 | 4.136616 | false | false | false | false |
FurhatRobotics/example-skills | ComplimentBot/src/main/kotlin/furhatos/app/complimentbot/gestures/gestures.kt | 1 | 1906 | package furhatos.app.complimentbot.gestures
import furhatos.gestures.BasicParams
import furhatos.gestures.defineGesture
val cSmile = defineGesture("cSmile") {
frame(0.5, persist = true){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
fun rollHead(strength: Double = 1.0, duration: Double = 1.0) =
defineGesture("rollHead") {
frame(0.4, duration) {
BasicParams.NECK_ROLL to strength
}
reset(duration+0.1)
}
val FallAsleep = defineGesture("FallAsleep") {
frame(0.5, persist = true){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
val MySmile = defineGesture("MySmile") {
frame(0.32, 0.72) {
BasicParams.SMILE_CLOSED to 2.0
}
frame(0.2, 0.72){
BasicParams.BROW_UP_LEFT to 4.0
BasicParams.BROW_UP_RIGHT to 4.0
}
frame(0.16, 0.72){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 0.1
}
reset(1.04)
}
val TripleBlink = defineGesture("TripleBlink") {
frame(0.1, 0.3){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.3, 0.5){
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(0.5, 0.7){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.7, 0.9){
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
BasicParams.BROW_UP_LEFT to 2.0
BasicParams.BROW_UP_RIGHT to 2.0
}
frame(0.9, 1.1){
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(1.1, 1.4){
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(1.4, 1.5){
BasicParams.BROW_UP_LEFT to 0
BasicParams.BROW_UP_RIGHT to 0
}
reset(1.5)
} | mit | b65209c229f95da513eee9bbb246d4e6 | 23.766234 | 62 | 0.590766 | 3.309028 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/test/kotlin/org/jitsi/rtp/rtcp/rtcpfb/transport_layer_fb/tcc/RtcpFbTccPacketTest.kt | 1 | 7810 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.rtp.rtcp.rtcpfb.transport_layer_fb.tcc
import io.kotest.assertions.withClue
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.maps.shouldContainKey
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.beInstanceOf
import org.jitsi.rtp.rtcp.RtcpHeaderBuilder
import org.jitsi.rtp.util.byteBufferOf
import java.time.Duration
class RtcpFbTccPacketTest : ShouldSpec() {
fun Int.toTicks(): Short = (this * 4).toShort()
private val tccRleData = byteBufferOf(
// V=2,P=false,FMT=15,PT=205,L=7(32 bytes)
0x8f, 0xcd, 0x00, 0x07,
// Sender SSRC = 839852602
0x32, 0x0f, 0x22, 0x3a,
// Media source SSRC = 2397376430
0x8e, 0xe5, 0x0f, 0xae,
// Base seq num = 0xfffa, packet status count = 9
0xff, 0xfa, 0x00, 0x09,
// Reference Time: 1683633 = 107752512ms, feedback packet count = 87
0x19, 0xb0, 0xb1, 0x57,
// Chunks
// RLE, small delta, length = 9
0x20, 0x09,
// Deltas (9), one byte each
0xd8, 0x00,
0x18, 0x14, 0x18, 0x14,
0x18, 0x14, 0x18,
// Recv delta padding
0x00
)
/**
* These correspond to the Deltas section above.
*/
val expectedTccRlePacketInfo = mapOf<Int, Short> (
0xfffa to 0xd8,
0xfffb to 0x00,
0xfffc to 0x18,
0xfffd to 0x14,
0xfffe to 0x18,
0xffff to 0x14,
0x0000 to 0x18,
0x0001 to 0x14,
0x0002 to 0x18
)
// This also has a negative delta
private val tccMixedChunkTypeData = byteBufferOf(
// V=2,P=false,FMT=15,PT=205,L=9(40 bytes)
0x8f, 0xcd, 0x00, 0x09,
// Sender SSRC = 839852602
0x32, 0x0f, 0x22, 0x3a,
// Media source SSRC = 2397376430
0x8e, 0xe5, 0x0f, 0xae,
// Base seq num = 5376, packet status count = 12
0x15, 0x00, 0x00, 0x0c,
// Reference Time: 1684065 = 107780160ms, feedback packet count = 88
0x19, 0xb2, 0x61, 0x58,
// Chunks
// RLE: small delta, length = 9
0x20, 0x09,
// SV, 2 bit symbols: LD, SD, SD
0xe5, 0x00,
// Deltas (12)
// 2, 0, 0, 0
0x08, 0x00, 0x00, 0x00,
// 22, 1, 0, 0
0x58, 0x04, 0x00, 0x00,
// 8, -1, 1
0x20, 0xff, 0xfc, 0x04,
// 0
0x00,
// Recv delta padding
0x00, 0x00, 0x00
)
val expectedTccMixedChunkTypePacketInfo = mapOf<Int, Short> (
5376 to 2.toTicks(),
5377 to 0.toTicks(),
5378 to 0.toTicks(),
5379 to 0.toTicks(),
5380 to 22.toTicks(),
5381 to 1.toTicks(),
5382 to 0.toTicks(),
5383 to 0.toTicks(),
5384 to 8.toTicks(),
5385 to (-1).toTicks(),
5386 to 1.toTicks(),
5387 to 0.toTicks()
)
private val tccSvChunkData = byteBufferOf(
// V=2,P=false,FMT=15,PT=205,length=5(24 bytes)
0x8f, 0xcd, 0x00, 0x05,
// Sender SSRC: 839852602
0x32, 0x0f, 0x22, 0x3a,
// Media source SSRC: 2397376430
0x8e, 0xe5, 0x0f, 0xae,
// Base seq num = 6227, packet status count = 2
0x18, 0x53, 0x00, 0x02,
// Reference Time: 1684126 (107784064ms), feedback packet count = 162
0x19, 0xb2, 0x9e, 0xa2,
// Chunks
// SV chunk, 2 bit symbols: NR, SD
0xc4, 0x00,
// Deltas (1)
// 00
0x00,
// Recv delta padding
0x00
)
val expectedTccSvChunkPacketInfo = mapOf<Int, Long> (
6227 to -1,
6228 to 107784064 + 27
)
init {
context("Parsing an RtcpFbTccPacket") {
context("with RLE") {
val rtcpFbTccPacket = RtcpFbTccPacket(tccRleData.array(), tccRleData.arrayOffset(), tccRleData.limit())
should("parse the values correctly") {
rtcpFbTccPacket.forEach {
it should beInstanceOf<ReceivedPacketReport>()
it as ReceivedPacketReport
expectedTccRlePacketInfo shouldContainKey it.seqNum
withClue("seqNum ${it.seqNum} deltaTicks") {
it.deltaTicks shouldBe expectedTccRlePacketInfo[it.seqNum]
it.deltaDuration shouldBe Duration.ofNanos(it.deltaTicks * 250 * 1000L)
}
}
}
}
context("with mixed chunk types and a negative delta") {
val rtcpFbTccPacket = RtcpFbTccPacket(
tccMixedChunkTypeData.array(), tccMixedChunkTypeData.arrayOffset(), tccMixedChunkTypeData.limit()
)
should("parse the values correctly") {
rtcpFbTccPacket.forEach {
it should beInstanceOf<ReceivedPacketReport>()
it as ReceivedPacketReport
expectedTccMixedChunkTypePacketInfo shouldContainKey it.seqNum
withClue("seqNum ${it.seqNum} deltaTicks") {
it.deltaTicks shouldBe expectedTccMixedChunkTypePacketInfo[it.seqNum]
it.deltaDuration shouldBe Duration.ofNanos(it.deltaTicks * 250 * 1000L)
}
}
}
}
}
context("Creating an RtcpFbTccPacket") {
val rtcpFbTccPacketBuilder = RtcpFbTccPacketBuilder(
rtcpHeader = RtcpHeaderBuilder(
senderSsrc = 839852602
),
mediaSourceSsrc = 2397376430,
feedbackPacketSeqNum = 162
)
rtcpFbTccPacketBuilder.SetBase(6227, 107784064)
rtcpFbTccPacketBuilder.AddReceivedPacket(6228, 107784064) shouldBe true
}
context("Creating and parsing an RtcpFbTccPacket") {
context("with missing packets") {
val kBaseSeqNo = 1000
val kBaseTimestampUs = 10000L
val rtcpFbTccPacketBuilder = RtcpFbTccPacketBuilder(
rtcpHeader = RtcpHeaderBuilder(
senderSsrc = 839852602
),
mediaSourceSsrc = 2397376430,
feedbackPacketSeqNum = 163
)
rtcpFbTccPacketBuilder.SetBase(kBaseSeqNo, kBaseTimestampUs)
rtcpFbTccPacketBuilder.AddReceivedPacket(kBaseSeqNo + 0, kBaseTimestampUs)
rtcpFbTccPacketBuilder.AddReceivedPacket(kBaseSeqNo + 3, kBaseTimestampUs + 2000)
val coded = rtcpFbTccPacketBuilder.build()
val packet = RtcpFbTccPacket(coded.buffer, coded.offset, coded.length)
val it = packet.iterator()
it.next() should beInstanceOf<ReceivedPacketReport>()
it.next() should beInstanceOf<UnreceivedPacketReport>()
it.next() should beInstanceOf<UnreceivedPacketReport>()
it.next() should beInstanceOf<ReceivedPacketReport>()
}
}
}
}
| apache-2.0 | e1adee389eba31a48971773ad6f19f63 | 36.729469 | 119 | 0.570038 | 3.780252 | false | false | false | false |
nlefler/Glucloser | Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/MealFactory.kt | 1 | 3616 | package com.nlefler.glucloser.a.dataSource
import com.nlefler.glucloser.a.dataSource.jsonAdapter.MealJsonAdapter
import com.nlefler.glucloser.a.db.DBManager
import com.nlefler.glucloser.a.models.*
import com.nlefler.glucloser.a.models.parcelable.MealParcelable
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import io.requery.kotlin.eq
import io.requery.query.Result
import rx.Observable
import java.util.Date
import java.util.UUID
import javax.inject.Inject
/**
* Created by Nathan Lefler on 12/24/14.
*/
class MealFactory @Inject constructor(val dbManager: DBManager,
val bolusPatternFactory: BolusPatternFactory,
val bloodSugarFactory: BloodSugarFactory,
val placeFactory: PlaceFactory,
val foodFactory: FoodFactory) {
private val LOG_TAG = "MealFactory"
fun parcelableFromMeal(meal: Meal): MealParcelable {
val parcelable = MealParcelable()
val place = meal.place
if (place != null) {
val placePar = placeFactory.parcelableFromPlace(place)
if (placePar != null) {
parcelable.placeParcelable = placePar
}
}
parcelable.carbs = meal.carbs
parcelable.insulin = meal.insulin
parcelable.primaryId = meal.primaryId
parcelable.isCorrection = meal.isCorrection
val beforeSugar = meal.beforeSugar
if (beforeSugar != null) {
parcelable.bloodSugarParcelable = bloodSugarFactory.parcelableFromBloodSugar(beforeSugar)
}
parcelable.date = meal.eatenDate
val bolusPattern = meal.bolusPattern
if (bolusPattern != null) {
parcelable.bolusPatternParcelable = bolusPatternFactory.parcelableFromBolusPattern(bolusPattern)
}
meal.foods.forEach { food ->
parcelable.foodParcelables.add(foodFactory.parcelableFromFood(food))
}
return parcelable
}
fun jsonAdapter(): JsonAdapter<MealEntity> {
return Moshi.Builder()
.add(MealJsonAdapter())
.build()
.adapter(MealEntity::class.java)
}
fun mealFromParcelable(parcelable: MealParcelable): Meal {
val patternPar = parcelable.bolusPatternParcelable
val pattern = if (patternPar != null) {bolusPatternFactory.bolusPatternFromParcelable(patternPar)} else null
val sugar = if (parcelable.bloodSugarParcelable != null) {bloodSugarFactory.bloodSugarFromParcelable(parcelable.bloodSugarParcelable!!)} else {null}
val foods = parcelable.foodParcelables.map {fp -> foodFactory.foodFromParcelable(fp)}
val placePar = parcelable.placeParcelable
val place = if (placePar != null) placeFactory.placeFromParcelable(placePar) else null
val meal = MealEntity()
meal.primaryId = parcelable.primaryId
meal.eatenDate = parcelable.date
meal.bolusPattern = pattern
meal.carbs = parcelable.carbs
meal.insulin = parcelable.insulin
meal.beforeSugar = sugar
meal.isCorrection = parcelable.isCorrection
meal.foods = foods
meal.place = place
return meal
}
private fun mealForMealId(id: String): Observable<Result<MealEntity>> {
if (id.isEmpty()) {
return Observable.error(Exception("Invalid Id"))
}
return dbManager.data.select(MealEntity::class).where(Meal::primaryId.eq(id)).get().toSelfObservable()
}
}
| gpl-2.0 | 82221c7df90956907d8f53b95402eacb | 38.304348 | 156 | 0.655697 | 4.577215 | false | false | false | false |
lttng/lttng-scope | jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/trace/layout/PerfEventLayout.kt | 2 | 5862 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2012-2015 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.trace.layout
/**
* Event and field definitions for perf traces in CTF format.
*
* TODO The "by LttngKernel20EventLayout.instance" is to define the entries commented-out at the bottom.
* This file was previously like this, but ideally the perf hierarchy should define its own events/fields.
*/
class PerfEventLayout : LttngKernelEventLayout by LttngKernel20EventLayout.instance {
companion object {
val instance = PerfEventLayout()
}
// ------------------------------------------------------------------------
// Event names
// ------------------------------------------------------------------------
override val eventIrqHandlerEntry = "irq:irq_handler_entry"
override val eventIrqHandlerExit = "irq:irq_handler_exit"
override val eventSoftIrqEntry = "irq:softirq_entry"
override val eventSoftIrqExit = "irq:softirq_exit"
override val eventSoftIrqRaise = "irq:softirq_raise"
override val eventSchedSwitch = "sched:sched_switch"
override val eventSchedPiSetPrio = "sched:sched_pi_setprio"
override val eventsSchedWakeup = listOf("sched:sched_wakeup", "sched:sched_wakeup_new")
override val eventSchedProcessFork = "sched:sched_process_fork"
override val eventSchedProcessExit = "sched:sched_process_exit"
override val eventSchedProcessFree = "sched:sched_process_free"
/* Not present in perf traces */
override val eventStatedumpProcessState: String? = null
override val eventSyscallEntryPrefix = "raw_syscalls:sys_enter"
override val eventCompatSyscallEntryPrefix = eventSyscallEntryPrefix
override val eventSyscallExitPrefix = "raw_syscalls:sys_exit"
override val eventCompatSyscallExitPrefix = eventSyscallExitPrefix
override val eventSchedProcessExec = "sched:sched_process_exec"
override val eventSchedProcessWakeup = "sched:sched_process_wakeup"
override val eventSchedProcessWakeupNew = "sched:process_wakeup_new"
override val eventSchedProcessWaking = "sched:sched_waking"
override val eventSchedMigrateTask = "sched:sched_migrate_task"
override val eventHRTimerStart = "timer:hrtimer_start"
override val eventHRTimerCancel = "timer:hrtimer_cancel"
override val eventHRTimerExpireEntry = "timer:hrtimer_expire_entry"
override val eventHRTimerExpireExit = "timer:hrtimer_expire_exit"
override val eventKmemPageAlloc = "kmem:page_alloc"
override val eventKmemPageFree = "kmem:page_free"
// ------------------------------------------------------------------------
// Field names
// ------------------------------------------------------------------------
override val fieldIrq = "irq"
override val fieldVec = "vec"
override val fieldTid = "pid" // yes, "pid", what lttng calls a "tid" perf calls a "pid"
override val fieldPrevTid = "prev_pid"
override val fieldPrevState = "prev_state"
override val fieldNextComm = "next_comm"
override val fieldNextTid = "next_pid"
override val fieldChildComm = "child_comm"
override val fieldParentTid = "parent_pid"
override val fieldChildTid = "child_pid"
override val fieldPrio = "prio"
override val fieldNewPrio = "newprio"
override val fieldPrevPrio = "prev_prio"
override val fieldNextPrio = "next_prio"
override val fieldComm = "comm"
override val fieldName = "name"
override val fieldStatus = "status"
override val fieldPrevComm = "prev_comm"
override val fieldFilename = "filename"
override val fieldHRtimer = "hrtimer"
override val fieldHRtimerFunction = "function"
override val fieldHRtimerExpires = "expires"
override val fieldHRtimerSoftexpires = "softexpires"
override val fieldHRtimerNow = "now"
override val fieldOrder = "order"
// ------------------------------------------------------------------------
// I/O events and fields
// ------------------------------------------------------------------------
override val eventBlockRqInsert = "block:block_rq_insert"
override val eventBlockRqIssue = "block:block_rq_issue"
override val eventBlockRqComplete = "block:block_rq_complete"
override val eventBlockBioFrontmerge = "block:block_bio_frontmerge"
override val eventBlockBioBackmerge = "block:block_bio_backmerge"
/* TODO Define these below specifically for perf */
// override val eventBlockRqMerge: String
// override val eventStatedumpBlockDevice: String?
//
// override val eventsNetworkSend: Collection<String>
// override val eventsNetworkReceive: Collection<String>
// override val eventsKVMEntry: Collection<String>
// override val eventsKVMExit: Collection<String>
// override val ipiIrqVectorsEntries: Collection<String>
// override val ipiIrqVectorsExits: Collection<String>
//
// override val fieldSyscallRet: String
// override val fieldTargetCpu: String
// override val fieldDestCpu: String
//
// override val fieldBlockDeviceId: String
// override val fieldBlockSector: String
// override val fieldBlockNrSector: String
// override val fieldBlockRwbs: String
// override val fieldBlockRqSector: String
// override val fieldBlockNextRqSector: String
// override val fieldDiskname: String
// override val fieldIPIVector: String
//
// override val fieldPathTcpSeq: Collection<String>
// override val fieldPathTcpAckSeq: Collection<String>
// override val fieldPathTcpFlags: Collection<String>
}
| epl-1.0 | 2c5f9642e6929ed21c08963fb82d6b6c | 44.092308 | 106 | 0.686114 | 4.430839 | false | false | false | false |
lanhuaguizha/Christian | common/src/main/java/com/christian/common/data/source/local/GospelDao.kt | 1 | 1289 | package com.christian.common.data.source.local
import androidx.lifecycle.LiveData
import androidx.room.*
import com.christian.common.data.Result
import com.christian.common.data.Gospel
@Dao
interface GospelDao {
// Insert
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertGospel(gospel: Gospel)
// Delete
@Query("DELETE FROM gospels")
suspend fun deleteWritings()
@Query("DELETE FROM gospels WHERE gospelId = :writingId")
suspend fun deleteWritingById(writingId: String): Int
@Query("DELETE FROM gospels WHERE completed = 1")
suspend fun deleteCompletedWritings(): Int
// Update
@Update
suspend fun updateWriting(gospel: Gospel): Int
@Query("UPDATE gospels SET completed = :completed WHERE gospelId = :gospelId")
suspend fun updateCompleted(gospelId: String, completed: Boolean)
// Query
@Query("SELECT * FROM gospels")
fun observeWritings(): LiveData<List<Gospel>>
@Query("SELECT * FROM gospels WHERE gospelId = :gospelId")
fun observeWritingById(gospelId: String): LiveData<Gospel>
@Query("SELECT * FROM gospels")
suspend fun getWritings(): List<Gospel>
@Query("SELECT * FROM gospels WHERE gospelId = :gospelId")
suspend fun getWritingById(gospelId: String): Gospel
} | gpl-3.0 | 308e8060521cf49839f356dc30cbec72 | 29 | 82 | 0.723817 | 3.89426 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-android/src/main/java/reactivecircus/flowbinding/android/widget/SearchViewQueryTextEventFlow.kt | 1 | 2548 | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.android.widget
import android.widget.SearchView
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.InitialValueFlow
import reactivecircus.flowbinding.common.asInitialValueFlow
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [InitialValueFlow] of query text events on the [SearchView] instance
* where the value emitted is one of the 2 event types:
* [QueryTextEvent.QueryChanged],
* [QueryTextEvent.QuerySubmitted]
*
* Note: Created flow keeps a strong reference to the [SearchView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* searchView.queryTextEvents()
* .onEach { queryTextEvent ->
* // handle search view query text cha
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun SearchView.queryTextEvents(): InitialValueFlow<QueryTextEvent> = callbackFlow {
checkMainThread()
val listener = object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String): Boolean {
trySend(
QueryTextEvent.QueryChanged(
view = this@queryTextEvents,
queryText = newText
)
)
return true
}
override fun onQueryTextSubmit(query: String): Boolean {
trySend(
QueryTextEvent.QuerySubmitted(
view = this@queryTextEvents,
queryText = query
)
)
return true
}
}
setOnQueryTextListener(listener)
awaitClose { setOnQueryTextListener(null) }
}
.conflate()
.asInitialValueFlow {
QueryTextEvent.QueryChanged(
view = this,
queryText = query
)
}
public sealed class QueryTextEvent {
public abstract val view: SearchView
public abstract val queryText: CharSequence
public data class QueryChanged(
override val view: SearchView,
override val queryText: CharSequence
) : QueryTextEvent()
public data class QuerySubmitted(
override val view: SearchView,
override val queryText: CharSequence
) : QueryTextEvent()
}
| apache-2.0 | 8ab781f288ce38cfa490257c6127710a | 29.698795 | 90 | 0.675432 | 5.232033 | false | false | false | false |
toastkidjp/Jitte | article/src/test/java/jp/toastkid/article_viewer/article/list/listener/ArticleLoadStateListenerTest.kt | 2 | 3870 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.list.listener
import androidx.paging.CombinedLoadStates
import androidx.paging.LoadState
import androidx.paging.LoadStates
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.ContentViewModel
import org.junit.After
import org.junit.Before
import org.junit.Test
class ArticleLoadStateListenerTest {
@InjectMockKs
private lateinit var articleLoadStateListener: ArticleLoadStateListener
@MockK
private lateinit var contentViewModel: ContentViewModel
@MockK
private lateinit var countSupplier: () -> Int
@MockK
private lateinit var stringResolver: (Int) -> String
@Before
fun setUp() {
MockKAnnotations.init(this)
every { countSupplier.invoke() }.returns(10)
every { contentViewModel.snackShort(any<String>()) }.just(Runs)
every { stringResolver.invoke(any()) }.returns("test %d count.")
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvoke() {
val combinedLoadStates = CombinedLoadStates(
LoadState.Loading,
LoadState.NotLoading(false),
LoadState.NotLoading(false),
LoadStates(
LoadState.Loading,
LoadState.NotLoading(false),
LoadState.NotLoading(false)
)
)
articleLoadStateListener.invoke(combinedLoadStates)
verify(exactly = 0) { countSupplier.invoke() }
verify(exactly = 0) { contentViewModel.snackShort(any<String>()) }
verify(exactly = 0) { stringResolver.invoke(any()) }
val completeLoadStates = makeCompleteStatus()
articleLoadStateListener.invoke(completeLoadStates)
verify(exactly = 1) { countSupplier.invoke() }
verify(exactly = 1) { contentViewModel.snackShort(any<String>()) }
verify(exactly = 1) { stringResolver.invoke(any()) }
}
@Test
fun testCannotInvokedCase() {
val combinedLoadStates = CombinedLoadStates(
LoadState.NotLoading(false),
LoadState.Loading,
LoadState.NotLoading(false),
LoadStates(
LoadState.NotLoading(false),
LoadState.Loading,
LoadState.NotLoading(false)
),
null
)
articleLoadStateListener.invoke(combinedLoadStates)
verify(exactly = 0) { countSupplier.invoke() }
verify(exactly = 0) { contentViewModel.snackShort(any<String>()) }
verify(exactly = 0) { stringResolver.invoke(any()) }
val completeLoadStates = makeCompleteStatus()
articleLoadStateListener.invoke(completeLoadStates)
verify(exactly = 0) { countSupplier.invoke() }
verify(exactly = 0) { contentViewModel.snackShort(any<String>()) }
verify(exactly = 0) { stringResolver.invoke(any()) }
}
private fun makeCompleteStatus(): CombinedLoadStates {
val completeLoadStates = CombinedLoadStates(
LoadState.NotLoading(false),
LoadState.NotLoading(false),
LoadState.NotLoading(false),
LoadStates(
LoadState.NotLoading(false),
LoadState.NotLoading(false),
LoadState.NotLoading(false)
),
null
)
return completeLoadStates
}
} | epl-1.0 | e195e82caa09dd167712e835477c1b8c | 29.722222 | 88 | 0.652455 | 4.825436 | false | true | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/documentation/SimpleAllLayoutTransitionComponent.kt | 1 | 2222 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.documentation
import android.graphics.Color
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.Transition
import com.facebook.litho.core.margin
import com.facebook.litho.dp
import com.facebook.litho.transition.useTransition
import com.facebook.litho.useState
import com.facebook.litho.view.onClick
import com.facebook.litho.widget.SolidColor
import com.facebook.yoga.YogaAlign
class SimpleAllLayoutTransitionKComponent : KComponent() {
// layout_start
override fun ComponentScope.render(): Component {
val toRight = useState { false }
return Column(
style = Style.margin(all = 10.dp).onClick { toRight.update { !it } },
alignItems = if (toRight.value) YogaAlign.FLEX_END else YogaAlign.FLEX_START) {
child(SolidColor.create(context).color(Color.YELLOW).widthDip(80f).heightDip(80f).build())
}
}
// layout_end
}
class SimpleAllLayoutTransitionKComponentV2 : KComponent() {
override fun ComponentScope.render(): Component {
val toRight = useState { false }
// transition_start
useTransition(Transition.allLayout())
// transition_end
return Column(
style = Style.margin(all = 10.dp).onClick { toRight.update { !it } },
alignItems = if (toRight.value) YogaAlign.FLEX_END else YogaAlign.FLEX_START) {
child(SolidColor.create(context).color(Color.YELLOW).widthDip(80f).heightDip(80f).build())
}
}
}
| apache-2.0 | ae7ef17942cda262f6f1a33c12188ede | 35.42623 | 100 | 0.737174 | 3.946714 | false | false | false | false |
moxi/weather-app-demo | weather-app/src/main/java/rcgonzalezf/org/weather/common/BaseActivity.kt | 1 | 3922 | package rcgonzalezf.org.weather.common
import android.content.Intent
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import rcgonzalezf.org.weather.R
import rcgonzalezf.org.weather.SettingsActivity
import rcgonzalezf.org.weather.common.analytics.Analytics
import rcgonzalezf.org.weather.common.analytics.AnalyticsLifecycleObserver
import rcgonzalezf.org.weather.databinding.WeatherBinding
abstract class BaseActivity : AppCompatActivity(),
ActivityCompat.OnRequestPermissionsResultCallback {
private lateinit var drawerLayout: DrawerLayout
protected lateinit var content: View
protected lateinit var analyticsLifecycleObserver: AnalyticsLifecycleObserver
protected lateinit var weatherBinding: WeatherBinding
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
weatherBinding = DataBindingUtil.setContentView(this, R.layout.weather)
initToolbar()
setupDrawerLayout()
content = weatherBinding.content
analyticsLifecycleObserver = AnalyticsLifecycleObserver(this.javaClass.simpleName,
Analytics())
lifecycle.addObserver(analyticsLifecycleObserver)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
drawerLayout.openDrawer(GravityCompat.START)
return true
}
R.id.action_settings -> {
navigateToSettings()
return true
}
}
return super.onOptionsItemSelected(item)
}
fun initToolbar() {
val toolbar = weatherBinding.toolbar
setSupportActionBar(toolbar)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp)
actionBar.setDisplayHomeAsUpEnabled(true)
}
}
fun setupDrawerLayout() {
drawerLayout = weatherBinding.drawerLayout
val view = weatherBinding.navigationView
view.setNavigationItemSelectedListener(navigationListener)
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val textView = weatherBinding
.drawerLayout.findViewById<View>(R.id.user_display_name) as TextView?
textView?.text =
prefs.getString(SettingsActivity.USER_NAME_TO_DISPLAY,
getString(R.string.pref_default_display_name))
}
@VisibleForTesting
fun homePressed(menuItem: MenuItem) {
Snackbar.make(content, "${menuItem.title} pressed", Snackbar.LENGTH_SHORT).show()
menuItem.isChecked = true
drawerLayout.closeDrawers()
}
@get:VisibleForTesting
val navigationListener: NavigationView.OnNavigationItemSelectedListener
get() = NavigationView.OnNavigationItemSelectedListener { menuItem ->
if (menuItem.itemId == R.id.drawer_settings) {
navigateToSettings()
} else {
homePressed(menuItem)
}
true
}
private fun navigateToSettings() {
val intent = Intent(this@BaseActivity, SettingsActivity::class.java)
startActivity(intent)
}
}
| mit | 555696bdbdc593151ea5987e3c1b945d | 36.352381 | 90 | 0.706782 | 5.42462 | false | false | false | false |
android/camera-samples | Camera2Extensions/app/src/main/java/com/example/android/camera2/extensions/GenericListAdapter.kt | 1 | 2029 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera2.extensions
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
/** List adapter for generic types, intended used for small-medium lists of data */
class GenericListAdapter<T:Any>(
private val dataset: List<T>,
private val itemLayoutId: Int? = null,
private val itemViewFactory: (() -> View)? = null,
private val onBind: (view: View, data: T, position: Int) -> Unit
) : RecyclerView.Adapter<GenericListAdapter.GenericListViewHolder>() {
class GenericListViewHolder(val view: View) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = GenericListViewHolder(
when {
itemViewFactory != null -> itemViewFactory.invoke()
itemLayoutId != null -> {
LayoutInflater.from(parent.context)
.inflate(itemLayoutId, parent, false)
}
else -> {
throw IllegalStateException(
"Either the layout ID or the view factory need to be non-null")
}
})
override fun onBindViewHolder(holder: GenericListViewHolder, position: Int) {
if (position < 0 || position > dataset.size) return
onBind(holder.view, dataset[position], position)
}
override fun getItemCount() = dataset.size
} | apache-2.0 | 483e22358dddaf3c1f1e5e7b65c16e80 | 37.301887 | 94 | 0.693938 | 4.549327 | false | false | false | false |
google/horologist | media-sample/src/main/java/com/google/android/horologist/mediasample/di/DatabaseModule.kt | 1 | 2384 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.di
import android.content.Context
import androidx.room.Room
import com.google.android.horologist.media.data.database.MediaDatabase
import com.google.android.horologist.media.data.database.dao.MediaDao
import com.google.android.horologist.media.data.database.dao.MediaDownloadDao
import com.google.android.horologist.media.data.database.dao.PlaylistDao
import com.google.android.horologist.media.data.database.dao.PlaylistMediaDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
private const val MEDIA_DATABASE_NAME = "media-database"
@Provides
@Singleton
fun mediaDatabase(
@ApplicationContext context: Context
): MediaDatabase {
return Room.databaseBuilder(
context,
MediaDatabase::class.java,
MEDIA_DATABASE_NAME
)
// Until stable, don't require incrementing MediaDatabase version.
.fallbackToDestructiveMigration()
.build()
}
@Provides
@Singleton
fun mediaDownloadDao(
database: MediaDatabase
): MediaDownloadDao = database.mediaDownloadDao()
@Provides
@Singleton
fun playlistDao(
database: MediaDatabase
): PlaylistDao = database.playlistDao()
@Provides
@Singleton
fun playlistMediaDao(
database: MediaDatabase
): PlaylistMediaDao = database.playlistMediaDao()
@Provides
@Singleton
fun mediaDao(
database: MediaDatabase
): MediaDao = database.mediaDao()
}
| apache-2.0 | 78821eeae33bc556f6be87e7ca393b29 | 29.961039 | 78 | 0.732802 | 4.506616 | false | false | false | false |
tsegismont/vertx-hawkular-metrics | src/main/kotlin/io/vertx/kotlin/ext/hawkular/VertxHawkularOptions.kt | 1 | 5683 | package io.vertx.kotlin.ext.hawkular
import io.vertx.ext.hawkular.VertxHawkularOptions
import io.vertx.core.http.HttpClientOptions
import io.vertx.ext.hawkular.AuthenticationOptions
import io.vertx.ext.hawkular.MetricTagsMatch
import io.vertx.ext.hawkular.MetricsType
/**
* A function providing a DSL for building [io.vertx.ext.hawkular.VertxHawkularOptions] objects.
*
* Vert.x Hawkular monitoring configuration.
*
* @param authenticationOptions Set the options for authentication.
* @param batchDelay Set the maximum delay between two consecutive batches (in seconds). To reduce the number of HTTP exchanges, metric data is sent to the Hawkular server in batches. A batch is sent as soon as the number of metrics collected reaches the configured <code>batchSize</code>, or after the <code>batchDelay</code> expires. Defaults to <code>1</code> second.
* @param batchSize Set the maximum number of metrics in a batch. To reduce the number of HTTP exchanges, metric data is sent to the Hawkular server in batches. A batch is sent as soon as the number of metrics collected reaches the configured <code>batchSize</code>, or after the <code>batchDelay</code> expires. Defaults to <code>50</code>.
* @param disabledMetricsTypes Sets metrics types that are disabled.
* @param enabled Set whether metrics will be enabled on the Vert.x instance. Metrics are not enabled by default.
* @param host Set the Hawkular Metrics service host. Defaults to <code>localhost</code>.
* @param httpHeaders Set specific headers to include in HTTP requests.
* @param httpOptions Set the configuration of the Hawkular Metrics HTTP client.
* @param metricTagsMatches Sets a list of [io.vertx.ext.hawkular.MetricTagsMatch].
* @param metricsBridgeAddress Sets the metric bridge address on which the application is sending the custom metrics. Application can send metrics to this event bus address. The message is a JSON object specifying at least the <code>id</code> and <code>value</code> fields. <p/> Don't forget to also enable the bridge with <code>metricsBridgeEnabled</code>.
* @param metricsBridgeEnabled Sets whether or not the metrics bridge should be enabled. The metrics bridge is disabled by default.
* @param metricsServiceUri Set the Hawkular Metrics service URI. Defaults to <code>/hawkular/metrics</code>. This can be useful if you host the Hawkular server behind a proxy and manipulate the default service URI.
* @param port Set the Hawkular Metrics service port. Defaults to <code>8080</code>.
* @param prefix Set the metric name prefix. Metric names are not prefixed by default. Prefixing metric names is required to distinguish data sent by different Vert.x instances.
* @param schedule Set the metric collection interval (in seconds). Defaults to <code>1</code>.
* @param sendTenantHeader Set whether Hawkular tenant header should be sent. Defaults to <code>true</code>. Must be set to <code>false</code> when working with pre-Alpha13 Hawkular servers.
* @param taggedMetricsCacheSize Set the number of metric names to cache in order to avoid repeated tagging requests.
* @param tags Set tags applied to all metrics.
* @param tenant Set the Hawkular tenant. Defaults to <code>default</code>.
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.hawkular.VertxHawkularOptions original] using Vert.x codegen.
*/
fun VertxHawkularOptions(
authenticationOptions: io.vertx.ext.hawkular.AuthenticationOptions? = null,
batchDelay: Int? = null,
batchSize: Int? = null,
disabledMetricsTypes: Iterable<MetricsType>? = null,
enabled: Boolean? = null,
host: String? = null,
httpHeaders: io.vertx.core.json.JsonObject? = null,
httpOptions: io.vertx.core.http.HttpClientOptions? = null,
metricTagsMatches: Iterable<io.vertx.ext.hawkular.MetricTagsMatch>? = null,
metricsBridgeAddress: String? = null,
metricsBridgeEnabled: Boolean? = null,
metricsServiceUri: String? = null,
port: Int? = null,
prefix: String? = null,
schedule: Int? = null,
sendTenantHeader: Boolean? = null,
taggedMetricsCacheSize: Int? = null,
tags: io.vertx.core.json.JsonObject? = null,
tenant: String? = null): VertxHawkularOptions = io.vertx.ext.hawkular.VertxHawkularOptions().apply {
if (authenticationOptions != null) {
this.setAuthenticationOptions(authenticationOptions)
}
if (batchDelay != null) {
this.setBatchDelay(batchDelay)
}
if (batchSize != null) {
this.setBatchSize(batchSize)
}
if (disabledMetricsTypes != null) {
this.setDisabledMetricsTypes(disabledMetricsTypes.toSet())
}
if (enabled != null) {
this.setEnabled(enabled)
}
if (host != null) {
this.setHost(host)
}
if (httpHeaders != null) {
this.setHttpHeaders(httpHeaders)
}
if (httpOptions != null) {
this.setHttpOptions(httpOptions)
}
if (metricTagsMatches != null) {
this.setMetricTagsMatches(metricTagsMatches.toList())
}
if (metricsBridgeAddress != null) {
this.setMetricsBridgeAddress(metricsBridgeAddress)
}
if (metricsBridgeEnabled != null) {
this.setMetricsBridgeEnabled(metricsBridgeEnabled)
}
if (metricsServiceUri != null) {
this.setMetricsServiceUri(metricsServiceUri)
}
if (port != null) {
this.setPort(port)
}
if (prefix != null) {
this.setPrefix(prefix)
}
if (schedule != null) {
this.setSchedule(schedule)
}
if (sendTenantHeader != null) {
this.setSendTenantHeader(sendTenantHeader)
}
if (taggedMetricsCacheSize != null) {
this.setTaggedMetricsCacheSize(taggedMetricsCacheSize)
}
if (tags != null) {
this.setTags(tags)
}
if (tenant != null) {
this.setTenant(tenant)
}
}
| apache-2.0 | fe6abd341b38c55cc11f26fa241b1f39 | 47.991379 | 371 | 0.747317 | 3.796259 | false | false | false | false |
toastkidjp/Yobidashi_kt | todo/src/main/java/jp/toastkid/todo/view/addition/TaskAdditionDialogFragmentViewModel.kt | 1 | 1143 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.todo.view.addition
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import jp.toastkid.lib.lifecycle.Event
import jp.toastkid.todo.model.TodoTask
import java.io.Serializable
/**
* @author toastkidjp
*/
class TaskAdditionDialogFragmentViewModel : ViewModel(), Serializable {
private val _task = MutableLiveData<TodoTask?>()
val task: LiveData<TodoTask?> = _task
fun setTask(task: TodoTask?) {
_task.postValue(
task
?: TodoTask(0).also { it.dueDate = System.currentTimeMillis() }
)
}
private val _refresh = MutableLiveData<Event<TodoTask>>()
val refresh: LiveData<Event<TodoTask>> = _refresh
fun refresh(task: TodoTask) {
_refresh.postValue(Event(task))
}
} | epl-1.0 | db5d0c2cf8c625da83b97eaf09ec51d6 | 26.902439 | 88 | 0.711286 | 4.329545 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/utils/ExprUtils.kt | 4 | 6977 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psi.ext.LogicOp.*
/**
* Returns `true` if all elements are `true`, `false` if there exists
* `false` element and `null` otherwise.
*/
private fun <T> List<T>.allMaybe(predicate: (T) -> Boolean?): Boolean? {
val values = map(predicate)
val nullsTrue = values.all {
it ?: true
}
val nullsFalse = values.all {
it ?: false
}
return if (nullsTrue == nullsFalse) nullsTrue else null
}
/**
* Check if an expression is functionally pure
* (has no side-effects and throws no errors).
*
* @return `true` if the expression is pure, `false` if
* > it is not pure (has side-effects / throws errors)
* > or `null` if it is unknown.
*/
fun RsExpr.isPure(): Boolean? {
return when (this) {
is RsArrayExpr -> when (semicolon) {
null -> exprList.allMaybe(RsExpr::isPure)
else -> exprList[0].isPure() // Array literal of form [expr; size],
// size is a compile-time constant, so it is always pure
}
is RsStructLiteral -> when (structLiteralBody.dotdot) {
null -> structLiteralBody.structLiteralFieldList
.map { it.expr }
.allMaybe { it?.isPure() } // TODO: Why `it` can be null?
else -> null // TODO: handle update case (`Point{ y: 0, z: 10, .. base}`)
}
is RsBinaryExpr -> when (operatorType) {
is LogicOp -> listOfNotNull(left, right).allMaybe(RsExpr::isPure)
else -> null // Have to search if operation is overloaded
}
is RsTupleExpr -> exprList.allMaybe(RsExpr::isPure)
is RsDotExpr -> if (methodCall != null) null else expr.isPure()
is RsParenExpr -> expr.isPure()
is RsBreakExpr, is RsContExpr, is RsRetExpr, is RsTryExpr -> false // Changes execution flow
is RsPathExpr, is RsLitExpr, is RsUnitExpr -> true
// TODO: more complex analysis of blocks of code and search of implemented traits
is RsBlockExpr, // Have to analyze lines, very hard case
is RsCastExpr, // `expr.isPure()` maybe not true, think about side-effects, may panic while cast
is RsCallExpr, // All arguments and function itself must be pure, very hard case
is RsForExpr, // Always return (), if pure then can be replaced with it
is RsIfExpr,
is RsIndexExpr, // Index trait can be overloaded, can panic if out of bounds
is RsLambdaExpr,
is RsLoopExpr,
is RsMacroExpr,
is RsMatchExpr,
is RsRangeExpr,
is RsUnaryExpr, // May be overloaded
is RsWhileExpr -> null
else -> null
}
}
fun RsExpr.canBeSimplified(): Boolean =
simplifyBooleanExpression(peek = true).second
fun RsExpr.simplifyBooleanExpression() =
simplifyBooleanExpression(peek = false)
/**
* Simplifies a boolean expression if can.
*
* @param peek if true then does not perform any changes on PSI,
* `expr` is not defined and `result` indicates if this expression
* can be simplified
* @return `(expr, result)` where `expr` is a resulting expression,
* `result` is true if an expression was actually simplified.
*/
private fun RsExpr.simplifyBooleanExpression(peek: Boolean): Pair<RsExpr, Boolean> {
val original = this to false
if (this is RsLitExpr) return original
val value = this.evalBooleanExpression()
if (value != null) {
return (if (peek) this else createPsiElement(project, value)) to true
}
return when (this) {
is RsBinaryExpr -> {
val right = right ?: return original
val (leftExpr, leftSimplified) = left.simplifyBooleanExpression(peek)
val (rightExpr, rightSimplified) = right.simplifyBooleanExpression(peek)
if (leftExpr is RsLitExpr) {
if (peek)
return this to true
simplifyBinaryOperation(this, leftExpr, rightExpr, project)?.let {
return it to true
}
}
if (rightExpr is RsLitExpr) {
if (peek)
return this to true
simplifyBinaryOperation(this, rightExpr, leftExpr, project)?.let {
return it to true
}
}
if (!peek) {
if (leftSimplified)
left.replace(leftExpr)
if (rightSimplified)
right.replace(rightExpr)
}
this to (leftSimplified || rightSimplified)
}
else -> original
}
}
private fun simplifyBinaryOperation(op: RsBinaryExpr, const: RsLitExpr, expr: RsExpr, project: Project): RsExpr? {
return const.boolLiteral?.let {
when (op.operatorType) {
AND ->
when (it.text) {
"true" -> expr
"false" -> createPsiElement(project, "false")
else -> null
}
OR ->
when (it.text) {
"true" -> createPsiElement(project, "true")
"false" -> expr
else -> null
}
else ->
null
}
}
}
/**
* Evaluates a boolean expression if can.
*
* @return result of evaluation or `null` if can't simplify or
* if it is not a boolean expression.
*/
fun RsExpr.evalBooleanExpression(): Boolean? {
return when (this) {
is RsLitExpr ->
(kind as? RsLiteralKind.Boolean)?.value
is RsBinaryExpr -> when (operatorType) {
AND -> {
val lhs = left.evalBooleanExpression() ?: return null
if (!lhs) return false
val rhs = right?.evalBooleanExpression() ?: return null
lhs && rhs
}
OR -> {
val lhs = left.evalBooleanExpression() ?: return null
if (lhs) return true
val rhs = right?.evalBooleanExpression() ?: return null
lhs || rhs
}
ArithmeticOp.BIT_XOR -> {
val lhs = left.evalBooleanExpression() ?: return null
val rhs = right?.evalBooleanExpression() ?: return null
lhs xor rhs
}
else -> null
}
is RsUnaryExpr -> when (operatorType) {
UnaryOperator.NOT -> expr?.evalBooleanExpression()?.let { !it }
else -> null
}
is RsParenExpr -> expr.evalBooleanExpression()
else -> null
}
}
private fun createPsiElement(project: Project, value: Any) = RsPsiFactory(project).createExpression(value.toString())
| mit | 24d75ea1336d89b87e64f7b4fae65935 | 34.416244 | 117 | 0.570159 | 4.566099 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/PostSolveHandler.kt | 1 | 2054 | package com.binarymonks.jj.core.physics
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.physics.box2d.Contact
import com.badlogic.gdx.physics.box2d.ContactImpulse
import com.badlogic.gdx.physics.box2d.Fixture
import com.binarymonks.jj.core.copy
import com.binarymonks.jj.core.scenes.Scene
abstract class PostSolveHandler {
protected var ignoreProperties: Array<String> = Array()
protected var matchProperties: Array<String> = Array()
private var enabled = true
init {
init()
}
internal fun postSolveCollision(me: Scene, myFixture: Fixture, other: Scene, otherFixture: Fixture, contact: Contact, impulse: ContactImpulse): Boolean {
if (enabled) {
val gameData = otherFixture.userData as PhysicsNode
for (ignore in ignoreProperties) {
if (gameData.hasProperty(ignore)) {
return false
}
}
if (matchProperties.size > 0) {
for (matchProp in matchProperties) {
if (gameData.hasProperty(matchProp)) {
return postSolve(me, myFixture, other, otherFixture, contact, impulse)
}
}
} else {
return postSolve(me, myFixture, other, otherFixture, contact, impulse)
}
}
return false
}
/**
* Handle the collision, return True if propagation of the collision should stop. [CollisionHandler]s after this
* will not be called if True is returned, including physics root [CollisionHandler]s
*/
abstract fun postSolve(me: Scene, myFixture: Fixture, other: Scene, otherFixture: Fixture, contact: Contact, impulse: ContactImpulse): Boolean
open fun init() {
}
open fun clone(): PostSolveHandler {
return copy(this)
}
fun disable() {
enabled = false
}
fun enable() {
init()
enabled = true
}
open fun onAddToWorld() {
}
open fun onRemoveFromWorld() {
}
}
| apache-2.0 | 19f54bccca1191956d009c8607d9bd12 | 27.929577 | 157 | 0.616358 | 4.455531 | false | false | false | false |
danfma/kodando | kodando-runtime/src/main/kotlin/kodando/runtime/Metadata.kt | 1 | 2248 | package kodando.runtime
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
/**
* Created by danfma on 16/01/2017.
*/
class Metadata<T : Any>(val type: JsClass<T>) {
constructor(clazz: KClass<T>) : this(clazz.js)
fun <TProperty> decorateProperty(
property: KProperty<TProperty>,
vararg decorators: PropertyDecorator) {
val prototype = type.asDynamic().prototype
val propertyName = property.name
val propertyDescriptor = getOwnPropertyDescriptor(prototype, propertyName)
decorate(decorators, prototype, propertyName, propertyDescriptor ?: undefined)
}
fun decorateMethod(
memberName: String,
vararg decorators: MethodDecorator) {
val prototype = type.asDynamic().prototype
val propertyName = memberName
val propertyDescriptor = getOwnPropertyDescriptor(prototype, propertyName)
decorate(decorators, prototype, propertyName, propertyDescriptor ?: undefined)
}
companion object {
private val getOwnPropertyDescriptor: dynamic = js("Object.getOwnPropertyDescriptor")
private val decorate: dynamic = js("""
(function (decorators, target, key, desc) {
var previousDescriptor = (desc && !desc.configurable) ? desc : null;
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
if (previousDescriptor) {
if (c > 3 && r) {
previousDescriptor.get = r.get;
previousDescriptor.set = r.set;
}
return previousDescriptor;
}
return c > 3 && r && Object.defineProperty(target, key, r), r;
})
""")
private val metadata: dynamic = js("""
(function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
})
""")
}
}
fun <T : Any> metadataOf(type: KClass<T>, configurer: Metadata<T>.() -> Unit): Metadata<T> {
return Metadata(type).apply(configurer)
}
interface PropertyDecorator
interface MethodDecorator
| mit | eb124f19c59316651590e84c41d0a89b | 29.794521 | 150 | 0.682384 | 3.902778 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-amphibians | app/src/main/java/com/example/amphibians/ui/AmphibiansApp.kt | 1 | 2002 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.amphibians.ui
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.amphibians.ui.screens.HomeScreen
import com.example.amphibians.R
import com.example.amphibians.ui.screens.AmphibiansViewModel
@Composable
fun AmphibiansApp(modifier: Modifier = Modifier) {
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) }
) {
Surface(
modifier = Modifier
.fillMaxSize()
.padding(it),
color = MaterialTheme.colors.background
) {
val amphibiansViewModel: AmphibiansViewModel =
viewModel(factory = AmphibiansViewModel.Factory)
HomeScreen(
amphibiansUiState = amphibiansViewModel.amphibiansUiState,
retryAction = amphibiansViewModel::getAmphibians
)
}
}
}
| apache-2.0 | d8751b93b8419d4c1bd3e1147c6480d0 | 36.074074 | 83 | 0.724276 | 4.591743 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/tangram/TouchGestureManager.kt | 2 | 5264 | package de.westnordost.streetcomplete.map.tangram
import com.mapzen.tangram.MapController
import com.mapzen.tangram.TouchInput
/**
* Manages touch gesture responders. Use in place of directly setting the responders on the
* touchInput.
*
* TouchInput Responders set via the Tangram MapController.touchInput (0.12.0) completely override
* the default behavior, independent of what they return in on*Begin().
*
* A responder set via this class will default to the built-in gesture handling behavior
* if the custom responder does return false (= not consume the event).
* See https://github.com/tangrams/tangram-es/issues/1960
* */
class TouchGestureManager(private val c: MapController) {
// the getters actually do not get but _create_ the responders, so we need to keep them as fields
private val defaultShoveResponder = c.shoveResponder
private val defaultRotateResponse = c.rotateResponder
private val defaultPanResponder = c.panResponder
private val defaultScaleResponder = c.scaleResponder
fun setShoveResponder(responder: TouchInput.ShoveResponder?) {
if (responder == null) {
c.touchInput.setShoveResponder(defaultShoveResponder)
}
else {
c.touchInput.setShoveResponder(object : TouchInput.ShoveResponder {
override fun onShoveBegin(): Boolean {
if (responder.onShoveBegin()) return false
return defaultShoveResponder.onShoveBegin()
}
override fun onShove(distance: Float): Boolean {
if (responder.onShove(distance)) return false
return defaultShoveResponder.onShove(distance)
}
override fun onShoveEnd(): Boolean {
responder.onShoveEnd()
return defaultShoveResponder.onShoveEnd()
}
})
}
}
fun setScaleResponder(responder: TouchInput.ScaleResponder?) {
if (responder == null) {
c.touchInput.setScaleResponder(defaultScaleResponder)
}
else {
c.touchInput.setScaleResponder(object : TouchInput.ScaleResponder {
override fun onScaleBegin(): Boolean {
if (responder.onScaleBegin()) return false
return defaultScaleResponder.onScaleBegin()
}
override fun onScale(x: Float, y: Float, scale: Float, velocity: Float): Boolean {
if (responder.onScale(x, y, scale, velocity)) return false
return defaultScaleResponder.onScale(x, y, scale, velocity)
}
override fun onScaleEnd(): Boolean {
responder.onScaleEnd()
return defaultScaleResponder.onScaleEnd()
}
})
}
}
fun setRotateResponder(responder: TouchInput.RotateResponder?) {
if (responder == null) {
c.touchInput.setRotateResponder(defaultRotateResponse)
}
else {
c.touchInput.setRotateResponder(object : TouchInput.RotateResponder {
override fun onRotateBegin(): Boolean {
if (responder.onRotateBegin()) return false
return defaultRotateResponse.onRotateBegin()
}
override fun onRotate(x: Float, y: Float, rotation: Float): Boolean {
if (responder.onRotate(x, y, rotation)) return false
return defaultRotateResponse.onRotate(x, y, rotation)
}
override fun onRotateEnd(): Boolean {
responder.onRotateEnd()
return defaultRotateResponse.onRotateEnd()
}
})
}
}
fun setPanResponder(responder: TouchInput.PanResponder?) {
if (responder == null) {
c.touchInput.setPanResponder(defaultPanResponder)
}
else {
c.touchInput.setPanResponder(object : TouchInput.PanResponder {
override fun onPanBegin(): Boolean {
if (responder.onPanBegin()) return false
return defaultPanResponder.onPanBegin()
}
override fun onPan(startX: Float, startY: Float, endX: Float, endY: Float ): Boolean {
if (responder.onPan(startX, startY, endX, endY)) return false
return defaultPanResponder.onPan(startX, startY, endX, endY)
}
override fun onPanEnd(): Boolean {
responder.onPanEnd()
return defaultPanResponder.onPanEnd()
}
override fun onFling(posX: Float, posY: Float, velocityX: Float, velocityY: Float): Boolean {
if (responder.onFling(posX, posY, velocityX, velocityY)) return false
return defaultPanResponder.onFling(posX, posY, velocityX, velocityY)
}
override fun onCancelFling(): Boolean {
responder.onCancelFling()
return defaultPanResponder.onCancelFling()
}
})
}
}
}
| gpl-3.0 | c47e45d50fc24ecf58b734f3cd868168 | 39.492308 | 109 | 0.586816 | 4.887651 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/baby_changing_table/AddBabyChangingTable.kt | 1 | 1633 | package de.westnordost.streetcomplete.quests.baby_changing_table
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBabyChangingTable : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes, ways with
(
(
(amenity ~ restaurant|cafe|fuel|fast_food or shop ~ mall|department_store)
and name
and toilets = yes
)
or amenity = toilets
)
and !diaper and !changing_table
"""
override val commitMessage = "Add baby changing table"
override val wikiLink = "Key:changing_table"
override val icon = R.drawable.ic_quest_baby
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside
override val isReplaceShopEnabled = true
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_baby_changing_table_title
else
R.string.quest_baby_changing_table_toilets_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("changing_table", answer.toYesNo())
}
}
| gpl-3.0 | a7c4034390fb2e43f131f6cf93a384e7 | 36.976744 | 88 | 0.718922 | 4.679083 | false | false | false | false |
airien/workbits | android-sunflower-master/app/src/main/java/no/politiet/soip/data/GardenPlantingRepository.kt | 1 | 1872 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 no.politiet.soip.data
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext
class GardenPlantingRepository private constructor(
private val gardenPlantingDao: GardenPlantingDao
) {
suspend fun createGardenPlanting(plantId: String) {
withContext(IO) {
val gardenPlanting = GardenPlanting(plantId)
gardenPlantingDao.insertGardenPlanting(gardenPlanting)
}
}
suspend fun removeGardenPlanting(gardenPlanting: GardenPlanting) {
withContext(IO) {
gardenPlantingDao.deleteGardenPlanting(gardenPlanting)
}
}
fun getGardenPlantingForPlant(plantId: String) =
gardenPlantingDao.getGardenPlantingForPlant(plantId)
fun getGardenPlantings() = gardenPlantingDao.getGardenPlantings()
fun getPlantAndGardenPlantings() = gardenPlantingDao.getPlantAndGardenPlantings()
companion object {
// For Singleton instantiation
@Volatile private var instance: GardenPlantingRepository? = null
fun getInstance(gardenPlantingDao: GardenPlantingDao) =
instance ?: synchronized(this) {
instance ?: GardenPlantingRepository(gardenPlantingDao).also { instance = it }
}
}
} | lgpl-3.0 | d2c52899aa152a83d000b361eb4050af | 32.446429 | 98 | 0.715278 | 4.703518 | false | false | false | false |
adityaDave2017/my-vocab | app/src/main/java/com/android/vocab/provider/bean/Word.kt | 1 | 1538 | package com.android.vocab.provider.bean
import android.os.Parcel
import android.os.Parcelable
open class Word(var wordId: Long = 0,
var word: String = "",
var typeId: Long = 0L,
var meaning: String = "",
var frequency: Int = 0,
var createTime: Long = 0L,
var lastAccessTime: Long = 0L
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readString(),
parcel.readLong(),
parcel.readString(),
parcel.readInt(),
parcel.readLong(),
parcel.readLong()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(wordId)
parcel.writeString(word)
parcel.writeLong(typeId)
parcel.writeString(meaning)
parcel.writeInt(frequency)
parcel.writeLong(createTime)
parcel.writeLong(lastAccessTime)
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
return "Word(wordId=$wordId, word='$word', typeId=$typeId, meaning='$meaning', frequency=$frequency, createTime=$createTime, lastAccessTime=$lastAccessTime)"
}
companion object CREATOR : Parcelable.Creator<Word> {
override fun createFromParcel(parcel: Parcel): Word {
return Word(parcel)
}
override fun newArray(size: Int): Array<Word?> {
return arrayOfNulls(size)
}
}
} | mit | 9e694c7909ee60056ac72fb3bca9f36c | 27.5 | 165 | 0.583875 | 4.76161 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.