repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/user/QuestTypeInfoFragment.kt | 1 | 3757 | package de.westnordost.streetcomplete.user
import android.animation.ValueAnimator
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.core.animation.doOnStart
import androidx.core.net.toUri
import androidx.core.view.isInvisible
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.databinding.FragmentQuestTypeInfoDialogBinding
import de.westnordost.streetcomplete.ktx.tryStartActivity
import de.westnordost.streetcomplete.ktx.viewBinding
import de.westnordost.streetcomplete.view.CircularOutlineProvider
import kotlin.math.min
import kotlin.math.pow
/** Shows the details for a certain quest type as a fake-dialog. */
class QuestTypeInfoFragment : AbstractInfoFakeDialogFragment(R.layout.fragment_quest_type_info_dialog) {
private val binding by viewBinding(FragmentQuestTypeInfoDialogBinding::bind)
override val dialogAndBackgroundContainer get() = binding.dialogAndBackgroundContainer
override val dialogBackground get() = binding.dialogBackground
override val dialogContentContainer get() = binding.dialogContentContainer
override val dialogBubbleBackground get() = binding.dialogBubbleBackground
override val titleView get() = binding.titleView
// need to keep the animators here to be able to clear them on cancel
private var counterAnimation: ValueAnimator? = null
/* ---------------------------------------- Lifecycle --------------------------------------- */
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.titleView.outlineProvider = CircularOutlineProvider
}
override fun onDestroy() {
super.onDestroy()
counterAnimation?.cancel()
counterAnimation = null
}
/* ---------------------------------------- Interface --------------------------------------- */
fun show(questType: QuestType<*>, questCount: Int, questBubbleView: View) {
if (!show(questBubbleView)) return
binding.titleView.setImageResource(questType.icon)
binding.questTitleText.text = resources.getString(questType.title, *Array(10){"…"})
binding.solvedQuestsText.text = ""
val scale = (0.4 + min( questCount / 100.0, 1.0)*0.6).toFloat()
binding.solvedQuestsContainer.visibility = View.INVISIBLE
binding.solvedQuestsContainer.scaleX = scale
binding.solvedQuestsContainer.scaleY = scale
binding.solvedQuestsContainer.setOnClickListener { counterAnimation?.end() }
binding.wikiLinkButton.isInvisible = questType !is OsmElementQuestType || questType.wikiLink == null
if (questType is OsmElementQuestType && questType.wikiLink != null) {
binding.wikiLinkButton.setOnClickListener {
openUrl("https://wiki.openstreetmap.org/wiki/${questType.wikiLink}")
}
}
counterAnimation?.cancel()
val anim = ValueAnimator.ofInt(0, questCount)
anim.doOnStart { binding.solvedQuestsContainer.visibility = View.VISIBLE }
anim.duration = 300 + (questCount * 500.0).pow(0.6).toLong()
anim.addUpdateListener { binding.solvedQuestsText.text = it.animatedValue.toString() }
anim.interpolator = DecelerateInterpolator()
anim.startDelay = ANIMATION_TIME_IN_MS
anim.start()
counterAnimation = anim
}
private fun openUrl(url: String): Boolean {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
return tryStartActivity(intent)
}
}
| gpl-3.0 | f135f116f262317ce51633e7ea85cd4e | 44.240964 | 108 | 0.709987 | 5.215278 | false | false | false | false |
lure0xaos/CoffeeTime | util/src/main/kotlin/gargoyle/ct/util/resource/internal/TempLocalResource.kt | 1 | 1583 | package gargoyle.ct.util.resource.internal
import java.io.File
import java.io.IOException
import java.net.URL
import java.nio.file.Files
import java.nio.file.StandardCopyOption
class TempLocalResource : ClasspathResource {
private constructor(loader: ClassLoader, base: ClasspathResource, location: String) :
super(loader, base, location)
constructor(location: String) : super(location)
override fun createResource(
base: VirtualResource<ClasspathResource>?,
location: String
): VirtualResource<ClasspathResource> {
val loader = getLoader(base)
val resource: ClasspathResource =
base?.let { ClasspathResource(loader, it as ClasspathResource, location) } ?: ClasspathResource(location)
if (!resource.exists()) {
return TempLocalResource(location)
}
try {
resource.inputStream.use { stream ->
val tempFile = File.createTempFile(baseName, ".$extension")
Files.copy(stream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
tempFile.deleteOnExit()
return TempLocalResource(loader, resource, tempFile.path)
}
} catch (e: IOException) {
throw IllegalArgumentException(location, e)
}
}
override fun toURL(): URL = File(location).toURI().toURL()
override fun exists(): Boolean =
try {
exists(toURL())
} catch (ex: Exception) {
false
}
fun toFile(): File = File(toURL().path.substring(1))
}
| unlicense | f5f46489f799583cb74720b9221a2034 | 32.680851 | 117 | 0.635502 | 4.946875 | false | false | false | false |
kantega/niagara | niagara-json/src/main/kotlin/org/kantega/niagara/json/JsonMapper.kt | 1 | 3094 | package org.kantega.niagara.json
import org.kantega.niagara.data.*
data class JsonMapper<A>(val encoder:JsonEncoder<A>, val decoder: JsonDecoder<A>){
inline fun <reified B> xmap(crossinline f:(A)->B, noinline g:(B)->A):JsonMapper<B> = JsonMapper(
encoder.comap(g),
decoder.map(f)
)
}
data class ObjectMapperBuilder<OBJ,C,REST>(val encoder:JsonObjectBuilder<OBJ,REST>, val decoder: JsonDecoder<C>)
fun <A> ObjectMapperBuilder<A,A,*>.build() =
JsonMapper(this.encoder,this.decoder)
inline fun <OBJ,reified FIRST,reified REST,TAIL:HList> ObjectMapperBuilder<OBJ,(FIRST)->REST,HCons<FIRST,TAIL>>
.field(name:String,endec:JsonMapper<FIRST>):ObjectMapperBuilder<OBJ,REST,TAIL> =
ObjectMapperBuilder(encoder.field(name,endec.encoder),decoder.field(name,endec.decoder))
fun <A> mapper(encoder:JsonEncoder<A>, decoder: JsonDecoder<A>) : JsonMapper<A> =
JsonMapper(encoder,decoder)
val mapString = JsonMapper(encodeString, decodeString)
val mapInt = JsonMapper(encodeInt, decodeInt)
val mapLong = JsonMapper(encodeLong, decodeLong)
val mapDouble = JsonMapper(encodeDouble, decodeDouble)
val mapBool = JsonMapper(encodeBool, decodeBool)
fun <A> mapArray(elemEndec:JsonMapper<A>) = JsonMapper(encodeArray(elemEndec.encoder), decodeArray(elemEndec.decoder))
fun <A, B, C, D, E, F, G, H, I, J,T> mapObject(constructor: (A, B, C, D, E, F, G, H, I, J) -> T, destructor:(T)->HList10<A,B,C,D,E,F,G,H,I,J>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, E, F, G, H, I, T> mapObject(constructor: (A, B, C, D, E, F, G, H, I) -> T, destructor:(T)->HList9<A,B,C,D,E,F,G,H,I>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, E, F, G, H, T> mapObject(constructor: (A, B, C, D, E, F, G, H) -> T, destructor:(T)->HList8<A,B,C,D,E,F,G,H>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, E, F, G, T> mapObject(constructor: (A, B, C, D, E, F, G) -> T, destructor:(T)->HList7<A,B,C,D,E,F,G>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, E, F, T> mapObject(constructor: (A, B, C, D, E, F) -> T, destructor:(T)->HList6<A,B,C,D,E,F>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, E,T> mapObject(constructor: (A, B, C, D, E) -> T, destructor:(T)->HList5<A,B,C,D,E>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, D, T> mapObject(constructor: (A, B, C, D) -> T, destructor:(T)->HList4<A,B,C,D>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B, C, T> mapObject(constructor: (A, B, C) -> T, destructor:(T)->HList3<A,B,C>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, B,T> mapObject(constructor: (A, B) -> T, destructor:(T)->HList2<A,B>) =
ObjectMapperBuilder(encode(destructor),decode(constructor.curried()))
fun <A, T> mapObject(constructor: (A) -> T, destructor:(T)->HList1<A>) =
ObjectMapperBuilder(encode(destructor),decode(constructor))
| apache-2.0 | 4fe3b17a06ee2d8347f92803e4667992 | 46.6 | 144 | 0.694893 | 2.972142 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/duchy/daemon/testing/TestRequisition.kt | 1 | 2826 | /*
* Copyright 2021 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.duchy.daemon.testing
import com.google.protobuf.ByteString
import com.google.protobuf.kotlin.toByteString
import kotlin.random.Random
import org.wfanet.measurement.common.crypto.hashSha256
import org.wfanet.measurement.internal.duchy.externalRequisitionKey
import org.wfanet.measurement.internal.duchy.requisitionDetails
import org.wfanet.measurement.internal.duchy.requisitionMetadata
import org.wfanet.measurement.system.v1alpha.ComputationParticipantKey
import org.wfanet.measurement.system.v1alpha.Requisition
import org.wfanet.measurement.system.v1alpha.RequisitionKey
import org.wfanet.measurement.system.v1alpha.requisition
data class TestRequisition(
val externalRequisitionId: String,
val serializedMeasurementSpecProvider: () -> ByteString
) {
val requisitionSpecHash: ByteString = Random.Default.nextBytes(32).toByteString()
val nonce: Long = Random.Default.nextLong()
val nonceHash = hashSha256(nonce)
val requisitionFingerprint
get() = hashSha256(serializedMeasurementSpecProvider().concat(requisitionSpecHash))
fun toSystemRequisition(
globalId: String,
state: Requisition.State,
externalDuchyId: String = ""
) = requisition {
name = RequisitionKey(globalId, externalRequisitionId).toName()
requisitionSpecHash = [email protected]
nonceHash = [email protected]
this.state = state
if (state == Requisition.State.FULFILLED) {
nonce = [email protected]
fulfillingComputationParticipant =
ComputationParticipantKey(globalId, externalDuchyId).toName()
}
}
fun toRequisitionMetadata(state: Requisition.State, externalDuchyId: String = "") =
requisitionMetadata {
externalKey = externalRequisitionKey {
externalRequisitionId = [email protected]
requisitionFingerprint = [email protected]
}
details = requisitionDetails {
nonceHash = [email protected]
if (state == Requisition.State.FULFILLED) {
nonce = [email protected]
externalFulfillingDuchyId = externalDuchyId
}
}
}
}
| apache-2.0 | 113056005547a29831e41b2698de8bd9 | 38.802817 | 87 | 0.76787 | 4.757576 | false | true | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/latex/logtab/LatexOutputListener.kt | 1 | 12107 | package nl.hannahsten.texifyidea.run.latex.logtab
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutputType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexLogMessage
import nl.hannahsten.texifyidea.run.bibtex.logtab.BibtexOutputListener
import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.DUPLICATE_WHITESPACE
import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.LINE_WIDTH
import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.PACKAGE_WARNING_CONTINUATION
import nl.hannahsten.texifyidea.run.latex.logtab.ui.LatexCompileMessageTreeView
import nl.hannahsten.texifyidea.util.files.findFile
import nl.hannahsten.texifyidea.util.remove
import nl.hannahsten.texifyidea.util.removeAll
import org.apache.commons.collections.Buffer
import org.apache.commons.collections.BufferUtils
import org.apache.commons.collections.buffer.CircularFifoBuffer
class LatexOutputListener(
val project: Project,
val mainFile: VirtualFile?,
val messageList: MutableList<LatexLogMessage>,
val bibMessageList: MutableList<BibtexLogMessage>,
val treeView: LatexCompileMessageTreeView
) : ProcessListener {
// This should probably be located somewhere else
companion object {
/**
* Returns true if firstLine is most likely the last line of the message.
*/
fun isLineEndOfMessage(secondLine: String, firstLine: String): Boolean {
return firstLine.remove("\n").length < LINE_WIDTH - 1 &&
// Indent of LaTeX Warning/Error messages
!secondLine.startsWith(" ") &&
// Package warning/error continuation.
!PACKAGE_WARNING_CONTINUATION.toRegex().containsMatchIn(secondLine) &&
// Assume the undefined control sequence always continues on the next line
!firstLine.trim().endsWith("Undefined control sequence.") &&
// Case of the first line pointing out something interesting on the second line
!(firstLine.endsWith(":") && secondLine.startsWith(" "))
}
}
/**
* Window of the last two log output messages.
*/
val window: Buffer = BufferUtils.synchronizedBuffer(CircularFifoBuffer(2))
// For latexmk, collect the bibtex/biber messages in a separate list, so
// we don't lose them when resetting on each new (pdfla)tex run.
private var isCollectingBib = false
private val bibtexOutputListener = BibtexOutputListener(project, mainFile, bibMessageList, treeView)
var isCollectingMessage = false
var currentLogMessage: LatexLogMessage? = null
// Stack with the filenames, where the first is the current file.
private var fileStack = LatexFileStack()
private var collectingOutputLine: String = ""
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
if (outputType !is ProcessOutputType) return
// Latexmk outputs on stderr, which interleaves with the pdflatex/bibtex/etc output on stdout
if (outputType.isStderr) return
// The following code wants complete lines as input.
// However, this function onTextAvailable will simply give us text when it's available,
// which may be only part of a line.
// Since it does always include newlines to designate linebreaks, we simply wait here until
// we have the full line collected.
// It looks like we never get a line ending in the middle of even.text, but not completely sure about that.
if (event.text.endsWith("\n").not()) {
collectingOutputLine += event.text
return
}
else {
val collectedLine = collectingOutputLine + event.text
collectingOutputLine = ""
// We look for specific strings in the log output for which we know it was probably an error message
// (it might be that it is actually not, since anything can be typed to the LaTeX output log, but we ignore
// that for now and assume the log is of reasonable format).
// Standard log output is only 79 characters wide, meaning these strings might occur over two lines.
// We assume the match tokens will always fit over two lines.
// Therefore, we maintain a window of two log output lines to detect the error messages.
//
// We assume that if the first line of the error/warning is exactly the maximum line width, it will continue
// on the next line. This may not be accurate, but there is no way of distinguishing this.
// Newlines are important to check when message end. Keep.
processNewText(collectedLine)
}
}
fun processNewText(newText: String) {
if (isCollectingBib) {
// Don't chunk bibtex lines, as they don't usually break by themselves and they are often not long anyway
bibtexOutputListener.processNewText(newText)
}
else {
newText.chunked(LINE_WIDTH).forEach {
processNewTextLatex(it)
}
}
resetIfNeeded(newText)
}
private fun processNewTextLatex(newText: String) {
window.add(newText)
// No idea how we could possibly get an IndexOutOfBoundsException on the buffer, but we did
val text = try {
window.joinToString(separator = "")
}
catch (e: IndexOutOfBoundsException) {
return
}
// Check if we are currently in the process of collecting the full message of a matched message of interest
if (isCollectingMessage) {
collectMessageLine(text, newText)
fileStack.update(newText)
}
else {
// Skip line if it is irrelevant.
if (LatexLogMessageExtractor.skip(window.firstOrNull() as? String)) {
// The first line might be irrelevant, but the new text could
// contain useful information about the file stack.
fileStack.update(newText)
return
}
// Find an error message or warning in the current text.
val logMessage = LatexLogMessageExtractor.findMessage(text.removeAll("\n", "\r"), newText.removeAll("\n"), fileStack.peek())
// Check for potential file opens/closes, modify the stack accordingly.
fileStack.update(newText)
// Finally add the message to the log, or continue collecting this message when necessary.
addOrCollectMessage(text, newText, logMessage ?: return)
}
}
private fun findProjectFileRelativeToMain(fileName: String?): VirtualFile? =
mainFile?.parent?.findFile(fileName ?: mainFile.name, setOf("tex"))
/**
* Reset the tree view and the message list when starting a new run. (latexmk)
*/
private fun resetIfNeeded(newText: String) {
"""Latexmk: applying rule '(?<program>\w+)""".toRegex().apply {
val result = find(newText) ?: return@apply
if (result.groups["program"]?.value in setOf("biber", "bibtex")) {
isCollectingBib = true
}
else {
isCollectingBib = false
treeView.errorViewStructure.clear()
messageList.clear()
// Re-add the bib messages to the tree.
bibMessageList.forEach { bibtexOutputListener.addBibMessageToTree(it) }
}
}
}
/**
* Keep collecting the message if necessary, otherwise add it to the log.
*/
private fun addOrCollectMessage(text: String, newText: String, logMessage: LatexLogMessage) {
logMessage.apply {
if (message.isEmpty()) return
if (!isLineEndOfMessage(newText, logMessage.message) || text.removeSuffix(newText).length >= LINE_WIDTH) {
// Keep on collecting output for this message
currentLogMessage = logMessage
isCollectingMessage = true
}
else {
val file = findProjectFileRelativeToMain(fileName)
if (messageList.isEmpty() || !messageList.contains(logMessage)) {
// Use original filename, especially for tests to work (which cannot find the real file)
// Trim message here instead of earlier in order to keep spaces in case we needed to continue
// collecting the message and the spaces were actually relevant
addMessageToLog(LatexLogMessage(message.trim(), fileName, line, type), file)
}
}
}
}
/**
* Add the current/new message to the log if it does not continue on the
* next line.
*/
private fun collectMessageLine(text: String, newText: String, logMessage: LatexLogMessage? = null) {
// Check if newText is interesting before appending it to the message
if (currentLogMessage?.message?.endsWith(newText.trim()) == false && !isLineEndOfMessage(newText, text.removeSuffix(newText))) {
// Append new text
val message = logMessage ?: currentLogMessage!!
// Assume that lines that end prematurely do need an extra space to be inserted, like LaTeX and package
// warnings with manual newlines, unlike 80-char forced linebreaks which should not have a space inserted
val newTextTrimmed = if (text.removeSuffix(newText).length < LINE_WIDTH) " ${newText.trim()}" else newText.trim()
// LaTeX Warning: is replaced here because this method is also run when a message is added,
// and the above check needs to return false so we can't replace this in the WarningHandler
var newMessage = (message.message + newTextTrimmed).replace("LaTeX Warning: ", "")
.replace(PACKAGE_WARNING_CONTINUATION.toRegex(), "")
.replace(DUPLICATE_WHITESPACE.toRegex(), " ")
.replace(""". l.\d+ """.toRegex(), " ") // Continuation of Undefined control sequence
// The 'on input line <line>' may be a lot of lines after the 'LaTeX Warning:', thus the original regex may
// not have caught it. Try to catch the line number here.
var line = message.line
if (line == -1) {
LatexLogMagicRegex.REPORTED_ON_LINE_REGEX.find(newMessage)?.apply {
line = groups["line"]?.value?.toInt() ?: -1
newMessage = newMessage.removeAll(this.value).trim()
}
}
currentLogMessage = LatexLogMessage(newMessage, message.fileName, line, message.type)
}
else {
isCollectingMessage = false
addMessageToLog(currentLogMessage!!)
currentLogMessage = null
}
}
private fun addMessageToLog(logMessage: LatexLogMessage, givenFile: VirtualFile? = null) {
// Don't log the same message twice
if (!messageList.contains(logMessage)) {
val file = givenFile ?: findProjectFileRelativeToMain(logMessage.fileName)
val message = LatexLogMessage(logMessage.message.trim(), logMessage.fileName, logMessage.line, logMessage.type, file)
messageList.add(message)
treeView.applyFilters(message)
}
}
override fun processTerminated(event: ProcessEvent) {
if (event.exitCode == 0) {
treeView.setProgressText("Compilation was successful.")
}
else {
treeView.setProgressText("Compilation failed.")
}
}
override fun processWillTerminate(event: ProcessEvent, willBeDestroyed: Boolean) {
}
override fun startNotified(event: ProcessEvent) {
treeView.setProgressText("Compilation in progress...")
}
} | mit | e9ee31223b51d9fc88fb9e032da2d0b8 | 45.390805 | 136 | 0.647477 | 5.097684 | false | false | false | false |
FHannes/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/JavaUastLanguagePlugin.kt | 7 | 18335 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUNamedExpression
import org.jetbrains.uast.java.expressions.JavaUSynchronizedExpression
class JavaUastLanguagePlugin : UastLanguagePlugin {
override val priority = 0
override fun isFileSupported(fileName: String) = fileName.endsWith(".java", ignoreCase = true)
override val language: Language
get() = JavaLanguage.INSTANCE
override fun isExpressionValueUsed(element: UExpression): Boolean = when (element) {
is JavaUDeclarationsExpression -> false
is UnknownJavaExpression -> (element.uastParent as? UExpression)?.let { isExpressionValueUsed(it) } ?: false
else -> {
val statement = element.psi as? PsiStatement
statement != null && statement.parent !is PsiExpressionStatement
}
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
if (element !is PsiMethodCallExpression) return null
if (element.methodExpression.referenceName != methodName) return null
val uElement = convertElementWithParent(element, null)
val callExpression = when (uElement) {
is UCallExpression -> uElement
is UQualifiedReferenceExpression -> uElement.selector as UCallExpression
else -> error("Invalid element type: $uElement")
}
val method = callExpression.resolve() ?: return null
if (containingClassFqName != null) {
val containingClass = method.containingClass ?: return null
if (containingClass.qualifiedName != containingClassFqName) return null
}
return UastLanguagePlugin.ResolvedMethod(callExpression, method)
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
if (element !is PsiNewExpression) return null
val simpleName = fqName.substringAfterLast('.')
if (element.classReference?.referenceName != simpleName) return null
val callExpression = convertElementWithParent(element, null) as? UCallExpression ?: return null
val constructorMethod = element.resolveConstructor() ?: return null
val containingClass = constructorMethod.containingClass ?: return null
if (containingClass.qualifiedName != fqName) return null
return UastLanguagePlugin.ResolvedConstructor(callExpression, constructorMethod, containingClass)
}
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
if (element !is PsiElement) return null
val parentCallback = parent.toCallback()
return convertDeclaration(element, parentCallback, requiredType) ?:
JavaConverter.convertPsiElement(element, parentCallback, requiredType)
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
if (element !is PsiElement) return null
if (element is PsiJavaFile) return requiredType.el<UFile> { JavaUFile(element, this) }
JavaConverter.getCached<UElement>(element)?.let { return it }
val parentCallback = fun(): UElement? {
val parent = JavaConverter.unwrapElements(element.parent) ?: return null
return convertElementWithParent(parent, null) ?: return null
}
return convertDeclaration(element, parentCallback, requiredType) ?:
JavaConverter.convertPsiElement(element, parentCallback, requiredType)
}
private fun convertDeclaration(element: PsiElement,
parentCallback: (() -> UElement?)?,
requiredType: Class<out UElement>?): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return fun(): UElement? {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
return ctor(element as P, parent)
}
}
if (element.isValid) element.getUserData(JAVA_CACHED_UELEMENT_KEY)?.let { ref ->
ref.get()?.let { return it }
}
return with (requiredType) { when (element) {
is PsiJavaFile -> el<UFile> { JavaUFile(element, this@JavaUastLanguagePlugin) }
is UDeclaration -> el<UDeclaration> { element }
is PsiClass -> el<UClass> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
JavaUClass.create(element, parent)
}
is PsiMethod -> el<UMethod> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
JavaUMethod.create(element, this@JavaUastLanguagePlugin, parent)
}
is PsiClassInitializer -> el<UClassInitializer>(build(::JavaUClassInitializer))
is PsiEnumConstant -> el<UEnumConstant>(build(::JavaUEnumConstant))
is PsiLocalVariable -> el<ULocalVariable>(build(::JavaULocalVariable))
is PsiParameter -> el<UParameter>(build(::JavaUParameter))
is PsiField -> el<UField>(build(::JavaUField))
is PsiVariable -> el<UVariable>(build(::JavaUVariable))
is PsiAnnotation -> el<UAnnotation>(build(::JavaUAnnotation))
else -> null
}}
}
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.el(f: () -> UElement?): UElement? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.expr(f: () -> UExpression?): UExpression? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
private fun UElement?.toCallback() = if (this != null) fun(): UElement? { return this } else null
internal object JavaConverter {
internal inline fun <reified T : UElement> getCached(element: PsiElement): T? {
return null
//todo
}
internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) {
is PsiExpressionStatement -> unwrapElements(element.parent)
is PsiParameterList -> unwrapElements(element.parent)
is PsiAnnotationParameterList -> unwrapElements(element.parent)
is PsiModifierList -> unwrapElements(element.parent)
is PsiExpressionList -> unwrapElements(element.parent)
else -> element
}
internal fun convertPsiElement(el: PsiElement,
parentCallback: (() -> UElement?)?,
requiredType: Class<out UElement>? = null): UElement? {
getCached<UElement>(el)?.let { return it }
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return fun(): UElement? {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
return ctor(el as P, parent)
}
}
return with (requiredType) { when (el) {
is PsiCodeBlock -> el<UBlockExpression>(build(::JavaUCodeBlockExpression))
is PsiResourceExpression -> convertExpression(el.expression, parentCallback, requiredType)
is PsiExpression -> convertExpression(el, parentCallback, requiredType)
is PsiStatement -> convertStatement(el, parentCallback, requiredType)
is PsiIdentifier -> el<USimpleNameReferenceExpression> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
JavaUSimpleNameReferenceExpression(el, el.text, parent)
}
is PsiNameValuePair -> el<UNamedExpression>(build(::JavaUNamedExpression))
is PsiArrayInitializerMemberValue -> el<UCallExpression>(build(::JavaAnnotationArrayInitializerUCallExpression))
is PsiTypeElement -> el<UTypeReferenceExpression>(build(::JavaUTypeReferenceExpression))
is PsiJavaCodeReferenceElement -> convertReference(el, parentCallback, requiredType)
else -> null
}}
}
internal fun convertBlock(block: PsiCodeBlock, parent: UElement?): UBlockExpression =
getCached(block) ?: JavaUCodeBlockExpression(block, parent)
internal fun convertReference(reference: PsiJavaCodeReferenceElement, parentCallback: (() -> UElement?)?, requiredType: Class<out UElement>?): UExpression? {
return with (requiredType) {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
if (reference.isQualified) {
expr<UQualifiedReferenceExpression> { JavaUQualifiedReferenceExpression(reference, parent) }
} else {
val name = reference.referenceName ?: "<error name>"
expr<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(reference, name, parent, reference) }
}
}
}
internal fun convertExpression(el: PsiExpression,
parentCallback: (() -> UElement?)?,
requiredType: Class<out UElement>? = null): UExpression? {
getCached<UExpression>(el)?.let { return it }
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
return fun(): UExpression? {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
return ctor(el as P, parent)
}
}
return with (requiredType) { when (el) {
is PsiAssignmentExpression -> expr<UBinaryExpression>(build(::JavaUAssignmentExpression))
is PsiConditionalExpression -> expr<UIfExpression>(build(::JavaUTernaryIfExpression))
is PsiNewExpression -> {
if (el.anonymousClass != null)
expr<UObjectLiteralExpression>(build(::JavaUObjectLiteralExpression))
else
expr<UCallExpression>(build(::JavaConstructorUCallExpression))
}
is PsiMethodCallExpression -> {
if (el.methodExpression.qualifierExpression != null) {
if (requiredType == null ||
requiredType.isAssignableFrom(UQualifiedReferenceExpression::class.java) ||
requiredType.isAssignableFrom(UCallExpression::class.java)) {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
val expr = JavaUCompositeQualifiedExpression(el, parent).apply {
receiver = convertOrEmpty(el.methodExpression.qualifierExpression!!, this)
selector = JavaUCallExpression(el, this)
}
if (requiredType?.isAssignableFrom(UCallExpression::class.java) != null)
expr.selector
else
expr
}
else
null
}
else
expr<UCallExpression>(build(::JavaUCallExpression))
}
is PsiArrayInitializerExpression -> expr<UCallExpression>(build(::JavaArrayInitializerUCallExpression))
is PsiBinaryExpression -> expr<UBinaryExpression>(build(::JavaUBinaryExpression))
// Should go after PsiBinaryExpression since it implements PsiPolyadicExpression
is PsiPolyadicExpression -> expr<UPolyadicExpression>(build(::JavaUPolyadicExpression))
is PsiParenthesizedExpression -> expr<UParenthesizedExpression>(build(::JavaUParenthesizedExpression))
is PsiPrefixExpression -> expr<UPrefixExpression>(build(::JavaUPrefixExpression))
is PsiPostfixExpression -> expr<UPostfixExpression>(build(::JavaUPostfixExpression))
is PsiLiteralExpression -> expr<ULiteralExpression>(build(::JavaULiteralExpression))
is PsiMethodReferenceExpression -> expr<UCallableReferenceExpression>(build(::JavaUCallableReferenceExpression))
is PsiReferenceExpression -> convertReference(el, parentCallback, requiredType)
is PsiThisExpression -> expr<UThisExpression>(build(::JavaUThisExpression))
is PsiSuperExpression -> expr<USuperExpression>(build(::JavaUSuperExpression))
is PsiInstanceOfExpression -> expr<UBinaryExpressionWithType>(build(::JavaUInstanceCheckExpression))
is PsiTypeCastExpression -> expr<UBinaryExpressionWithType>(build(::JavaUTypeCastExpression))
is PsiClassObjectAccessExpression -> expr<UClassLiteralExpression>(build(::JavaUClassLiteralExpression))
is PsiArrayAccessExpression -> expr<UArrayAccessExpression>(build(::JavaUArrayAccessExpression))
is PsiLambdaExpression -> expr<ULambdaExpression>(build(::JavaULambdaExpression))
else -> expr<UExpression>(build(::UnknownJavaExpression))
}}
}
internal fun convertStatement(el: PsiStatement,
parentCallback: (() -> UElement?)?,
requiredType: Class<out UElement>? = null): UExpression? {
getCached<UExpression>(el)?.let { return it }
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
return fun(): UExpression? {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
return ctor(el as P, parent)
}
}
return with (requiredType) { when (el) {
is PsiDeclarationStatement -> expr<UDeclarationsExpression> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
convertDeclarations(el.declaredElements, parent!!)
}
is PsiExpressionListStatement -> expr<UDeclarationsExpression> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
convertDeclarations(el.expressionList.expressions, parent!!)
}
is PsiBlockStatement -> expr<UBlockExpression>(build(::JavaUBlockExpression))
is PsiLabeledStatement -> expr<ULabeledExpression>(build(::JavaULabeledExpression))
is PsiExpressionStatement -> convertExpression(el.expression, parentCallback, requiredType)
is PsiIfStatement -> expr<UIfExpression>(build(::JavaUIfExpression))
is PsiSwitchStatement -> expr<USwitchExpression>(build(::JavaUSwitchExpression))
is PsiWhileStatement -> expr<UWhileExpression>(build(::JavaUWhileExpression))
is PsiDoWhileStatement -> expr<UDoWhileExpression>(build(::JavaUDoWhileExpression))
is PsiForStatement -> expr<UForExpression>(build(::JavaUForExpression))
is PsiForeachStatement -> expr<UForEachExpression>(build(::JavaUForEachExpression))
is PsiBreakStatement -> expr<UBreakExpression>(build(::JavaUBreakExpression))
is PsiContinueStatement -> expr<UContinueExpression>(build(::JavaUContinueExpression))
is PsiReturnStatement -> expr<UReturnExpression>(build(::JavaUReturnExpression))
is PsiAssertStatement -> expr<UCallExpression>(build(::JavaUAssertExpression))
is PsiThrowStatement -> expr<UThrowExpression>(build(::JavaUThrowExpression))
is PsiSynchronizedStatement -> expr<UBlockExpression>(build(::JavaUSynchronizedExpression))
is PsiTryStatement -> expr<UTryExpression>(build(::JavaUTryExpression))
is PsiEmptyStatement -> expr<UExpression> { UastEmptyExpression }
else -> expr<UExpression>(build(::UnknownJavaExpression))
}}
}
private fun convertDeclarations(elements: Array<out PsiElement>, parent: UElement): UDeclarationsExpression {
return JavaUDeclarationsExpression(parent).apply {
val declarations = mutableListOf<UDeclaration>()
for (element in elements) {
if (element is PsiVariable) {
declarations += JavaUVariable.create(element, this)
}
else if (element is PsiClass) {
declarations += JavaUClass.create(element, this)
}
}
this.declarations = declarations
}
}
internal fun convertOrEmpty(statement: PsiStatement?, parent: UElement?): UExpression {
return statement?.let { convertStatement(it, parent.toCallback(), null) } ?: UastEmptyExpression
}
internal fun convertOrEmpty(expression: PsiExpression?, parent: UElement?): UExpression {
return expression?.let { convertExpression(it, parent.toCallback()) } ?: UastEmptyExpression
}
internal fun convertOrNull(expression: PsiExpression?, parent: UElement?): UExpression? {
return if (expression != null) convertExpression(expression, parent.toCallback()) else null
}
internal fun convertOrEmpty(block: PsiCodeBlock?, parent: UElement?): UExpression {
return if (block != null) convertBlock(block, parent) else UastEmptyExpression
}
} | apache-2.0 | 0bcf0215cea590d8a9707a00af49b5f6 | 52.147826 | 161 | 0.645814 | 5.863447 | false | false | false | false |
AcapellaSoft/Aconite | aconite-core/src/io/aconite/serializers/GsonBodySerializer.kt | 1 | 1270 | package io.aconite.serializers
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParseException
import io.aconite.*
import io.aconite.utils.toJavaType
import java.lang.reflect.Type
import kotlin.reflect.KAnnotatedElement
import kotlin.reflect.KType
class GsonBodySerializer(val gson: Gson, val type: Type): BodySerializer {
class Factory(val gson: Gson = Gson()): BodySerializer.Factory {
constructor(builder: GsonBuilder): this(builder.create())
override fun create(annotations: KAnnotatedElement, type: KType) = GsonBodySerializer(gson, type.toJavaType())
}
override fun serialize(obj: Any?) = BodyBuffer(
content = Buffer.wrap(gson.toJson(obj, type)),
contentType = "application/json"
)
override fun deserialize(body: BodyBuffer): Any? {
if (body.content.bytes.isEmpty()) return null
if (body.contentType.toLowerCase() != "application/json")
throw UnsupportedMediaTypeException("Only 'application/json' media type supported")
try {
return gson.fromJson(body.content.string, type)
} catch (ex: JsonParseException) {
throw BadRequestException("Bad JSON format. ${ex.message}")
}
}
} | mit | d7c0640192f583289a9cd3a16feabca5 | 34.305556 | 118 | 0.698425 | 4.425087 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/viewmodels/mobile/VideosViewModel.kt | 1 | 8737 | /*****************************************************************************
* VideosViewModel.kt
*****************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.viewmodels.mobile
import android.app.Activity
import android.content.Context
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import org.videolan.medialibrary.interfaces.media.Folder
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.interfaces.media.VideoGroup
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.tools.FORCE_PLAY_ALL
import org.videolan.tools.Settings
import org.videolan.tools.isStarted
import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist
import org.videolan.vlc.gui.video.VideoGridFragment
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.media.getAll
import org.videolan.vlc.providers.medialibrary.FoldersProvider
import org.videolan.vlc.providers.medialibrary.MedialibraryProvider
import org.videolan.vlc.providers.medialibrary.VideoGroupsProvider
import org.videolan.vlc.providers.medialibrary.VideosProvider
import org.videolan.vlc.viewmodels.MedialibraryViewModel
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
class VideosViewModel(context: Context, type: VideoGroupingType, val folder: Folder?, val group: VideoGroup?) : MedialibraryViewModel(context) {
var groupingType = type
private set
var provider = loadProvider()
private set
private fun loadProvider(): MedialibraryProvider<out MediaLibraryItem> = when (groupingType) {
VideoGroupingType.NONE -> VideosProvider(folder, group, context, this)
VideoGroupingType.FOLDER -> FoldersProvider(context, this, Folder.TYPE_FOLDER_VIDEO)
VideoGroupingType.NAME -> VideoGroupsProvider(context, this)
}
override val providers: Array<MedialibraryProvider<out MediaLibraryItem>> = arrayOf(provider)
internal fun changeGroupingType(type: VideoGroupingType) {
if (groupingType == type) return
groupingType = type
provider = loadProvider()
providers[0] = provider
refresh()
}
init {
watchMedia()
watchMediaGroups()
}
class Factory(val context: Context, private val groupingType: VideoGroupingType, val folder: Folder? = null, val group: VideoGroup? = null) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return VideosViewModel(context.applicationContext, groupingType, folder, group) as T
}
}
// Folders & Groups
internal fun play(position: Int) = viewModelScope.launch {
val item = provider.pagedList.value?.get(position) ?: return@launch
withContext(Dispatchers.IO) {
when (item) {
is Folder -> item.getAll()
is VideoGroup -> item.getAll()
else -> null
}
}?.let { MediaUtils.openList(context, it, 0) }
}
internal fun append(position: Int) = viewModelScope.launch {
val item = provider.pagedList.value?.get(position) ?: return@launch
withContext(Dispatchers.IO) {
when (item) {
is Folder -> item.getAll()
is VideoGroup -> item.getAll()
else -> null
}
}?.let { MediaUtils.appendMedia(context, it) }
}
internal fun playFoldersSelection(selection: List<Folder>) = viewModelScope.launch {
val list = selection.flatMap { it.getAll() }
MediaUtils.openList(context, list, 0)
}
internal fun addItemToPlaylist(activity: FragmentActivity, position: Int) = viewModelScope.launch {
val item = provider.pagedList.value?.get(position) ?: return@launch
withContext(Dispatchers.IO) {
when (item) {
is Folder -> item.getAll()
is VideoGroup -> item.getAll()
else -> null
}
}?.let { if (activity.isStarted()) activity.addToPlaylist(it) }
}
internal fun appendFoldersSelection(selection: List<Folder>) = viewModelScope.launch {
val list = selection.flatMap { it.getAll() }
MediaUtils.appendMedia(context, list)
}
internal fun playVideo(context: Activity?, mw: MediaWrapper, position: Int, fromStart: Boolean = false) {
if (context === null) return
mw.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
val settings = Settings.getInstance(context)
if (settings.getBoolean(FORCE_PLAY_ALL, false)) {
when(val prov = provider) {
is VideosProvider -> MediaUtils.playAll(context, prov, position, false)
is FoldersProvider -> MediaUtils.playAllTracks(context, prov, position, false)
is VideoGroupsProvider -> MediaUtils.playAllTracks(context, prov, position, false)
}
} else {
if (fromStart) mw.addFlags(MediaWrapper.MEDIA_FROM_START)
MediaUtils.openMedia(context, mw)
}
}
internal fun playAll(activity: FragmentActivity?, position: Int = 0) {
if (activity?.isStarted() == true) when (groupingType) {
VideoGroupingType.NONE -> MediaUtils.playAll(activity, provider as VideosProvider, position, false)
VideoGroupingType.FOLDER -> MediaUtils.playAllTracks(activity, (provider as FoldersProvider), position, false)
VideoGroupingType.NAME -> MediaUtils.playAllTracks(activity, (provider as VideoGroupsProvider), position, false)
}
}
internal fun playAudio(activity: FragmentActivity?, media: MediaWrapper) {
if (activity == null) return
media.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
MediaUtils.openMedia(activity, media)
}
fun renameGroup(videoGroup: VideoGroup, newName: String) = viewModelScope.launch {
withContext(Dispatchers.IO) {
videoGroup.rename(newName)
}
}
fun removeFromGroup(medias: List<MediaWrapper>) = viewModelScope.launch {
withContext(Dispatchers.IO) {
medias.forEach { media ->
group?.remove(media.id)
}
}
}
fun removeFromGroup(media: MediaWrapper) = viewModelScope.launch {
withContext(Dispatchers.IO) {
group?.remove(media.id)
}
}
fun ungroup(groups: List<MediaWrapper>) = viewModelScope.launch {
withContext(Dispatchers.IO) {
groups.forEach { group ->
if (group is VideoGroup) group.destroy()
}
}
}
fun ungroup(group: VideoGroup) = viewModelScope.launch {
withContext(Dispatchers.IO) {
group.destroy()
}
}
suspend fun createGroup(medias: List<MediaWrapper>): VideoGroup? {
if (medias.size < 2) return null
return withContext(Dispatchers.IO) {
val newGroup = medialibrary.createVideoGroup(medias.map { it.id }.toLongArray())
if (newGroup.title.isNullOrBlank()) {
newGroup.rename(medias[0].title)
}
newGroup
}
}
suspend fun groupSimilar(media: MediaWrapper) = withContext(Dispatchers.IO) {
medialibrary.regroup(media.id)
}
}
enum class VideoGroupingType {
NONE, FOLDER, NAME
}
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
internal fun VideoGridFragment.getViewModel(type: VideoGroupingType = VideoGroupingType.NONE, folder: Folder?, group: VideoGroup?) = ViewModelProviders.of(requireActivity(), VideosViewModel.Factory(requireContext(), type, folder, group)).get(VideosViewModel::class.java)
| gpl-2.0 | b9bda41d5e0777e3bf1ed350e70dd1dc | 39.444444 | 270 | 0.662889 | 4.829187 | false | false | false | false |
SalomonBrys/Kotson | src/test/kotlin/com/github/salomonbrys/kotson/RWRegistrationSpecs.kt | 1 | 3927 | package com.github.salomonbrys.kotson
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonSyntaxException
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class RWRegistrationSpecs : Spek({
given("a non-generic stream type adapter") {
val adapter = typeAdapter<Person> {
write { beginArray().value(it.name).value(it.age).endArray() }
read { beginArray() ; val p = Person(nextString(), nextInt()) ; endArray() ; p }
}
val gson = GsonBuilder()
.registerTypeAdapter<Person>(adapter)
.create()
on("serialization") {
it("should serialize accordingly") {
val json = gson.toJsonTree(Person("Salomon", 29))
assertTrue(json is JsonArray)
assertEquals("Salomon", json[0].string)
assertEquals(29, json[1].int)
}
}
on("deserialization") {
it("should deserialize accordingly") {
val person = gson.fromJson<Person>("[\"Salomon\", 29]")
assertEquals(Person("Salomon", 29), person)
}
}
}
given("a specialized stream type adapter") {
val gson = GsonBuilder()
.registerTypeAdapter<GenericPerson<Int>> {
write { beginArray().value(it.name).value(it.info).endArray() }
read { beginArray() ; val p = GenericPerson(nextString(), nextInt()) ; endArray() ; p }
}
.create()
on("serializattion") {
it("should serialize specific type accordingly") {
val json = gson.typedToJsonTree(GenericPerson("Salomon", 29))
assertTrue(json is JsonArray)
assertEquals("Salomon", json[0].string)
assertEquals(29, json[1].int)
}
it("should not serialize differently parameterized type accordingly") {
val json = gson.typedToJsonTree(GenericPerson("Salomon", "Brys"))
assertTrue(json is JsonObject)
}
}
on("deserialization") {
it("should deserialize specific type accordingly") {
val person = gson.fromJson<GenericPerson<Int>>("[\"Salomon\", 29]")
assertEquals(GenericPerson("Salomon", 29), person)
}
it("should not deserialize differently parameterized type accordingly") {
assertFailsWith<JsonSyntaxException> { gson.fromJson<GenericPerson<String>>("[\"Salomon\", \"Brys\"]") }
}
}
}
given ("a bad type adapter") {
on("definition of both serialize and read") {
it("should throw an exception") {
assertFailsWith<IllegalArgumentException> {
GsonBuilder()
.registerTypeAdapter<Person> {
serialize { jsonArray(it.src.name, it.src.age) }
read { beginArray() ; val p = Person(nextString(), nextInt()) ; endArray() ; p }
}
.create()
}
}
}
on("definition of only write") {
it("should throw an exception") {
assertFailsWith<IllegalArgumentException> {
GsonBuilder()
.registerTypeAdapter<Person> {
write { beginArray().value(it.name).value(it.age).endArray() }
}
.create()
}
}
}
}
})
| mit | 0e374e15a516804fe0467bec24e09469 | 33.147826 | 120 | 0.530685 | 5.242991 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/Main.kt | 1 | 8781 | /*
* 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.videobridge
import org.eclipse.jetty.servlet.ServletHolder
import org.glassfish.jersey.servlet.ServletContainer
import org.ice4j.ice.harvest.MappingCandidateHarvesters
import org.jitsi.cmd.CmdLine
import org.jitsi.config.JitsiConfig
import org.jitsi.metaconfig.MetaconfigLogger
import org.jitsi.metaconfig.MetaconfigSettings
import org.jitsi.rest.JettyBundleActivatorConfig
import org.jitsi.rest.createServer
import org.jitsi.rest.enableCors
import org.jitsi.rest.isEnabled
import org.jitsi.rest.servletContextHandler
import org.jitsi.shutdown.ShutdownServiceImpl
import org.jitsi.stats.media.Utils
import org.jitsi.utils.logging2.LoggerImpl
import org.jitsi.utils.queue.PacketQueue
import org.jitsi.videobridge.health.JvbHealthChecker
import org.jitsi.videobridge.ice.Harvesters
import org.jitsi.videobridge.rest.root.Application
import org.jitsi.videobridge.stats.MucStatsTransport
import org.jitsi.videobridge.stats.StatsCollector
import org.jitsi.videobridge.stats.VideobridgeStatistics
import org.jitsi.videobridge.stats.callstats.CallstatsService
import org.jitsi.videobridge.util.TaskPools
import org.jitsi.videobridge.version.JvbVersionService
import org.jitsi.videobridge.websocket.ColibriWebSocketService
import org.jitsi.videobridge.xmpp.XmppConnection
import org.jitsi.videobridge.xmpp.config.XmppClientConnectionConfig
import org.jxmpp.stringprep.XmppStringPrepUtil
import kotlin.concurrent.thread
import org.jitsi.videobridge.octo.singleton as octoRelayService
import org.jitsi.videobridge.websocket.singleton as webSocketServiceSingleton
fun main(args: Array<String>) {
val cmdLine = CmdLine().apply { parse(args) }
val logger = LoggerImpl("org.jitsi.videobridge.Main")
setupMetaconfigLogger()
setSystemPropertyDefaults()
// Some of our dependencies bring in slf4j, which means Jetty will default to using
// slf4j as its logging backend. The version of slf4j brought in, however, is too old
// for Jetty so it throws errors. We use java.util.logging so tell Jetty to use that
// as its logging backend.
// TODO: Instead of setting this here, we should integrate it with the infra/debian scripts
// to be passed.
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog")
// Before initializing the application programming interfaces (APIs) of
// Jitsi Videobridge, set any System properties which they use and which
// may be specified by the command-line arguments.
cmdLine.getOptionValue("--apis")?.let {
System.setProperty(
Videobridge.REST_API_PNAME,
it.contains(Videobridge.REST_API).toString()
)
}
// Reload the Typesafe config used by ice4j, because the original was initialized before the new system
// properties were set.
JitsiConfig.reloadNewConfig()
val versionService = JvbVersionService().also {
logger.info("Starting jitsi-videobridge version ${it.currentVersion}")
}
startIce4j()
XmppStringPrepUtil.setMaxCacheSizes(XmppClientConnectionConfig.jidCacheSize)
PacketQueue.setEnableStatisticsDefault(true)
val xmppConnection = XmppConnection().apply { start() }
val shutdownService = ShutdownServiceImpl()
val videobridge = Videobridge(xmppConnection, shutdownService, versionService.currentVersion).apply { start() }
val healthChecker = JvbHealthChecker().apply { start() }
val octoRelayService = octoRelayService().get()?.apply { start() }
val statsCollector = StatsCollector(VideobridgeStatistics(videobridge, octoRelayService, xmppConnection)).apply {
start()
addTransport(MucStatsTransport(xmppConnection), xmppConnection.config.presenceInterval.toMillis())
}
val callstats = if (CallstatsService.config.enabled) {
CallstatsService(videobridge.version).apply {
start {
statsTransport?.let { statsTransport ->
statsCollector.addTransport(statsTransport, CallstatsService.config.interval.toMillis())
} ?: throw IllegalStateException("Stats transport is null after the service is started")
videobridge.addEventHandler(videobridgeEventHandler)
}
}
} else {
logger.info("Not starting CallstatsService, disabled in configuration.")
null
}
val publicServerConfig = JettyBundleActivatorConfig(
"org.jitsi.videobridge.rest",
"videobridge.http-servers.public"
)
val publicHttpServer = if (publicServerConfig.isEnabled()) {
logger.info("Starting public http server")
val websocketService = ColibriWebSocketService(publicServerConfig.isTls)
webSocketServiceSingleton().setColibriWebSocketService(websocketService)
createServer(publicServerConfig).also {
websocketService.registerServlet(it.servletContextHandler, videobridge)
it.start()
}
} else {
logger.info("Not starting public http server")
null
}
val privateServerConfig = JettyBundleActivatorConfig(
"org.jitsi.videobridge.rest.private",
"videobridge.http-servers.private"
)
val privateHttpServer = if (privateServerConfig.isEnabled()) {
logger.info("Starting private http server")
val restApp = Application(
videobridge,
xmppConnection,
statsCollector,
versionService.currentVersion,
healthChecker
)
createServer(privateServerConfig).also {
it.servletContextHandler.addServlet(
ServletHolder(ServletContainer(restApp)),
"/*"
)
it.servletContextHandler.enableCors()
it.start()
}
} else {
logger.info("Not starting private http server")
null
}
// Block here until the bridge shuts down
shutdownService.waitForShutdown()
logger.info("Bridge shutting down")
healthChecker.stop()
octoRelayService?.stop()
xmppConnection.stop()
callstats?.let {
videobridge.removeEventHandler(it.videobridgeEventHandler)
it.statsTransport?.let { statsTransport ->
statsCollector.removeTransport(statsTransport)
}
it.stop()
}
statsCollector.stop()
try {
publicHttpServer?.stop()
privateHttpServer?.stop()
} catch (t: Throwable) {
logger.error("Error shutting down http servers", t)
}
videobridge.stop()
stopIce4j()
TaskPools.SCHEDULED_POOL.shutdownNow()
TaskPools.CPU_POOL.shutdownNow()
TaskPools.IO_POOL.shutdownNow()
}
private fun setupMetaconfigLogger() {
val configLogger = LoggerImpl("org.jitsi.config")
MetaconfigSettings.logger = object : MetaconfigLogger {
override fun warn(block: () -> String) = configLogger.warn(block)
override fun error(block: () -> String) = configLogger.error(block)
override fun debug(block: () -> String) = configLogger.debug(block)
}
}
private fun setSystemPropertyDefaults() {
val defaults = getSystemPropertyDefaults()
defaults.forEach { (key, value) ->
if (System.getProperty(key) == null) {
System.setProperty(key, value)
}
}
}
private fun getSystemPropertyDefaults(): Map<String, String> {
val defaults = mutableMapOf<String, String>()
Utils.getCallStatsJavaSDKSystemPropertyDefaults(defaults)
// Make legacy ice4j properties system properties.
val cfg = JitsiConfig.SipCommunicatorProps
val ice4jPropNames = cfg.getPropertyNamesByPrefix("org.ice4j", false)
ice4jPropNames?.forEach { key ->
cfg.getString(key)?.let { value ->
defaults.put(key, value)
}
}
return defaults
}
private fun startIce4j() {
// Start the initialization of the mapping candidate harvesters.
// Asynchronous, because the AWS and STUN harvester may take a long
// time to initialize.
thread(start = true) {
MappingCandidateHarvesters.initialize()
}
}
private fun stopIce4j() {
// Shut down harvesters.
Harvesters.closeStaticConfiguration()
}
| apache-2.0 | c5de6d17c0ac5e3b0a8e277dfb3e1562 | 36.050633 | 117 | 0.713472 | 4.59979 | false | true | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/tracklist/TracksBindingAdapters.kt | 1 | 3370 | package nl.sogeti.android.gpstracker.ng.features.tracklist
import androidx.databinding.BindingAdapter
import android.net.Uri
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import nl.sogeti.android.gpstracker.ng.base.common.postMainThread
import nl.sogeti.android.opengpstrack.ng.features.R
import timber.log.Timber
open class TracksBindingAdapters {
@BindingAdapter("tracks")
fun setTracks(recyclerView: androidx.recyclerview.widget.RecyclerView, tracks: List<Uri>?) {
val viewAdapter: TrackListViewAdapter
if (recyclerView.adapter is TrackListViewAdapter) {
viewAdapter = recyclerView.adapter as TrackListViewAdapter
viewAdapter.updateTracks(tracks ?: emptyList())
} else {
viewAdapter = TrackListViewAdapter(recyclerView.context)
viewAdapter.updateTracks(tracks ?: emptyList())
recyclerView.adapter = viewAdapter
}
}
@BindingAdapter("selected")
fun setTracks(recyclerView: androidx.recyclerview.widget.RecyclerView, track: Uri?) {
val viewAdapter: TrackListViewAdapter
if (recyclerView.adapter is TrackListViewAdapter) {
viewAdapter = recyclerView.adapter as TrackListViewAdapter
viewAdapter.selection = track
} else {
viewAdapter = TrackListViewAdapter(recyclerView.context)
viewAdapter.selection = track
recyclerView.adapter = viewAdapter
}
}
@BindingAdapter("tracksListener")
fun setListener(recyclerView: androidx.recyclerview.widget.RecyclerView, listener: TrackListAdapterListener?) {
val adapter = recyclerView.adapter
if (adapter != null && adapter is TrackListViewAdapter) {
adapter.listener = listener
} else {
Timber.e("Binding listener when missing adapter, are the xml attributes out of order")
}
}
@BindingAdapter("editMode")
fun setEditMode(card: androidx.cardview.widget.CardView, editMode: Boolean) {
val share = card.findViewById<View>(R.id.row_track_share)
val delete = card.findViewById<View>(R.id.row_track_delete)
val edit = card.findViewById<View>(R.id.row_track_edit)
if (editMode) {
if (share.visibility != VISIBLE) {
share.alpha = 0F
edit.alpha = 0F
delete.alpha = 0F
}
share.visibility = VISIBLE
edit.visibility = VISIBLE
delete.visibility = VISIBLE
share.animate().alpha(1.0F)
edit.animate().alpha(1.0F)
delete.animate().alpha(1.0F)
} else if (share.visibility == VISIBLE) {
share.animate().alpha(0.0F)
edit.animate().alpha(0.0F)
delete.animate().alpha(0.0F).withEndAction {
share.visibility = GONE
edit.visibility = GONE
delete.visibility = GONE
}
}
}
@BindingAdapter("focusPosition")
fun setFocusPosition(list: androidx.recyclerview.widget.RecyclerView, position: Int?) {
if (position != null && position > 0) {
postMainThread { list.layoutManager?.scrollToPosition(position) }
}
}
}
| gpl-3.0 | a0def1596521da426a844f2f7c5083b5 | 38.186047 | 115 | 0.650742 | 4.862915 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/AbstractTaskPrompter.kt | 1 | 2728 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.gui
import javafx.application.Platform
import javafx.geometry.Orientation
import javafx.scene.Scene
import javafx.scene.layout.BorderPane
import javafx.scene.layout.FlowPane
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.ParaTask
import uk.co.nickthecoder.paratask.Task
import uk.co.nickthecoder.paratask.parameters.fields.TaskForm
import uk.co.nickthecoder.paratask.util.AutoExit
import uk.co.nickthecoder.paratask.util.findScrollbar
abstract class AbstractTaskPrompter(val task: Task) {
var root = BorderPane()
var taskForm = TaskForm(task)
var stage: Stage? = null
val buttons = FlowPane()
open protected fun close() {
stage?.hide()
}
open fun build() {
taskForm.build()
with(buttons) {
styleClass.add("buttons")
}
with(root) {
styleClass.add("task-prompter")
center = taskForm.scrollPane
bottom = buttons
}
}
fun placeOnStage(stage: Stage) {
build()
this.stage = stage
stage.title = task.taskD.label
val scene = Scene(root)
ParaTask.style(scene)
stage.scene = scene
// Once the stage has been fully created, listen for when the taskForm's scroll bar appears, and
// attempt to resize the stage, so that the scroll bar is no longer needed.
Platform.runLater {
val scrollBar = taskForm.scrollPane.findScrollbar(Orientation.VERTICAL)
scrollBar?.visibleProperty()?.addListener { _, _, newValue ->
if (newValue == true) {
val extra = taskForm.scrollPane.prefHeight(-1.0) - taskForm.scrollPane.height
if (extra > 0 && stage.height < 700) {
stage.sizeToScene()
Platform.runLater {
taskForm.form.requestLayout()
}
}
}
}
}
AutoExit.show(stage)
}
}
| gpl-3.0 | d459fd99ce54668e4608aab8050206d6 | 28.021277 | 104 | 0.644062 | 4.561873 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/matcher/ParameterPathMatcher.kt | 1 | 2864 | package com.fireflysource.net.http.server.impl.matcher
import com.fireflysource.net.http.server.Matcher
import com.fireflysource.net.http.server.Router
import java.util.*
class ParameterPathMatcher : AbstractMatcher<ParameterPathMatcher.ParameterRule>(), Matcher {
companion object {
fun isParameterPath(path: String): Boolean {
val paths = split(path)
return paths.any { it[0] == ':' }
}
fun split(path: String): List<String> {
val paths: MutableList<String> = LinkedList()
var start = 1
val last = path.lastIndex
for (i in 1..last) {
if (path[i] == '/') {
paths.add(path.substring(start, i).trim())
start = i + 1
}
}
if (path[last] != '/') {
paths.add(path.substring(start).trim())
}
return paths
}
}
inner class ParameterRule(val rule: String) {
val paths = split(rule)
fun match(list: List<String>): Map<String, String> {
if (paths.size != list.size) return emptyMap()
val param: MutableMap<String, String> = HashMap()
for (i in list.indices) {
val path = paths[i]
val value = list[i]
if (path[0] != ':') {
if (path != value) {
return emptyMap()
}
} else {
param[path.substring(1)] = value
}
}
return param
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ParameterRule
return rule == other.rule
}
override fun hashCode(): Int {
return rule.hashCode()
}
}
override fun getMatchType(): Matcher.MatchType {
return Matcher.MatchType.PATH
}
override fun add(rule: String, router: Router) {
val parameterRule = ParameterRule(rule)
routersMap.computeIfAbsent(parameterRule) { TreeSet() }.add(router)
}
override fun match(value: String): Matcher.MatchResult? {
if (routersMap.isEmpty()) return null
val routers = TreeSet<Router>()
val parameters = HashMap<Router, Map<String, String>>()
val paths = split(value)
routersMap.forEach { (rule, routerSet) ->
val param = rule.match(paths)
if (param.isNotEmpty()) {
routers.addAll(routerSet)
routerSet.forEach { router -> parameters[router] = param }
}
}
return if (routers.isEmpty()) null else Matcher.MatchResult(routers, parameters, matchType)
}
} | apache-2.0 | 19b3e25372167b4cb82467f3ca813d7b | 29.157895 | 99 | 0.524092 | 4.641815 | false | false | false | false |
SeunAdelekan/Kanary | src/main/com/iyanuadelekan/kanary/app/router/RouteNode.kt | 1 | 2772 | package com.iyanuadelekan.kanary.app.router
import com.iyanuadelekan.kanary.app.RouteList
import com.iyanuadelekan.kanary.app.RouterAction
import com.iyanuadelekan.kanary.app.adapter.component.middleware.MiddlewareAdapter
import com.iyanuadelekan.kanary.app.lifecycle.AppContext
/**
* @author Iyanu Adelekan on 18/11/2018.
*/
internal class RouteNode(val path: String, var action: RouterAction? = null) {
private val children = RouteList()
private var middleware: ArrayList<MiddlewareAdapter> = ArrayList()
/**
* Adds a child node to the current node.
*
* @param routeNode - node to be added.
*/
fun addChild(routeNode: RouteNode) = this.children.add(routeNode)
/**
* Invoked to check if a route node has a specified child node.
*
* @param path - path to be matched.
* @return [Boolean] - true if child exists and false otherwise.
*/
fun hasChild(path: String): Boolean {
children.forEach {
if (it.path == path) {
return true
}
}
return false
}
/**
* Gets a child node matching a specific path.
*
* @params path - path to be matched.
* @return [RouteNode] - node if one exists and null otherwise.
*/
fun getChild(path: String): RouteNode? {
children.forEach {
if (it.path == path) {
return it
}
}
return null
}
/**
* Gets children of given node.
*
* @return [RouteList] - children.
*/
fun getChildren(): RouteList = this.children
/**
* Returns number of child nodes.
*
* @return [Int] - number of child nodes.
*/
fun getChildCount(): Int = children.size
/**
* Invoked to add a collection of middleware to route node.
*
* @param middleware - middleware to be added.
*/
fun addMiddleware(middleware: List<MiddlewareAdapter>) {
this.middleware.addAll(middleware)
}
fun runMiddleWare(ctx: AppContext) {
middleware.forEach { it.run(ctx) }
}
fun executeAction(ctx: AppContext) {
action?.invoke(ctx)
}
/**
* Converts [RouteNode] to its corresponding string representation.
*
* @return [String] - String representation of route node.
*/
override fun toString(): String {
val builder = StringBuilder()
builder.append("$path => [")
if (!children.isEmpty()) {
for (i in 0 until children.size) {
builder.append(children[i])
if (i != children.size - 1) {
builder.append(",")
}
}
}
builder.append("]")
return builder.toString()
}
} | apache-2.0 | 526b7a422afc008e8a867beb9b35c89e | 25.160377 | 82 | 0.580808 | 4.406995 | false | false | false | false |
nemerosa/ontrack | ontrack-it-utils/src/main/java/net/nemerosa/ontrack/it/TimeTestUtils.kt | 1 | 2773 | package net.nemerosa.ontrack.it
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import net.nemerosa.ontrack.common.seconds
import org.slf4j.LoggerFactory
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
/**
* Waits until a given condition is met.
*
* @param message Activity being waited for
* @param initial Initial time to wait
* @param interval Interval to wait between two attemps
* @param timeout Total timeout for the operatiion to complete
* @param ignoreExceptions Set to `true` if exceptions do not abort the wait
* @param check Must return `true` when the wait is over
* @receiver Message to associate with the waiting (name of the task)
*/
@ExperimentalTime
fun waitUntil(
message: String,
initial: Duration? = null,
interval: Duration = 5.seconds,
timeout: Duration = 60.seconds,
ignoreExceptions: Boolean = false,
check: () -> Boolean
) {
TimeTestUtils().waitUntil(message, initial, interval, timeout, ignoreExceptions, check)
}
class TimeTestUtils {
private val logger = LoggerFactory.getLogger(TimeTestUtils::class.java)
@ExperimentalTime
fun waitUntil(
message: String,
initial: Duration?,
interval: Duration,
timeout: Duration,
ignoreExceptions: Boolean,
check: () -> Boolean
) {
runBlocking {
val timeoutMs = timeout.inWholeMilliseconds
val start = System.currentTimeMillis()
// Logging
log(message, "Starting...")
// Waiting some initial time
if (initial != null) {
log(message, "Initial delay ($initial")
delay(initial.inWholeMilliseconds)
}
// Checks
while ((System.currentTimeMillis() - start) < timeoutMs) {
// Check
log(message, "Checking...")
val ok = try {
check()
} catch (ex: Exception) {
if (ignoreExceptions) {
false // We don't exit because of the exception, but we still need to carry on
} else {
throw ex
}
}
if (ok) {
// OK
log(message, "OK.")
return@runBlocking
} else {
log(message, "Interval delay ($interval")
delay(interval.inWholeMilliseconds)
}
}
// Timeout
throw IllegalStateException("$message: Timeout exceeded after $timeout")
}
}
private fun log(message: String, info: String) {
logger.info("$message: $info")
}
}
| mit | fbadd6cf2aa1c06c081831af076890d3 | 31.244186 | 102 | 0.570862 | 5.060219 | false | false | false | false |
SrirangaDigital/shankara-android | app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/books/ttssettings/bindings/SettingsRVAdapter.kt | 1 | 1191 | package co.ideaportal.srirangadigital.shankaraandroid.books.ttssettings.bindings
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import co.ideaportal.srirangadigital.shankaraandroid.R
import co.ideaportal.srirangadigital.shankaraandroid.books.ttssettings.model.Settings
import co.ideaportal.srirangadigital.shankaraandroid.util.AdapterClickListener
class SettingsRVAdapter(private val context : Context, private val items: ArrayList<Settings>, private val mAdapterClickListener: AdapterClickListener) : RecyclerView.Adapter<SettingsViewHolder>() {
var settingsList: MutableList<Settings> = items
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder =
SettingsViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_settings, parent, false), mAdapterClickListener)
override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) {
val item = getItemAtPos(position)
}
override fun getItemCount(): Int = settingsList.size
private fun getItemAtPos(pos: Int): Settings = settingsList[pos]
}
| gpl-2.0 | 10414d889b4987fcaa24328939be0d39 | 43.111111 | 198 | 0.811083 | 5.004202 | false | false | false | false |
Dominick1993/GD-lunch-Brno | src/main/kotlin/gdlunch/parser/BistroFranzParser.kt | 1 | 1298 | package gdlunch.parser
import com.labuda.gdlunch.parser.AbstractRestaurantWebParser
import com.labuda.gdlunch.parser.DailyParser
import com.labuda.gdlunch.repository.entity.DailyMenu
import com.labuda.gdlunch.repository.entity.MenuItem
import com.labuda.gdlunch.repository.entity.Restaurant
import mu.KotlinLogging
import org.jsoup.Jsoup
import java.time.LocalDate
/**
* Parses daily menu from Bistro Franz restaurant
*/
class BistroFranzParser(restaurant: Restaurant) : AbstractRestaurantWebParser(restaurant), DailyParser {
val logger = KotlinLogging.logger { }
override fun parse(): DailyMenu {
val result = DailyMenu()
result.restaurant = restaurant
result.date = LocalDate.now()
val document = Jsoup.connect(restaurant.parserUrl).get()
document.select(".obedmenu .tabnab.polevka .radj .mnam").forEach {
result.menu.add(MenuItem(it.ownText(), 0f))
}
document.select(".obedmenu .tabnab.jidlo .radj").forEach {
result.menu.add(
MenuItem(
it.selectFirst(".mnam").ownText(),
parsePrice(it.selectFirst(".cena").ownText()
)
)
)
}
return result
}
}
| gpl-3.0 | aa016bcc33e78e69a965da7ace424e1e | 31.45 | 104 | 0.638675 | 4.255738 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Compose/src/main/kotlin/com/groupdocs/ui/result/ResultViewModel.kt | 1 | 6267 | package com.groupdocs.ui.result
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import com.groupdocs.comparison.Comparer
import com.groupdocs.comparison.Document
import com.groupdocs.comparison.license.License
import com.groupdocs.comparison.options.CompareOptions
import com.groupdocs.comparison.options.PreviewOptions
import com.groupdocs.comparison.options.enums.PreviewFormats
import com.groupdocs.comparison.result.FileType
import com.groupdocs.ui.common.NavigationException
import com.groupdocs.ui.common.Screen
import com.groupdocs.ui.common.Settings
import kotlinx.coroutines.*
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JFileChooser
import javax.swing.filechooser.FileNameExtensionFilter
import kotlin.io.path.nameWithoutExtension
class ResultViewModel(private val screen: MutableState<Screen>) {
private val _state: MutableState<ResultState> = mutableStateOf(ResultState())
val state: State<ResultState> = _state
private val tempDir: Path
init {
var resultPath = ""
val sourcePath: String
val targetPath: String
val targetName: String
tempDir = Paths.get(System.getenv("TMP"))
if (screen.value is Screen.Result) {
sourcePath = (screen.value as Screen.Result).source
targetPath = (screen.value as Screen.Result).target
targetName = Paths.get(targetPath).fileName.nameWithoutExtension
} else throw NavigationException()
//
val licensePath = Settings.instance.licensePath
if (licensePath == null || Files.exists(Paths.get(licensePath))) {
CoroutineScope(Dispatchers.IO).launch {
licensePath?.let { License().setLicense(it) }
println("License is ${if (License.isValidLicense()) "valid" else "invalid"}")
Comparer(sourcePath).use { comparison ->
comparison.add(targetPath)
try {
val fileType = FileType.fromFileNameOrExtension(targetPath)
resultPath = comparison.compare(
tempDir.resolve("Result_$targetName${fileType.extension}").toString(),
CompareOptions().apply {
detalisationLevel = Settings.instance.detalisationLevel
generateSummaryPage = Settings.instance.generateSummaryPage
}
).toString()
} catch (e: Exception) {
_state.value = _state.value.copy(
errorMessage = "Converting error: ${e.message}",
isInProgress = false
)
return@use
}
}
_state.value = _state.value.copy(
sourcePath = sourcePath,
targetPath = targetPath,
resultPath = resultPath
)
displayResult(resultPath)
}
} else {
_state.value = _state.value.copy(
errorMessage = "License not found: '$licensePath'",
isInProgress = false
)
}
}
private fun displayResult(resultPath: String) {
println("Comparison result temporary saved to ${state.value.resultPath}")
val pageList = mutableListOf<String>()
CoroutineScope(Dispatchers.IO).launch {
try {
val result = Document(resultPath)
result.generatePreview(PreviewOptions {
val pagePath = tempDir.resolve("gd_${System.currentTimeMillis()}_page_$it.png")
pageList.add(pagePath.toString())
FileOutputStream(pagePath.toFile())
}.apply {
previewFormat = PreviewFormats.PNG
})
} catch (e: Exception) {
_state.value = _state.value.copy(
errorMessage = "Preview generating error: ${e.message}",
isInProgress = false
)
return@launch
}
_state.value = _state.value.copy(
isInProgress = false,
pageList = pageList
)
}
}
fun onDownload() {
val resultName = state.value.resultName
val extension =
if (resultName.contains('.'))
resultName.substring(resultName.lastIndexOf('.') + 1)
else null
JFileChooser().apply {
extension?.let {
fileFilter = FileNameExtensionFilter("Pdf file", extension)
}
selectedFile = File(resultName)
if (showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
val resultPath = state.value.resultPath
val downloadPath = selectedFile.path
CoroutineScope(Dispatchers.IO).launch {
FileUtils.copyFile(File(resultPath), File(downloadPath))
withContext(Dispatchers.Main) {
_state.value = _state.value.copy(
infoMessage = "File was saved!"
)
delay(2500L)
_state.value = _state.value.copy(
infoMessage = null
)
}
}
}
}
}
fun onDispose() {
print("Deleting temporary files...")
CoroutineScope(Dispatchers.IO).launch {
state.value.pageList.toMutableList().apply {
add(state.value.resultPath)
forEach { path ->
try {
FileUtils.delete(File(path))
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
println("Finished")
}
} | mit | c5305bdd7bae0677b98db8e0fa831437 | 38.175 | 99 | 0.549386 | 5.497368 | false | false | false | false |
pr0ves/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/tasks/DropUselessItems.kt | 2 | 4784 | /**
* 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.tasks
import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId
import POGOProtos.Networking.Responses.RecycleInventoryItemResponseOuterClass
import ink.abb.pogo.api.request.RecycleInventoryItem
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.Task
import ink.abb.pogo.scraper.util.Log
import java.util.concurrent.atomic.AtomicInteger
class DropUselessItems : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
// ignores the items that have -1
val itemsToDrop = settings.uselessItems.filter { it.value != -1 }
if (settings.groupItemsByType) dropGroupedItems(ctx, itemsToDrop, settings) else dropItems(ctx, itemsToDrop, settings)
}
/**
* Drops the excess items by group
*/
fun dropGroupedItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) {
// map with what items to keep in what amounts
val itemsToDrop = mutableMapOf<ItemId, Int>()
// adds not groupable items on map
itemsToDrop.putAll(items.filter { singlesFilter.contains(it.key) })
// groups items
val groupedItems = groupItems(items)
// adds new items to the map
val itemBag = ctx.api.inventory.items
groupedItems.forEach groupedItems@ {
var groupCount = 0
it.key.forEach { groupCount += itemBag.getOrPut(it, { AtomicInteger(0) }).get() }
var neededToDrop = groupCount - it.value
if (neededToDrop > 0)
it.key.forEach {
val item = itemBag.getOrPut(it, { AtomicInteger(0) })
if (neededToDrop <= item.get()) {
itemsToDrop.put(it, item.get() - neededToDrop)
return@groupedItems
} else {
neededToDrop -= item.get()
itemsToDrop.put(it, 0)
}
}
}
// drops excess items
dropItems(ctx, itemsToDrop, settings)
}
/**
* Groups the items using the groupFilters
* Each group contains the list of itemIds of the group and sum of all its number
*/
fun groupItems(items: Map<ItemId, Int>): Map<Array<ItemId>, Int> {
val groupedItems = mutableMapOf<Array<ItemId>, Int>()
groupFilters.forEach {
val filter = it
val filteredItems = items.filter { filter.contains(it.key) }
groupedItems.put(filteredItems.keys.toTypedArray(), filteredItems.values.sum())
}
return groupedItems
}
// Items that can be grouped
val groupFilters = arrayOf(
arrayOf(ItemId.ITEM_REVIVE, ItemId.ITEM_MAX_REVIVE),
arrayOf(ItemId.ITEM_POTION, ItemId.ITEM_SUPER_POTION, ItemId.ITEM_HYPER_POTION, ItemId.ITEM_MAX_POTION),
arrayOf(ItemId.ITEM_POKE_BALL, ItemId.ITEM_GREAT_BALL, ItemId.ITEM_ULTRA_BALL, ItemId.ITEM_MASTER_BALL)
)
// Items that cant be grouped
val singlesFilter = arrayOf(ItemId.ITEM_RAZZ_BERRY, ItemId.ITEM_LUCKY_EGG, ItemId.ITEM_INCENSE_ORDINARY, ItemId.ITEM_TROY_DISK)
/**
* Drops the excess items by item
*/
fun dropItems(ctx: Context, items: Map<ItemId, Int>, settings: Settings) {
val itemBag = ctx.api.inventory.items
items.forEach {
val item = itemBag.getOrPut(it.key, { AtomicInteger(0) })
val count = item.get() - it.value
if (count > 0) {
val dropItem = it.key
val drop = RecycleInventoryItem().withCount(count).withItemId(dropItem)
val result = ctx.api.queueRequest(drop).toBlocking().first().response
if (result.result == RecycleInventoryItemResponseOuterClass.RecycleInventoryItemResponse.Result.SUCCESS) {
ctx.itemStats.second.getAndAdd(count)
Log.yellow("Dropped ${count}x ${dropItem.name}")
ctx.server.sendProfile()
} else {
Log.red("Failed to drop ${count}x ${dropItem.name}: $result")
}
}
if (settings.itemDropDelay != (-1).toLong()) {
val itemDropDelay = settings.itemDropDelay / 2 + (Math.random() * settings.itemDropDelay).toLong()
Thread.sleep(itemDropDelay)
}
}
}
}
| gpl-3.0 | 1b011c1080154a57a23512493459d67c | 42.099099 | 131 | 0.621028 | 4.397059 | false | false | false | false |
pyamsoft/pasterino | app/src/main/java/com/pyamsoft/pasterino/main/MainAppBar.kt | 1 | 2090 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pasterino.main
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material.AppBarDefaults
import androidx.compose.material.MaterialTheme
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.graphics.Color
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.statusBarsHeight
import com.pyamsoft.pasterino.R
@Composable
@JvmOverloads
internal fun MainAppBar(
onHeightMeasured: (height: Int) -> Unit,
modifier: Modifier = Modifier,
) {
Surface(
modifier = modifier,
color = MaterialTheme.colors.primary,
contentColor = Color.White,
elevation = AppBarDefaults.TopAppBarElevation,
) {
Column {
Box(modifier = Modifier.statusBarsHeight())
TopAppBar(
modifier = Modifier.onSizeChanged { onHeightMeasured(it.height) },
elevation = 0.dp,
backgroundColor = MaterialTheme.colors.primary,
title = { Text(text = stringResource(R.string.app_name)) },
)
}
}
}
@Preview
@Composable
private fun PreviewMainAppBar() {
MainAppBar(
onHeightMeasured = {},
)
}
| apache-2.0 | 46806f08ab58fbce443803e9be284c50 | 30.666667 | 76 | 0.750239 | 4.239351 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning06File.kt | 1 | 1463 | package org.pixelndice.table.pixelclient.connection.lobby.client
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ds.File
import org.pixelndice.table.pixelprotocol.Protobuf
import java.io.FileOutputStream
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
private val logger = LogManager.getLogger(StateRunning06File::class.java)
class StateRunning06File: State {
private val tmpPath: Path = FileSystems.getDefault().getPath("tmp")
init {
try{
Files.createDirectories(tmpPath)
}catch (e: FileAlreadyExistsException){
logger.trace("tmp directory already exists. It is all ok, nothing to do")
}
}
override fun process(ctx: Context) {
val packet = ctx.channel.packet
if( packet != null ){
if( packet.payloadCase == Protobuf.Packet.PayloadCase.FILE){
val path = tmpPath.resolve(packet.file.name)
val out = FileOutputStream(path.toFile())
out.write(packet.file.data.toByteArray())
out.close()
File.addFile(path)
path.toFile().delete()
logger.debug("Received file ${packet.file.name}")
}else{
logger.error("Expecting ShareFile, instead received: $packet. IP: ${ctx.channel.address}")
}
ctx.state = StateRunning()
}
}
} | bsd-2-clause | f957967d2dd0d323cbdfdb797dfc4c3e | 28.28 | 106 | 0.63363 | 4.433333 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/SettingsActivity.kt | 1 | 18540 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.activity
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.support.annotation.DrawableRes
import android.support.annotation.XmlRes
import android.support.v4.app.Fragment
import android.support.v4.view.ViewCompat
import android.support.v7.app.AlertDialog
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.preference.PreferenceFragmentCompat.OnPreferenceStartFragmentCallback
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import kotlinx.android.synthetic.main.activity_settings.*
import org.mariotaku.chameleon.Chameleon
import org.mariotaku.ktextension.Bundle
import org.mariotaku.ktextension.set
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.*
import de.vanita5.twittnuker.constant.KeyboardShortcutConstants.ACTION_NAVIGATION_BACK
import de.vanita5.twittnuker.constant.KeyboardShortcutConstants.CONTEXT_TAG_NAVIGATION
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.fragment.*
import de.vanita5.twittnuker.util.DeviceUtils
import de.vanita5.twittnuker.util.KeyboardShortcutsHandler
import de.vanita5.twittnuker.util.ThemeUtils
import java.util.*
class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartFragmentCallback {
var shouldRecreate: Boolean = false
var shouldRestart: Boolean = false
var shouldTerminate: Boolean = false
private lateinit var entriesAdapter: EntriesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
entriesAdapter = EntriesAdapter(this)
if (savedInstanceState != null) {
shouldRecreate = savedInstanceState.getBoolean(EXTRA_SHOULD_RECREATE, shouldRecreate)
shouldRestart = savedInstanceState.getBoolean(EXTRA_SHOULD_RESTART, shouldRestart)
shouldTerminate = savedInstanceState.getBoolean(EXTRA_SHOULD_TERMINATE, shouldTerminate)
} else if (intent.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false)) {
finishNoRestart()
System.exit(0)
return
}
val backgroundOption = currentThemeBackgroundOption
val backgroundAlpha = currentThemeBackgroundAlpha
detailFragmentContainer.setBackgroundColor(ThemeUtils.getColorBackground(this,
backgroundOption, backgroundAlpha))
slidingPane.setShadowResourceLeft(R.drawable.sliding_pane_shadow_left)
slidingPane.setShadowResourceRight(R.drawable.sliding_pane_shadow_right)
slidingPane.sliderFadeColor = 0
ViewCompat.setOnApplyWindowInsetsListener(slidingPane) listener@ { view, insets ->
onApplyWindowInsets(view, insets)
entriesList.setPadding(0, insets.systemWindowInsetTop, 0, insets.systemWindowInsetBottom)
return@listener insets
}
initEntries()
entriesList.adapter = entriesAdapter
entriesList.choiceMode = AbsListView.CHOICE_MODE_SINGLE
entriesList.onItemClickListener = this
//Twittnuker - Settings pane opened
slidingPane.openPane()
if (savedInstanceState == null) {
val initialTag = intent.data?.authority
var initialItem = -1
var firstEntry = -1
for (i in 0 until entriesAdapter.count) {
val entry = entriesAdapter.getItem(i)
if (entry is PreferenceEntry) {
if (firstEntry == -1) {
firstEntry = i
}
if (initialTag == entry.tag) {
initialItem = i
break
}
}
}
if (initialItem == -1) {
initialItem = firstEntry
}
if (initialItem != -1) {
openDetails(initialItem)
entriesList.setItemChecked(initialItem, true)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_SETTINGS_CHANGED && data != null) {
shouldRecreate = data.getBooleanExtra(EXTRA_SHOULD_RECREATE, false)
shouldRestart = data.getBooleanExtra(EXTRA_SHOULD_RESTART, false)
shouldTerminate = data.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false)
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun finish() {
if (shouldRecreate || shouldRestart) {
val data = Intent()
data.putExtra(EXTRA_SHOULD_RECREATE, shouldRecreate)
data.putExtra(EXTRA_SHOULD_RESTART, shouldRestart)
setResult(RESULT_SETTINGS_CHANGED, data)
}
super.finish()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(EXTRA_SHOULD_RECREATE, shouldRecreate)
outState.putBoolean(EXTRA_SHOULD_RESTART, shouldRestart)
}
override fun handleKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean {
val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState)
if (ACTION_NAVIGATION_BACK == action) {
onBackPressed()
return true
}
return super.handleKeyboardShortcutSingle(handler, keyCode, event, metaState)
}
override fun isKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean {
val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState)
return ACTION_NAVIGATION_BACK == action
}
override fun handleKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int, repeatCount: Int, event: KeyEvent, metaState: Int): Boolean {
return super.handleKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState)
}
override fun onSupportNavigateUp(): Boolean {
if (notifyUnsavedChange()) {
return true
}
return super.onSupportNavigateUp()
}
override fun onBackPressed() {
if (notifyUnsavedChange()) return
super.onBackPressed()
}
override fun onPreferenceStartFragment(fragment: PreferenceFragmentCompat, preference: Preference): Boolean {
val fm = supportFragmentManager
val ft = fm.beginTransaction()
val f = Fragment.instantiate(this, preference.fragment, preference.extras)
ft.replace(R.id.detailFragmentContainer, f)
ft.addToBackStack(preference.title.toString())
ft.commit()
return true
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
openDetails(position)
}
private fun finishNoRestart() {
super.finish()
}
private val isTopSettings: Boolean = true
private fun initEntries() {
entriesAdapter.addHeader(getString(R.string.appearance))
entriesAdapter.addPreference("theme", R.drawable.ic_action_color_palette, getString(R.string.theme),
R.xml.preferences_theme)
entriesAdapter.addPreference("cards", R.drawable.ic_action_card, getString(R.string.cards),
R.xml.preferences_cards)
if (DeviceUtils.isDeviceTablet(this)) {
entriesAdapter.addPreference("tablet_mode", R.drawable.ic_action_tablet, getString(R.string.preference_title_tablet_mode),
R.xml.preferences_tablet_mode)
}
entriesAdapter.addHeader(getString(R.string.function))
entriesAdapter.addPreference("tabs", R.drawable.ic_action_tab, getString(R.string.tabs),
CustomTabsFragment::class.java)
entriesAdapter.addPreference("refresh", R.drawable.ic_action_refresh, getString(R.string.action_refresh),
R.xml.preferences_refresh)
entriesAdapter.addPreference("streaming", R.drawable.ic_action_streaming, getString(R.string.settings_streaming),
R.xml.preferences_streaming)
entriesAdapter.addPreference("notifications", R.drawable.ic_action_notification, getString(R.string.settings_notifications),
R.xml.preferences_notifications)
entriesAdapter.addPreference("network", R.drawable.ic_action_web, getString(R.string.network),
R.xml.preferences_network)
entriesAdapter.addPreference("compose", R.drawable.ic_action_status_compose, getString(R.string.action_compose),
R.xml.preferences_compose)
entriesAdapter.addPreference("content", R.drawable.ic_action_twittnuker_square, getString(R.string.content),
R.xml.preferences_content)
entriesAdapter.addPreference("storage", R.drawable.ic_action_storage, getString(R.string.preference_title_storage),
R.xml.preferences_storage)
entriesAdapter.addPreference("other", R.drawable.ic_action_more_horizontal, getString(R.string.other_settings),
R.xml.preferences_other)
entriesAdapter.addHeader(getString(R.string.title_about))
entriesAdapter.addPreference("about", R.drawable.ic_action_info, getString(R.string.title_about),
R.xml.preferences_about)
val browserArgs = Bundle()
browserArgs.putString(EXTRA_URI, "file:///android_asset/gpl-3.0-standalone.html")
entriesAdapter.addPreference("license", R.drawable.ic_action_open_source, getString(R.string.title_open_source_license),
BrowserFragment::class.java, browserArgs)
}
private fun openDetails(position: Int) {
if (isFinishing) return
val entry = entriesAdapter.getItem(position) as? PreferenceEntry ?: return
val fm = supportFragmentManager
fm.popBackStackImmediate(null, 0)
val ft = fm.beginTransaction()
if (entry.preference != 0) {
val args = Bundle()
args.putInt(EXTRA_RESID, entry.preference)
val f = Fragment.instantiate(this, SettingsDetailsFragment::class.java.name,
args)
ft.replace(R.id.detailFragmentContainer, f)
} else if (entry.fragment != null) {
ft.replace(R.id.detailFragmentContainer, Fragment.instantiate(this, entry.fragment,
entry.args))
}
ft.setBreadCrumbTitle(entry.title)
ft.commit()
//KEEP disable closing pane
//slidingPane.closePane()
}
private fun notifyUnsavedChange(): Boolean {
if (isTopSettings && (shouldRecreate || shouldRestart || shouldTerminate)) {
executeAfterFragmentResumed {
if (it.isFinishing) return@executeAfterFragmentResumed
it as SettingsActivity
val df = RestartConfirmDialogFragment()
df.arguments = Bundle {
this[EXTRA_SHOULD_RECREATE] = it.shouldRecreate
this[EXTRA_SHOULD_RESTART] = it.shouldRestart
this[EXTRA_SHOULD_TERMINATE] = it.shouldTerminate
}
df.show(it.supportFragmentManager, "restart_confirm")
}
return true
}
return false
}
internal class EntriesAdapter(context: Context) : BaseAdapter() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private val entries: MutableList<Entry> = ArrayList()
fun addPreference(tag: String, @DrawableRes icon: Int, title: String, @XmlRes preference: Int) {
entries.add(PreferenceEntry(tag, icon, title, preference, null, null))
notifyDataSetChanged()
}
fun addPreference(tag: String, @DrawableRes icon: Int, title: String, cls: Class<out Fragment>,
args: Bundle? = null) {
entries.add(PreferenceEntry(tag, icon, title, 0, cls.name, args))
notifyDataSetChanged()
}
fun addHeader(title: String) {
entries.add(HeaderEntry(title))
notifyDataSetChanged()
}
override fun getCount(): Int {
return entries.size
}
override fun getItem(position: Int): Entry {
return entries[position]
}
override fun getItemId(position: Int): Long {
return getItem(position).hashCode().toLong()
}
override fun isEnabled(position: Int): Boolean {
return getItemViewType(position) == VIEW_TYPE_PREFERENCE_ENTRY
}
override fun getViewTypeCount(): Int {
return 2
}
override fun getItemViewType(position: Int): Int {
val entry = getItem(position)
if (entry is PreferenceEntry) {
return VIEW_TYPE_PREFERENCE_ENTRY
} else if (entry is HeaderEntry) {
return VIEW_TYPE_HEADER_ENTRY
}
throw UnsupportedOperationException()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val viewType = getItemViewType(position)
val entry = getItem(position)
val view: View = convertView ?: let {
when (viewType) {
VIEW_TYPE_PREFERENCE_ENTRY -> {
return@let inflater.inflate(R.layout.list_item_preference_header_item, parent, false)
}
VIEW_TYPE_HEADER_ENTRY -> {
return@let inflater.inflate(R.layout.list_item_preference_header_category, parent, false)
}
else -> {
throw UnsupportedOperationException()
}
}
}
entry.bind(view)
return view
}
companion object {
val VIEW_TYPE_PREFERENCE_ENTRY = 0
val VIEW_TYPE_HEADER_ENTRY = 1
}
}
internal abstract class Entry {
abstract fun bind(view: View)
}
internal class PreferenceEntry(
val tag: String,
val icon: Int,
val title: String,
val preference: Int,
val fragment: String?,
val args: Bundle?
) : Entry() {
override fun bind(view: View) {
view.findViewById<ImageView>(android.R.id.icon).setImageResource(icon)
view.findViewById<TextView>(android.R.id.title).text = title
}
}
internal class HeaderEntry(private val title: String) : Entry() {
override fun bind(view: View) {
val theme = Chameleon.getOverrideTheme(view.context, view.context)
val textView: TextView = view.findViewById(android.R.id.title)
textView.setTextColor(ThemeUtils.getOptimalAccentColor(theme.colorAccent,
theme.colorForeground))
textView.text = title
}
}
class RestartConfirmDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
if (arguments.getBoolean(EXTRA_SHOULD_TERMINATE)) {
builder.setMessage(R.string.app_terminate_confirm)
builder.setNegativeButton(R.string.action_dont_terminate, this)
} else {
builder.setMessage(R.string.app_restart_confirm)
builder.setNegativeButton(R.string.action_dont_restart, this)
}
builder.setPositiveButton(android.R.string.ok, this)
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
override fun onClick(dialog: DialogInterface, which: Int) {
val activity = activity as SettingsActivity
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
if (arguments.getBoolean(EXTRA_SHOULD_TERMINATE)) {
val intent = Intent(context, SettingsActivity::class.java)
intent.putExtra(EXTRA_SHOULD_TERMINATE, true)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
activity.startActivity(intent)
} else {
activity.finish()
}
}
DialogInterface.BUTTON_NEGATIVE -> {
activity.finishNoRestart()
}
}
}
}
companion object {
private val RESULT_SETTINGS_CHANGED = 10
fun setShouldRecreate(activity: Activity) {
if (activity !is SettingsActivity) return
activity.shouldRecreate = true
}
fun setShouldRestart(activity: Activity) {
if (activity !is SettingsActivity) return
activity.shouldRestart = true
}
fun setShouldTerminate(activity: Activity) {
if (activity !is SettingsActivity) return
activity.shouldTerminate = true
}
}
} | gpl-3.0 | ef4ff164ee3a3490ddd7379213857447 | 39.571116 | 156 | 0.643528 | 4.971842 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/UserFavoritesLoader.kt | 1 | 4194 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.statuses
import android.content.Context
import android.support.annotation.WorkerThread
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.Mastodon
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.microblog.library.twitter.model.ResponseList
import de.vanita5.microblog.library.twitter.model.Status
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.annotation.FilterScope
import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
import de.vanita5.twittnuker.util.database.ContentFiltersUtils
class UserFavoritesLoader(
context: Context,
accountKey: UserKey?,
private val userKey: UserKey?,
private val screenName: String?,
data: List<ParcelableStatus>?,
savedStatusesArgs: Array<String>?,
tabPosition: Int,
fromUser: Boolean,
loadingMore: Boolean
) : AbsRequestStatusesLoader(context, accountKey, data, savedStatusesArgs, tabPosition, fromUser, loadingMore) {
@Throws(MicroBlogException::class)
override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> {
when (account.type) {
AccountType.MASTODON -> {
return getMastodonStatuses(account, paging)
}
}
return getMicroBlogStatuses(account, paging).mapMicroBlogToPaginated {
it.toParcelable(account, profileImageSize)
}
}
@WorkerThread
override fun shouldFilterStatus(status: ParcelableStatus): Boolean {
return ContentFiltersUtils.isFiltered(context.contentResolver, status, false,
FilterScope.FAVORITES)
}
private fun getMicroBlogStatuses(account: AccountDetails, paging: Paging): ResponseList<Status> {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
if (userKey != null) {
return microBlog.getFavorites(userKey.id, paging)
} else if (screenName != null) {
return microBlog.getFavoritesByScreenName(screenName, paging)
}
throw MicroBlogException("Null user")
}
private fun getMastodonStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> {
if (userKey != null && userKey != account.key) {
throw MicroBlogException("Only current account favorites is supported")
}
if (screenName != null && !screenName.equals(account.user?.screen_name, ignoreCase = true)) {
throw MicroBlogException("Only current account favorites is supported")
}
val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java)
return mastodon.getFavourites(paging).mapToPaginated { it.toParcelable(account) }
}
} | gpl-3.0 | 9e9489f7ce5b8fd2f735bbcdac081449 | 43.157895 | 112 | 0.739628 | 4.618943 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/announcement/AnnouncementCard.kt | 1 | 1530 | package org.wikipedia.feed.announcement
import android.net.Uri
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.model.CardType
open class AnnouncementCard(private val announcement: Announcement) : Card() {
val isArticlePlacement get() = Announcement.PLACEMENT_ARTICLE == announcement.placement
override fun title(): String {
return announcement.type
}
override fun extract(): String? {
return announcement.text
}
override fun image(): Uri {
return Uri.parse(announcement.imageUrl.orEmpty())
}
override fun type(): CardType {
return CardType.ANNOUNCEMENT
}
override fun dismissHashCode(): Int {
return announcement.id.hashCode()
}
fun imageHeight(): Int {
return announcement.imageHeight.orEmpty().ifEmpty { "0" }.toIntOrNull() ?: 0
}
fun hasAction(): Boolean {
return announcement.hasAction()
}
fun actionTitle(): String {
return announcement.actionTitle()
}
fun actionUri(): Uri {
return Uri.parse(announcement.actionUrl())
}
fun negativeText(): String? {
return announcement.negativeText
}
fun hasFooterCaption(): Boolean {
return announcement.hasFooterCaption()
}
fun footerCaption(): String {
return announcement.footerCaption.orEmpty()
}
fun hasImage(): Boolean {
return announcement.hasImageUrl()
}
fun hasBorder(): Boolean {
return announcement.border == true
}
}
| apache-2.0 | 060bf5ff6baea2230406d48a2cf90552 | 22.181818 | 91 | 0.650327 | 4.903846 | false | false | false | false |
AlexLandau/semlang | kotlin/semlang-module-test-utils/src/main/kotlin/moduleCorpuses.kt | 1 | 1493 | package net.semlang.internal.test
import net.semlang.api.CURRENT_NATIVE_MODULE_VERSION
import net.semlang.api.ValidatedModule
import net.semlang.modules.getDefaultLocalRepository
import net.semlang.modules.parseAndValidateModuleDirectory
import java.io.File
/**
* First argument: Standalone compilable file as a File
* Second argument: List of ValidatedModules to be used as libraries
*/
fun getCompilableFilesWithAssociatedLibraries(): Collection<Array<Any?>> {
val compilerTestsFolder = File("../../semlang-parser-tests/pass")
val corpusFolder = File("../../semlang-corpus/src/main/semlang")
val standardLibraryCorpusFolder = File("../../semlang-library-corpus/src/main/semlang")
val allResults = ArrayList<Array<Any?>>()
val allStandaloneFiles = compilerTestsFolder.listFiles() + corpusFolder.listFiles()
allResults.addAll(allStandaloneFiles.map { file ->
arrayOf<Any?>(file, listOf<Any?>())
})
val standardLibrary: ValidatedModule = validateStandardLibraryModule()
allResults.addAll(standardLibraryCorpusFolder.listFiles().map { file ->
arrayOf<Any?>(file, listOf(standardLibrary))
})
return allResults
}
fun validateStandardLibraryModule(): ValidatedModule {
val standardLibraryFolder = File("../../semlang-library/src/main/semlang")
return parseAndValidateModuleDirectory(standardLibraryFolder, CURRENT_NATIVE_MODULE_VERSION, getDefaultLocalRepository()).assumeSuccess()
}
| apache-2.0 | d296bf734e3eb67ff850f31e9d043925 | 39.472222 | 141 | 0.74347 | 4.551829 | false | true | false | false |
Studium-SG/neurals | src/test/java/training/TrainClassificationInMemory.kt | 1 | 4085 | package training
import org.deeplearning4j.earlystopping.EarlyStoppingConfiguration
import org.deeplearning4j.earlystopping.saver.InMemoryModelSaver
import org.deeplearning4j.earlystopping.scorecalc.DataSetLossCalculator
import org.deeplearning4j.earlystopping.termination.MaxEpochsTerminationCondition
import org.deeplearning4j.earlystopping.termination.MaxTimeIterationTerminationCondition
import org.deeplearning4j.earlystopping.trainer.EarlyStoppingTrainer
import org.deeplearning4j.nn.api.OptimizationAlgorithm
import org.deeplearning4j.nn.conf.NeuralNetConfiguration
import org.deeplearning4j.nn.conf.layers.DenseLayer
import org.deeplearning4j.nn.conf.layers.OutputLayer
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork
import org.deeplearning4j.nn.weights.WeightInit
import org.nd4j.linalg.activations.Activation
import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize
import org.nd4j.linalg.dataset.api.preprocessor.serializer.NormalizerSerializer
import org.nd4j.linalg.lossfunctions.LossFunctions
import resource
import sg.studium.neurals.dataset.InMemoryDataSetIterator
import sg.studium.neurals.dataset.csvToXY
import sg.studium.neurals.model.Dl4jModel
import java.io.FileOutputStream
import java.util.concurrent.TimeUnit
/**
* Speed: 14199 epochs in 2 minutes on T460p I7 nd4j-native
* Score: 0.7069 @ epoch 14198
*/
class TrainClassificationInMemory {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val batchSize = 10
val iterator = InMemoryDataSetIterator(csvToXY(resource("iris.onehot.csv"), "class"), batchSize)
val normalizer = NormalizerStandardize()
normalizer.fit(iterator)
iterator.preProcessor = normalizer
val netConf = NeuralNetConfiguration.Builder()
.seed(123)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(0.001)
.iterations(1)
.list(
DenseLayer.Builder()
.nIn(iterator.inputColumns())
.nOut(iterator.inputColumns())
.weightInit(WeightInit.XAVIER)
.activation(Activation.SIGMOID)
.build(),
OutputLayer.Builder(LossFunctions.LossFunction.XENT)
.nIn(iterator.inputColumns())
.nOut(iterator.totalOutcomes())
.weightInit(WeightInit.XAVIER)
.activation(Activation.SIGMOID)
.build()
)
.pretrain(false)
.backprop(true)
.build()
val net = MultiLayerNetwork(netConf)
val esms = InMemoryModelSaver<MultiLayerNetwork>()
val esc = EarlyStoppingConfiguration.Builder<MultiLayerNetwork>()
// .epochTerminationConditions(MaxEpochsTerminationCondition(1000))
.iterationTerminationConditions(MaxTimeIterationTerminationCondition(2, TimeUnit.MINUTES))
.scoreCalculator(DataSetLossCalculator(iterator, false))
.modelSaver(esms)
.build()
val trainer = EarlyStoppingTrainer(esc, net, iterator)
val result = trainer.fit()
println(result)
val bestModel = result.bestModel
val dl4jModel = Dl4jModel.build(iterator.getAllColumns(), iterator.getlYColumns(), normalizer, bestModel)
dl4jModel.save(FileOutputStream("/tmp/iris.onehot.dl4jmodel.zip"))
val xy = csvToXY(resource("iris.onehot.csv"), "class")
xy.X.forEach { println(dl4jModel.predict(it).toList()) }
// ModelSerializer.writeModel(bestModel, "/tmp/iris.onehot.model.inmemory.zip", true)
}
}
} | gpl-3.0 | df73c0c679216042a68e109492ba9dc6 | 44.910112 | 117 | 0.639657 | 4.766628 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/ConnectedAppList.kt | 1 | 519 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Page
/**
* List of the logged in user's [ConnectedApps][ConnectedApp].
*/
@JsonClass(generateAdapter = true)
data class ConnectedAppList(
@Json(name = "total")
override val total: Int? = null,
@Json(name = "data")
override val data: List<ConnectedApp>? = null,
@Json(name = "filtered_total")
override val filteredTotal: Int? = null
) : Page<ConnectedApp>
| mit | 63f92f5b2b2553bee3f473a17ea3a2a5 | 23.714286 | 62 | 0.710983 | 3.57931 | false | false | false | false |
kittinunf/Fuel | fuel/src/main/kotlin/com/github/kittinunf/fuel/util/Delegates.kt | 1 | 802 | package com.github.kittinunf.fuel.util
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
internal fun <T> readWriteLazy(initializer: () -> T): ReadWriteProperty<Any?, T> = ReadWriteLazyVal(initializer)
private class ReadWriteLazyVal<T>(private val initializer: () -> T) : ReadWriteProperty<Any?, T> {
private var value: Any? = null
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value == null) {
value = (initializer()) ?: throw IllegalStateException("Initializer block of property ${property.name} return null")
}
@Suppress("UNCHECKED_CAST")
return value as T
}
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
} | mit | 422282e60958f4749bac7de9b75bba29 | 33.913043 | 128 | 0.678304 | 4.406593 | false | false | false | false |
AndroidX/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KSDeclarationExt.kt | 3 | 3987 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import androidx.room.compiler.processing.ksp.synthetic.KspSyntheticFileMemberContainer
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.google.devtools.ksp.symbol.KSPropertyAccessor
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.symbol.Modifier
/**
* Finds the class that contains this declaration and throws [IllegalStateException] if it cannot
* be found.
* @see [findEnclosingAncestorClassDeclaration]
*/
internal fun KSDeclaration.requireEnclosingMemberContainer(
env: KspProcessingEnv
): KspMemberContainer {
return checkNotNull(findEnclosingMemberContainer(env)) {
"Cannot find required enclosing type for $this"
}
}
/**
* Find the class that contains this declaration.
*
* Node that this is not necessarily the parent declaration. e.g. when a property is declared in
* a constructor, its containing type is actual two levels up.
*/
@OptIn(KspExperimental::class)
internal fun KSDeclaration.findEnclosingMemberContainer(
env: KspProcessingEnv
): KspMemberContainer? {
val memberContainer = findEnclosingAncestorClassDeclaration()?.let {
env.wrapClassDeclaration(it)
} ?: this.containingFile?.let {
env.wrapKSFile(it)
}
memberContainer?.let {
return it
}
// in compiled files, we may not find it. Try using the binary name
val ownerJvmClassName = when (this) {
is KSPropertyDeclaration -> env.resolver.getOwnerJvmClassName(this)
is KSFunctionDeclaration -> env.resolver.getOwnerJvmClassName(this)
else -> null
} ?: return null
// Binary name of a top level type is its canonical name. So we just load it directly by
// that value
env.findTypeElement(ownerJvmClassName)?.let {
return it
}
// When a top level function/property is compiled, its containing class does not exist in KSP,
// neither the file. So instead, we synthesize one
return KspSyntheticFileMemberContainer(ownerJvmClassName)
}
private fun KSDeclaration.findEnclosingAncestorClassDeclaration(): KSClassDeclaration? {
var parent = parentDeclaration
while (parent != null && parent !is KSClassDeclaration) {
parent = parent.parentDeclaration
}
return parent as? KSClassDeclaration
}
internal fun KSDeclaration.isStatic(): Boolean {
return modifiers.contains(Modifier.JAVA_STATIC) || hasJvmStaticAnnotation() ||
// declarations in the companion object move into the enclosing class as statics.
// https://kotlinlang.org/docs/java-to-kotlin-interop.html#static-fields
this.findEnclosingAncestorClassDeclaration()?.isCompanionObject == true ||
when (this) {
is KSPropertyAccessor -> this.receiver.findEnclosingAncestorClassDeclaration() == null
is KSPropertyDeclaration -> this.findEnclosingAncestorClassDeclaration() == null
is KSFunctionDeclaration -> this.findEnclosingAncestorClassDeclaration() == null
else -> false
}
}
internal fun KSDeclaration.isTransient(): Boolean {
return modifiers.contains(Modifier.JAVA_TRANSIENT) || hasJvmTransientAnnotation()
} | apache-2.0 | e2075a8e447255c8bab5f93a564cd83d | 39.282828 | 98 | 0.743416 | 4.892025 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/formatter/impl/alignment.kt | 4 | 3364 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter.impl
import org.rust.ide.formatter.RsAlignmentStrategy
import org.rust.ide.formatter.blocks.RsFmtBlock
import org.rust.lang.core.psi.RsElementTypes.*
fun RsFmtBlock.getAlignmentStrategy(): RsAlignmentStrategy = when (node.elementType) {
TUPLE_EXPR, VALUE_ARGUMENT_LIST, in SPECIAL_MACRO_ARGS, USE_GROUP ->
RsAlignmentStrategy.wrap()
.alignIf { child, parent, _ ->
// Do not align if we have only one argument as this may lead to
// some quirks when that argument is tuple expr.
// Alignment do not allow "negative indentation" i.e.:
// func((
// happy tuple param
// ))
// would be formatted to:
// func((
// happy tuple param
// ))
// because due to applied alignment, closing paren has to be
// at least in the same column as the opening one.
var result = true
if (parent != null) {
val lBrace = parent.firstChildNode
val rBrace = parent.lastChildNode
if (lBrace.isBlockDelim(parent) && rBrace.isBlockDelim(parent)) {
result = child.treeNonWSPrev() != lBrace || child.treeNonWSNext() != rBrace
}
}
result
}
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS)
TUPLE_TYPE, TUPLE_FIELDS ->
RsAlignmentStrategy.wrap()
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS)
VALUE_PARAMETER_LIST ->
RsAlignmentStrategy.shared()
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS)
in FN_DECLS ->
RsAlignmentStrategy.shared()
.alignIf { c, _, _ ->
c.elementType == RET_TYPE && ctx.rustSettings.ALIGN_RET_TYPE ||
c.elementType == WHERE_CLAUSE && ctx.rustSettings.ALIGN_WHERE_CLAUSE
}
PAT_TUPLE_STRUCT ->
RsAlignmentStrategy.wrap()
.alignIf { c, p, x -> x.metLBrace && !c.isBlockDelim(p) }
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS)
DOT_EXPR ->
RsAlignmentStrategy.shared()
.alignIf(DOT) // DOT is synthetic's block representative
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_CHAINED_METHODS)
WHERE_CLAUSE ->
RsAlignmentStrategy.wrap()
.alignIf(WHERE_PRED)
.alignIf(ctx.rustSettings.ALIGN_WHERE_BOUNDS)
TYPE_PARAMETER_LIST ->
RsAlignmentStrategy.wrap()
.alignIf(TYPE_PARAMETER, LIFETIME_PARAMETER)
.alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS)
FOR_LIFETIMES ->
RsAlignmentStrategy.wrap()
.alignIf(LIFETIME_PARAMETER)
.alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS)
else -> RsAlignmentStrategy.NullStrategy
}
fun RsAlignmentStrategy.alignUnlessBlockDelim(): RsAlignmentStrategy = alignIf { c, p, _ -> !c.isBlockDelim(p) }
| mit | 4a168c8c1a81556fdc5f37440b4de433 | 38.116279 | 112 | 0.583234 | 4.764873 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/util/TagWrappers.kt | 1 | 2283 | package com.teamwizardry.librarianlib.foundation.util
import net.minecraft.block.Block
import net.minecraft.entity.EntityType
import net.minecraft.fluid.Fluid
import net.minecraft.item.Item
import net.minecraft.tags.*
import net.minecraft.util.Identifier
/**
* A utility class for easily creating tags.
*
* **Note:** You'll almost always want to create an item tag when you create a block tag. You can do this using
* [itemFormOf], and you can specify their equivalence using
* `registrationManager.datagen.blockTags.addItemForm(blockTag, itemTag)`
*/
public object TagWrappers {
/**
* Creates a tag for the item form of the given block. i.e. creates an item tag with the same ID as the block tag.
*/
@JvmStatic
public fun itemFormOf(blockTag: ITag.INamedTag<Block>): ITag.INamedTag<Item> = item(blockTag.name)
@JvmStatic
public fun block(name: String): ITag.INamedTag<Block> = BlockTags.makeWrapperTag(name)
@JvmStatic
public fun entityType(name: String): ITag.INamedTag<EntityType<*>> = EntityTypeTags.getTagById(name)
@JvmStatic
public fun fluid(name: String): ITag.INamedTag<Fluid> = FluidTags.makeWrapperTag(name)
@JvmStatic
public fun item(name: String): ITag.INamedTag<Item> = ItemTags.makeWrapperTag(name)
@JvmStatic
public fun block(modid: String, name: String): ITag.INamedTag<Block> = block(Identifier(modid, name))
@JvmStatic
public fun entityType(modid: String, name: String): ITag.INamedTag<EntityType<*>> = entityType(Identifier(modid, name))
@JvmStatic
public fun fluid(modid: String, name: String): ITag.INamedTag<Fluid> = fluid(Identifier(modid, name))
@JvmStatic
public fun item(modid: String, name: String): ITag.INamedTag<Item> = item(Identifier(modid, name))
@JvmStatic
public fun block(name: Identifier): ITag.INamedTag<Block> = BlockTags.makeWrapperTag(name.toString())
@JvmStatic
public fun entityType(name: Identifier): ITag.INamedTag<EntityType<*>> = EntityTypeTags.getTagById(name.toString())
@JvmStatic
public fun fluid(name: Identifier): ITag.INamedTag<Fluid> = FluidTags.makeWrapperTag(name.toString())
@JvmStatic
public fun item(name: Identifier): ITag.INamedTag<Item> = ItemTags.makeWrapperTag(name.toString())
} | lgpl-3.0 | 11f028ff79bbd3081cc9961612e483bc | 37.711864 | 123 | 0.735436 | 4.069519 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/os/windows/namedpipes/NamedPipeSocket.kt | 1 | 6157 | /*
Copyright 2017-2020 Charles Korn.
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 batect.os.windows.namedpipes
import batect.os.windows.WindowsNativeMethods
import jnr.posix.POSIXFactory
import kotlinx.io.IOException
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.nio.channels.SocketChannel
class NamedPipeSocket : Socket() {
private val nativeMethods = WindowsNativeMethods(POSIXFactory.getNativePOSIX())
private lateinit var pipe: NamedPipe
private var isOpen = false
private var readTimeout = 0
private val inputStream = object : InputStream() {
override fun skip(n: Long): Long = throw UnsupportedOperationException()
override fun available(): Int = 0
override fun close() = [email protected]()
override fun reset() = throw UnsupportedOperationException()
override fun mark(readlimit: Int): Unit = throw UnsupportedOperationException()
override fun markSupported(): Boolean = false
override fun read(): Int {
val bytes = ByteArray(1)
val result = read(bytes)
if (result == -1) {
return -1
}
return bytes.first().toInt()
}
override fun read(b: ByteArray): Int {
return read(b, 0, b.size)
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
return pipe.read(b, off, len, readTimeout)
}
}
private val outputStream = object : OutputStream() {
override fun write(b: Int) {
write(byteArrayOf(b.toByte()))
}
override fun write(b: ByteArray) {
write(b, 0, b.size)
}
override fun write(b: ByteArray, off: Int, len: Int) {
pipe.write(b, off, len)
}
override fun flush() {}
override fun close() = [email protected]()
}
override fun connect(addr: SocketAddress?) {
this.connect(addr, 0)
}
override fun connect(addr: SocketAddress?, timeout: Int) {
val encodedHostName = (addr as InetSocketAddress).hostName
val path = NamedPipeDns.decodePath(encodedHostName)
try {
pipe = nativeMethods.openNamedPipe(path, timeout)
isOpen = true
} catch (e: FileNotFoundException) {
throw IOException("Cannot connect to '$path': the named pipe does not exist", e)
}
}
override fun getInputStream(): InputStream = inputStream
override fun getOutputStream(): OutputStream = outputStream
override fun close() {
if (!isOpen) {
return
}
pipe.close()
isOpen = false
}
override fun getSoTimeout(): Int = readTimeout
override fun setSoTimeout(timeout: Int) {
readTimeout = timeout
}
override fun shutdownInput() {}
override fun shutdownOutput() {}
override fun isInputShutdown(): Boolean = !this.isConnected
override fun isOutputShutdown(): Boolean = !this.isConnected
override fun isBound(): Boolean = isOpen
override fun isConnected(): Boolean = isOpen
override fun isClosed(): Boolean = !isOpen
override fun getReuseAddress(): Boolean = throw UnsupportedOperationException()
override fun setReuseAddress(on: Boolean) = throw UnsupportedOperationException()
override fun getKeepAlive(): Boolean = throw UnsupportedOperationException()
override fun setKeepAlive(on: Boolean): Unit = throw UnsupportedOperationException()
override fun getPort(): Int = throw UnsupportedOperationException()
override fun getSoLinger(): Int = throw UnsupportedOperationException()
override fun setSoLinger(on: Boolean, linger: Int): Unit = throw UnsupportedOperationException()
override fun getTrafficClass(): Int = throw UnsupportedOperationException()
override fun setTrafficClass(tc: Int): Unit = throw UnsupportedOperationException()
override fun getTcpNoDelay(): Boolean = throw UnsupportedOperationException()
override fun setTcpNoDelay(on: Boolean): Unit = throw UnsupportedOperationException()
override fun getOOBInline(): Boolean = throw UnsupportedOperationException()
override fun setOOBInline(on: Boolean): Unit = throw UnsupportedOperationException()
override fun getLocalPort(): Int = throw UnsupportedOperationException()
override fun getLocalSocketAddress(): SocketAddress = throw UnsupportedOperationException()
override fun getRemoteSocketAddress(): SocketAddress = throw UnsupportedOperationException()
override fun getReceiveBufferSize(): Int = throw UnsupportedOperationException()
override fun getSendBufferSize(): Int = throw UnsupportedOperationException()
override fun sendUrgentData(data: Int): Unit = throw UnsupportedOperationException()
override fun setSendBufferSize(size: Int): Unit = throw UnsupportedOperationException()
override fun setReceiveBufferSize(size: Int): Unit = throw UnsupportedOperationException()
override fun getLocalAddress(): InetAddress = throw UnsupportedOperationException()
override fun getChannel(): SocketChannel = throw UnsupportedOperationException()
override fun setPerformancePreferences(connectionTime: Int, latency: Int, bandwidth: Int): Unit = throw UnsupportedOperationException()
override fun getInetAddress(): InetAddress = throw UnsupportedOperationException()
override fun bind(bindpoint: SocketAddress?): Unit = throw UnsupportedOperationException()
}
| apache-2.0 | 800974445a1d8c7e05d6d5544af7ec40 | 38.980519 | 139 | 0.705214 | 5.289519 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/SkillsRecyclerViewAdapter.kt | 1 | 6399 | package com.habitrpg.android.habitica.ui.adapter
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.SkillListItemBinding
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.extensions.isUsingNightModeResources
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.user.OwnedItem
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.subjects.PublishSubject
import io.realm.RealmList
class SkillsRecyclerViewAdapter : RecyclerView.Adapter<SkillsRecyclerViewAdapter.SkillViewHolder>() {
private val useSkillSubject = PublishSubject.create<Skill>()
val useSkillEvents: Flowable<Skill> = useSkillSubject.toFlowable(BackpressureStrategy.DROP)
var mana: Double = 0.0
set(value) {
field = value
notifyDataSetChanged()
}
var level: Int = 0
set(value) {
field = value
notifyDataSetChanged()
}
var specialItems: RealmList<OwnedItem>?? = null
set(value) {
field = value
notifyDataSetChanged()
}
private var skillList: List<Skill> = emptyList()
fun setSkillList(skillList: List<Skill>) {
this.skillList = skillList
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SkillViewHolder {
return SkillViewHolder(parent.inflate(R.layout.skill_list_item))
}
override fun onBindViewHolder(holder: SkillViewHolder, position: Int) {
holder.bind(skillList[position])
}
override fun getItemCount(): Int {
return skillList.size
}
inner class SkillViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = SkillListItemBinding.bind(itemView)
private val magicDrawable: Drawable
private val lockDrawable: Drawable
var skill: Skill? = null
var context: Context = itemView.context
init {
binding.buttonWrapper.setOnClickListener(this)
magicDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfMagic())
lockDrawable = BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfLocked(ContextCompat.getColor(context, R.color.text_dimmed)))
}
fun bind(skill: Skill) {
this.skill = skill
binding.skillText.text = skill.text
binding.skillNotes.text = skill.notes
binding.skillText.setTextColor(ContextCompat.getColor(context, R.color.text_primary))
binding.skillNotes.setTextColor(ContextCompat.getColor(context, R.color.text_ternary))
binding.skillNotes.visibility = View.VISIBLE
binding.priceLabel.visibility = View.VISIBLE
if ("special" == skill.habitClass) {
binding.countLabel.visibility = View.VISIBLE
binding.countLabel.text = getOwnedCount(skill.key).toString()
binding.priceLabel.setText(R.string.skill_transformation_use)
if (context.isUsingNightModeResources()) {
binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.brand_500))
} else {
binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.color_accent))
}
binding.buttonIconView.setImageDrawable(null)
binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background))
binding.buttonIconView.alpha = 1.0f
binding.priceLabel.alpha = 1.0f
} else {
binding.countLabel.visibility = View.GONE
binding.priceLabel.text = skill.mana?.toString()
if (context.isUsingNightModeResources()) {
binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.blue_500))
} else {
binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.blue_10))
}
binding.buttonIconView.setImageDrawable(magicDrawable)
if (skill.mana ?: 0 > mana) {
binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background))
binding.buttonIconView.alpha = 0.3f
binding.priceLabel.alpha = 0.3f
} else {
binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.blue_500_24))
binding.buttonIconView.alpha = 1.0f
binding.priceLabel.alpha = 1.0f
}
if ((skill.lvl ?: 0) > level) {
binding.buttonWrapper.setBackgroundColor(ContextCompat.getColor(context, R.color.offset_background))
binding.skillText.setTextColor(ContextCompat.getColor(context, R.color.text_dimmed))
binding.skillText.text = context.getString(R.string.skill_unlocks_at, skill.lvl)
binding.skillNotes.visibility = View.GONE
binding.buttonIconView.setImageDrawable(lockDrawable)
binding.priceLabel.visibility = View.GONE
}
}
DataBindingUtils.loadImage(binding.skillImage, "shop_" + skill.key)
}
override fun onClick(v: View) {
if ((skill?.lvl ?: 0) <= level) {
skill?.let { useSkillSubject.onNext(it) }
}
}
private fun getOwnedCount(key: String): Int {
return specialItems?.firstOrNull() { it.key == key }?.numberOwned ?: 0
}
}
}
| gpl-3.0 | 5ce535eb207f45313e07fdb9d816e534 | 43.382979 | 149 | 0.643069 | 4.983645 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/NutritionRecord.kt | 3 | 26230 | /*
* 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 androidx.health.connect.client.records
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType
import androidx.health.connect.client.aggregate.AggregateMetric.Companion.doubleMetric
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Energy
import androidx.health.connect.client.units.Mass
import java.time.Instant
import java.time.ZoneOffset
/** Captures what nutrients were consumed as part of a meal or a food item. */
public class NutritionRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
/** Biotin in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val biotin: Mass? = null,
/** Caffeine in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val caffeine: Mass? = null,
/** Calcium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val calcium: Mass? = null,
/** Energy in [Energy] unit. Optional field. Valid range: 0-100000 kcal. */
public val energy: Energy? = null,
/** Energy from fat in [Energy] unit. Optional field. Valid range: 0-100000 kcal. */
public val energyFromFat: Energy? = null,
/** Chloride in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val chloride: Mass? = null,
/** Cholesterol in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val cholesterol: Mass? = null,
/** Chromium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val chromium: Mass? = null,
/** Copper in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val copper: Mass? = null,
/** Dietary fiber in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val dietaryFiber: Mass? = null,
/** Folate in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val folate: Mass? = null,
/** Folic acid in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val folicAcid: Mass? = null,
/** Iodine in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val iodine: Mass? = null,
/** Iron in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val iron: Mass? = null,
/** Magnesium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val magnesium: Mass? = null,
/** Manganese in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val manganese: Mass? = null,
/** Molybdenum in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val molybdenum: Mass? = null,
/** Monounsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val monounsaturatedFat: Mass? = null,
/** Niacin in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val niacin: Mass? = null,
/** Pantothenic acid in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val pantothenicAcid: Mass? = null,
/** Phosphorus in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val phosphorus: Mass? = null,
/** Polyunsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val polyunsaturatedFat: Mass? = null,
/** Potassium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val potassium: Mass? = null,
/** Protein in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val protein: Mass? = null,
/** Riboflavin in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val riboflavin: Mass? = null,
/** Saturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val saturatedFat: Mass? = null,
/** Selenium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val selenium: Mass? = null,
/** Sodium in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val sodium: Mass? = null,
/** Sugar in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val sugar: Mass? = null,
/** Thiamin in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val thiamin: Mass? = null,
/** Total carbohydrate in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val totalCarbohydrate: Mass? = null,
/** Total fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val totalFat: Mass? = null,
/** Trans fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val transFat: Mass? = null,
/** Unsaturated fat in [Mass] unit. Optional field. Valid range: 0-100000 grams. */
public val unsaturatedFat: Mass? = null,
/** Vitamin A in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminA: Mass? = null,
/** Vitamin B12 in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminB12: Mass? = null,
/** Vitamin B6 in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminB6: Mass? = null,
/** Vitamin C in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminC: Mass? = null,
/** Vitamin D in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminD: Mass? = null,
/** Vitamin E in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminE: Mass? = null,
/** Vitamin K in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val vitaminK: Mass? = null,
/** Zinc in [Mass] unit. Optional field. Valid range: 0-100 grams. */
public val zinc: Mass? = null,
/** Name for food or drink, provided by the user. Optional field. */
public val name: String? = null,
/**
* Type of meal related to the nutrients consumed. Optional, enum field. Allowed values:
* [MealType].
*
* @see MealType
*/
@property:MealTypes public val mealType: Int = MealType.MEAL_TYPE_UNKNOWN,
override val metadata: Metadata = Metadata.EMPTY,
) : IntervalRecord {
init {
require(startTime.isBefore(endTime)) { "startTime must be before endTime." }
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NutritionRecord) return false
if (biotin != other.biotin) return false
if (caffeine != other.caffeine) return false
if (calcium != other.calcium) return false
if (energy != other.energy) return false
if (energyFromFat != other.energyFromFat) return false
if (chloride != other.chloride) return false
if (cholesterol != other.cholesterol) return false
if (chromium != other.chromium) return false
if (copper != other.copper) return false
if (dietaryFiber != other.dietaryFiber) return false
if (folate != other.folate) return false
if (folicAcid != other.folicAcid) return false
if (iodine != other.iodine) return false
if (iron != other.iron) return false
if (magnesium != other.magnesium) return false
if (manganese != other.manganese) return false
if (molybdenum != other.molybdenum) return false
if (monounsaturatedFat != other.monounsaturatedFat) return false
if (niacin != other.niacin) return false
if (pantothenicAcid != other.pantothenicAcid) return false
if (phosphorus != other.phosphorus) return false
if (polyunsaturatedFat != other.polyunsaturatedFat) return false
if (potassium != other.potassium) return false
if (protein != other.protein) return false
if (riboflavin != other.riboflavin) return false
if (saturatedFat != other.saturatedFat) return false
if (selenium != other.selenium) return false
if (sodium != other.sodium) return false
if (sugar != other.sugar) return false
if (thiamin != other.thiamin) return false
if (totalCarbohydrate != other.totalCarbohydrate) return false
if (totalFat != other.totalFat) return false
if (transFat != other.transFat) return false
if (unsaturatedFat != other.unsaturatedFat) return false
if (vitaminA != other.vitaminA) return false
if (vitaminB12 != other.vitaminB12) return false
if (vitaminB6 != other.vitaminB6) return false
if (vitaminC != other.vitaminC) return false
if (vitaminD != other.vitaminD) return false
if (vitaminE != other.vitaminE) return false
if (vitaminK != other.vitaminK) return false
if (zinc != other.zinc) return false
if (name != other.name) return false
if (mealType != other.mealType) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = biotin.hashCode()
result = 31 * result + caffeine.hashCode()
result = 31 * result + calcium.hashCode()
result = 31 * result + energy.hashCode()
result = 31 * result + energyFromFat.hashCode()
result = 31 * result + chloride.hashCode()
result = 31 * result + cholesterol.hashCode()
result = 31 * result + chromium.hashCode()
result = 31 * result + copper.hashCode()
result = 31 * result + dietaryFiber.hashCode()
result = 31 * result + folate.hashCode()
result = 31 * result + folicAcid.hashCode()
result = 31 * result + iodine.hashCode()
result = 31 * result + iron.hashCode()
result = 31 * result + magnesium.hashCode()
result = 31 * result + manganese.hashCode()
result = 31 * result + molybdenum.hashCode()
result = 31 * result + monounsaturatedFat.hashCode()
result = 31 * result + niacin.hashCode()
result = 31 * result + pantothenicAcid.hashCode()
result = 31 * result + phosphorus.hashCode()
result = 31 * result + polyunsaturatedFat.hashCode()
result = 31 * result + potassium.hashCode()
result = 31 * result + protein.hashCode()
result = 31 * result + riboflavin.hashCode()
result = 31 * result + saturatedFat.hashCode()
result = 31 * result + selenium.hashCode()
result = 31 * result + sodium.hashCode()
result = 31 * result + sugar.hashCode()
result = 31 * result + thiamin.hashCode()
result = 31 * result + totalCarbohydrate.hashCode()
result = 31 * result + totalFat.hashCode()
result = 31 * result + transFat.hashCode()
result = 31 * result + unsaturatedFat.hashCode()
result = 31 * result + vitaminA.hashCode()
result = 31 * result + vitaminB12.hashCode()
result = 31 * result + vitaminB6.hashCode()
result = 31 * result + vitaminC.hashCode()
result = 31 * result + vitaminD.hashCode()
result = 31 * result + vitaminE.hashCode()
result = 31 * result + vitaminK.hashCode()
result = 31 * result + zinc.hashCode()
result = 31 * result + (name?.hashCode() ?: 0)
result = 31 * result + mealType
result = 31 * result + startTime.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
companion object {
private const val TYPE_NAME = "Nutrition"
/**
* Metric identifier to retrieve the total biotin from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val BIOTIN_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "biotin", Mass::grams)
/**
* Metric identifier to retrieve the total caffeine from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val CAFFEINE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "caffeine", Mass::grams)
/**
* Metric identifier to retrieve the total calcium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val CALCIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "calcium", Mass::grams)
/**
* Metric identifier to retrieve the total energy from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val ENERGY_TOTAL: AggregateMetric<Energy> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "calories", Energy::kilocalories)
/**
* Metric identifier to retrieve the total energy from fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val ENERGY_FROM_FAT_TOTAL: AggregateMetric<Energy> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "caloriesFromFat", Energy::kilocalories)
/**
* Metric identifier to retrieve the total chloride from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val CHLORIDE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "chloride", Mass::grams)
/**
* Metric identifier to retrieve the total cholesterol from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val CHOLESTEROL_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "cholesterol", Mass::grams)
/**
* Metric identifier to retrieve the total chromium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val CHROMIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "chromium", Mass::grams)
/**
* Metric identifier to retrieve the total copper from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val COPPER_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "copper", Mass::grams)
/**
* Metric identifier to retrieve the total dietary fiber from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val DIETARY_FIBER_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "dietaryFiber", Mass::grams)
/**
* Metric identifier to retrieve the total folate from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val FOLATE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "folate", Mass::grams)
/**
* Metric identifier to retrieve the total folic acid from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val FOLIC_ACID_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "folicAcid", Mass::grams)
/**
* Metric identifier to retrieve the total iodine from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val IODINE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "iodine", Mass::grams)
/**
* Metric identifier to retrieve the total iron from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val IRON_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "iron", Mass::grams)
/**
* Metric identifier to retrieve the total magnesium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val MAGNESIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "magnesium", Mass::grams)
/**
* Metric identifier to retrieve the total manganese from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val MANGANESE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "manganese", Mass::grams)
/**
* Metric identifier to retrieve the total molybdenum from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val MOLYBDENUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "molybdenum", Mass::grams)
/**
* Metric identifier to retrieve the total monounsaturated fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val MONOUNSATURATED_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "monounsaturatedFat", Mass::grams)
/**
* Metric identifier to retrieve the total niacin from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val NIACIN_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "niacin", Mass::grams)
/**
* Metric identifier to retrieve the total pantothenic acid from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val PANTOTHENIC_ACID_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "pantothenicAcid", Mass::grams)
/**
* Metric identifier to retrieve the total phosphorus from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val PHOSPHORUS_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "phosphorus", Mass::grams)
/**
* Metric identifier to retrieve the total polyunsaturated fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val POLYUNSATURATED_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "polyunsaturatedFat", Mass::grams)
/**
* Metric identifier to retrieve the total potassium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val POTASSIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "potassium", Mass::grams)
/**
* Metric identifier to retrieve the total protein from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val PROTEIN_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "protein", Mass::grams)
/**
* Metric identifier to retrieve the total riboflavin from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val RIBOFLAVIN_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "riboflavin", Mass::grams)
/**
* Metric identifier to retrieve the total saturated fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SATURATED_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "saturatedFat", Mass::grams)
/**
* Metric identifier to retrieve the total selenium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SELENIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "selenium", Mass::grams)
/**
* Metric identifier to retrieve the total sodium from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SODIUM_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "sodium", Mass::grams)
/**
* Metric identifier to retrieve the total sugar from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SUGAR_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "sugar", Mass::grams)
/**
* Metric identifier to retrieve the total thiamin from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val THIAMIN_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "thiamin", Mass::grams)
/**
* Metric identifier to retrieve the total total carbohydrate from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val TOTAL_CARBOHYDRATE_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "totalCarbohydrate", Mass::grams)
/**
* Metric identifier to retrieve the total total fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val TOTAL_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "totalFat", Mass::grams)
/**
* Metric identifier to retrieve the total trans fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val TRANS_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "transFat", Mass::grams)
/**
* Metric identifier to retrieve the total unsaturated fat from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val UNSATURATED_FAT_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "unsaturatedFat", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin a from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_A_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminA", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin b12 from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_B12_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminB12", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin b6 from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_B6_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminB6", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin c from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_C_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminC", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin d from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_D_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminD", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin e from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_E_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminE", Mass::grams)
/**
* Metric identifier to retrieve the total vitamin k from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val VITAMIN_K_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "vitaminK", Mass::grams)
/**
* Metric identifier to retrieve the total zinc from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val ZINC_TOTAL: AggregateMetric<Mass> =
doubleMetric(TYPE_NAME, AggregationType.TOTAL, "zinc", Mass::grams)
}
}
| apache-2.0 | aff0bf14e373606abeca3b21a9c3c553 | 43.608844 | 99 | 0.639497 | 4.423272 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/FloatingActionButton.kt | 3 | 28312 | /*
* 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.compose.material3
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.foundation.interaction.FocusInteraction
import androidx.compose.foundation.interaction.HoverInteraction
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.material3.tokens.ExtendedFabPrimaryTokens
import androidx.compose.material3.tokens.FabPrimaryLargeTokens
import androidx.compose.material3.tokens.FabPrimarySmallTokens
import androidx.compose.material3.tokens.FabPrimaryTokens
import androidx.compose.material3.tokens.MotionTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design floating action button</a>.
*
* The FAB represents the most important action on a screen. It puts key actions within reach.
*
* ![FAB image](https://developer.android.com/images/reference/androidx/compose/material3/fab.png)
*
* FAB typically contains an icon, for a FAB with text and an icon, see
* [ExtendedFloatingActionButton].
*
* @sample androidx.compose.material3.samples.FloatingActionButtonSample
*
* @param onClick called when this FAB is clicked
* @param modifier the [Modifier] to be applied to this FAB
* @param shape defines the shape of this FAB's container and shadow (when using [elevation])
* @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to
* have no color.
* @param contentColor the preferred color for content inside this FAB. Defaults to either the
* matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in
* different states. This controls the size of the shadow below the FAB. Additionally, when the
* container color is [ColorScheme.surface], this controls the amount of primary color applied as an
* overlay. See also: [Surface].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s
* and customize the appearance / behavior of this FAB in different states.
* @param content the content of this FAB, typically an [Icon]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FloatingActionButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
shape: Shape = FloatingActionButtonDefaults.shape,
containerColor: Color = FloatingActionButtonDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
Surface(
onClick = onClick,
modifier = modifier,
shape = shape,
color = containerColor,
contentColor = contentColor,
tonalElevation = elevation.tonalElevation(interactionSource = interactionSource).value,
shadowElevation = elevation.shadowElevation(interactionSource = interactionSource).value,
interactionSource = interactionSource,
) {
CompositionLocalProvider(LocalContentColor provides contentColor) {
// Adding the text style from [ExtendedFloatingActionButton] to all FAB variations. In
// the majority of cases this will have no impact, because icons are expected, but if a
// developer decides to put some short text to emulate an icon, (like "?") then it will
// have the correct styling.
ProvideTextStyle(
MaterialTheme.typography.fromToken(ExtendedFabPrimaryTokens.LabelTextFont),
) {
Box(
modifier = Modifier
.defaultMinSize(
minWidth = FabPrimaryTokens.ContainerWidth,
minHeight = FabPrimaryTokens.ContainerHeight,
),
contentAlignment = Alignment.Center,
) { content() }
}
}
}
}
/**
* <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design small floating action button</a>.
*
* The FAB represents the most important action on a screen. It puts key actions within reach.
*
* ![Small FAB image](https://developer.android.com/images/reference/androidx/compose/material3/small-fab.png)
*
* @sample androidx.compose.material3.samples.SmallFloatingActionButtonSample
*
* @param onClick called when this FAB is clicked
* @param modifier the [Modifier] to be applied to this FAB
* @param shape defines the shape of this FAB's container and shadow (when using [elevation])
* @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to
* have no color.
* @param contentColor the preferred color for content inside this FAB. Defaults to either the
* matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in
* different states. This controls the size of the shadow below the FAB. Additionally, when the
* container color is [ColorScheme.surface], this controls the amount of primary color applied as an
* overlay. See also: [Surface].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s
* and customize the appearance / behavior of this FAB in different states.
* @param content the content of this FAB, typically an [Icon]
*/
@Composable
fun SmallFloatingActionButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
shape: Shape = FloatingActionButtonDefaults.smallShape,
containerColor: Color = FloatingActionButtonDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
FloatingActionButton(
onClick = onClick,
modifier = modifier.sizeIn(
minWidth = FabPrimarySmallTokens.ContainerWidth,
minHeight = FabPrimarySmallTokens.ContainerHeight,
),
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
elevation = elevation,
interactionSource = interactionSource,
content = content,
)
}
/**
* <a href="https://m3.material.io/components/floating-action-button/overview" class="external" target="_blank">Material Design large floating action button</a>.
*
* The FAB represents the most important action on a screen. It puts key actions within reach.
*
* ![Large FAB image](https://developer.android.com/images/reference/androidx/compose/material3/large-fab.png)
*
* @sample androidx.compose.material3.samples.LargeFloatingActionButtonSample
*
* @param onClick called when this FAB is clicked
* @param modifier the [Modifier] to be applied to this FAB
* @param shape defines the shape of this FAB's container and shadow (when using [elevation])
* @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to
* have no color.
* @param contentColor the preferred color for content inside this FAB. Defaults to either the
* matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in
* different states. This controls the size of the shadow below the FAB. Additionally, when the
* container color is [ColorScheme.surface], this controls the amount of primary color applied as an
* overlay. See also: [Surface].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s
* and customize the appearance / behavior of this FAB in different states.
* @param content the content of this FAB, typically an [Icon]
*/
@Composable
fun LargeFloatingActionButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
shape: Shape = FloatingActionButtonDefaults.largeShape,
containerColor: Color = FloatingActionButtonDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
FloatingActionButton(
onClick = onClick,
modifier = modifier.sizeIn(
minWidth = FabPrimaryLargeTokens.ContainerWidth,
minHeight = FabPrimaryLargeTokens.ContainerHeight,
),
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
elevation = elevation,
interactionSource = interactionSource,
content = content,
)
}
/**
* <a href="https://m3.material.io/components/extended-fab/overview" class="external" target="_blank">Material Design extended floating action button</a>.
*
* Extended FABs help people take primary actions. They're wider than FABs to accommodate a text
* label and larger target area.
*
* ![Extended FAB image](https://developer.android.com/images/reference/androidx/compose/material3/extended-fab.png)
*
* The other extended floating action button overload supports a text label and icon.
*
* @sample androidx.compose.material3.samples.ExtendedFloatingActionButtonTextSample
*
* @param onClick called when this FAB is clicked
* @param modifier the [Modifier] to be applied to this FAB
* @param shape defines the shape of this FAB's container and shadow (when using [elevation])
* @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to
* have no color.
* @param contentColor the preferred color for content inside this FAB. Defaults to either the
* matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in
* different states. This controls the size of the shadow below the FAB. Additionally, when the
* container color is [ColorScheme.surface], this controls the amount of primary color applied as an
* overlay. See also: [Surface].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s
* and customize the appearance / behavior of this FAB in different states.
* @param content the content of this FAB, typically a [Text] label
*/
@Composable
fun ExtendedFloatingActionButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
shape: Shape = FloatingActionButtonDefaults.extendedFabShape,
containerColor: Color = FloatingActionButtonDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable RowScope.() -> Unit,
) {
FloatingActionButton(
onClick = onClick,
modifier = modifier,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
elevation = elevation,
interactionSource = interactionSource,
) {
Row(
modifier = Modifier
.sizeIn(minWidth = ExtendedFabMinimumWidth)
.padding(horizontal = ExtendedFabTextPadding),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
content = content,
)
}
}
/**
* <a href="https://m3.material.io/components/extended-fab/overview" class="external" target="_blank">Material Design extended floating action button</a>.
*
* Extended FABs help people take primary actions. They're wider than FABs to accommodate a text
* label and larger target area.
*
* ![Extended FAB image](https://developer.android.com/images/reference/androidx/compose/material3/extended-fab.png)
*
* The other extended floating action button overload is for FABs without an icon.
*
* Default content description for accessibility is extended from the extended fabs icon. For custom
* behavior, you can provide your own via [Modifier.semantics].
*
* @sample androidx.compose.material3.samples.ExtendedFloatingActionButtonSample
* @sample androidx.compose.material3.samples.AnimatedExtendedFloatingActionButtonSample
*
* @param text label displayed inside this FAB
* @param icon optional icon for this FAB, typically an [Icon]
* @param onClick called when this FAB is clicked
* @param modifier the [Modifier] to be applied to this FAB
* @param expanded controls the expansion state of this FAB. In an expanded state, the FAB will show
* both the [icon] and [text]. In a collapsed state, the FAB will show only the [icon].
* @param shape defines the shape of this FAB's container and shadow (when using [elevation])
* @param containerColor the color used for the background of this FAB. Use [Color.Transparent] to
* have no color.
* @param contentColor the preferred color for content inside this FAB. Defaults to either the
* matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param elevation [FloatingActionButtonElevation] used to resolve the elevation for this FAB in
* different states. This controls the size of the shadow below the FAB. Additionally, when the
* container color is [ColorScheme.surface], this controls the amount of primary color applied as an
* overlay. See also: [Surface].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this FAB. You can create and pass in your own `remember`ed instance to observe [Interaction]s
* and customize the appearance / behavior of this FAB in different states.
*/
@Composable
fun ExtendedFloatingActionButton(
text: @Composable () -> Unit,
icon: @Composable () -> Unit,
onClick: () -> Unit,
modifier: Modifier = Modifier,
expanded: Boolean = true,
shape: Shape = FloatingActionButtonDefaults.extendedFabShape,
containerColor: Color = FloatingActionButtonDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
FloatingActionButton(
onClick = onClick,
modifier = modifier,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
elevation = elevation,
interactionSource = interactionSource,
) {
val startPadding = if (expanded) ExtendedFabStartIconPadding else 0.dp
val endPadding = if (expanded) ExtendedFabTextPadding else 0.dp
Row(
modifier = Modifier
.sizeIn(
minWidth = if (expanded) ExtendedFabMinimumWidth
else FabPrimaryTokens.ContainerWidth
)
.padding(start = startPadding, end = endPadding),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = if (expanded) Arrangement.Start else Arrangement.Center
) {
icon()
AnimatedVisibility(
visible = expanded,
enter = ExtendedFabExpandAnimation,
exit = ExtendedFabCollapseAnimation,
) {
Row(Modifier.clearAndSetSemantics {}) {
Spacer(Modifier.width(ExtendedFabEndIconPadding))
text()
}
}
}
}
}
/**
* Contains the default values used by [FloatingActionButton]
*/
object FloatingActionButtonDefaults {
/**
* The recommended size of the icon inside a [LargeFloatingActionButton].
*/
val LargeIconSize = FabPrimaryLargeTokens.IconSize
/** Default shape for a floating action button. */
val shape: Shape @Composable get() = FabPrimaryTokens.ContainerShape.toShape()
/** Default shape for a small floating action button. */
val smallShape: Shape @Composable get() = FabPrimarySmallTokens.ContainerShape.toShape()
/** Default shape for a large floating action button. */
val largeShape: Shape @Composable get() = FabPrimaryLargeTokens.ContainerShape.toShape()
/** Default shape for an extended floating action button. */
val extendedFabShape: Shape @Composable get() =
ExtendedFabPrimaryTokens.ContainerShape.toShape()
/** Default container color for a floating action button. */
val containerColor: Color @Composable get() = FabPrimaryTokens.ContainerColor.toColor()
/**
* Creates a [FloatingActionButtonElevation] that represents the elevation of a
* [FloatingActionButton] in different states. For use cases in which a less prominent
* [FloatingActionButton] is possible consider the [loweredElevation].
*
* @param defaultElevation the elevation used when the [FloatingActionButton] has no other
* [Interaction]s.
* @param pressedElevation the elevation used when the [FloatingActionButton] is pressed.
* @param focusedElevation the elevation used when the [FloatingActionButton] is focused.
* @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered.
*/
@Composable
fun elevation(
defaultElevation: Dp = FabPrimaryTokens.ContainerElevation,
pressedElevation: Dp = FabPrimaryTokens.PressedContainerElevation,
focusedElevation: Dp = FabPrimaryTokens.FocusContainerElevation,
hoveredElevation: Dp = FabPrimaryTokens.HoverContainerElevation,
): FloatingActionButtonElevation = FloatingActionButtonElevation(
defaultElevation = defaultElevation,
pressedElevation = pressedElevation,
focusedElevation = focusedElevation,
hoveredElevation = hoveredElevation,
)
/**
* Use this to create a [FloatingActionButton] with a lowered elevation for less emphasis. Use
* [elevation] to get a normal [FloatingActionButton].
*
* @param defaultElevation the elevation used when the [FloatingActionButton] has no other
* [Interaction]s.
* @param pressedElevation the elevation used when the [FloatingActionButton] is pressed.
* @param focusedElevation the elevation used when the [FloatingActionButton] is focused.
* @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered.
*/
@Composable
fun loweredElevation(
defaultElevation: Dp = FabPrimaryTokens.LoweredContainerElevation,
pressedElevation: Dp = FabPrimaryTokens.LoweredPressedContainerElevation,
focusedElevation: Dp = FabPrimaryTokens.LoweredFocusContainerElevation,
hoveredElevation: Dp = FabPrimaryTokens.LoweredHoverContainerElevation,
): FloatingActionButtonElevation = FloatingActionButtonElevation(
defaultElevation = defaultElevation,
pressedElevation = pressedElevation,
focusedElevation = focusedElevation,
hoveredElevation = hoveredElevation,
)
/**
* Use this to create a [FloatingActionButton] that represents the default elevation of a
* [FloatingActionButton] used for [BottomAppBar] in different states.
*
* @param defaultElevation the elevation used when the [FloatingActionButton] has no other
* [Interaction]s.
* @param pressedElevation the elevation used when the [FloatingActionButton] is pressed.
* @param focusedElevation the elevation used when the [FloatingActionButton] is focused.
* @param hoveredElevation the elevation used when the [FloatingActionButton] is hovered.
*/
fun bottomAppBarFabElevation(
defaultElevation: Dp = 0.dp,
pressedElevation: Dp = 0.dp,
focusedElevation: Dp = 0.dp,
hoveredElevation: Dp = 0.dp
): FloatingActionButtonElevation = FloatingActionButtonElevation(
defaultElevation,
pressedElevation,
focusedElevation,
hoveredElevation
)
}
/**
* Represents the tonal and shadow elevation for a floating action button in different states.
*
* See [FloatingActionButtonDefaults.elevation] for the default elevation used in a
* [FloatingActionButton] and [ExtendedFloatingActionButton].
*/
@Stable
open class FloatingActionButtonElevation internal constructor(
private val defaultElevation: Dp,
private val pressedElevation: Dp,
private val focusedElevation: Dp,
private val hoveredElevation: Dp,
) {
@Composable
internal fun shadowElevation(interactionSource: InteractionSource): State<Dp> {
return animateElevation(interactionSource = interactionSource)
}
@Composable
internal fun tonalElevation(interactionSource: InteractionSource): State<Dp> {
return animateElevation(interactionSource = interactionSource)
}
@Composable
private fun animateElevation(interactionSource: InteractionSource): State<Dp> {
val interactions = remember { mutableStateListOf<Interaction>() }
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is HoverInteraction.Enter -> {
interactions.add(interaction)
}
is HoverInteraction.Exit -> {
interactions.remove(interaction.enter)
}
is FocusInteraction.Focus -> {
interactions.add(interaction)
}
is FocusInteraction.Unfocus -> {
interactions.remove(interaction.focus)
}
is PressInteraction.Press -> {
interactions.add(interaction)
}
is PressInteraction.Release -> {
interactions.remove(interaction.press)
}
is PressInteraction.Cancel -> {
interactions.remove(interaction.press)
}
}
}
}
val interaction = interactions.lastOrNull()
val target = when (interaction) {
is PressInteraction.Press -> pressedElevation
is HoverInteraction.Enter -> hoveredElevation
is FocusInteraction.Focus -> focusedElevation
else -> defaultElevation
}
val animatable = remember { Animatable(target, Dp.VectorConverter) }
LaunchedEffect(target) {
val lastInteraction = when (animatable.targetValue) {
pressedElevation -> PressInteraction.Press(Offset.Zero)
hoveredElevation -> HoverInteraction.Enter()
focusedElevation -> FocusInteraction.Focus()
else -> null
}
animatable.animateElevation(
from = lastInteraction,
to = interaction,
target = target,
)
}
return animatable.asState()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is FloatingActionButtonElevation) return false
if (defaultElevation != other.defaultElevation) return false
if (pressedElevation != other.pressedElevation) return false
if (focusedElevation != other.focusedElevation) return false
if (hoveredElevation != other.hoveredElevation) return false
return true
}
override fun hashCode(): Int {
var result = defaultElevation.hashCode()
result = 31 * result + pressedElevation.hashCode()
result = 31 * result + focusedElevation.hashCode()
result = 31 * result + hoveredElevation.hashCode()
return result
}
}
private val ExtendedFabStartIconPadding = 16.dp
private val ExtendedFabEndIconPadding = 12.dp
private val ExtendedFabTextPadding = 20.dp
private val ExtendedFabMinimumWidth = 80.dp
private val ExtendedFabCollapseAnimation = fadeOut(
animationSpec = tween(
durationMillis = MotionTokens.DurationShort2.toInt(),
easing = MotionTokens.EasingLinearCubicBezier,
)
) + shrinkHorizontally(
animationSpec = tween(
durationMillis = MotionTokens.DurationLong2.toInt(),
easing = MotionTokens.EasingEmphasizedCubicBezier,
),
shrinkTowards = Alignment.Start,
)
private val ExtendedFabExpandAnimation = fadeIn(
animationSpec = tween(
durationMillis = MotionTokens.DurationShort4.toInt(),
delayMillis = MotionTokens.DurationShort2.toInt(),
easing = MotionTokens.EasingLinearCubicBezier,
),
) + expandHorizontally(
animationSpec = tween(
durationMillis = MotionTokens.DurationLong2.toInt(),
easing = MotionTokens.EasingEmphasizedCubicBezier,
),
expandFrom = Alignment.Start,
)
| apache-2.0 | da16a05afd7731ac191030d0a69f3c2b | 44.961039 | 161 | 0.718282 | 5.298896 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/OutlineResolver.android.kt | 3 | 12988 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.platform
import android.os.Build
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSimple
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.asAndroidPath
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import kotlin.math.roundToInt
import android.graphics.Outline as AndroidOutline
/**
* Resolves the [AndroidOutline] from the [Shape] of an [OwnedLayer].
*/
internal class OutlineResolver(private var density: Density) {
/**
* Flag to determine if the shape specified on the outline is supported.
* On older API levels, concave shapes are not allowed
*/
private var isSupportedOutline = true
/**
* The Android Outline that is used in the layer.
*/
private val cachedOutline = AndroidOutline().apply { alpha = 1f }
/**
* The size of the layer. This is used in generating the [Outline] from the [Shape].
*/
private var size: Size = Size.Zero
/**
* The [Shape] of the Outline of the Layer.
*/
private var shape: Shape = RectangleShape
/**
* Asymmetric rounded rectangles need to use a Path. This caches that Path so that
* a new one doesn't have to be generated each time.
*/
// TODO(andreykulikov): Make Outline API reuse the Path when generating.
private var cachedRrectPath: Path? = null // for temporary allocation in rounded rects
/**
* The outline Path when a non-conforming (rect or symmetric rounded rect) Outline
* is used. This Path is necessary when [usePathForClip] is true to indicate the
* Path to clip in [clipPath].
*/
private var outlinePath: Path? = null
/**
* True when there's been an update that caused a change in the path and the Outline
* has to be reevaluated.
*/
private var cacheIsDirty = false
/**
* True when Outline cannot clip the content and the path should be used instead.
* This is when an asymmetric rounded rect or general Path is used in the outline.
* This is false when a Rect or a symmetric RoundRect is used in the outline.
*/
private var usePathForClip = false
/**
* Scratch path used for manually clipping in software backed canvases
*/
private var tmpPath: Path? = null
/**
* Scratch [RoundRect] used for manually clipping round rects in software backed canvases
*/
private var tmpRoundRect: RoundRect? = null
/**
* Radius value used for symmetric rounded shapes. For rectangular or path based outlines
* this value is 0f
*/
private var roundedCornerRadius: Float = 0f
/**
* Returns the Android Outline to be used in the layer.
*/
val outline: AndroidOutline?
get() {
updateCache()
return if (!outlineNeeded || !isSupportedOutline) null else cachedOutline
}
/**
* Determines if the particular outline shape or path supports clipping.
* True for rect or symmetrical round rects.
* This method is used to determine if the framework can handle clipping to the outline
* for a particular shape. If not, then the clipped path must be applied directly to the canvas.
*/
val outlineClipSupported: Boolean
get() = !usePathForClip
/**
* Returns the path used to manually clip regardless if the layer supports clipping or not.
* In some cases (i.e. software rendering) clipping must be done manually.
* Consumers should query whether or not the layer will handle clipping with
* [outlineClipSupported] first before applying the clip manually.
* Or when rendering in software, the clip path provided here must always be clipped manually.
*/
val clipPath: Path?
get() {
updateCache()
return outlinePath
}
/**
* Returns the top left offset for a rectangular, or rounded rect outline (regardless if it
* is symmetric or asymmetric)
* For path based outlines this returns [Offset.Zero]
*/
private var rectTopLeft: Offset = Offset.Zero
/**
* Returns the size for a rectangular, or rounded rect outline (regardless if it
* is symmetric or asymmetric)
* For path based outlines this returns [Size.Zero]
*/
private var rectSize: Size = Size.Zero
/**
* True when we are going to clip or have a non-zero elevation for shadows.
*/
private var outlineNeeded = false
private var layoutDirection = LayoutDirection.Ltr
private var tmpTouchPointPath: Path? = null
private var tmpOpPath: Path? = null
private var calculatedOutline: Outline? = null
/**
* Updates the values of the outline. Returns `true` when the shape has changed.
*/
fun update(
shape: Shape,
alpha: Float,
clipToOutline: Boolean,
elevation: Float,
layoutDirection: LayoutDirection,
density: Density
): Boolean {
cachedOutline.alpha = alpha
val shapeChanged = this.shape != shape
if (shapeChanged) {
this.shape = shape
cacheIsDirty = true
}
val outlineNeeded = clipToOutline || elevation > 0f
if (this.outlineNeeded != outlineNeeded) {
this.outlineNeeded = outlineNeeded
cacheIsDirty = true
}
if (this.layoutDirection != layoutDirection) {
this.layoutDirection = layoutDirection
cacheIsDirty = true
}
if (this.density != density) {
this.density = density
cacheIsDirty = true
}
return shapeChanged
}
/**
* Returns true if there is a outline and [position] is outside the outline.
*/
fun isInOutline(position: Offset): Boolean {
if (!outlineNeeded) {
return true
}
val outline = calculatedOutline ?: return true
return isInOutline(outline, position.x, position.y, tmpTouchPointPath, tmpOpPath)
}
/**
* Manually applies the clip to the provided canvas based on the given outline.
* This is used in scenarios where clipping must be applied manually either because
* the outline cannot be clipped automatically for specific shapes or if the
* layer is being rendered in software
*/
fun clipToOutline(canvas: Canvas) {
// If we have a clip path that means we are clipping to an arbitrary path or
// a rounded rect with non-uniform corner radii
val targetPath = clipPath
if (targetPath != null) {
canvas.clipPath(targetPath)
} else {
// If we have a non-zero radius, that means we are clipping to a symmetrical
// rounded rectangle.
// Canvas does not include a clipRoundRect API so create a path with the round rect
// and clip to the given path/
if (roundedCornerRadius > 0f) {
var roundRectClipPath = tmpPath
var roundRect = tmpRoundRect
if (roundRectClipPath == null ||
!roundRect.isSameBounds(rectTopLeft, rectSize, roundedCornerRadius)) {
roundRect = RoundRect(
left = rectTopLeft.x,
top = rectTopLeft.y,
right = rectTopLeft.x + rectSize.width,
bottom = rectTopLeft.y + rectSize.height,
cornerRadius = CornerRadius(roundedCornerRadius)
)
if (roundRectClipPath == null) {
roundRectClipPath = Path()
} else {
roundRectClipPath.reset()
}
roundRectClipPath.addRoundRect(roundRect)
tmpRoundRect = roundRect
tmpPath = roundRectClipPath
}
canvas.clipPath(roundRectClipPath)
} else {
// ... otherwise, just clip to the bounds of the rect
canvas.clipRect(
left = rectTopLeft.x,
top = rectTopLeft.y,
right = rectTopLeft.x + rectSize.width,
bottom = rectTopLeft.y + rectSize.height,
)
}
}
}
/**
* Updates the size.
*/
fun update(size: Size) {
if (this.size != size) {
this.size = size
cacheIsDirty = true
}
}
private fun updateCache() {
if (cacheIsDirty) {
rectTopLeft = Offset.Zero
rectSize = size
roundedCornerRadius = 0f
outlinePath = null
cacheIsDirty = false
usePathForClip = false
if (outlineNeeded && size.width > 0.0f && size.height > 0.0f) {
// Always assume the outline type is supported
// The methods to configure the outline will determine/update the flag
// if it not supported on the API level
isSupportedOutline = true
val outline = shape.createOutline(size, layoutDirection, density)
calculatedOutline = outline
when (outline) {
is Outline.Rectangle -> updateCacheWithRect(outline.rect)
is Outline.Rounded -> updateCacheWithRoundRect(outline.roundRect)
is Outline.Generic -> updateCacheWithPath(outline.path)
}
} else {
cachedOutline.setEmpty()
}
}
}
private fun updateCacheWithRect(rect: Rect) {
rectTopLeft = Offset(rect.left, rect.top)
rectSize = Size(rect.width, rect.height)
cachedOutline.setRect(
rect.left.roundToInt(),
rect.top.roundToInt(),
rect.right.roundToInt(),
rect.bottom.roundToInt()
)
}
private fun updateCacheWithRoundRect(roundRect: RoundRect) {
val radius = roundRect.topLeftCornerRadius.x
rectTopLeft = Offset(roundRect.left, roundRect.top)
rectSize = Size(roundRect.width, roundRect.height)
if (roundRect.isSimple) {
cachedOutline.setRoundRect(
roundRect.left.roundToInt(),
roundRect.top.roundToInt(),
roundRect.right.roundToInt(),
roundRect.bottom.roundToInt(),
radius
)
roundedCornerRadius = radius
} else {
val path = cachedRrectPath ?: Path().also { cachedRrectPath = it }
path.reset()
path.addRoundRect(roundRect)
updateCacheWithPath(path)
}
}
@Suppress("deprecation")
private fun updateCacheWithPath(composePath: Path) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P || composePath.isConvex) {
// TODO(mount): Use setPath() for R+ when available.
cachedOutline.setConvexPath(composePath.asAndroidPath())
usePathForClip = !cachedOutline.canClip()
} else {
isSupportedOutline = false // Concave outlines are not supported on older API levels
cachedOutline.setEmpty()
usePathForClip = true
}
outlinePath = composePath
}
/**
* Helper method to see if the RoundRect has the same bounds as the offset as well as the same
* corner radius. If the RoundRect does not have symmetrical corner radii this method always
* returns false
*/
private fun RoundRect?.isSameBounds(offset: Offset, size: Size, radius: Float): Boolean {
if (this == null || !isSimple) {
return false
}
return left == offset.x &&
top == offset.y &&
right == (offset.x + size.width) &&
bottom == (offset.y + size.height) &&
topLeftCornerRadius.x == radius
}
}
| apache-2.0 | ea5baf72ff16a0aa1a475cdc3fcb26c1 | 35.585915 | 100 | 0.615799 | 5.003082 | false | false | false | false |
bfsmith/DataRecorder | app/src/main/java/com/github/bfsmith/recorder/MainActivity.kt | 1 | 10355 | package com.github.bfsmith.recorder
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.InputType.*
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ListAdapter
import com.github.bfsmith.recorder.util.MyListAdapter
import com.github.bfsmith.recorder.util.TemplateRenderer
import com.github.bfsmith.recorder.util.showKeyboardOnFocus
import org.jetbrains.anko.*
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.sdk25.coroutines.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainActivityUi().setContentView(this)
}
fun tagSelected(ui: AnkoContext<MainActivity>, tag: Tag) {
ui.doAsync {
activityUiThreadWithContext {
toast("You selected tag ${tag.tag}.")
startActivity<TagViewActivity>("TagId" to tag.id)
}
}
}
}
class MainActivityUi : AnkoComponent<MainActivity> {
override fun createView(ui: AnkoContext<MainActivity>): View = with(ui) {
fun addValue(tagId: Int, value: Double?): Boolean {
if (value != null) {
ui.owner.database.addRecordForTag(tagId, value)
toast("Recorded ${value}")
return true
}
return false
}
var listAdapter: MyListAdapter<Tag>? = null
fun removeTag(tagId: Int) {
ui.owner.database.removeTag(tagId)
listAdapter?.notifyDataSetChanged()
}
listAdapter = MyListAdapter(owner.database.tags, { it.id }) {
tag ->
TemplateRenderer(owner) {
with(it) {
relativeLayout {
// backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent)
val buttonContainer = linearLayout {
id = R.id.buttonContainer
// Add value button
imageButton(android.R.drawable.ic_input_add) {
isFocusable = false
onClick {
var valueField: EditText? = null
val alertDialog = alert {
customView {
verticalLayout {
toolbar {
lparams(width = matchParent, height = wrapContent)
backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent)
title = "Add a value"
setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white))
}
valueField = editText {
hint = "Value"
padding = dip(20)
inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
// isFocusable = true
// isFocusableInTouchMode = true
showKeyboardOnFocus(ctx)
imeOptions = EditorInfo.IME_ACTION_DONE
}
positiveButton("Add") {
val value = valueField?.text.toString().toDoubleOrNull()
if (addValue(tag.id, value)) {
it.dismiss()
}
}
cancelButton { }
}
}
}.show()
valueField?.onEditorAction { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE
&& addValue(tag.id, valueField?.text.toString().toDoubleOrNull())) {
alertDialog.dismiss()
}
}
}
}
imageButton(android.R.drawable.ic_delete) {
isFocusable = false
onClick {
alert {
customView {
verticalLayout {
toolbar {
lparams(width = matchParent, height = wrapContent)
backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent)
title = "Delete '${tag.tag}'?"
setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white))
}
positiveButton("Yes") {
removeTag(tag.id)
it.dismiss()
}
negativeButton("No") {}
}
}
}.show()
}
}
}.lparams {
width = wrapContent
height = wrapContent
alignParentRight()
alignParentTop()
}
textView {
text = tag.tag
textSize = 32f
// background = ContextCompat.getDrawable(ctx, R.drawable.border)
// onClick {
// ui.owner.tagSelected(ui, tag)
// }
}.lparams {
alignParentLeft()
alignParentTop()
leftOf(buttonContainer)
}
}
}
}
}
coordinatorLayout {
verticalLayout {
padding = dip(8)
listView {
adapter = listAdapter
onItemClick { _, _, _, id ->
val tag = owner.database.tags.find { it.id == id.toInt() }
if (tag != null) {
owner.tagSelected(ui, tag)
}
}
}.lparams {
margin = dip(8)
width = matchParent
height = matchParent
}
}.lparams {
width = matchParent
height = matchParent
}
floatingActionButton {
imageResource = android.R.drawable.ic_input_add
onClick {
fun addTag(tag: String?): Boolean {
if (!tag.isNullOrEmpty()) {
owner.database.addTag(tag!!)
listAdapter?.notifyDataSetChanged()
return true
}
return false
}
var tagField: EditText? = null
val alertDialog = alert {
customView {
verticalLayout {
toolbar {
lparams(width = matchParent, height = wrapContent)
backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent)
title = "Add a Tag"
setTitleTextColor(ContextCompat.getColor(ctx, android.R.color.white))
}
tagField = editText {
hint = "Tag"
padding = dip(20)
showKeyboardOnFocus(ctx)
inputType = TYPE_CLASS_TEXT or TYPE_TEXT_FLAG_CAP_WORDS
imeOptions = EditorInfo.IME_ACTION_DONE
}
positiveButton("Add") {
if (addTag(tagField?.text.toString())) {
it.dismiss()
}
}
cancelButton { }
}
}
}.show()
tagField?.onEditorAction { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE
&& addTag(tagField?.text.toString())) {
alertDialog.dismiss()
}
}
}
}.lparams {
margin = dip(10)
gravity = Gravity.BOTTOM or Gravity.END
}
}
}
}
| mit | 3accfb8bcf6968cbbc97ea7d152532c3 | 45.855204 | 121 | 0.363399 | 7.541879 | false | false | false | false |
angelgladin/Photo_Exif_Toolkit | app/src/main/kotlin/com/angelgladin/photoexiftoolkit/dialog/MapsDialog.kt | 1 | 6830 | /**
* Photo EXIF Toolkit for Android.
*
* Copyright (C) 2017 Ángel Iván Gladín García
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.angelgladin.photoexiftoolkit.dialog
import android.app.Activity
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.*
import com.angelgladin.photoexiftoolkit.R
import com.angelgladin.photoexiftoolkit.domain.Location
import com.angelgladin.photoexiftoolkit.util.Constants
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
/**
* Created on 12/22/16.
*/
class MapDialog : DialogFragment(), OnMapReadyCallback, GoogleMap.OnMapClickListener, Toolbar.OnMenuItemClickListener {
lateinit var dialogEvents: DialogEvents
lateinit var toolbar: Toolbar
lateinit var mMap: GoogleMap
lateinit var location: LatLng
lateinit var marker: Marker
var editModeLocation = false
var locationChanged = false
companion object {
fun newInstance(latitude: Double, longitude: Double): MapDialog {
val frag = MapDialog()
val bundle = Bundle()
bundle.putDouble(Constants.EXIF_LATITUDE, latitude)
bundle.putDouble(Constants.EXIF_LONGITUDE, longitude)
frag.arguments = bundle
return frag
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.dialog_maps, container, false)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
toolbar = view.findViewById(R.id.toolbar) as Toolbar
toolbar.apply {
inflateMenu(R.menu.menu_dialog_maps)
setOnMenuItemClickListener(this@MapDialog)
setNavigationIcon(R.drawable.ic_arrow_back_black_24dp)
setNavigationOnClickListener { dismiss() }
title = resources.getString(R.string.dialog_maps_title)
}
return view
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
try {
dialogEvents = activity as DialogEvents
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + " must implement DialogEvents")
}
}
override fun onResume() {
super.onResume()
val mapFragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onDestroyView() {
super.onDestroyView()
dialogEvents.locationChanged(locationChanged, Location(location.latitude, location.longitude))
Log.d(this.javaClass.simpleName, "Location changed: $locationChanged, Location: $location")
val f = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
if (f != null) fragmentManager.beginTransaction().remove(f).commit()
}
override fun onMenuItemClick(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_edit_location -> {
editLocation()
true
}
R.id.action_done_editing -> {
doneEditing()
true
}
else -> false
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
location = LatLng(arguments.getDouble(Constants.EXIF_LATITUDE), arguments.getDouble(Constants.EXIF_LONGITUDE))
mMap.apply {
setOnMapClickListener(this@MapDialog)
uiSettings.isZoomControlsEnabled = true
isMyLocationEnabled = true
moveCamera(CameraUpdateFactory.newLatLngZoom(location, 14.8f))
}
addMarker(location)
}
override fun onMapClick(latLng: LatLng) {
if (editModeLocation) {
Log.d(this.javaClass.simpleName, "Latitude ${latLng.latitude} -- Longitude ${latLng.longitude}")
marker.remove()
addMarker(latLng)
}
}
private fun editLocation() {
editModeLocation = true
toolbar.title = resources.getString(R.string.dialog_maps_title_tap_for_new_location)
toolbar.menu.findItem(R.id.action_edit_location).isVisible = false
toolbar.menu.findItem(R.id.action_done_editing).isVisible = true
}
private fun doneEditing() {
editModeLocation = false
showAlertDialog()
toolbar.title = resources.getString(R.string.dialog_maps_title)
toolbar.menu.findItem(R.id.action_done_editing).isVisible = false
toolbar.menu.findItem(R.id.action_edit_location).isVisible = true
}
private fun showAlertDialog() {
AlertDialog.Builder(context)
.setTitle(resources.getString(R.string.dialog_maps_title_edit_location))
.setMessage(resources.getString(R.string.dialog_maps_title_edit_location_message))
.setPositiveButton(resources.getString(android.R.string.ok),
{ dialogInterface, i ->
locationChanged = true
location = marker.position
dismiss()
})
.setNegativeButton(resources.getString(android.R.string.cancel),
{ dialogInterface, i ->
marker.remove()
addMarker(location)
})
.show()
}
private fun addMarker(location: LatLng) {
marker = mMap.addMarker(MarkerOptions().position(location))
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
}
interface DialogEvents {
fun locationChanged(locationChanged: Boolean, location: Location)
}
} | gpl-3.0 | 3985783ba51933f4bdb47db8602ed466 | 36.103261 | 119 | 0.665251 | 4.736988 | false | false | false | false |
elect86/helloTriangle | src/main/kotlin/gl4/helloGlobe.kt | 1 | 13057 | package gl4
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.KeyListener
import com.jogamp.newt.event.WindowAdapter
import com.jogamp.newt.event.WindowEvent
import com.jogamp.newt.opengl.GLWindow
import com.jogamp.opengl.*
import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_HIGH
import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_MEDIUM
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL4.GL_MAP_COHERENT_BIT
import com.jogamp.opengl.GL4.GL_MAP_PERSISTENT_BIT
import com.jogamp.opengl.util.Animator
import com.jogamp.opengl.util.texture.TextureIO
import framework.Semantic
import glm.*
import glm.mat.Mat4
import glm.vec._2.Vec2
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import uno.buffer.*
import uno.debug.GlDebugOutput
import uno.glsl.Program
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import java.nio.ShortBuffer
import kotlin.properties.Delegates
fun main(args: Array<String>) {
HelloGlobe_().setup()
}
class HelloGlobe_ : GLEventListener, KeyListener {
var window by Delegates.notNull<GLWindow>()
val animator = Animator()
object Buffer {
val VERTEX = 0
val ELEMENT = 1
val GLOBAL_MATRICES = 2
val MODEL_MATRIX = 3
val MAX = 4
}
val bufferName = intBufferBig(Buffer.MAX)
val vertexArrayName = intBufferBig(1)
val textureName = intBufferBig(1)
val samplerName = intBufferBig(1)
val clearColor = floatBufferBig(Vec4.length)
val clearDepth = floatBufferBig(1)
var globalMatricesPointer by Delegates.notNull<ByteBuffer>()
var modelMatrixPointer by Delegates.notNull<ByteBuffer>()
// https://jogamp.org/bugzilla/show_bug.cgi?id=1287
val bug1287 = true
var program by Delegates.notNull<Program>()
var start = 0L
var elementCount = 0
fun setup() {
val glProfile = GLProfile.get(GLProfile.GL3)
val glCapabilities = GLCapabilities(glProfile)
window = GLWindow.create(glCapabilities)
window.title = "Hello Globe"
window.setSize(1024, 768)
window.contextCreationFlags = GLContext.CTX_OPTION_DEBUG
window.isVisible = true
window.addGLEventListener(this)
window.addKeyListener(this)
animator.add(window)
animator.start()
window.addWindowListener(object : WindowAdapter() {
override fun windowDestroyed(e: WindowEvent?) {
animator.stop()
System.exit(1)
}
})
}
override fun init(drawable: GLAutoDrawable) {
val gl = drawable.gl.gL4
initDebug(gl)
initBuffers(gl)
initTexture(gl)
initSampler(gl)
initVertexArray(gl)
program = Program(gl, this::class.java, "shaders/gl4", "hello-globe.vert", "hello-globe.frag")
gl.glEnable(GL.GL_DEPTH_TEST)
start = System.currentTimeMillis()
}
fun initDebug(gl: GL4) = with(gl) {
window.context.addGLDebugListener(GlDebugOutput())
glDebugMessageControl(
GL_DONT_CARE,
GL_DONT_CARE,
GL_DONT_CARE,
0, null,
false)
glDebugMessageControl(
GL_DONT_CARE,
GL_DONT_CARE,
GL_DEBUG_SEVERITY_HIGH,
0, null,
true)
glDebugMessageControl(
GL_DONT_CARE,
GL_DONT_CARE,
GL_DEBUG_SEVERITY_MEDIUM,
0, null,
true)
}
fun initBuffers(gl: GL4) = with(gl) {
val radius = 1f
val rings = 100.s
val sectors = 100.s
val vertexBuffer = getVertexBuffer(radius, rings, sectors)
val elementBuffer = getElementBuffer(radius, rings, sectors)
elementCount = elementBuffer.capacity()
glCreateBuffers(Buffer.MAX, bufferName)
if (!bug1287) {
glNamedBufferStorage(bufferName[Buffer.VERTEX], vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW)
glNamedBufferStorage(bufferName[Buffer.ELEMENT], elementBuffer.SIZE.L, elementBuffer, GL_STATIC_DRAW)
glNamedBufferStorage(bufferName[Buffer.GLOBAL_MATRICES], Mat4.SIZE * 2.L, null, GL_MAP_WRITE_BIT)
glNamedBufferStorage(bufferName[Buffer.MODEL_MATRIX], Mat4.SIZE.L, null, GL_MAP_WRITE_BIT)
} else {
glBindBuffer(GL_ARRAY_BUFFER, bufferName[Buffer.VERTEX])
glBufferStorage(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName[Buffer.ELEMENT])
glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.SIZE.L, elementBuffer, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
val uniformBufferOffset = intBufferBig(1)
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, uniformBufferOffset)
val globalBlockSize = glm.max(Mat4.SIZE * 2, uniformBufferOffset[0])
val modelBlockSize = glm.max(Mat4.SIZE, uniformBufferOffset[0])
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.GLOBAL_MATRICES])
glBufferStorage(GL_UNIFORM_BUFFER, globalBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.MODEL_MATRIX])
glBufferStorage(GL_UNIFORM_BUFFER, modelBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
uniformBufferOffset.destroy()
}
destroyBuffers(vertexBuffer, elementBuffer)
// map the transform buffers and keep them mapped
globalMatricesPointer = glMapNamedBufferRange(
bufferName[Buffer.GLOBAL_MATRICES],
0,
Mat4.SIZE * 2.L,
GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT)
modelMatrixPointer = glMapNamedBufferRange(
bufferName[Buffer.MODEL_MATRIX],
0,
Mat4.SIZE.L,
GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT)
}
fun getVertexBuffer(radius: Float, rings: Short, sectors: Short): FloatBuffer {
val R = 1f / (rings - 1).toFloat()
val S = 1f / (sectors - 1).toFloat()
var r: Short = 0
var s: Short
var x: Float
var y: Float
var z: Float
val vertexBuffer = floatBufferBig(rings.toInt() * sectors.toInt() * (3 + 2))
while (r < rings) {
s = 0
while (s < sectors) {
x = glm.cos(2f * glm.pi.toFloat() * s.toFloat() * S) * glm.sin(glm.pi.toFloat() * r.toFloat() * R)
y = glm.sin(-glm.pi.toFloat() / 2 + glm.pi.toFloat() * r.toFloat() * R)
z = glm.sin(2f * glm.pi.toFloat() * s.toFloat() * S) * glm.sin(glm.pi.toFloat() * r.toFloat() * R)
// positions
vertexBuffer.put(x * radius)
vertexBuffer.put(y * radius)
vertexBuffer.put(z * radius)
// texture coordinates
vertexBuffer.put(1 - s * S)
vertexBuffer.put(r * R)
s++
}
r++
}
vertexBuffer.position(0)
return vertexBuffer
}
fun getElementBuffer(radius: Float, rings: Short, sectors: Short): ShortBuffer {
val R = 1f / (rings - 1).f
val S = 1f / (sectors - 1).f
var r = 0.s
var s: Short
val x: Float
val y: Float
val z: Float
val elementBuffer = shortBufferBig(rings.i * sectors.i * 6)
while (r < rings - 1) {
s = 0
while (s < sectors - 1) {
elementBuffer.put((r * sectors + s).s)
elementBuffer.put((r * sectors + (s + 1)).s)
elementBuffer.put(((r + 1) * sectors + (s + 1)).s)
elementBuffer.put(((r + 1) * sectors + (s + 1)).s)
elementBuffer.put((r * sectors + s).s)
// elementBuffer.put((short) (r * sectors + (s + 1)));
elementBuffer.put(((r + 1) * sectors + s).s)
s++
}
r++
}
elementBuffer.position(0)
return elementBuffer
}
fun initVertexArray(gl: GL4) = with(gl) {
glCreateVertexArrays(1, vertexArrayName)
glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.POSITION, Semantic.Stream.A)
glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.TEXCOORD, Semantic.Stream.A)
glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.POSITION, Vec3.length, GL_FLOAT, false, 0)
glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.TEXCOORD, Vec2.length, GL_FLOAT, false, Vec3.SIZE)
glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.POSITION)
glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.TEXCOORD)
glVertexArrayElementBuffer(vertexArrayName[0], bufferName[Buffer.ELEMENT])
glVertexArrayVertexBuffer(vertexArrayName[0], Semantic.Stream.A, bufferName[Buffer.VERTEX], 0, Vec2.SIZE + Vec3.SIZE)
}
fun initTexture(gl: GL4) = with(gl) {
val texture = this::class.java.classLoader.getResource("images/globe.png")
val textureData = TextureIO.newTextureData(glProfile, texture!!, false, TextureIO.PNG)
glCreateTextures(GL_TEXTURE_2D, 1, textureName)
glTextureParameteri(textureName[0], GL_TEXTURE_BASE_LEVEL, 0)
glTextureParameteri(textureName[0], GL_TEXTURE_MAX_LEVEL, 0)
glTextureStorage2D(textureName[0],
1, // level
textureData.internalFormat,
textureData.width, textureData.height)
glTextureSubImage2D(textureName.get(0),
0, // level
0, 0, // offset
textureData.width, textureData.height,
textureData.pixelFormat, textureData.pixelType,
textureData.buffer)
}
fun initSampler(gl: GL4) = with(gl) {
glGenSamplers(1, samplerName)
glSamplerParameteri(samplerName[0], GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glSamplerParameteri(samplerName[0], GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glSamplerParameteri(samplerName[0], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glSamplerParameteri(samplerName[0], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
}
override fun display(drawable: GLAutoDrawable) = with(drawable.gl.gL4) {
// view matrix
run {
val view = glm.lookAt(Vec3(0f, 0f, 3f), Vec3(), Vec3(0f, 1f, 0f))
view.to(globalMatricesPointer, Mat4.SIZE)
}
glClearBufferfv(GL_COLOR, 0, clearColor.put(1f, .5f, 0f, 1f))
glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1f))
// model matrix
run {
val now = System.currentTimeMillis()
val diff = (now - start).f / 1_000f
val model = Mat4().rotate_(-diff, 0f, 1f, 0f)
model to modelMatrixPointer
}
glUseProgram(program.name)
glBindVertexArray(vertexArrayName[0])
glBindBufferBase(
GL_UNIFORM_BUFFER,
Semantic.Uniform.TRANSFORM0,
bufferName[Buffer.GLOBAL_MATRICES])
glBindBufferBase(
GL_UNIFORM_BUFFER,
Semantic.Uniform.TRANSFORM1,
bufferName[Buffer.MODEL_MATRIX])
glBindTextureUnit(
Semantic.Sampler.DIFFUSE,
textureName[0])
glBindSampler(Semantic.Sampler.DIFFUSE, samplerName[0])
glDrawElements(
GL.GL_TRIANGLES,
elementCount,
GL_UNSIGNED_SHORT,
0)
}
override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) {
val gl = drawable.gl.gL4
val aspect = width.f / height
val proj = glm.perspective(glm.pi.f * 0.25f, aspect, 0.1f, 100f)
proj to globalMatricesPointer
}
override fun dispose(drawable: GLAutoDrawable) = with(drawable.gl.gL4) {
glUnmapNamedBuffer(bufferName[Buffer.GLOBAL_MATRICES])
glUnmapNamedBuffer(bufferName[Buffer.MODEL_MATRIX])
glDeleteProgram(program.name)
glDeleteVertexArrays(1, vertexArrayName)
glDeleteBuffers(Buffer.MAX, bufferName)
glDeleteTextures(1, textureName)
glDeleteSamplers(1, samplerName)
destroyBuffers(vertexArrayName, bufferName, textureName, samplerName, clearColor, clearDepth)
}
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ESCAPE) {
Thread { window.destroy() }.start()
}
}
override fun keyReleased(e: KeyEvent) {}
} | mit | a011a71ef48a86583a1629ed92940168 | 31.162562 | 137 | 0.610094 | 4.151669 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/com/jagrosh/jdautilities/menu/Selector.kt | 1 | 6384 | package com.jagrosh.jdautilities.menu
import com.jagrosh.jdautilities.waiter.EventWaiter
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageEmbed
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent
import xyz.gnarbot.gnar.utils.embed
import java.awt.Color
import java.util.concurrent.TimeUnit
class Selector(waiter: EventWaiter,
user: User?,
title: String?,
description: String?,
color: Color?,
fields: List<MessageEmbed.Field>,
val type: Type,
val options: List<Entry>,
timeout: Long,
unit: TimeUnit,
finally: (Message?) -> Unit) : Menu(waiter, user, title, description, color, fields, timeout, unit, finally) {
enum class Type {
REACTIONS,
MESSAGE
}
val cancel = "\u274C"
var message: Message? = null
fun display(channel: TextChannel) {
if (!channel.guild.selfMember.hasPermission(channel, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_MANAGE, Permission.MESSAGE_EMBED_LINKS)) {
channel.sendMessage(embed("Error") {
color { Color.RED }
desc {
buildString {
append("The bot requires the permission `${Permission.MESSAGE_ADD_REACTION.getName()}`, ")
append("`${Permission.MESSAGE_MANAGE.getName()}` and ")
append("`${Permission.MESSAGE_EMBED_LINKS.getName()}` for selection menus.")
}
}
}.build()).queue()
finally(message)
return
}
channel.sendMessage(embed(title) {
color { channel.guild.selfMember.color }
description {
buildString {
append(description).append('\n').append('\n')
options.forEachIndexed { index, (name) ->
append("${'\u0030' + index}\u20E3 $name\n")
}
}
}
field("Select an Option") {
when (type) {
Type.REACTIONS -> "Pick a reaction corresponding to the options."
Type.MESSAGE -> "Type a number corresponding to the options. ie: `0` or `cancel`"
}
}
super.fields.forEach {
addField(it)
}
setFooter("This selection will time out in $timeout ${unit.toString().toLowerCase()}.", null)
}.build()).queue {
message = it
when (type) {
Type.REACTIONS -> {
options.forEachIndexed { index, _ ->
it.addReaction("${'\u0030' + index}\u20E3").queue()
}
it.addReaction(cancel).queue()
}
Type.MESSAGE -> { /* pass */
}
}
}
when (type) {
Type.REACTIONS -> {
waiter.waitFor(MessageReactionAddEvent::class.java) {
if (it.reaction.reactionEmote.name == cancel) {
finally(message)
return@waitFor
}
val value = it.reaction.reactionEmote.name[0] - '\u0030'
it.channel.retrieveMessageById(it.messageIdLong).queue {
options[value].action(it)
}
finally(message)
}.predicate {
when {
it.messageIdLong != message?.idLong -> false
it!!.user!!.isBot -> false
user != null && it.user != user -> {
it.reaction.removeReaction(it!!.user!!).queue()
false
}
else -> {
if (it.reaction.reactionEmote.name == cancel) {
true
} else {
val value = it.reaction.reactionEmote.name[0] - '\u0030'
if (value in 0 until options.size) {
true
} else {
it.reaction.removeReaction(it!!.user!!).queue()
false
}
}
}
}
}.timeout(timeout, unit) {
finally(message)
}
}
Type.MESSAGE -> {
waiter.waitFor(GuildMessageReceivedEvent::class.java) {
val content = it.message.contentDisplay
if (content == "cancel") {
finally(message)
return@waitFor
}
val value = content.toIntOrNull() ?: return@waitFor
it.channel.retrieveMessageById(it.messageIdLong).queue {
options[value].action(it)
}
finally(message)
}.predicate {
when {
it.author.isBot -> false
user != null && it.author != user -> {
false
}
else -> {
val content = it.message.contentDisplay
if (content == "cancel") {
true
} else {
val value = content.toIntOrNull() ?: return@predicate false
value in 0 until options.size
}
}
}
}.timeout(timeout, unit) {
finally(message)
}
}
}
}
data class Entry(val name: String, val action: (Message) -> Unit)
} | mit | e2b3c7f20d8b9cb41dcb9e3a5be8f7ec | 37.932927 | 155 | 0.4375 | 5.556136 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/test/java/com/reactnativenavigation/utils/TitleAndButtonsMeasurer.kt | 1 | 13596 | package com.reactnativenavigation.utils
import com.reactnativenavigation.BaseTest
import com.reactnativenavigation.views.stack.topbar.titlebar.DEFAULT_LEFT_MARGIN_PX
import com.reactnativenavigation.views.stack.topbar.titlebar.resolveLeftButtonsBounds
import com.reactnativenavigation.views.stack.topbar.titlebar.resolveRightButtonsBounds
import com.reactnativenavigation.views.stack.topbar.titlebar.resolveHorizontalTitleBoundsLimit
import org.junit.Test
import kotlin.test.assertEquals
class TitleAndButtonsMeasurer : BaseTest() {
private val parentWidth = 1080
@Test
fun `left buttons should be at parent start`() {
val barWidth = 200
val isRTL = false
val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(barWidth, right)
}
@Test
fun `left buttons should not exceed parent width`() {
val barWidth = parentWidth + 1
val isRTL = false
val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(parentWidth, right)
}
@Test
fun `RTL - left buttons should be at parent end`() {
val barWidth = 200
val isRTL = true
val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(parentWidth - barWidth, left)
assertEquals(parentWidth, right)
}
@Test
fun `RTL - left buttons should not exceed parent left`() {
val barWidth = parentWidth + 1
val isRTL = true
val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(parentWidth, right)
}
@Test
fun `right buttons should be at parent end`() {
val barWidth = 200
val isRTL = false
val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(parentWidth - barWidth, left)
assertEquals(parentWidth, right)
}
@Test
fun `right buttons should not exceed parent start`() {
val barWidth = parentWidth + 1
val isRTL = false
val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(parentWidth, right)
}
@Test
fun `RTL - right buttons should be at parent start`() {
val barWidth = 200
val isRTL = true
val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(barWidth, right)
}
@Test
fun `RTL - right buttons should not exceed parent end`() {
val barWidth = parentWidth + 1
val isRTL = true
val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL)
assertEquals(0, left)
assertEquals(parentWidth, right)
}
@Test
fun `No Buttons - Aligned start - Title should be at default left margin bar width and right margin`() {
val barWidth = 200
val leftButtons = 0
val rightButtons = 0
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `RTL - No Buttons - Aligned start - Title should be at the end with default margins`() {
val barWidth = 200
val leftButtons = 0
val rightButtons = 0
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - barWidth - DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `RTL - No Buttons - Aligned start - Title should not exceed boundaries`() {
val barWidth = parentWidth + 1
val leftButtons = 0
val rightButtons = 0
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `No Buttons - Aligned start - Title should not exceed parent boundaries`() {
val barWidth = parentWidth + 1
val leftButtons = 0
val rightButtons = 0
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `No Buttons - Aligned center - Title should not exceed parent boundaries`() {
val barWidth = parentWidth + 1
val leftButtons = 0
val rightButtons = 0
val isRTL = false
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(0, left)
assertEquals(parentWidth, right)
}
@Test
fun `No Buttons - Aligned center - Title should have no margin and in center`() {
val barWidth = 200
val leftButtons = 0
val rightButtons = 0
val isRTL = false
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth / 2 - barWidth / 2, left)
assertEquals(parentWidth / 2 + barWidth / 2, right)
}
@Test
fun `RTL - No Buttons - Aligned center - Title should have no effect`() {
val barWidth = 200
val leftButtons = 0
val rightButtons = 0
val isRTL = true
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth / 2 - barWidth / 2, left)
assertEquals(parentWidth / 2 + barWidth / 2, right)
}
@Test
fun `Left Buttons - Aligned start - Title should be after left buttons with default margins`() {
val barWidth = 200
val leftButtons = 100
val rightButtons = 0
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `Left Buttons - Aligned start - Title should not exceed boundaries`() {
val barWidth = parentWidth + 1
val leftButtons = 100
val rightButtons = 0
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `RTL - Left Buttons - Aligned start - Title should be after left (right) buttons with default margins`() {
val barWidth = 200
val leftButtons = 100
val rightButtons = 0
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - leftButtons - barWidth - DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - leftButtons, right)
}
@Test
fun `RTL - Left Buttons - Aligned start - Title should not exceed boundaries`() {
val barWidth = parentWidth + 1
val leftButtons = 100
val rightButtons = 0
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `Left Buttons - Aligned center - Title should be at center`() {
val barWidth = 200
val leftButtons = 100
val rightButtons = 0
val isRTL = false
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth / 2 - barWidth / 2, left)
assertEquals(parentWidth / 2 + barWidth / 2, right)
}
@Test
fun `Left Buttons - Aligned center - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 0
val isRTL = false
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
val expectedOverlap = leftButtons - (parentWidth / 2 - barWidth / 2)
assertEquals(parentWidth / 2 - barWidth / 2 + expectedOverlap, left)
assertEquals(parentWidth / 2 + barWidth / 2 - expectedOverlap, right)
}
@Test
fun `RTL - Left Buttons - Aligned center - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 0
val isRTL = true
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
val expectedOverlap = leftButtons - (parentWidth / 2 - barWidth / 2)
assertEquals(parentWidth / 2 - barWidth / 2 + expectedOverlap, left)
assertEquals(parentWidth / 2 + barWidth / 2 - expectedOverlap, right)
}
@Test
fun `Left + Right Buttons - Aligned center - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 350
val isRTL = false
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(leftButtons, left)
assertEquals(parentWidth - rightButtons, right)
}
@Test
fun `RTL - Left + Right Buttons - Aligned center - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 350
val isRTL = true
val center = true
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(rightButtons, left)
assertEquals(parentWidth - leftButtons, right)
}
@Test
fun `Left + Right Buttons - Aligned start - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 350
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - rightButtons - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `Left + Right Buttons - Aligned start - Title should'nt take amount of needed width only between buttons only`() {
val barWidth = 100
val leftButtons = 300
val rightButtons = 350
val isRTL = false
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `RTL - Left + Right Buttons - Aligned start - Title should not exceed boundaries`() {
val parentWidth = 1000
val barWidth = 500
val leftButtons = 300
val rightButtons = 350
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(rightButtons + DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right)
}
@Test
fun `RTL - Left + Right Buttons - Aligned start - Title should take amount of needed width only`() {
val parentWidth = 1000
val barWidth = 100
val leftButtons = 300
val rightButtons = 100
val isRTL = true
val center = false
val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL)
assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX - barWidth - DEFAULT_LEFT_MARGIN_PX, left)
assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right)
}
} | mit | 09f1f3e69a5da722805291d53c829e00 | 37.086835 | 126 | 0.656664 | 5.002208 | false | true | false | false |
haozileung/test | src/main/kotlin/com/haozileung/web/domain/permission/User.kt | 1 | 584 | /*
* Powered By [rapid-framework]
* Web Site: http://www.rapid-framework.org.cn
* Google Code: http://code.google.com/p/rapid-framework/
* Since 2008 - 2016
*/
package com.haozileung.web.domain.permission
import java.io.Serializable
/**
* @author Haozi
* *
* @version 1.0
* *
* @since 1.0
*/
data class User(var userId: Long? = null,
var username: String? = null,
var password: String? = null,
var email: String? = null,
var remarks: String? = null,
var status: Int? = null) : Serializable | mit | 4a1754cd5a42662503f9e5353fe92f63 | 22.4 | 57 | 0.580479 | 3.415205 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt | 1 | 4814 | package eu.kanade.tachiyomi.ui.reader.viewer.pager
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView
import eu.kanade.tachiyomi.ui.reader.viewer.ViewerConfig
import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation
import eu.kanade.tachiyomi.ui.reader.viewer.navigation.DisabledNavigation
import eu.kanade.tachiyomi.ui.reader.viewer.navigation.EdgeNavigation
import eu.kanade.tachiyomi.ui.reader.viewer.navigation.KindlishNavigation
import eu.kanade.tachiyomi.ui.reader.viewer.navigation.LNavigation
import eu.kanade.tachiyomi.ui.reader.viewer.navigation.RightAndLeftNavigation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/**
* Configuration used by pager viewers.
*/
class PagerConfig(
private val viewer: PagerViewer,
scope: CoroutineScope,
readerPreferences: ReaderPreferences = Injekt.get(),
) : ViewerConfig(readerPreferences, scope) {
var theme = readerPreferences.readerTheme().get()
private set
var automaticBackground = false
private set
var dualPageSplitChangedListener: ((Boolean) -> Unit)? = null
var imageScaleType = 1
private set
var imageZoomType = ReaderPageImageView.ZoomStartPosition.LEFT
private set
var imageCropBorders = false
private set
var navigateToPan = false
private set
var landscapeZoom = false
private set
init {
readerPreferences.readerTheme()
.register(
{
theme = it
automaticBackground = it == 3
},
{ imagePropertyChangedListener?.invoke() },
)
readerPreferences.imageScaleType()
.register({ imageScaleType = it }, { imagePropertyChangedListener?.invoke() })
readerPreferences.zoomStart()
.register({ zoomTypeFromPreference(it) }, { imagePropertyChangedListener?.invoke() })
readerPreferences.cropBorders()
.register({ imageCropBorders = it }, { imagePropertyChangedListener?.invoke() })
readerPreferences.navigateToPan()
.register({ navigateToPan = it })
readerPreferences.landscapeZoom()
.register({ landscapeZoom = it }, { imagePropertyChangedListener?.invoke() })
readerPreferences.navigationModePager()
.register({ navigationMode = it }, { updateNavigation(navigationMode) })
readerPreferences.pagerNavInverted()
.register({ tappingInverted = it }, { navigator.invertMode = it })
readerPreferences.pagerNavInverted().changes()
.drop(1)
.onEach { navigationModeChangedListener?.invoke() }
.launchIn(scope)
readerPreferences.dualPageSplitPaged()
.register(
{ dualPageSplit = it },
{
imagePropertyChangedListener?.invoke()
dualPageSplitChangedListener?.invoke(it)
},
)
readerPreferences.dualPageInvertPaged()
.register({ dualPageInvert = it }, { imagePropertyChangedListener?.invoke() })
}
private fun zoomTypeFromPreference(value: Int) {
imageZoomType = when (value) {
// Auto
1 -> when (viewer) {
is L2RPagerViewer -> ReaderPageImageView.ZoomStartPosition.LEFT
is R2LPagerViewer -> ReaderPageImageView.ZoomStartPosition.RIGHT
else -> ReaderPageImageView.ZoomStartPosition.CENTER
}
// Left
2 -> ReaderPageImageView.ZoomStartPosition.LEFT
// Right
3 -> ReaderPageImageView.ZoomStartPosition.RIGHT
// Center
else -> ReaderPageImageView.ZoomStartPosition.CENTER
}
}
override var navigator: ViewerNavigation = defaultNavigation()
set(value) {
field = value.also { it.invertMode = this.tappingInverted }
}
override fun defaultNavigation(): ViewerNavigation {
return when (viewer) {
is VerticalPagerViewer -> LNavigation()
else -> RightAndLeftNavigation()
}
}
override fun updateNavigation(navigationMode: Int) {
navigator = when (navigationMode) {
0 -> defaultNavigation()
1 -> LNavigation()
2 -> KindlishNavigation()
3 -> EdgeNavigation()
4 -> RightAndLeftNavigation()
5 -> DisabledNavigation()
else -> defaultNavigation()
}
navigationModeChangedListener?.invoke()
}
}
| apache-2.0 | ba028d2264e77db42c9e4e3ff0b67396 | 33.385714 | 97 | 0.643332 | 5.402918 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/bindingutils/TodoBindingUtils.kt | 1 | 5833 | package com.rolandvitezhu.todocloud.ui.activity.main.bindingutils
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.rolandvitezhu.todocloud.app.AppController
import com.rolandvitezhu.todocloud.data.Todo
import com.rolandvitezhu.todocloud.listener.RecyclerViewOnItemTouchListener
import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.TodoAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.fragment.SearchFragment
import com.rolandvitezhu.todocloud.ui.activity.main.fragment.TodoListFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@BindingAdapter("todoSelectedState")
fun ConstraintLayout.setTodoSelectedState(todo: Todo) {
isActivated = todo.isSelected
}
@BindingAdapter("todoCompletedCheckedState")
fun AppCompatCheckBox.setTodoCompletedCheckedState(todo: Todo) {
isChecked = todo.completed ?: false
}
@BindingAdapter("todoPriority")
fun ImageView.setTodoPriority(todo: Todo) {
if (todo.priority != null && todo.priority == true)
visibility = View.VISIBLE
else
visibility = View.GONE
}
@BindingAdapter("todoDragHandleVisible")
fun ImageView.setTodoDragHandleVisible(todo: Todo) {
visibility =
if (AppController.isActionMode() && AppController.isDraggingEnabled)
View.VISIBLE
else
View.GONE
}
@BindingAdapter(value = ["dragHandleOnTouchListenerTodoAdapter",
"dragHandleOnTouchListenerItemViewHolder"])
fun ImageView.setDragHandleOnTouchListener(
todoAdapter: TodoAdapter, itemViewHolder: TodoAdapter.ItemViewHolder) {
setOnTouchListener { v, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
todoAdapter.itemTouchHelper?.startDrag(itemViewHolder)
}
false
}
}
@BindingAdapter(value = ["checkBoxTodoCompletedOnTouchListenerTodoAdapter",
"checkBoxTodoCompletedOnTouchListenerItemViewHolder", "checkBoxTodoCompletedOnTouchListenerTodo"])
fun AppCompatCheckBox.setCheckBoxTodoCompletedOnTouchListener(
todoAdapter: TodoAdapter, itemViewHolder: TodoAdapter.ItemViewHolder, todo: Todo) {
setOnTouchListener { v, event ->
if (todoAdapter.shouldHandleCheckBoxTouchEvent(event, itemViewHolder)) {
todoAdapter.toggleCompleted(todo)
val scope = CoroutineScope(Dispatchers.IO)
scope.launch { todoAdapter.updateTodo(todo) }
todoAdapter.removeTodoFromAdapter(itemViewHolder.adapterPosition)
todoAdapter.handleReminderService(todo)
}
true
}
}
@BindingAdapter("todoListItemTouchListener")
fun RecyclerView.setTodoListItemTouchListener(todoListFragment: TodoListFragment) {
addOnItemTouchListener(RecyclerViewOnItemTouchListener(
context,
this,
object : RecyclerViewOnItemTouchListener.OnClickListener {
override fun onClick(childView: View, childViewAdapterPosition: Int) {
if (!todoListFragment.isActionMode()) {
todoListFragment.openModifyTodoFragment(childViewAdapterPosition)
} else {
todoListFragment.todoAdapter.toggleSelection(childViewAdapterPosition)
if (todoListFragment.areSelectedItems()) {
todoListFragment.actionMode?.invalidate()
} else {
todoListFragment.actionMode?.finish()
}
}
}
override fun onLongClick(childView: View, childViewAdapterPosition: Int) {
if (!todoListFragment.isActionMode()) {
(todoListFragment.activity as MainActivity?)?.
onStartActionMode(todoListFragment.callback)
todoListFragment.todoAdapter.toggleSelection(childViewAdapterPosition)
todoListFragment.actionMode?.invalidate()
}
}
}
)
)
}
@BindingAdapter("searchItemTouchListener")
fun RecyclerView.setSearchItemTouchListener(searchFragment: SearchFragment) {
addOnItemTouchListener(RecyclerViewOnItemTouchListener(
context,
this,
object : RecyclerViewOnItemTouchListener.OnClickListener {
override fun onClick(childView: View, childViewAdapterPosition: Int) {
if (!searchFragment.isActionMode()) {
searchFragment.openModifyTodoFragment(childViewAdapterPosition)
} else {
searchFragment.todoAdapter.toggleSelection(childViewAdapterPosition)
if (searchFragment.areSelectedItems()) {
searchFragment.actionMode?.invalidate()
} else {
searchFragment.actionMode?.finish()
}
}
}
override fun onLongClick(childView: View, childViewAdapterPosition: Int) {
if (!searchFragment.isActionMode()) {
(searchFragment.activity as MainActivity?)?.
onStartActionMode(searchFragment.callback)
searchFragment.todoAdapter.toggleSelection(childViewAdapterPosition)
searchFragment.actionMode?.invalidate()
}
}
}
)
)
} | mit | 25046239b54b0af8a925802a17187092 | 41.275362 | 98 | 0.663981 | 6.152954 | false | false | false | false |
SumiMakito/AwesomeQRCode | library/src/main/java/com/github/sumimakito/awesomeqr/option/logo/Logo.kt | 1 | 732 | package com.github.sumimakito.awesomeqr.option.logo
import android.graphics.Bitmap
import android.graphics.RectF
class Logo(var bitmap: Bitmap? = null,
var scale: Float = 0.2f,
var borderRadius: Int = 8,
var borderWidth: Int = 10,
var clippingRect: RectF? = null) {
fun recycle() {
if (bitmap == null) return
if (bitmap!!.isRecycled) return
bitmap!!.recycle()
bitmap = null
}
fun duplicate(): Logo {
return Logo(
if (bitmap != null) bitmap!!.copy(Bitmap.Config.ARGB_8888, true) else null,
scale,
borderRadius,
borderWidth,
clippingRect
)
}
} | apache-2.0 | a22ff66d7d1b32d570d2d0cf427909de | 26.148148 | 91 | 0.545082 | 4.575 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/lessons-data/src/main/java/app/ss/lessons/data/di/ApiModule.kt | 1 | 4008 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.lessons.data.di
import app.ss.auth.api.TokenAuthenticator
import app.ss.lessons.data.BuildConfig
import app.ss.lessons.data.api.SSLessonsApi
import app.ss.lessons.data.api.SSMediaApi
import app.ss.lessons.data.api.SSQuarterliesApi
import app.ss.storage.db.dao.UserDao
import com.cryart.sabbathschool.core.misc.SSConstants
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object ApiModule {
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private fun retrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder()
.baseUrl(SSConstants.apiBaseUrl())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(okHttpClient)
.build()
@Provides
@Singleton
fun provideOkhttpClient(
userDao: UserDao,
tokenAuthenticator: TokenAuthenticator
): OkHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
.addInterceptor(
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
}
)
.addInterceptor { chain ->
chain.proceed(
chain.request().newBuilder().also { request ->
request.addHeader("Accept", "application/json")
userDao.getCurrent()?.let {
request.addHeader("x-ss-auth-access-token", it.stsTokenManager.accessToken)
}
}.build()
)
}
.authenticator(tokenAuthenticator)
.retryOnConnectionFailure(true)
.build()
@Provides
@Singleton
internal fun provideMediaApi(
okHttpClient: OkHttpClient
): SSMediaApi = retrofit(okHttpClient)
.create(SSMediaApi::class.java)
@Provides
@Singleton
internal fun provideQuarterliesApi(
okHttpClient: OkHttpClient
): SSQuarterliesApi = retrofit(okHttpClient)
.create(SSQuarterliesApi::class.java)
@Provides
@Singleton
internal fun provideLessonsApi(
okHttpClient: OkHttpClient
): SSLessonsApi = retrofit(okHttpClient)
.create(SSLessonsApi::class.java)
}
| mit | 1062706f947f1b90d17bc92f781e04db | 35.108108 | 99 | 0.697355 | 4.811525 | false | false | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/framework/helper.kt | 1 | 2778 | //package ogl_samples.framework
//
//import glm_.vec2.Vec2i
//import org.lwjgl.glfw.Callbacks
//import org.lwjgl.glfw.GLFW.*
//import uno.buffer.destroyBuffers
//import uno.buffer.floatBufferBig
//import uno.buffer.intBufferBig
//
///**
// * Created by elect on 18/04/17.
// */
//
//val mat3Buffer = floatBufferBig(9)
//val mat4Buffer = floatBufferBig(16)
//val vec4Buffer = floatBufferBig(4)
//val int = intBufferBig(1)
//val float = floatBufferBig(1)
//
//
//object windowHint {
// var resizable = true
// set(value) = glfwWindowHint(GLFW_RESIZABLE, if (value) GLFW_TRUE else GLFW_FALSE)
// var visible = true
// set(value) = glfwWindowHint(GLFW_VISIBLE, if (value) GLFW_TRUE else GLFW_FALSE)
// var srgb = true
// set(value) = glfwWindowHint(GLFW_SRGB_CAPABLE, if (value) GLFW_TRUE else GLFW_FALSE)
// var decorated = true
// set(value) = glfwWindowHint(GLFW_DECORATED, if (value) GLFW_TRUE else GLFW_FALSE)
// var api = ""
// set(value) = glfwWindowHint(GLFW_CLIENT_API, when (value) {
// "gl" -> GLFW_OPENGL_API
// "es" -> GLFW_OPENGL_ES_API
// else -> GLFW_NO_API
// })
// var major = 0
// set(value) = glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, value)
// var minor = 0
// set(value) = glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, value)
// var profile = ""
// set(value) = glfwWindowHint(GLFW_OPENGL_PROFILE,
// when (value) {
// "core" -> GLFW_OPENGL_CORE_PROFILE
// "compat" -> GLFW_OPENGL_COMPAT_PROFILE
// else -> GLFW_OPENGL_ANY_PROFILE
// })
// var forwardComp = true
// set(value) = glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, if (value) GLFW_TRUE else GLFW_FALSE)
// var debug = true
// set(value) = glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, if (value) GLFW_TRUE else GLFW_FALSE)
//}
//
//infix fun Int.or(e: Test.Heuristic) = this or e.i
//
//
//class GlfwWindow(windowSize: Vec2i, title: String) {
//
// private val x = intBufferBig(1)
// val y = intBufferBig(1)
// val handle = glfwCreateWindow(windowSize.x, windowSize.y, title, 0L, 0L)
// var shouldClose = false
//
// var pos = Vec2i()
// get() {
// glfwGetWindowPos(handle, x, y)
// return field.put(x[0], y[0])
// }
// set(value) = glfwSetWindowPos(handle, value.x, value.y)
//
// fun dispose() {
//
// destroyBuffers(x, y)
//
// // Free the window callbacks and destroy the window
// Callbacks.glfwFreeCallbacks(handle)
// glfwDestroyWindow(handle)
//
// // Terminate GLFW and free the error callback
// glfwTerminate()
//// glfwSetErrorCallback(null).free()
// }
//} | mit | fa9871a55ce766bcdcb1574ec66fa077 | 32.890244 | 103 | 0.599352 | 3.416974 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/widget/icon/SsIconButtonColors.kt | 1 | 3941 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.design.compose.widget.icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.State
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Color
/**
* Copy of [androidx.compose.material3.IconButtonColors]
* Represents the container and content colors used in an icon button in different states.
*/
@Immutable
class SsIconButtonColors internal constructor(
private val containerColor: Color,
private val contentColor: Color,
private val disabledContainerColor: Color,
private val disabledContentColor: Color
) {
/**
* Represents the container color for this icon button, depending on [enabled].
*
* @param enabled whether the icon button is enabled
*/
@Composable
internal fun containerColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor)
}
/**
* Represents the content color for this icon button, depending on [enabled].
*
* @param enabled whether the icon button is enabled
*/
@Composable
internal fun contentColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) contentColor else disabledContentColor)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is SsIconButtonColors) return false
if (containerColor != other.containerColor) return false
if (contentColor != other.contentColor) return false
if (disabledContainerColor != other.disabledContainerColor) return false
if (disabledContentColor != other.disabledContentColor) return false
return true
}
override fun hashCode(): Int {
var result = containerColor.hashCode()
result = 31 * result + contentColor.hashCode()
result = 31 * result + disabledContainerColor.hashCode()
result = 31 * result + disabledContentColor.hashCode()
return result
}
}
object SsIconButtonColorsDefaults {
private const val DisabledIconOpacity = 0.38f
@Composable
fun iconButtonColors(
containerColor: Color = Color.Transparent,
contentColor: Color = LocalContentColor.current,
disabledContainerColor: Color = Color.Transparent,
disabledContentColor: Color = contentColor.copy(alpha = DisabledIconOpacity)
): SsIconButtonColors =
SsIconButtonColors(
containerColor = containerColor,
contentColor = contentColor,
disabledContainerColor = disabledContainerColor,
disabledContentColor = disabledContentColor
)
}
| mit | 8c0085bf65f5fbb78c7bd99d27279d05 | 38.019802 | 92 | 0.725704 | 5.171916 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt | 2 | 4772 | // 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.presentation
import com.intellij.ide.IconProvider
import com.intellij.navigation.ColoredItemPresentation
import com.intellij.navigation.ItemPresentation
import com.intellij.navigation.ItemPresentationProvider
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.Iconable
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinIconProvider
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import javax.swing.Icon
open class KotlinDefaultNamedDeclarationPresentation(private val declaration: KtNamedDeclaration) : ColoredItemPresentation {
override fun getTextAttributesKey(): TextAttributesKey? {
if (KtPsiUtil.isDeprecated(declaration)) {
return CodeInsightColors.DEPRECATED_ATTRIBUTES
}
return null
}
override fun getPresentableText() = declaration.name
override fun getLocationString(): String? {
if ((declaration is KtFunction && declaration.isLocal) || (declaration is KtClassOrObject && declaration.isLocal)) {
val containingDeclaration = declaration.getStrictParentOfType<KtNamedDeclaration>() ?: return null
val containerName = containingDeclaration.fqName ?: containingDeclaration.name
return KotlinBundle.message("presentation.text.in.container.paren", containerName.toString())
}
val name = declaration.fqName
val parent = declaration.parent
val containerText = if (name != null) {
val qualifiedContainer = name.parent().toString()
if (parent is KtFile && declaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
KotlinBundle.message("presentation.text.in.container", parent.name, qualifiedContainer)
} else {
qualifiedContainer
}
} else {
getNameForContainingObjectLiteral() ?: return null
}
val receiverTypeRef = (declaration as? KtCallableDeclaration)?.receiverTypeReference
return when {
receiverTypeRef != null -> {
KotlinBundle.message("presentation.text.for.receiver.in.container.paren", receiverTypeRef.text, containerText)
}
parent is KtFile -> KotlinBundle.message("presentation.text.paren", containerText)
else -> KotlinBundle.message("presentation.text.in.container.paren", containerText)
}
}
private fun getNameForContainingObjectLiteral(): String? {
val objectLiteral = declaration.getStrictParentOfType<KtObjectLiteralExpression>() ?: return null
val container = objectLiteral.getStrictParentOfType<KtNamedDeclaration>() ?: return null
val containerFqName = container.fqName?.asString() ?: return null
return KotlinBundle.message("presentation.text.object.in.container", containerFqName)
}
override fun getIcon(unused: Boolean): Icon? {
val instance = IconProvider.EXTENSION_POINT_NAME.findFirstSafe { it is KotlinIconProvider }
return instance?.getIcon(declaration, Iconable.ICON_FLAG_VISIBILITY or Iconable.ICON_FLAG_READ_STATUS)
}
}
class KtDefaultDeclarationPresenter : ItemPresentationProvider<KtNamedDeclaration> {
override fun getPresentation(item: KtNamedDeclaration) = KotlinDefaultNamedDeclarationPresentation(item)
}
open class KotlinFunctionPresentation(
private val function: KtFunction,
private val name: String? = function.name
) : KotlinDefaultNamedDeclarationPresentation(function) {
override fun getPresentableText(): String {
return buildString {
name?.let { append(it) }
append("(")
append(function.valueParameters.joinToString {
(if (it.isVarArg) "vararg " else "") + (it.typeReference?.text ?: "")
})
append(")")
}
}
override fun getLocationString(): String? {
if (function is KtConstructor<*>) {
val name = function.getContainingClassOrObject().fqName ?: return null
return KotlinBundle.message("presentation.text.in.container.paren", name)
}
return super.getLocationString()
}
}
class KtFunctionPresenter : ItemPresentationProvider<KtFunction> {
override fun getPresentation(function: KtFunction): ItemPresentation? {
if (function is KtFunctionLiteral) return null
return KotlinFunctionPresentation(function)
}
}
| apache-2.0 | 368fa84c1ce22031771015abf8f51474 | 42.779817 | 158 | 0.713118 | 5.441277 | false | false | false | false |
Maccimo/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogRepositoryListModel.kt | 2 | 3374 | // 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.plugins.github.ui.cloneDialog
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.api.data.GithubRepo
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import javax.swing.AbstractListModel
internal class GHCloneDialogRepositoryListModel : AbstractListModel<GHRepositoryListItem>() {
private val itemsByAccount = LinkedHashMap<GithubAccount, MutableList<GHRepositoryListItem>>()
private val repositoriesByAccount = hashMapOf<GithubAccount, MutableSet<GithubRepo>>()
override fun getSize(): Int = itemsByAccount.values.sumOf { it.size }
override fun getElementAt(index: Int): GHRepositoryListItem {
var offset = 0
for ((_, items) in itemsByAccount) {
if (index >= offset + items.size) {
offset += items.size
continue
}
return items[index - offset]
}
throw IndexOutOfBoundsException(index)
}
fun clear(account: GithubAccount) {
repositoriesByAccount.remove(account)
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
itemsByAccount.remove(account)
fireIntervalRemoved(this, startOffset, endOffset)
}
fun setError(account: GithubAccount, error: Throwable) {
val accountItems = itemsByAccount.getOrPut(account) { mutableListOf() }
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
val errorItem = GHRepositoryListItem.Error(account, error)
accountItems.add(0, errorItem)
fireIntervalAdded(this, endOffset, endOffset + 1)
fireContentsChanged(this, startOffset, endOffset + 1)
}
/**
* Since each repository can be in several states at the same time (shared access for a collaborator and shared access for org member) and
* repositories for collaborators are loaded in separate request before repositories for org members, we need to update order of re-added
* repo in order to place it close to other organization repos
*/
fun addRepositories(account: GithubAccount, details: GithubAuthenticatedUser, repos: List<GithubRepo>) {
val repoSet = repositoriesByAccount.getOrPut(account) { mutableSetOf() }
val items = itemsByAccount.getOrPut(account) { mutableListOf() }
var (startOffset, endOffset) = findAccountOffsets(account) ?: return
val toAdd = mutableListOf<GHRepositoryListItem.Repo>()
for (repo in repos) {
val item = GHRepositoryListItem.Repo(account, details, repo)
val isNew = repoSet.add(repo)
if (isNew) {
toAdd.add(item)
}
else {
val idx = items.indexOf(item)
items.removeAt(idx)
fireIntervalRemoved(this, startOffset + idx, startOffset + idx)
endOffset--
}
}
items.addAll(toAdd)
fireIntervalAdded(this, endOffset, endOffset + toAdd.size)
}
private fun findAccountOffsets(account: GithubAccount): Pair<Int, Int>? {
if (!itemsByAccount.containsKey(account)) return null
var startOffset = 0
var endOffset = 0
for ((_account, items) in itemsByAccount) {
endOffset = startOffset + items.size
if (_account == account) {
break
}
else {
startOffset += items.size
}
}
return startOffset to endOffset
}
} | apache-2.0 | fe8db132e668aaa4c35027b95d386cc2 | 37.793103 | 140 | 0.71725 | 4.792614 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/component/text/TextStyles.kt | 1 | 2918 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package com.acornui.component.text
import com.acornui.component.ComponentInit
import com.acornui.component.style.cssClass
import com.acornui.di.Context
import com.acornui.dom.createElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLImageElement
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* Common text style tags.
*/
object TextStyleTags {
val error by cssClass()
val warning by cssClass()
val info by cssClass()
}
/**
* A shortcut to creating a text field with the [TextStyleTags.error] tag.
*/
inline fun Context.errorText(text: String = "", init: ComponentInit<TextField> = {}): TextField {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
val t = TextField(this)
t.addClass(TextStyleTags.error)
t.text = text
t.init()
return t
}
/**
* A shortcut to creating a text field with the [TextStyleTags.warning] tag.
*/
inline fun Context.warningText(text: String = "", init: ComponentInit<TextField> = {}): TextField {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
val t = TextField(this)
t.addClass(TextStyleTags.warning)
t.text = text
t.init()
return t
}
/**
* A shortcut to creating a text field with the [TextStyleTags.info] tag.
*/
inline fun Context.infoText(text: String = "", init: ComponentInit<TextField> = {}): TextField {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
val t = TextField(this)
t.addClass(TextStyleTags.info)
t.text = text
t.init()
return t
}
object FontStyle {
const val NORMAL = "normal"
const val ITALIC = "italic"
}
/**
* Needs to be an inline element without a baseline (so its bottom (not baseline) is used for alignment)
*/
private val baselineLocator by lazy {
createElement<HTMLImageElement>("img") {
style.verticalAlign = "baseline"
}
}
/**
* Calculates the baseline height of this element by temporarily adding an empty component with no baseline and a
* baseline alignment to this element, measuring its bottom bounds and comparing to this component's bottom bounds.
*/
fun HTMLElement.calculateBaselineHeight(): Double {
val bottomY = getBoundingClientRect().bottom
appendChild(baselineLocator)
val baselineY = baselineLocator.getBoundingClientRect().bottom
removeChild(baselineLocator)
return bottomY - baselineY
} | apache-2.0 | 7455759abcca5fa791fe4b4927ea5694 | 28.19 | 115 | 0.747772 | 3.844532 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/component/input/inputComponents.kt | 1 | 26645 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Thanks to Aaron Iker
* https://css-tricks.com/custom-styling-form-inputs-with-modern-css-features/
*/
@file:Suppress("unused")
package com.acornui.component.input
import com.acornui.Disposable
import com.acornui.UidUtil
import com.acornui.component.*
import com.acornui.component.input.LabelComponentStyle.labelComponent
import com.acornui.component.input.LabelComponentStyle.labelComponentSpan
import com.acornui.component.style.CommonStyleTags
import com.acornui.component.style.CssClassToggle
import com.acornui.component.style.cssClass
import com.acornui.component.text.text
import com.acornui.css.prefix
import com.acornui.di.Context
import com.acornui.dom.addStyleToHead
import com.acornui.dom.createElement
import com.acornui.formatters.*
import com.acornui.google.Icons
import com.acornui.google.icon
import com.acornui.graphic.Color
import com.acornui.input.*
import com.acornui.number.zeroPadding
import com.acornui.observe.Observable
import com.acornui.properties.afterChange
import com.acornui.recycle.Clearable
import com.acornui.signal.once
import com.acornui.signal.signal
import com.acornui.signal.unmanagedSignal
import com.acornui.skins.CssProps
import com.acornui.time.Date
import org.w3c.dom.*
import org.w3c.dom.events.MouseEvent
import org.w3c.dom.events.MouseEventInit
import org.w3c.files.FileList
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.js.Date as JsDate
object InputStyles {
val switch by cssClass()
init {
@Suppress("CssUnresolvedCustomProperty", "CssInvalidFunction", "CssInvalidPropertyValue",
"CssNoGenericFontName"
)
addStyleToHead(
"""
input {
font: inherit;
}
select {
font: inherit;
color: ${CssProps.inputTextColor.v};;
border-width: ${CssProps.borderThickness.v};;
border-color: ${CssProps.borderColor.v};
border-radius: ${CssProps.inputBorderRadius.v};
padding: ${CssProps.inputPadding.v};
background: ${CssProps.inputBackground.v};
box-shadow: ${CssProps.componentShadow.v};
}
option {
font: inherit;
color: ${CssProps.inputTextColor.v};
background: ${CssProps.inputBackground.v};
}
input[type="datetime-local"]:after,
input[type="week"]:after,
input[type="month"]:after,
input[type="time"]:after,
input[type="date"]:after {
font-family: "Material Icons";
-webkit-font-feature-settings: 'liga';
-webkit-font-smoothing: antialiased;
text-transform: none;
font-size: 1.2em;
margin-right: 3px;
pointer-events: none;
}
input[type="week"]:after,
input[type="month"]:after,
input[type="date"]:after {
content: "calendar_today";
}
input[type="time"]:after {
content: "access_time";
}
::-webkit-calendar-picker-indicator {
background: transparent;
color: rgba(0, 0, 0, 0);
opacity: 1;
margin-right: -20px;
}
input[type='date'],
input[type='month'],
input[type='number'],
input[type='email'],
input[type='password'],
input[type='search'],
input[type='time'],
input[type='color'],
input[type='text'] {
color: ${CssProps.inputTextColor.v};
border-width: ${CssProps.borderThickness.v};;
border-color: ${CssProps.borderColor.v};
border-radius: ${CssProps.inputBorderRadius.v};
border-style: solid;
padding: ${CssProps.inputPadding.v};
background: ${CssProps.inputBackground.v};
box-shadow: ${CssProps.componentShadow.v};
}
input:disabled {
background: ${CssProps.disabledInner.v};
border-color: ${CssProps.disabled.v};
color: ${CssProps.toggledInnerDisabled.v};
pointer-events: none;
}
input:active {
border-color: ${CssProps.accentActive.v};
}
input[type='date'],
input[type='month'],
input[type='time'],
input[type='datetime-local'],
input[type='button'],
input[type='submit'],
input[type='reset'],
input[type='search'],
input[type='checkbox'],
input[type='radio'] {
${prefix("appearance", "none")};
}
input:disabled {
opacity: ${CssProps.disabledOpacity.v};
}
input[type='checkbox'],
input[type='radio'] {
height: 21px;
outline: none;
display: inline-block;
vertical-align: top;
position: relative;
margin: 0;
cursor: pointer;
border: 1px solid var(--bc, ${CssProps.borderColor.v});
background: var(--b, ${CssProps.componentBackground.v});
transition: background 0.3s, border-color 0.3s, box-shadow 0.2s;
}
input[type='checkbox']::after,
input[type='radio']::after {
content: '';
display: block;
left: 0;
top: 0;
position: absolute;
transition: transform var(--d-t, 0.3s) var(--d-t-e, ease), opacity var(--d-o, 0.2s);
box-sizing: border-box;
}
input[type='checkbox']:indeterminate,
input[type='checkbox']:checked,
input[type='radio']:checked {
--b: ${CssProps.accentFill.v};
--bc: ${CssProps.accentFill.v};
--d-o: 0.3s;
--d-t: 0.6s;
--d-t-e: cubic-bezier(0.2, 0.85, 0.32, 1.2);
}
input[type='checkbox']:disabled,
input[type='radio']:disabled {
--b: ${CssProps.disabled.v};
cursor: not-allowed;
}
input[type='checkbox']:disabled:indeterminate,
input[type='checkbox']:disabled:checked,
input[type='radio']:disabled:checked {
--b: ${CssProps.disabledInner.v};
--bc: ${CssProps.borderDisabled.v};
}
input[type='checkbox']:disabled + label,
input[type='radio']:disabled + label {
cursor: not-allowed;
opacity: ${CssProps.disabledOpacity.v};
}
input[type='checkbox']:hover:not(:indeterminate):not(:disabled),
input[type='checkbox']:hover:not(:checked):not(:disabled),
input[type='radio']:hover:not(:checked):not(:disabled) {
--bc: ${CssProps.accentHover.v};
}
input[type='checkbox']:not($switch),
input[type='radio']:not($switch) {
width: 21px;
}
input[type='checkbox']:not($switch)::after,
input[type='radio']:not($switch)::after {
opacity: var(--o, 0);
}
input[type='checkbox']:not($switch):indeterminate,
input[type='checkbox']:not($switch):checked,
input[type='radio']:not($switch):checked {
--o: 1;
}
input[type='checkbox'] + label,
input[type='radio'] + label {
display: inline-block;
vertical-align: top;
cursor: pointer;
user-select: none;
-moz-user-select: none;
}
input[type='checkbox']:not($switch) {
border-radius: 7px;
}
input[type='checkbox']:not($switch):not(:indeterminate)::after {
width: 5px;
height: 9px;
border: 2px solid ${CssProps.toggledInner.v};
border-top: 0;
border-left: 0;
left: 7px;
top: 4px;
transform: rotate(var(--r, 20deg));
}
input[type='checkbox']:not(.switch):indeterminate::after {
width: 9px;
height: 2px;
border-top: 2px solid ${CssProps.toggledInner.v};
left: 5px;
top: 9px;
}
input[type='checkbox']:not($switch)::after {
width: 7px;
height: 2px;
border-top: 2px solid ${CssProps.toggledInner.v};
left: 4px;
top: 7px;
}
input[type='checkbox']:not($switch):checked {
--r: 43deg;
}
input[type='checkbox']$switch {
width: 38px;
border-radius: 11px;
}
input[type='checkbox']$switch::after {
left: 2px;
top: 2px;
border-radius: 50%;
width: 15px;
height: 15px;
background: var(--ab, ${CssProps.borderColor.v});
transform: translateX(var(--x, 0));
}
input[type='checkbox']$switch:checked {
--ab: ${CssProps.toggledInner.v};
--x: 17px;
}
input[type='checkbox']$switch:disabled:not(:checked)::after {
opacity: 0.6;
}
input[type='radio'] {
border-radius: 50%;
}
input[type='radio']:checked {
--scale: 0.5;
}
input[type='radio']::after {
width: 19px;
height: 19px;
border-radius: 50%;
background: ${CssProps.toggledInner.v};
opacity: 0;
transform: scale(var(--scale, 0.7));
}
input::before,
input::after {
box-sizing: border-box;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
-webkit-text-fill-color: ${CssProps.inputTextColor.v};
font-style: italic;
}
"""
)
}
}
open class Button(owner: Context, type: String = "button") : DivWithInputComponent(owner) {
var toggleOnClick = false
final override val inputComponent = addChild(InputImpl(this, type).apply {
addClass(CommonStyleTags.hidden)
tabIndex = -1
})
val labelComponent = addChild(text {
addClass(ButtonStyle.label)
})
var type: String
get() = inputComponent.dom.type
set(value) {
inputComponent.dom.type = value
}
var multiple: Boolean
get() = inputComponent.dom.multiple
set(value) {
inputComponent.dom.multiple = value
}
init {
addClass(ButtonStyle.button)
tabIndex = 0
mousePressOnKey()
mousePressed.listen {
active = true
stage.mouseReleased.once {
active = false
}
}
touchStarted.listen {
active = true
stage.touchEnded.once {
active = false
}
}
clicked.listen {
if (it.target != inputComponent.dom) {
inputComponent.dom.dispatchEvent(MouseEvent("click", MouseEventInit(bubbles = false)))
if (toggleOnClick) {
toggled = !toggled
toggledChanged.dispatch(Unit)
}
}
}
}
override var label: String
get() = labelComponent.label
set(value) {
labelComponent.label = value
}
override fun onElementAdded(oldIndex: Int, newIndex: Int, element: WithNode) {
labelComponent.addElement(newIndex, element)
}
override fun onElementRemoved(index: Int, element: WithNode) {
labelComponent.removeElement(index)
}
override var disabled: Boolean by afterChange(false) {
inputComponent.disabled = it
toggleClass(CommonStyleTags.disabled)
}
private var active: Boolean by CssClassToggle(CommonStyleTags.active)
/**
* If [toggleOnClick] is true, when the user clicks this button, [toggled] is changed and [toggledChanged] is
* dispatched.
* This will only dispatch on a user event, not on setting [toggled].
*/
val toggledChanged = signal<Unit>()
/**
* Returns true if the dom contains the class [CommonStyleTags.toggled].
*/
var toggled: Boolean by CssClassToggle(CommonStyleTags.toggled)
}
object ButtonStyle {
val button by cssClass()
val label by cssClass()
init {
addStyleToHead("""
$button {
-webkit-tap-highlight-color: transparent;
padding: ${CssProps.componentPadding.v};
border-radius: ${CssProps.borderRadius.v};
background: ${CssProps.buttonBackground.v};
border-color: ${CssProps.borderColor.v};
border-width: ${CssProps.borderThickness.v};
color: ${CssProps.buttonTextColor.v};
font-size: inherit;
/*text-shadow: 1px 1px 1px #0004;*/
border-style: solid;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
text-align: center;
vertical-align: middle;
overflow: hidden;
box-sizing: border-box;
box-shadow: ${CssProps.componentShadow.v};
cursor: pointer;
font-weight: bolder;
flex-shrink: 0;
}
$button:hover {
background: ${CssProps.buttonBackgroundHover.v};
border-color: ${CssProps.accentHover.v};
color: ${CssProps.buttonTextHoverColor.v};
}
$button${CommonStyleTags.active} {
background: ${CssProps.buttonBackgroundActive.v};
border-color: ${CssProps.accentActive.v};
color: ${CssProps.buttonTextActiveColor.v};
}
$button${CommonStyleTags.toggled} {
background: ${CssProps.accentFill.v};
border-color: ${CssProps.accentFill.v};
color: ${CssProps.toggledInner.v};
}
$button${CommonStyleTags.toggled}:hover {
background: ${CssProps.accentFill.v};
border-color: ${CssProps.accentHover.v};
}
$button${CommonStyleTags.toggled}${CommonStyleTags.active} {
border-color: ${CssProps.accentActive.v};
}
$button${CommonStyleTags.disabled} {
background: ${CssProps.disabledInner.v};
border-color: ${CssProps.disabled.v};
color: ${CssProps.toggledInnerDisabled.v};
pointer-events: none;
opacity: ${CssProps.disabledOpacity.v};
}
$button > div {
overflow: hidden;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
""")
}
}
inline fun Context.button(label: String = "", init: ComponentInit<Button> = {}): Button {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Button(this).apply {
this.label = label
init()
}
}
inline fun Context.checkbox(defaultChecked: Boolean = false, init: ComponentInit<ToggleInput> = {}): ToggleInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return ToggleInput(this, "checkbox").apply {
this.defaultChecked = defaultChecked
init()
}
}
open class ColorInput(owner: Context) : InputImpl(owner, "color") {
var valueAsColor: Color?
get() = if (dom.value.length < 3) null else Color.fromStr(dom.value)
set(value) {
dom.value = if (value == null) "" else "#" + value.toRgbString()
}
}
inline fun Context.colorInput(init: ComponentInit<ColorInput> = {}): ColorInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return ColorInput(this).apply(init)
}
open class DateInput(owner: Context) : InputImpl(owner, "date") {
private val parser = DateTimeParser()
/**
* Sets/gets the default date.
*/
var defaultValueAsDate: Date?
get() = parseDate(dom.defaultValue, isUtc = true)
set(value) {
dom.defaultValue = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}"
}
var valueAsDate: Date?
get() = Date(dom.valueAsDate.unsafeCast<JsDate>())
set(value) {
dom.valueAsDate = value?.jsDate
}
var step: Double?
get() = dom.step.toDoubleOrNull()
set(value) {
dom.step = value.toString()
}
var min: Date?
get() = parseDate(dom.min, isUtc = true)
set(value) {
dom.min = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}"
}
var max: Date?
get() = parseDate(dom.max, isUtc = true)
set(value) {
dom.max = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}"
}
/**
* Returns a String representation of the value.
* This will use the [DateTimeFormatter], set to UTC timezone.
*/
fun valueToString(year: YearFormat = YearFormat.NUMERIC, month: MonthFormat = MonthFormat.TWO_DIGIT, day: TimePartFormat = TimePartFormat.TWO_DIGIT) : String {
val valueAsDate = valueAsDate ?: return ""
val formatter = DateTimeFormatter(timeZone = "UTC", year = year, month = month, day = day)
return formatter.format(valueAsDate)
}
}
inline fun Context.dateInput(init: ComponentInit<DateInput> = {}): DateInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return DateInput(this).apply(init)
}
// Does not work in Fx
@ExperimentalJsExport
inline fun Context.dateTimeInput(init: ComponentInit<InputImpl> = {}): InputImpl {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return InputImpl(this, "datetime-local").apply(init)
}
open class FileInput(owner: Context) : Button(owner, "file"), Clearable {
var accept: String
get() = inputComponent.dom.accept
set(value) {
inputComponent.dom.accept = value
}
val files: FileList?
get() = inputComponent.dom.files
var value: String
get() = inputComponent.dom.value
set(value) {
inputComponent.dom.value = value
}
override fun clear() {
value = ""
}
}
/**
* Creates an input element of type file, styled like a button.
*/
inline fun Context.fileInput(init: ComponentInit<FileInput> = {}): FileInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return FileInput(this).apply {
init()
}
}
inline fun Context.hiddenInput(init: ComponentInit<InputImpl> = {}): InputImpl {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return InputImpl(this, "hidden").apply(init)
}
open class MonthInput(owner: Context) : InputImpl(owner, "month") {
private val parser = DateTimeParser()
/**
* Returns the default month as a UTC Date.
*/
var defaultValueAsDate: Date?
get() = parseDate(dom.defaultValue, isUtc = true)
set(value) {
dom.defaultValue = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}"
}
/**
* Returns/sets the selected month as a UTC Date.
*/
var valueAsDate: Date?
get() = Date(dom.valueAsDate.unsafeCast<JsDate>())
set(value) {
dom.valueAsDate = value?.jsDate
}
var value: String
get() = dom.value
set(value) {
dom.value = value
}
/**
* Returns a String representation of the value.
* This will use the [DateTimeFormatter], set to UTC timezone.
*/
fun valueToString(year: YearFormat = YearFormat.NUMERIC, month: MonthFormat = MonthFormat.TWO_DIGIT) : String {
val valueAsDate = valueAsDate ?: return ""
val formatter = DateTimeFormatter(timeZone = "UTC", year = year, month = month)
return formatter.format(valueAsDate)
}
}
inline fun Context.monthInput(init: ComponentInit<MonthInput> = {}): MonthInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return MonthInput(this).apply(init)
}
inline fun Context.resetInput(label: String = "", init: ComponentInit<Button> = {}): Button {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Button(this, "reset").apply {
this.label = label
init()
}
}
inline fun Context.submitInput(label: String = "", init: ComponentInit<Button> = {}): Button {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Button(this, "submit").apply {
this.label = label
init()
}
}
open class TimeInput(owner: Context) : InputImpl(owner, "time") {
private val parser = DateTimeParser()
/**
* Sets/gets the default date.
*/
var defaultValueAsDate: Date?
get() = parseDate(dom.defaultValue)
set(value) {
dom.defaultValue = if (value == null) "" else "${value.hours.zeroPadding(2)}:${value.minutes.zeroPadding(2)}"
}
fun defaultValueAsDate(value: Date, useMinutes: Boolean = true, useSeconds: Boolean = false, useMilliseconds: Boolean = false) {
dom.defaultValue = formatTimeForDom(value, useMinutes, useSeconds, useMilliseconds)
}
var valueAsDate: Date?
get() = Date(dom.valueAsDate.unsafeCast<JsDate>())
set(value) {
dom.valueAsDate = value?.jsDate
}
var step: Double?
get() = dom.step.toDoubleOrNull()
set(value) {
dom.step = value.toString()
}
var min: Date?
get() = parseDate(dom.min)
set(value) {
dom.min = formatTimeForDom(value)
}
var max: Date?
get() = parseDate(dom.max, isUtc = true)
set(value) {
dom.max = formatTimeForDom(value)
}
/**
* Returns a String representation of the value.
* This will use the [DateTimeFormatter], set to UTC timezone.
*/
fun valueToString(hour: TimePartFormat? = TimePartFormat.NUMERIC, minute: TimePartFormat? = TimePartFormat.TWO_DIGIT, second: TimePartFormat? = TimePartFormat.TWO_DIGIT) : String {
val valueAsDate = valueAsDate ?: return ""
val formatter = DateTimeFormatter(hour = hour, minute = minute, second = second)
return formatter.format(valueAsDate)
}
private fun formatTimeForDom(value: Date?, useMinutes: Boolean = true, useSeconds: Boolean = false, useMilliseconds: Boolean = false): String {
if (value == null) return ""
val minutes = if (useMinutes || useSeconds || useMilliseconds) ":${value.minutes.zeroPadding(2)}" else ""
val seconds = if (useSeconds || useMilliseconds) ":${value.seconds.zeroPadding(2)}" else ""
val milli = if (useMilliseconds) ".${value.milliseconds.zeroPadding(3)}" else ""
return "${value.hours.zeroPadding(2)}$minutes$seconds$milli"
}
}
inline fun Context.timeInput(init: ComponentInit<TimeInput> = {}): TimeInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return TimeInput(this).apply(init)
}
@ExperimentalJsExport
inline fun Context.weekInput(init: ComponentInit<InputImpl> = {}): InputImpl {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return InputImpl(this, "week").apply(init)
}
/**
* An input component such as a radio, switch, or checkbox that should be inline with a label.
*/
open class ToggleInput(owner: Context, type: String) : DivWithInputComponent(owner) {
public final override val inputComponent = addChild(InputImpl(this, type))
val labelComponent = addChild(label(inputComponent) {
hide()
})
init {
addClass(ToggleInputStyle.toggleInput)
inputComponent.style.flexShrink = "0"
}
var indeterminate: Boolean
get() = inputComponent.dom.indeterminate
set(value) {
inputComponent.dom.indeterminate = value
}
var defaultChecked: Boolean
get() = inputComponent.dom.defaultChecked
set(value) {
inputComponent.dom.defaultChecked = value
}
var checked: Boolean
get() = inputComponent.dom.checked
set(value) {
inputComponent.dom.checked = value
}
var value: String
get() = inputComponent.dom.value
set(value) {
inputComponent.dom.value = value
}
override fun onElementAdded(oldIndex: Int, newIndex: Int, element: WithNode) {
labelComponent.addElement(newIndex, element)
}
override fun onElementRemoved(index: Int, element: WithNode) {
labelComponent.removeElement(index)
}
override var label: String
get() = labelComponent.label
set(value) {
labelComponent.label = value
labelComponent.visible(value.isNotEmpty())
}
}
object ToggleInputStyle {
val toggleInput by cssClass()
init {
addStyleToHead("""
$toggleInput {
display: inline-flex;
flex-direction: row;
align-items: center;
}
$toggleInput label {
padding-left: 0.8ch;
display: inline-flex;
flex-direction: row;
align-items: center;
}
""")
}
}
inline fun Context.switch(defaultChecked: Boolean = false, init: ComponentInit<ToggleInput> = {}): ToggleInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return ToggleInput(this, "checkbox").apply {
inputComponent.addClass(InputStyles.switch)
this.defaultChecked = defaultChecked
init()
}
}
/**
*
* This name should be unique to the radio button groups on the page.
*/
class RadioGroup(val name: String = UidUtil.createUid()) : Observable, Disposable {
override val changed = unmanagedSignal<Observable>()
/**
* A list of all radio inputs belonging to this radio group.
*/
val allButtons = ArrayList<ToggleInput>()
var value: String?
get() = allButtons.first { it.checked }.value
set(value) {
for (radio in allButtons) {
radio.checked = radio.value == value
}
}
fun notifyChanged() {
changed.dispatch(this)
}
override fun dispose() {
allButtons.clear()
changed.dispose()
}
}
open class RadioInput(owner: Context, val group: RadioGroup) : ToggleInput(owner, "radio") {
init {
name = group.name
group.allButtons.add(this)
changed.listen {
group.notifyChanged()
}
}
}
inline fun Context.radio(group: RadioGroup, value: String, defaultChecked: Boolean = false, init: ComponentInit<RadioInput> = {}): RadioInput {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return RadioInput(this, group).apply {
this.defaultChecked = defaultChecked
this.value = value
init()
}
}
/**
* LabelComponent is a label element with a nested span. Settings [UiComponent.label] will set the text on that span,
* thus not replacing any other nested elements.
*/
class LabelComponent(owner: Context) : UiComponentImpl<HTMLLabelElement>(owner, createElement<Element>("label").unsafeCast<HTMLLabelElement>()) {
private val span = addChild(span {
addClass(labelComponentSpan)
})
/**
* Sets the text within a span.
*/
override var label: String
get() = span.label
set(value) {
span.label = value
}
init {
addClass(labelComponent)
}
}
object LabelComponentStyle {
val labelComponent by cssClass()
val labelComponentSpan by cssClass()
}
inline fun Context.label(htmlFor: String = "", value: String = "", init: ComponentInit<LabelComponent> = {}): LabelComponent {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return LabelComponent(this).apply {
if (htmlFor.isNotEmpty())
dom.htmlFor = htmlFor
label = value
init()
}
}
inline fun Context.label(forComponent: UiComponent, value: String = "", init: ComponentInit<LabelComponent> = {}): LabelComponent =
label(forComponent.id, value, init)
open class Select(owner: Context) : UiComponentImpl<HTMLSelectElement>(owner, createElement("select")) {
var disabled: Boolean
get() = dom.disabled
set(value) {
dom.disabled = value
}
var multiple: Boolean
get() = dom.multiple
set(value) {
dom.multiple = value
}
var required: Boolean
get() = dom.required
set(value) {
dom.required = value
}
val size: Int
get() = dom.size
val options: HTMLOptionsCollection
get() = dom.options
val selectedOptions: HTMLCollection
get() = dom.selectedOptions
var selectedIndex: Int
get() = dom.selectedIndex
set(value) {
dom.selectedIndex = value
}
var value: String
get() = dom.value
set(value) {
dom.value = value
}
val willValidate: Boolean
get() = dom.willValidate
val validity: ValidityState
get() = dom.validity
val validationMessage: String
get() = dom.validationMessage
val labels: NodeList
get() = dom.labels
fun namedItem(name: String): HTMLOptionElement? = dom.namedItem(name)
fun add(element: UnionHTMLOptGroupElementOrHTMLOptionElement) = dom.add(element)
fun add(element: UnionHTMLOptGroupElementOrHTMLOptionElement, before: dynamic) = dom.add(element, before)
fun remove(index: Int) = dom.remove(index)
fun checkValidity(): Boolean = dom.checkValidity()
fun reportValidity(): Boolean = dom.reportValidity()
fun setCustomValidity(error: String) = dom.setCustomValidity(error)
}
inline fun Context.select(init: ComponentInit<Select> = {}): Select {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Select(this).apply(init)
}
open class Option(owner: Context) : UiComponentImpl<HTMLOptionElement>(owner, createElement("option")) {
open var disabled: Boolean
get() = dom.disabled
set(value) {
dom.disabled = value
}
override var label: String
get() = dom.label
set(value) {
dom.label = value
}
var defaultSelected: Boolean
get() = dom.defaultSelected
set(value) {
dom.defaultSelected = value
}
var selected: Boolean
get() = dom.selected
set(value) {
dom.selected = value
}
var value: String
get() = dom.value
set(value) {
dom.value = value
}
val index: Int
get() = dom.index
}
inline fun Context.option(init: ComponentInit<Option> = {}): Option {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return Option(this).apply(init)
} | apache-2.0 | 0a6176f7a2bddaf40c89200a62c2a2c9 | 23.695088 | 181 | 0.711953 | 3.324392 | false | false | false | false |
SourceUtils/hl2-toolkit | src/main/kotlin/com/timepath/vgui/HudFont.kt | 1 | 2144 | package com.timepath.vgui
import com.timepath.Logger
import com.timepath.steam.io.VDFNode
import java.awt.Font
import java.awt.GraphicsEnvironment
import java.awt.Toolkit
import java.io.File
import java.util.logging.Level
public class HudFont(private val fontname: String, node: VDFNode) {
var name: String? = null
var tall: Int = 0
var aa: Boolean = false
init {
for (p in node.getProperties()) {
val key = p.getKey().toLowerCase()
val value = p.getValue().toString().toLowerCase()
when (key) {
"name" -> name = value
"tall" -> tall = value.toInt()
"antialias" -> aa = value.toInt() == 1
}
}
}
public val font: Font? get() {
val screenRes = Toolkit.getDefaultToolkit().getScreenResolution()
val fontSize = Math.round((tall * screenRes).toDouble() / 72.0).toInt()
val ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
val fontFamilies = ge.getAvailableFontFamilyNames()
if (name in fontFamilies) {
// System font
return Font(name, Font.PLAIN, fontSize)
}
try {
LOG.info { "Loading font: ${fontname}... (${name})}" }
fontFileForName(name!!)?.let {
ge.registerFont(it)
return Font(fontname, Font.PLAIN, fontSize)
}
} catch (ex: Exception) {
LOG.log(Level.SEVERE, { null }, ex)
}
return null
}
companion object {
private val LOG = Logger()
private fun fontFileForName(name: String): Font? {
File("").listFiles { dir, name ->
name.endsWith(".ttf") // XXX: hardcoded
}?.forEach {
val f = Font.createFont(Font.TRUETYPE_FONT, it)
// System.out.println(f.getFamily().toLowerCase());
if (f.getFamily().equals(name, ignoreCase = true)) {
LOG.info { "Found font for ${name}" }
return f
}
}
return null
}
}
}
| artistic-2.0 | ad612b8d61c1faa1bf407c44ddbe693f | 31 | 79 | 0.533116 | 4.402464 | false | false | false | false |
ligi/PassAndroid | android/src/withMaps/java/org/ligi/passandroid/LocationsMapFragment.kt | 1 | 2680 | package org.ligi.passandroid
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.model.MarkerOptions
import org.koin.android.ext.android.inject
import org.ligi.kaxt.startActivityFromClass
import org.ligi.passandroid.model.PassStore
import org.ligi.passandroid.ui.PassViewActivityBase
import kotlin.math.min
class LocationsMapFragment : SupportMapFragment() {
var clickToFullscreen = false
val passStore : PassStore by inject()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = super.onCreateView(inflater, container, savedInstanceState)
val baseActivity = activity as PassViewActivityBase
getMapAsync { map ->
map.setOnMapLoadedCallback {
if (clickToFullscreen)
map.setOnMapClickListener {
passStore.currentPass = baseActivity.currentPass
baseActivity.startActivityFromClass(FullscreenMapActivity::class.java)
}
var boundBuilder = LatLngBounds.Builder()
val locations = baseActivity.currentPass.locations
for (l in locations) {
// yea that looks stupid but need to split LatLng free/nonfree - google play services ^^
val latLng = LatLng(l.lat, l.lon)
val marker = MarkerOptions().position(latLng).title(l.getNameWithFallback(baseActivity.currentPass))
map.addMarker(marker)
boundBuilder = boundBuilder.include(latLng)
}
map.setOnInfoWindowClickListener { marker ->
val i = Intent()
i.action = Intent.ACTION_VIEW
i.data = ("geo:" + marker.position.latitude + "," + marker.position.longitude + "?q=" + marker.title).toUri()
baseActivity.startActivity(i)
}
map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundBuilder.build(), 100))
// limit zoom-level to 17 - otherwise we could be so zoomed in that it looks buggy
map.moveCamera(CameraUpdateFactory.zoomTo(min(17f, map.cameraPosition.zoom)))
}
}
return root
}
} | gpl-3.0 | 6f3c442888c4c4305636c414a4a71990 | 38.426471 | 129 | 0.654851 | 5.056604 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/repository/search/SearchRepository.kt | 1 | 1324 | package forpdateam.ru.forpda.model.repository.search
import forpdateam.ru.forpda.entity.remote.others.user.ForumUser
import forpdateam.ru.forpda.entity.remote.search.SearchResult
import forpdateam.ru.forpda.entity.remote.search.SearchSettings
import forpdateam.ru.forpda.model.SchedulersProvider
import forpdateam.ru.forpda.model.data.cache.forumuser.ForumUsersCache
import forpdateam.ru.forpda.model.data.remote.api.search.SearchApi
import forpdateam.ru.forpda.model.repository.BaseRepository
import io.reactivex.Observable
import io.reactivex.Single
/**
* Created by radiationx on 01.01.18.
*/
class SearchRepository(
private val schedulers: SchedulersProvider,
private val searchApi: SearchApi,
private val forumUsersCache: ForumUsersCache
) : BaseRepository(schedulers) {
fun getSearch(settings: SearchSettings): Single<SearchResult> = Single
.fromCallable { searchApi.getSearch(settings) }
.doOnSuccess { saveUsers(it) }
.runInIoToUi()
private fun saveUsers(page: SearchResult) {
val forumUsers = page.items.map { post ->
ForumUser().apply {
id = post.userId
nick = post.nick
avatar = post.avatar
}
}
forumUsersCache.saveUsers(forumUsers)
}
}
| gpl-3.0 | a45e553936fc52e34d069a455fef1e90 | 32.948718 | 74 | 0.709215 | 4.442953 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/ChangePackageIntention.kt | 1 | 4808 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.changePackage
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.*
import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.refactoring.hasIdentifiersOnly
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.psi.KtPackageDirective
class ChangePackageIntention : SelfTargetingOffsetIndependentIntention<KtPackageDirective>(
KtPackageDirective::class.java,
KotlinBundle.lazyMessage("intention.change.package.text")
) {
companion object {
private const val PACKAGE_NAME_VAR = "PACKAGE_NAME"
}
override fun isApplicableTo(element: KtPackageDirective) = element.packageNameExpression != null
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
// Rename template only intention: no reasonable preview possible
return IntentionPreviewInfo.EMPTY
}
override fun applyTo(element: KtPackageDirective, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val file = element.containingKtFile
val project = file.project
val nameExpression = element.packageNameExpression!!
val currentName = element.qualifiedName
val builder = TemplateBuilderImpl(file)
builder.replaceElement(
nameExpression,
PACKAGE_NAME_VAR,
object : Expression() {
override fun calculateQuickResult(context: ExpressionContext?) = TextResult(currentName)
override fun calculateResult(context: ExpressionContext?) = TextResult(currentName)
override fun calculateLookupItems(context: ExpressionContext?) = arrayOf(LookupElementBuilder.create(currentName))
},
true
)
var enteredName: String? = null
var affectedRange: TextRange? = null
editor.caretModel.moveToOffset(0)
TemplateManager.getInstance(project).startTemplate(
editor,
builder.buildInlineTemplate(),
object : TemplateEditingAdapter() {
override fun beforeTemplateFinished(state: TemplateState, template: Template?) {
enteredName = state.getVariableValue(PACKAGE_NAME_VAR)!!.text
affectedRange = state.getSegmentRange(0)
}
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (brokenOff) return
val name = enteredName ?: return
val range = affectedRange ?: return
// Restore original name and run refactoring
val document = editor.document
project.executeWriteCommand(text) {
document.replaceString(
range.startOffset,
range.endOffset,
FqName(currentName).quoteSegmentsIfNeeded()
)
}
PsiDocumentManager.getInstance(project).commitDocument(document)
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document)
if (!FqNameUnsafe(name).hasIdentifiersOnly()) {
KotlinSurrounderUtils.showErrorHint(
project,
editor,
KotlinBundle.message("text.0.is.not.valid.package.name", name),
KotlinBundle.message("intention.change.package.text"),
null
)
return
}
KotlinChangePackageRefactoring(file).run(FqName(name))
}
}
)
}
}
| apache-2.0 | 6e2b24fa96773fac28273b9cd2a98e24 | 43.934579 | 158 | 0.65703 | 5.856273 | false | false | false | false |
mdaniel/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/ui/BookmarksViewState.kt | 7 | 1165 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.ui
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
class BookmarksViewState : BaseState() {
companion object {
@JvmStatic
fun getInstance(project: Project) = project.getService(BookmarksViewStateComponent::class.java).state
}
var proportionPopup by property(0.3f)
var proportionView by property(0.5f)
var groupLineBookmarks by property(true)
var rewriteBookmarkType by property(false)
var askBeforeDeletingLists by property(true)
var autoscrollFromSource by property(false)
var autoscrollToSource by property(false)
var showPreview by property(false)
}
@State(name = "BookmarksViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))])
internal class BookmarksViewStateComponent : SimplePersistentStateComponent<BookmarksViewState>(BookmarksViewState()) {
override fun noStateLoaded() {
state.autoscrollToSource = UISettings.getInstance().state.defaultAutoScrollToSource
}
}
| apache-2.0 | 06b2430aa1ea7af55b0a3807b50aa39c | 37.833333 | 120 | 0.79485 | 4.463602 | false | false | false | false |
Major-/Vicis | scene3d/src/main/kotlin/rs/emulate/scene3d/backend/opengl/bindings/OpenGLShaderProgram.kt | 1 | 4278 | package rs.emulate.scene3d.backend.opengl.bindings
import org.joml.*
import org.lwjgl.BufferUtils
import org.lwjgl.opengl.GL20.*
import rs.emulate.scene3d.backend.opengl.bindings.util.glmType
import rs.emulate.scene3d.buffer.GeometryDataBuffer
import kotlin.reflect.KClass
/**
* A high-level representation of a compiled and linked OpenGL shader program.
*
* @param id The unique ID of the shader program returned by OpenGL.
* @param uniformTypes A mapping of uniform names to the index they occur at.
* @param uniformBuffers A mapping of uniform locations to th buffers representing them.
*/
class OpenGLShaderProgram(
private val id: Int,
val attributeLocations: Map<String, Int>,
val attributeTypes: Map<String, KClass<out Any>>,
private val uniformBuffers: Map<String, GeometryDataBuffer<out Any>>,
private val uniformLocations: Map<String, Int>
) {
/**
* Bind this shader program as active and bind the [uniforms] to
* their respective locations.
*/
fun bind(vararg uniforms: Pair<String, Any>) {
glUseProgram(id)
for ((name, value) in uniforms) {
val location = uniformLocations[name] ?: throw IllegalArgumentException("No uniform named ${name}")
val data = uniformBuffers[name] as GeometryDataBuffer<Any>
data.set(value)
val buffer = data.buffer.asFloatBuffer()
buffer.position(0)
when (value) {
is Vector2f -> glUniform2fv(location, buffer)
is Vector3f -> glUniform3fv(location, buffer)
is Vector4f -> glUniform4fv(location, buffer)
// is Matrix -> glUniformMatrix2fv(location, false, buffer)
is Matrix3f -> glUniformMatrix3fv(location, false, buffer)
is Matrix4f -> glUniformMatrix4fv(location, false, buffer)
}
}
glValidateProgram(id)
if (glGetProgrami(id, GL_VALIDATE_STATUS) <= 0) {
throw RuntimeException("Failed to validate program: ${glGetProgramInfoLog(id)}, error: ${glGetError()}")
}
}
fun dispose() {
glDeleteProgram(id)
}
companion object {
fun create(vararg modules: OpenGLShaderModule): OpenGLShaderProgram {
val id = glCreateProgram()
val attributeLocations = mutableMapOf<String, Int>()
val attributeTypes = mutableMapOf<String, KClass<out Any>>()
val uniformBuffers = mutableMapOf<String, GeometryDataBuffer<out Any>>()
val uniformLocations = mutableMapOf<String, Int>()
modules.forEach { glAttachShader(id, it.id) }
glLinkProgram(id)
if (glGetProgrami(id, GL_LINK_STATUS) <= 0) {
throw RuntimeException("Failed to link program: ${glGetProgramInfoLog(id)}")
}
val typeBuffer = BufferUtils.createIntBuffer(1)
val sizeBuffer = BufferUtils.createIntBuffer(1)
val attributesLength = glGetProgrami(id, GL_ACTIVE_ATTRIBUTES)
for (attributeOffset in 0 until attributesLength) {
val name = glGetActiveAttrib(id, attributeOffset, sizeBuffer, typeBuffer)
val loc = glGetAttribLocation(id, name)
attributeLocations[name] = loc
attributeTypes[name] = glmType(typeBuffer[0])
}
val uniformsLength = glGetProgrami(id, GL_ACTIVE_UNIFORMS);
for (uniformOffset in 0 until uniformsLength) {
val name = glGetActiveUniform(id, uniformOffset, sizeBuffer, typeBuffer)
val loc = glGetUniformLocation(id, name)
val type = glmType(typeBuffer[0])
val size = sizeBuffer[0]
if (size > 1) {
throw IllegalStateException("Uniform arrays are currently unsupported")
}
val buffer = GeometryDataBuffer.create(type)
uniformLocations[name] = loc
uniformBuffers[name] = buffer
}
return OpenGLShaderProgram(
id,
attributeLocations,
attributeTypes,
uniformBuffers,
uniformLocations
)
}
}
}
| isc | 6abb2f6012ac4d2fea73265365a81770 | 36.858407 | 116 | 0.616877 | 4.9229 | false | false | false | false |
iPoli/iPoli-android | app/src/test/java/io/ipoli/android/quest/show/usecase/CancelTimerUseCaseSpek.kt | 1 | 2423 | package io.ipoli.android.quest.show.usecase
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doAnswer
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import io.ipoli.android.TestUtil
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.TimeRange
import io.ipoli.android.quest.data.persistence.QuestRepository
import io.ipoli.android.quest.show.job.TimerCompleteScheduler
import io.ipoli.android.quest.show.pomodoros
import org.amshove.kluent.`should be false`
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.threeten.bp.Instant
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 1/18/18.
*/
class CancelTimerUseCaseSpek : Spek({
describe("CancelTimerUseCase") {
fun executeUseCase(
quest: Quest
): Quest {
val questRepoMock = mock<QuestRepository> {
on { findById(any()) } doReturn quest
on { save(any<Quest>()) } doAnswer { invocation ->
invocation.getArgument(0)
}
}
return CancelTimerUseCase(questRepoMock, mock(), mock())
.execute(CancelTimerUseCase.Params(quest.id))
}
val simpleQuest = TestUtil.quest
it("should cancel count down") {
val result = executeUseCase(
simpleQuest.copy(
timeRanges = listOf(
TimeRange(
TimeRange.Type.COUNTDOWN,
simpleQuest.duration,
start = Instant.now(),
end = null
)
)
)
)
result.hasCountDownTimer.`should be false`()
}
it("should cancel current pomodoro") {
val result = executeUseCase(
simpleQuest.copy(
timeRanges = listOf(
TimeRange(
TimeRange.Type.POMODORO_WORK,
1.pomodoros(),
start = Instant.now(),
end = null
)
)
)
)
result.hasPomodoroTimer.`should be false`()
}
}
}) | gpl-3.0 | 6f2eec8903436ad189dda7f0429c315b | 31.756757 | 68 | 0.539001 | 5.111814 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/BuildTasksImpl.kt | 1 | 59473 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.NioFiles
import com.intellij.openapi.util.text.Formats
import com.intellij.util.io.Decompressor
import com.intellij.util.io.ZipUtil
import com.intellij.util.system.CpuArch
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.*
import org.apache.commons.compress.archivers.zip.Zip64Mode
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.jetbrains.idea.maven.aether.ArtifactKind
import org.jetbrains.idea.maven.aether.ArtifactRepositoryManager
import org.jetbrains.idea.maven.aether.ProgressConsumer
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.impl.projectStructureMapping.DistributionFileEntry
import org.jetbrains.intellij.build.impl.projectStructureMapping.includedModules
import org.jetbrains.intellij.build.impl.projectStructureMapping.writeProjectStructureReport
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.writeNewFile
import org.jetbrains.intellij.build.io.zipWithCompression
import org.jetbrains.intellij.build.tasks.*
import org.jetbrains.jps.model.JpsGlobal
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.artifact.JpsArtifactService
import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryService
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.library.*
import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService
import org.jetbrains.jps.util.JpsPathUtil
import java.io.FileOutputStream
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.DosFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.function.Predicate
import java.util.stream.Collectors
import java.util.zip.ZipOutputStream
class BuildTasksImpl(context: BuildContext) : BuildTasks {
private val context = context as BuildContextImpl
override suspend fun zipSourcesOfModules(modules: List<String>, targetFile: Path, includeLibraries: Boolean) {
zipSourcesOfModules(modules = modules, targetFile = targetFile, includeLibraries = includeLibraries, context = context)
}
override suspend fun compileModulesFromProduct() {
checkProductProperties(context)
compileModulesForDistribution(context)
}
override suspend fun buildDistributions() {
buildDistributions(context)
}
override suspend fun buildDmg(macZipDir: Path) {
supervisorScope {
sequenceOf(JvmArchitecture.x64, JvmArchitecture.aarch64)
.map { arch ->
val macZip = find(directory = macZipDir, suffix = "${arch}.zip", context = context)
val builtModule = readBuiltinModulesFile(find(directory = macZipDir, suffix = "builtinModules.json", context = context))
async {
MacDistributionBuilder(context = context,
customizer = context.macDistributionCustomizer!!,
ideaProperties = null).buildAndSignDmgFromZip(macZip = macZip,
macZipWithoutRuntime = null,
arch = arch,
builtinModule = builtModule)
}
}
.toList()
}.collectCompletedOrError()
}
override suspend fun buildNonBundledPlugins(mainPluginModules: List<String>) {
checkProductProperties(context)
checkPluginModules(mainPluginModules, "mainPluginModules", context)
copyDependenciesFile(context)
val pluginsToPublish = getPluginLayoutsByJpsModuleNames(mainPluginModules, context.productProperties.productLayout)
val distributionJARsBuilder = DistributionJARsBuilder(compilePlatformAndPluginModules(pluginsToPublish, context))
distributionJARsBuilder.buildSearchableOptions(context)
distributionJARsBuilder.buildNonBundledPlugins(pluginsToPublish = pluginsToPublish,
compressPluginArchive = context.options.compressZipFiles,
buildPlatformLibJob = null,
context = context)
}
override fun compileProjectAndTests(includingTestsInModules: List<String>) {
compileModules(null, includingTestsInModules)
}
override fun compileModules(moduleNames: Collection<String>?, includingTestsInModules: List<String>) {
CompilationTasks.create(context).compileModules(moduleNames, includingTestsInModules)
}
override fun compileModules(moduleNames: Collection<String>?) {
CompilationTasks.create(context).compileModules(moduleNames)
}
override fun buildFullUpdaterJar() {
buildUpdaterJar(context, "updater-full.jar")
}
override suspend fun buildUnpackedDistribution(targetDirectory: Path, includeBinAndRuntime: Boolean) {
val currentOs = OsFamily.currentOs
context.paths.distAllDir = targetDirectory
context.options.targetOs = persistentListOf(currentOs)
context.options.buildStepsToSkip.add(BuildOptions.GENERATE_JAR_ORDER_STEP)
BundledMavenDownloader.downloadMavenCommonLibs(context.paths.communityHomeDirRoot)
BundledMavenDownloader.downloadMavenDistribution(context.paths.communityHomeDirRoot)
DistributionJARsBuilder(compileModulesForDistribution(context)).buildJARs(context = context, isUpdateFromSources = true)
val arch = if (SystemInfo.isMac && CpuArch.isIntel64() && CpuArch.isEmulated()) {
JvmArchitecture.aarch64
}
else {
JvmArchitecture.currentJvmArch
}
layoutShared(context)
if (includeBinAndRuntime) {
val propertiesFile = patchIdeaPropertiesFile(context)
val builder = getOsDistributionBuilder(os = currentOs, ideaProperties = propertiesFile, context = context)!!
builder.copyFilesForOsDistribution(targetDirectory, arch)
context.bundledRuntime.extractTo(prefix = BundledRuntimeImpl.getProductPrefix(context),
os = currentOs,
destinationDir = targetDirectory.resolve("jbr"),
arch = arch)
updateExecutablePermissions(targetDirectory, builder.generateExecutableFilesPatterns(true))
builder.checkExecutablePermissions(targetDirectory, root = "")
}
else {
copyDistFiles(context = context, newDir = targetDirectory, os = currentOs, arch = arch)
}
}
}
/**
* Generates a JSON file containing mapping between files in the product distribution and modules and libraries in the project configuration
*/
suspend fun generateProjectStructureMapping(targetFile: Path, context: BuildContext) {
val pluginLayoutRoot = withContext(Dispatchers.IO) {
Files.createDirectories(context.paths.tempDir)
Files.createTempDirectory(context.paths.tempDir, "pluginLayoutRoot")
}
writeProjectStructureReport(
entries = generateProjectStructureMapping(context = context,
state = DistributionBuilderState(pluginsToPublish = emptySet(), context = context),
pluginLayoutRoot = pluginLayoutRoot),
file = targetFile,
buildPaths = context.paths
)
}
data class SupportedDistribution(@JvmField val os: OsFamily, @JvmField val arch: JvmArchitecture)
@JvmField
val SUPPORTED_DISTRIBUTIONS: PersistentList<SupportedDistribution> = persistentListOf(
SupportedDistribution(os = OsFamily.MACOS, arch = JvmArchitecture.x64),
SupportedDistribution(os = OsFamily.MACOS, arch = JvmArchitecture.aarch64),
SupportedDistribution(os = OsFamily.WINDOWS, arch = JvmArchitecture.x64),
SupportedDistribution(os = OsFamily.WINDOWS, arch = JvmArchitecture.aarch64),
SupportedDistribution(os = OsFamily.LINUX, arch = JvmArchitecture.x64),
SupportedDistribution(os = OsFamily.LINUX, arch = JvmArchitecture.aarch64),
)
private fun isSourceFile(path: String): Boolean {
return path.endsWith(".java") || path.endsWith(".groovy") || path.endsWith(".kt")
}
private fun getLocalArtifactRepositoryRoot(global: JpsGlobal): Path {
JpsModelSerializationDataService.getPathVariablesConfiguration(global)!!.getUserVariableValue("MAVEN_REPOSITORY")?.let {
return Path.of(it)
}
val root = System.getProperty("user.home", null)
return if (root == null) Path.of(".m2/repository") else Path.of(root, ".m2/repository")
}
/**
* Building a list of modules that the IDE will provide for plugins.
*/
private suspend fun buildProvidedModuleList(targetFile: Path, state: DistributionBuilderState, context: BuildContext) {
context.executeStep(spanBuilder("build provided module list"), BuildOptions.PROVIDED_MODULES_LIST_STEP) {
withContext(Dispatchers.IO) {
Files.deleteIfExists(targetFile)
val ideClasspath = DistributionJARsBuilder(state).createIdeClassPath(context)
// start the product in headless mode using com.intellij.ide.plugins.BundledPluginsLister
runApplicationStarter(context = context,
tempDir = context.paths.tempDir.resolve("builtinModules"),
ideClasspath = ideClasspath,
arguments = listOf("listBundledPlugins", targetFile.toString()))
check(Files.exists(targetFile)) {
"Failed to build provided modules list: $targetFile doesn\'t exist"
}
}
context.productProperties.customizeBuiltinModules(context, targetFile)
context.builtinModule = readBuiltinModulesFile(targetFile)
context.notifyArtifactWasBuilt(targetFile)
}
}
private fun patchIdeaPropertiesFile(buildContext: BuildContext): Path {
val builder = StringBuilder(Files.readString(buildContext.paths.communityHomeDir.resolve("bin/idea.properties")))
for (it in buildContext.productProperties.additionalIDEPropertiesFilePaths) {
builder.append('\n').append(Files.readString(it))
}
//todo[nik] introduce special systemSelectorWithoutVersion instead?
val settingsDir = buildContext.systemSelector.replaceFirst("\\d+(\\.\\d+)?".toRegex(), "")
val temp = builder.toString()
builder.setLength(0)
val map = LinkedHashMap<String, String>(1)
map["settings_dir"] = settingsDir
builder.append(BuildUtils.replaceAll(temp, map, "@@"))
if (buildContext.applicationInfo.isEAP) {
builder.append(
"\n#-----------------------------------------------------------------------\n" +
"# Change to 'disabled' if you don't want to receive instant visual notifications\n" +
"# about fatal errors that happen to an IDE or plugins installed.\n" +
"#-----------------------------------------------------------------------\n" +
"idea.fatal.error.notification=enabled\n")
}
else {
builder.append(
"\n#-----------------------------------------------------------------------\n" +
"# Change to 'enabled' if you want to receive instant visual notifications\n" +
"# about fatal errors that happen to an IDE or plugins installed.\n" +
"#-----------------------------------------------------------------------\n" +
"idea.fatal.error.notification=disabled\n")
}
val propertiesFile = buildContext.paths.tempDir.resolve("idea.properties")
Files.writeString(propertiesFile, builder)
return propertiesFile
}
private suspend fun layoutShared(context: BuildContext) {
spanBuilder("copy files shared among all distributions").useWithScope2 {
val licenseOutDir = context.paths.distAllDir.resolve("license")
withContext(Dispatchers.IO) {
copyDir(context.paths.communityHomeDir.resolve("license"), licenseOutDir)
for (additionalDirWithLicenses in context.productProperties.additionalDirectoriesWithLicenses) {
copyDir(additionalDirWithLicenses, licenseOutDir)
}
context.applicationInfo.svgRelativePath?.let { svgRelativePath ->
val from = findBrandingResource(svgRelativePath, context)
val to = context.paths.distAllDir.resolve("bin/${context.productProperties.baseFileName}.svg")
Files.createDirectories(to.parent)
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING)
}
context.productProperties.copyAdditionalFiles(context, context.paths.getDistAll())
}
}
}
private fun findBrandingResource(relativePath: String, context: BuildContext): Path {
val normalizedRelativePath = relativePath.removePrefix("/")
val inModule = context.findFileInModuleSources(context.productProperties.applicationInfoModule, normalizedRelativePath)
if (inModule != null) {
return inModule
}
for (brandingResourceDir in context.productProperties.brandingResourcePaths) {
val file = brandingResourceDir.resolve(normalizedRelativePath)
if (Files.exists(file)) {
return file
}
}
throw RuntimeException("Cannot find \'$normalizedRelativePath\' " +
"neither in sources of \'${context.productProperties.applicationInfoModule}\' " +
"nor in ${context.productProperties.brandingResourcePaths}")
}
internal fun updateExecutablePermissions(destinationDir: Path, executableFilesPatterns: List<String>) {
val executable = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ,
PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ,
PosixFilePermission.OTHERS_EXECUTE)
val regular = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ)
val executableFilesMatchers = executableFilesPatterns.map { FileSystems.getDefault().getPathMatcher("glob:$it") }
Files.walk(destinationDir).use { stream ->
for (file in stream) {
if (Files.isDirectory(file)) {
continue
}
if (SystemInfoRt.isUnix) {
val relativeFile = destinationDir.relativize(file)
val isExecutable = Files.getPosixFilePermissions(file).contains(PosixFilePermission.OWNER_EXECUTE) ||
executableFilesMatchers.any { it.matches(relativeFile) }
Files.setPosixFilePermissions(file, if (isExecutable) executable else regular)
}
else {
(Files.getFileAttributeView(file, DosFileAttributeView::class.java) as DosFileAttributeView).setReadOnly(false)
}
}
}
}
private fun downloadMissingLibrarySources(
librariesWithMissingSources: List<JpsTypedLibrary<JpsSimpleElement<JpsMavenRepositoryLibraryDescriptor>>>,
context: BuildContext,
) {
spanBuilder("download missing sources")
.setAttribute(AttributeKey.stringArrayKey("librariesWithMissingSources"), librariesWithMissingSources.map { it.name })
.use { span ->
val configuration = JpsRemoteRepositoryService.getInstance().getRemoteRepositoriesConfiguration(context.project)
val repositories = configuration?.repositories?.map { ArtifactRepositoryManager.createRemoteRepository(it.id, it.url) } ?: emptyList()
val repositoryManager = ArtifactRepositoryManager(getLocalArtifactRepositoryRoot(context.projectModel.global).toFile(), repositories,
ProgressConsumer.DEAF)
for (library in librariesWithMissingSources) {
val descriptor = library.properties.data
span.addEvent("downloading sources for library", Attributes.of(
AttributeKey.stringKey("name"), library.name,
AttributeKey.stringKey("mavenId"), descriptor.mavenId,
))
val downloaded = repositoryManager.resolveDependencyAsArtifact(descriptor.groupId, descriptor.artifactId,
descriptor.version, EnumSet.of(ArtifactKind.SOURCES),
descriptor.isIncludeTransitiveDependencies,
descriptor.excludedDependencies)
span.addEvent("downloaded sources for library", Attributes.of(
AttributeKey.stringArrayKey("artifacts"), downloaded.map { it.toString() },
))
}
}
}
private class DistributionForOsTaskResult(@JvmField val builder: OsSpecificDistributionBuilder,
@JvmField val arch: JvmArchitecture,
@JvmField val outDir: Path)
private fun find(directory: Path, suffix: String, context: BuildContext): Path {
Files.walk(directory).use { stream ->
val found = stream.filter { (it.fileName.toString()).endsWith(suffix) }.collect(Collectors.toList())
if (found.isEmpty()) {
context.messages.error("No file with suffix $suffix is found in $directory")
}
if (found.size > 1) {
context.messages.error("Multiple files with suffix $suffix are found in $directory:\n${found.joinToString(separator = "\n")}")
}
return found.first()
}
}
private suspend fun buildOsSpecificDistributions(context: BuildContext): List<DistributionForOsTaskResult> {
val stepMessage = "build OS-specific distributions"
if (context.options.buildStepsToSkip.contains(BuildOptions.OS_SPECIFIC_DISTRIBUTIONS_STEP)) {
Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage))
return emptyList()
}
val propertiesFile = patchIdeaPropertiesFile(context)
return supervisorScope {
SUPPORTED_DISTRIBUTIONS.mapNotNull { (os, arch) ->
if (!context.shouldBuildDistributionForOS(os, arch)) {
return@mapNotNull null
}
val builder = getOsDistributionBuilder(os = os, ideaProperties = propertiesFile, context = context) ?: return@mapNotNull null
val stepId = "${os.osId} ${arch.name}"
if (context.options.buildStepsToSkip.contains(stepId)) {
Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("id"), stepId))
return@mapNotNull null
}
async {
spanBuilder(stepId).useWithScope2 {
val osAndArchSpecificDistDirectory = getOsAndArchSpecificDistDirectory(os, arch, context)
builder.buildArtifacts(osAndArchSpecificDistDirectory, arch)
DistributionForOsTaskResult(builder, arch, osAndArchSpecificDistDirectory)
}
}
}
}.collectCompletedOrError()
}
// call only after supervisorScope
private fun <T> List<Deferred<T>>.collectCompletedOrError(): List<T> {
var error: Throwable? = null
for (deferred in this) {
val e = deferred.getCompletionExceptionOrNull() ?: continue
if (error == null) {
error = e
}
else {
error.addSuppressed(e)
}
}
error?.let {
throw it
}
return map { it.getCompleted() }
}
private fun copyDependenciesFile(context: BuildContext): Path {
val outputFile = context.paths.artifactDir.resolve("dependencies.txt")
Files.createDirectories(outputFile.parent)
context.dependenciesProperties.copy(outputFile)
context.notifyArtifactWasBuilt(outputFile)
return outputFile
}
private fun checkProjectLibraries(names: Collection<String>, fieldName: String, context: BuildContext) {
val unknownLibraries = names.filter { context.project.libraryCollection.findLibrary(it) == null }
if (!unknownLibraries.isEmpty()) {
context.messages.error("The following libraries from $fieldName aren\'t found in the project: $unknownLibraries")
}
}
private suspend fun buildSourcesArchive(entries: List<DistributionFileEntry>, context: BuildContext) {
val productProperties = context.productProperties
val archiveName = "${productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)}-sources.zip"
val modulesFromCommunity = entries.includedModules.filter { moduleName ->
productProperties.includeIntoSourcesArchiveFilter.test(context.findRequiredModule(moduleName), context)
}.toList()
zipSourcesOfModules(modules = modulesFromCommunity,
targetFile = context.paths.artifactDir.resolve(archiveName),
includeLibraries = true,
context = context)
}
suspend fun zipSourcesOfModules(modules: List<String>, targetFile: Path, includeLibraries: Boolean, context: BuildContext) {
context.executeStep(spanBuilder("build module sources archives")
.setAttribute("path", context.paths.buildOutputDir.toString())
.setAttribute(AttributeKey.stringArrayKey("modules"), modules),
BuildOptions.SOURCES_ARCHIVE_STEP) {
withContext(Dispatchers.IO) {
Files.createDirectories(targetFile.parent)
Files.deleteIfExists(targetFile)
}
val includedLibraries = LinkedHashSet<JpsLibrary>()
if (includeLibraries) {
val debugMapping = mutableListOf<String>()
for (moduleName in modules) {
val module = context.findRequiredModule(moduleName)
if (moduleName.startsWith("intellij.platform.") && context.findModule("$moduleName.impl") != null) {
val libraries = JpsJavaExtensionService.dependencies(module).productionOnly().compileOnly().recursivelyExportedOnly().libraries
includedLibraries.addAll(libraries)
libraries.mapTo(debugMapping) { "${it.name} for $moduleName" }
}
}
Span.current().addEvent("collect libraries to include into archive",
Attributes.of(AttributeKey.stringArrayKey("mapping"), debugMapping))
val librariesWithMissingSources = includedLibraries
.asSequence()
.map { it.asTyped(JpsRepositoryLibraryType.INSTANCE) }
.filterNotNull()
.filter { library -> library.getFiles(JpsOrderRootType.SOURCES).any { Files.notExists(it.toPath()) } }
.toList()
if (!librariesWithMissingSources.isEmpty()) {
withContext(Dispatchers.IO) {
downloadMissingLibrarySources(librariesWithMissingSources, context)
}
}
}
val zipFileMap = LinkedHashMap<Path, String>()
for (moduleName in modules) {
val module = context.findRequiredModule(moduleName)
for (root in module.getSourceRoots(JavaSourceRootType.SOURCE)) {
if (root.file.absoluteFile.exists()) {
val sourceFiles = filterSourceFilesOnly(root.file.name, context) { FileUtil.copyDirContent(root.file.absoluteFile, it.toFile()) }
zipFileMap[sourceFiles] = root.properties.packagePrefix.replace(".", "/")
}
}
for (root in module.getSourceRoots(JavaResourceRootType.RESOURCE)) {
if (root.file.absoluteFile.exists()) {
val sourceFiles = filterSourceFilesOnly(root.file.name, context) { FileUtil.copyDirContent(root.file.absoluteFile, it.toFile()) }
zipFileMap[sourceFiles] = root.properties.relativeOutputPath
}
}
}
val libraryRootUrls = includedLibraries.flatMap { it.getRootUrls(JpsOrderRootType.SOURCES) }
context.messages.debug(" include ${libraryRootUrls.size} roots from ${includedLibraries.size} libraries:")
for (url in libraryRootUrls) {
if (url.startsWith(JpsPathUtil.JAR_URL_PREFIX) && url.endsWith(JpsPathUtil.JAR_SEPARATOR)) {
val file = JpsPathUtil.urlToFile(url).absoluteFile
if (file.isFile) {
context.messages.debug(" $file, ${Formats.formatFileSize(file.length())}, ${file.length().toString().padEnd(9, '0')} bytes")
val sourceFiles = filterSourceFilesOnly(file.name, context) { tempDir ->
Decompressor.Zip(file).filter(Predicate { isSourceFile(it) }).extract(tempDir)
}
zipFileMap[sourceFiles] = ""
}
else {
context.messages.debug(" skipped root $file: file doesn\'t exist")
}
}
else {
context.messages.debug(" skipped root $url: not a jar file")
}
}
spanBuilder("pack")
.setAttribute("targetFile", context.paths.buildOutputDir.relativize(targetFile).toString())
.useWithScope {
zipWithCompression(targetFile, zipFileMap)
}
context.notifyArtifactWasBuilt(targetFile)
}
}
private inline fun filterSourceFilesOnly(name: String, context: BuildContext, configure: (Path) -> Unit): Path {
val sourceFiles = context.paths.tempDir.resolve("$name-${UUID.randomUUID()}")
NioFiles.deleteRecursively(sourceFiles)
Files.createDirectories(sourceFiles)
configure(sourceFiles)
Files.walk(sourceFiles).use { stream ->
stream.forEach {
if (!Files.isDirectory(it) && !isSourceFile(it.toString())) {
Files.delete(it)
}
}
}
return sourceFiles
}
private fun compilePlatformAndPluginModules(pluginsToPublish: Set<PluginLayout>, context: BuildContext): DistributionBuilderState {
val distState = DistributionBuilderState(pluginsToPublish, context)
val compilationTasks = CompilationTasks.create(context)
compilationTasks.compileModules(
distState.getModulesForPluginsToPublish() +
listOf("intellij.idea.community.build.tasks", "intellij.platform.images.build", "intellij.tools.launcherGenerator"))
compilationTasks.buildProjectArtifacts(distState.getIncludedProjectArtifacts())
return distState
}
private suspend fun compileModulesForDistribution(pluginsToPublish: Set<PluginLayout>, context: BuildContext): DistributionBuilderState {
val productProperties = context.productProperties
val mavenArtifacts = productProperties.mavenArtifacts
val toCompile = LinkedHashSet<String>()
toCompile.addAll(getModulesToCompile(context))
context.proprietaryBuildTools.scrambleTool?.let {
toCompile.addAll(it.additionalModulesToCompile)
}
toCompile.addAll(productProperties.productLayout.mainModules)
toCompile.addAll(mavenArtifacts.additionalModules)
toCompile.addAll(mavenArtifacts.squashedModules)
toCompile.addAll(mavenArtifacts.proprietaryModules)
toCompile.addAll(productProperties.modulesToCompileTests)
CompilationTasks.create(context).compileModules(toCompile)
if (context.shouldBuildDistributions()) {
val providedModuleFile = context.paths.artifactDir.resolve("${context.applicationInfo.productCode}-builtinModules.json")
val state = compilePlatformAndPluginModules(pluginsToPublish, context)
buildProvidedModuleList(targetFile = providedModuleFile, state = state, context = context)
if (!productProperties.productLayout.buildAllCompatiblePlugins) {
return state
}
if (context.options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) {
Span.current().addEvent("skip collecting compatible plugins because PROVIDED_MODULES_LIST_STEP was skipped")
}
else {
return compilePlatformAndPluginModules(
pluginsToPublish = pluginsToPublish + collectCompatiblePluginsToPublish(providedModuleFile, context),
context = context
)
}
}
return compilePlatformAndPluginModules(pluginsToPublish, context)
}
private suspend fun compileModulesForDistribution(context: BuildContext): DistributionBuilderState {
return compileModulesForDistribution(
pluginsToPublish = getPluginLayoutsByJpsModuleNames(modules = context.productProperties.productLayout.pluginModulesToPublish,
productLayout = context.productProperties.productLayout),
context = context
)
}
suspend fun buildDistributions(context: BuildContext): Unit = spanBuilder("build distributions").useWithScope2 {
checkProductProperties(context as BuildContextImpl)
copyDependenciesFile(context)
logFreeDiskSpace("before compilation", context)
val pluginsToPublish = getPluginLayoutsByJpsModuleNames(modules = context.productProperties.productLayout.pluginModulesToPublish,
productLayout = context.productProperties.productLayout)
val distributionState = compileModulesForDistribution(context)
logFreeDiskSpace("after compilation", context)
coroutineScope {
createMavenArtifactJob(context, distributionState)
spanBuilder("build platform and plugin JARs").useWithScope2<Unit> {
val distributionJARsBuilder = DistributionJARsBuilder(distributionState)
if (context.productProperties.buildDocAuthoringAssets)
buildInspectopediaArtifacts(distributionJARsBuilder, context)
if (context.shouldBuildDistributions()) {
val entries = distributionJARsBuilder.buildJARs(context)
if (context.productProperties.buildSourcesArchive) {
buildSourcesArchive(entries, context)
}
}
else {
Span.current().addEvent("skip building product distributions because " +
"\"intellij.build.target.os\" property is set to \"${BuildOptions.OS_NONE}\"")
distributionJARsBuilder.buildSearchableOptions(context)
distributionJARsBuilder.buildNonBundledPlugins(pluginsToPublish = pluginsToPublish,
compressPluginArchive = context.options.compressZipFiles,
buildPlatformLibJob = null,
context = context)
}
}
if (!context.shouldBuildDistributions()) {
return@coroutineScope
}
layoutShared(context)
val distDirs = buildOsSpecificDistributions(context)
@Suppress("SpellCheckingInspection")
if (java.lang.Boolean.getBoolean("intellij.build.toolbox.litegen")) {
@Suppress("SENSELESS_COMPARISON")
if (context.buildNumber == null) {
Span.current().addEvent("Toolbox LiteGen is not executed - it does not support SNAPSHOT build numbers")
}
else if (context.options.targetOs != OsFamily.ALL) {
Span.current().addEvent("Toolbox LiteGen is not executed - it doesn't support installers are being built only for specific OS")
}
else {
context.executeStep("build toolbox lite-gen links", BuildOptions.TOOLBOX_LITE_GEN_STEP) {
val toolboxLiteGenVersion = System.getProperty("intellij.build.toolbox.litegen.version")
checkNotNull(toolboxLiteGenVersion) {
"Toolbox Lite-Gen version is not specified!"
}
ToolboxLiteGen.runToolboxLiteGen(context.paths.communityHomeDirRoot, context.messages,
toolboxLiteGenVersion, "/artifacts-dir=" + context.paths.artifacts,
"/product-code=" + context.applicationInfo.productCode,
"/isEAP=" + context.applicationInfo.isEAP.toString(),
"/output-dir=" + context.paths.buildOutputRoot + "/toolbox-lite-gen")
}
}
}
if (context.productProperties.buildCrossPlatformDistribution) {
if (distDirs.size == SUPPORTED_DISTRIBUTIONS.size) {
context.executeStep(spanBuilder("build cross-platform distribution"), BuildOptions.CROSS_PLATFORM_DISTRIBUTION_STEP) {
buildCrossPlatformZip(distDirs, context)
}
}
else {
Span.current().addEvent("skip building cross-platform distribution because some OS/arch-specific distributions were skipped")
}
}
logFreeDiskSpace("after building distributions", context)
}
}
private fun CoroutineScope.createMavenArtifactJob(context: BuildContext, distributionState: DistributionBuilderState): Job? {
val mavenArtifacts = context.productProperties.mavenArtifacts
if (!mavenArtifacts.forIdeModules &&
mavenArtifacts.additionalModules.isEmpty() &&
mavenArtifacts.squashedModules.isEmpty() &&
mavenArtifacts.proprietaryModules.isEmpty()) {
return null
}
return createSkippableJob(spanBuilder("generate maven artifacts"), BuildOptions.MAVEN_ARTIFACTS_STEP, context) {
val moduleNames = ArrayList<String>()
if (mavenArtifacts.forIdeModules) {
moduleNames.addAll(distributionState.platformModules)
val productLayout = context.productProperties.productLayout
moduleNames.addAll(productLayout.getIncludedPluginModules(productLayout.bundledPluginModules))
}
val mavenArtifactsBuilder = MavenArtifactsBuilder(context)
moduleNames.addAll(mavenArtifacts.additionalModules)
if (!moduleNames.isEmpty()) {
mavenArtifactsBuilder.generateMavenArtifacts(moduleNames, mavenArtifacts.squashedModules, "maven-artifacts")
}
if (!mavenArtifacts.proprietaryModules.isEmpty()) {
mavenArtifactsBuilder.generateMavenArtifacts(mavenArtifacts.proprietaryModules, emptyList(), "proprietary-maven-artifacts")
}
}
}
private fun checkProductProperties(context: BuildContextImpl) {
checkProductLayout(context)
val properties = context.productProperties
checkPaths2(properties.brandingResourcePaths, "productProperties.brandingResourcePaths")
checkPaths2(properties.additionalIDEPropertiesFilePaths, "productProperties.additionalIDEPropertiesFilePaths")
checkPaths2(properties.additionalDirectoriesWithLicenses, "productProperties.additionalDirectoriesWithLicenses")
checkModules(properties.additionalModulesToCompile, "productProperties.additionalModulesToCompile", context)
checkModules(properties.modulesToCompileTests, "productProperties.modulesToCompileTests", context)
context.windowsDistributionCustomizer?.let { winCustomizer ->
checkPaths(listOfNotNull(winCustomizer.icoPath), "productProperties.windowsCustomizer.icoPath")
checkPaths(listOfNotNull(winCustomizer.icoPathForEAP), "productProperties.windowsCustomizer.icoPathForEAP")
checkPaths(listOfNotNull(winCustomizer.installerImagesPath), "productProperties.windowsCustomizer.installerImagesPath")
}
context.linuxDistributionCustomizer?.let { linuxDistributionCustomizer ->
checkPaths(listOfNotNull(linuxDistributionCustomizer.iconPngPath), "productProperties.linuxCustomizer.iconPngPath")
checkPaths(listOfNotNull(linuxDistributionCustomizer.iconPngPathForEAP), "productProperties.linuxCustomizer.iconPngPathForEAP")
}
context.macDistributionCustomizer?.let { macCustomizer ->
checkMandatoryField(macCustomizer.bundleIdentifier, "productProperties.macCustomizer.bundleIdentifier")
checkMandatoryPath(macCustomizer.icnsPath, "productProperties.macCustomizer.icnsPath")
checkPaths(listOfNotNull(macCustomizer.icnsPathForEAP), "productProperties.macCustomizer.icnsPathForEAP")
checkMandatoryPath(macCustomizer.dmgImagePath, "productProperties.macCustomizer.dmgImagePath")
checkPaths(listOfNotNull(macCustomizer.dmgImagePathForEAP), "productProperties.macCustomizer.dmgImagePathForEAP")
}
checkModules(properties.mavenArtifacts.additionalModules, "productProperties.mavenArtifacts.additionalModules", context)
checkModules(properties.mavenArtifacts.squashedModules, "productProperties.mavenArtifacts.squashedModules", context)
if (context.productProperties.scrambleMainJar) {
context.proprietaryBuildTools.scrambleTool?.let {
checkModules(modules = it.namesOfModulesRequiredToBeScrambled,
fieldName = "ProprietaryBuildTools.scrambleTool.namesOfModulesRequiredToBeScrambled",
context = context)
}
}
}
private fun checkProductLayout(context: BuildContext) {
val layout = context.productProperties.productLayout
// todo mainJarName type specified as not-null - does it work?
val messages = context.messages
@Suppress("SENSELESS_COMPARISON")
check(layout.mainJarName != null) {
"productProperties.productLayout.mainJarName is not specified"
}
val pluginLayouts = layout.pluginLayouts
checkScrambleClasspathPlugins(pluginLayouts)
checkPluginDuplicates(pluginLayouts)
checkPluginModules(layout.bundledPluginModules, "productProperties.productLayout.bundledPluginModules", context)
checkPluginModules(layout.pluginModulesToPublish, "productProperties.productLayout.pluginModulesToPublish", context)
checkPluginModules(layout.compatiblePluginsToIgnore, "productProperties.productLayout.compatiblePluginsToIgnore", context)
if (!layout.buildAllCompatiblePlugins && !layout.compatiblePluginsToIgnore.isEmpty()) {
messages.warning("layout.buildAllCompatiblePlugins option isn't enabled. Value of " +
"layout.compatiblePluginsToIgnore property will be ignored (${layout.compatiblePluginsToIgnore})")
}
if (layout.buildAllCompatiblePlugins && !layout.compatiblePluginsToIgnore.isEmpty()) {
checkPluginModules(layout.compatiblePluginsToIgnore, "productProperties.productLayout.compatiblePluginsToIgnore", context)
}
if (!context.shouldBuildDistributions() && layout.buildAllCompatiblePlugins) {
messages.warning("Distribution is not going to build. Hence all compatible plugins won't be built despite " +
"layout.buildAllCompatiblePlugins option is enabled. layout.pluginModulesToPublish will be used (" +
layout.pluginModulesToPublish + ")")
}
check(!layout.prepareCustomPluginRepositoryForPublishedPlugins ||
!layout.pluginModulesToPublish.isEmpty() ||
layout.buildAllCompatiblePlugins) {
"productProperties.productLayout.prepareCustomPluginRepositoryForPublishedPlugins option is enabled" +
" but no pluginModulesToPublish are specified"
}
checkModules(layout.productApiModules, "productProperties.productLayout.productApiModules", context)
checkModules(layout.productImplementationModules, "productProperties.productLayout.productImplementationModules", context)
checkModules(layout.additionalPlatformJars.values(), "productProperties.productLayout.additionalPlatformJars", context)
checkModules(layout.moduleExcludes.keys, "productProperties.productLayout.moduleExcludes", context)
checkModules(layout.mainModules, "productProperties.productLayout.mainModules", context)
checkProjectLibraries(layout.projectLibrariesToUnpackIntoMainJar,
"productProperties.productLayout.projectLibrariesToUnpackIntoMainJar", context)
for (plugin in pluginLayouts) {
checkBaseLayout(plugin, "\'${plugin.mainModule}\' plugin", context)
}
}
private fun checkBaseLayout(layout: BaseLayout, description: String, context: BuildContext) {
checkModules(layout.includedModuleNames.toList(), "moduleJars in $description", context)
checkArtifacts(layout.includedArtifacts.keys, "includedArtifacts in $description", context)
checkModules(layout.resourcePaths.map { it.moduleName }, "resourcePaths in $description", context)
checkModules(layout.moduleExcludes.keys, "moduleExcludes in $description", context)
checkProjectLibraries(layout.includedProjectLibraries.map { it.libraryName }, "includedProjectLibraries in $description", context)
for ((moduleName, libraryName) in layout.includedModuleLibraries) {
checkModules(listOf(moduleName), "includedModuleLibraries in $description", context)
check(context.findRequiredModule(moduleName).libraryCollection.libraries.any { getLibraryFileName(it) == libraryName }) {
"Cannot find library \'$libraryName\' in \'$moduleName\' (used in $description)"
}
}
checkModules(layout.excludedModuleLibraries.keySet(), "excludedModuleLibraries in $description", context)
for ((key, value) in layout.excludedModuleLibraries.entrySet()) {
val libraries = context.findRequiredModule(key).libraryCollection.libraries
for (libraryName in value) {
check(libraries.any { getLibraryFileName(it) == libraryName }) {
"Cannot find library \'$libraryName\' in \'$key\' (used in \'excludedModuleLibraries\' in $description)"
}
}
}
checkProjectLibraries(layout.projectLibrariesToUnpack.values(), "projectLibrariesToUnpack in $description", context)
checkModules(layout.modulesWithExcludedModuleLibraries, "modulesWithExcludedModuleLibraries in $description", context)
}
private fun checkPluginDuplicates(nonTrivialPlugins: List<PluginLayout>) {
val pluginsGroupedByMainModule = nonTrivialPlugins.groupBy { it.mainModule to it.bundlingRestrictions }.values
for (duplicatedPlugins in pluginsGroupedByMainModule) {
check(duplicatedPlugins.size <= 1) {
"Duplicated plugin description in productLayout.pluginLayouts: main module ${duplicatedPlugins.first().mainModule}"
}
}
// indexing-shared-ultimate has a separate layout for bundled & public plugins
val duplicateDirectoryNameExceptions = setOf("indexing-shared-ultimate")
val pluginsGroupedByDirectoryName = nonTrivialPlugins.groupBy { it.directoryName to it.bundlingRestrictions }.values
for (duplicatedPlugins in pluginsGroupedByDirectoryName) {
val pluginDirectoryName = duplicatedPlugins.first().directoryName
if (duplicateDirectoryNameExceptions.contains(pluginDirectoryName)) {
continue
}
check(duplicatedPlugins.size <= 1) {
"Duplicated plugin description in productLayout.pluginLayouts: directory name '$pluginDirectoryName', main modules: ${duplicatedPlugins.joinToString { it.mainModule }}"
}
}
}
private fun checkModules(modules: Collection<String>?, fieldName: String, context: CompilationContext) {
if (modules != null) {
val unknownModules = modules.filter { context.findModule(it) == null }
check(unknownModules.isEmpty()) {
"The following modules from $fieldName aren\'t found in the project: $unknownModules"
}
}
}
private fun checkArtifacts(names: Collection<String>, fieldName: String, context: CompilationContext) {
val unknownArtifacts = names - JpsArtifactService.getInstance().getArtifacts(context.project).map { it.name }.toSet()
check(unknownArtifacts.isEmpty()) {
"The following artifacts from $fieldName aren\'t found in the project: $unknownArtifacts"
}
}
private fun checkScrambleClasspathPlugins(pluginLayoutList: List<PluginLayout>) {
val pluginDirectories = pluginLayoutList.mapTo(HashSet()) { it.directoryName }
for (pluginLayout in pluginLayoutList) {
for ((pluginDirectoryName, _) in pluginLayout.scrambleClasspathPlugins) {
check(pluginDirectories.contains(pluginDirectoryName)) {
"Layout of plugin '${pluginLayout.mainModule}' declares an unresolved plugin directory name" +
" in ${pluginLayout.scrambleClasspathPlugins}: $pluginDirectoryName"
}
}
}
}
private fun checkPluginModules(pluginModules: Collection<String>?, fieldName: String, context: BuildContext) {
if (pluginModules == null) {
return
}
checkModules(pluginModules, fieldName, context)
val unknownBundledPluginModules = pluginModules.filter { context.findFileInModuleSources(it, "META-INF/plugin.xml") == null }
check(unknownBundledPluginModules.isEmpty()) {
"The following modules from $fieldName don\'t contain META-INF/plugin.xml file and aren\'t specified as optional plugin modules" +
"in productProperties.productLayout.pluginLayouts: ${unknownBundledPluginModules.joinToString()}."
}
}
private fun checkPaths(paths: Collection<String>, propertyName: String) {
val nonExistingFiles = paths.filter { Files.notExists(Path.of(it)) }
check(nonExistingFiles.isEmpty()) {
"$propertyName contains non-existing files: ${nonExistingFiles.joinToString()}"
}
}
private fun checkPaths2(paths: Collection<Path>, propertyName: String) {
val nonExistingFiles = paths.filter { Files.notExists(it) }
check(nonExistingFiles.isEmpty()) {
"$propertyName contains non-existing files: ${nonExistingFiles.joinToString()}"
}
}
private fun checkMandatoryField(value: String?, fieldName: String) {
checkNotNull(value) {
"Mandatory property \'$fieldName\' is not specified"
}
}
private fun checkMandatoryPath(path: String, fieldName: String) {
checkMandatoryField(path, fieldName)
checkPaths(listOf(path), fieldName)
}
private fun logFreeDiskSpace(phase: String, context: CompilationContext) {
if (context.options.printFreeSpace) {
logFreeDiskSpace(context.paths.buildOutputDir, phase)
}
}
internal fun logFreeDiskSpace(dir: Path, phase: String) {
Span.current().addEvent("free disk space", Attributes.of(
AttributeKey.stringKey("phase"), phase,
AttributeKey.stringKey("usableSpace"), Formats.formatFileSize(Files.getFileStore(dir).usableSpace),
AttributeKey.stringKey("dir"), dir.toString(),
))
}
fun buildUpdaterJar(context: BuildContext, artifactName: String = "updater.jar") {
val updaterModule = context.findRequiredModule("intellij.platform.updater")
val updaterModuleSource = DirSource(context.getModuleOutputDir(updaterModule))
val librarySources = JpsJavaExtensionService.dependencies(updaterModule)
.productionOnly()
.runtimeOnly()
.libraries
.asSequence()
.flatMap { it.getRootUrls(JpsOrderRootType.COMPILED) }
.filter { !JpsPathUtil.isJrtUrl(it) }
.map { ZipSource(Path.of(JpsPathUtil.urlToPath(it)), listOf(Regex("^META-INF/.*"))) }
val updaterJar = context.paths.artifactDir.resolve(artifactName)
buildJar(targetFile = updaterJar, sources = (sequenceOf(updaterModuleSource) + librarySources).toList(), compress = true)
context.notifyArtifactBuilt(updaterJar)
}
private suspend fun buildCrossPlatformZip(distResults: List<DistributionForOsTaskResult>, context: BuildContext): Path {
val executableName = context.productProperties.baseFileName
val productJson = generateMultiPlatformProductJson(
relativePathToBin = "bin",
builtinModules = context.builtinModule,
launch = sequenceOf(JvmArchitecture.x64, JvmArchitecture.aarch64).flatMap { arch ->
listOf(
ProductInfoLaunchData(
os = OsFamily.WINDOWS.osName,
arch = arch.dirName,
launcherPath = "bin/${executableName}.bat",
javaExecutablePath = null,
vmOptionsFilePath = "bin/win/${executableName}64.exe.vmoptions",
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch, isScript = true)),
ProductInfoLaunchData(
os = OsFamily.LINUX.osName,
arch = arch.dirName,
launcherPath = "bin/${executableName}.sh",
javaExecutablePath = null,
vmOptionsFilePath = "bin/linux/${executableName}64.vmoptions",
startupWmClass = getLinuxFrameClass(context),
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.LINUX, arch, isScript = true)),
ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
arch = arch.dirName,
launcherPath = "MacOS/$executableName",
javaExecutablePath = null,
vmOptionsFilePath = "bin/mac/${executableName}.vmoptions",
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.MACOS, arch, isPortableDist = true))
)
}.toList(),
context = context,
)
val zipFileName = context.productProperties.getCrossPlatformZipFileName(context.applicationInfo, context.buildNumber)
val targetFile = context.paths.artifactDir.resolve(zipFileName)
val dependenciesFile = copyDependenciesFile(context)
crossPlatformZip(
macX64DistDir = distResults.first { it.builder.targetOs == OsFamily.MACOS && it.arch == JvmArchitecture.x64 }.outDir,
macArm64DistDir = distResults.first { it.builder.targetOs == OsFamily.MACOS && it.arch == JvmArchitecture.aarch64 }.outDir,
linuxX64DistDir = distResults.first { it.builder.targetOs == OsFamily.LINUX && it.arch == JvmArchitecture.x64 }.outDir,
winX64DistDir = distResults.first { it.builder.targetOs == OsFamily.WINDOWS && it.arch == JvmArchitecture.x64 }.outDir,
targetFile = targetFile,
executableName = executableName,
productJson = productJson.encodeToByteArray(),
executablePatterns = distResults.flatMap { it.builder.generateExecutableFilesPatterns(includeRuntime = false) },
distFiles = context.getDistFiles(os = null, arch = null),
extraFiles = mapOf("dependencies.txt" to dependenciesFile),
distAllDir = context.paths.distAllDir,
compress = context.options.compressZipFiles,
)
coroutineScope {
launch { checkInArchive(archiveFile = targetFile, pathInArchive = "", context = context) }
launch { checkClassFiles(targetFile = targetFile, context = context) }
}
context.notifyArtifactBuilt(targetFile)
return targetFile
}
private suspend fun checkClassFiles(targetFile: Path, context: BuildContext) {
val versionCheckerConfig = if (context.isStepSkipped(BuildOptions.VERIFY_CLASS_FILE_VERSIONS)) {
emptyMap()
}
else {
context.productProperties.versionCheckerConfig
}
val forbiddenSubPaths = if (context.options.validateClassFileSubpaths) {
context.productProperties.forbiddenClassFileSubPaths
}
else {
emptyList()
}
val classFileCheckRequired = (versionCheckerConfig.isNotEmpty() || forbiddenSubPaths.isNotEmpty())
if (classFileCheckRequired) {
checkClassFiles(versionCheckerConfig, forbiddenSubPaths, targetFile, context.messages)
}
}
private fun getOsDistributionBuilder(os: OsFamily, ideaProperties: Path? = null, context: BuildContext): OsSpecificDistributionBuilder? {
return when (os) {
OsFamily.WINDOWS -> WindowsDistributionBuilder(context = context,
customizer = context.windowsDistributionCustomizer ?: return null,
ideaProperties = ideaProperties)
OsFamily.LINUX -> LinuxDistributionBuilder(context = context,
customizer = context.linuxDistributionCustomizer ?: return null,
ideaProperties = ideaProperties)
OsFamily.MACOS -> MacDistributionBuilder(context = context,
customizer = (context as BuildContextImpl).macDistributionCustomizer ?: return null,
ideaProperties = ideaProperties)
}
}
// keep in sync with AppUIUtil#getFrameClass
internal fun getLinuxFrameClass(context: BuildContext): String {
val name = context.applicationInfo.productNameWithEdition
.lowercase()
.replace(' ', '-')
.replace("intellij-idea", "idea")
.replace("android-studio", "studio")
.replace("-community-edition", "-ce")
.replace("-ultimate-edition", "")
.replace("-professional-edition", "")
return if (name.startsWith("jetbrains-")) name else "jetbrains-$name"
}
private fun crossPlatformZip(macX64DistDir: Path,
macArm64DistDir: Path,
linuxX64DistDir: Path,
winX64DistDir: Path,
targetFile: Path,
executableName: String,
productJson: ByteArray,
executablePatterns: List<String>,
distFiles: Collection<DistFile>,
extraFiles: Map<String, Path>,
distAllDir: Path,
compress: Boolean) {
writeNewFile(targetFile) { outFileChannel ->
NoDuplicateZipArchiveOutputStream(outFileChannel, compress = compress).use { out ->
out.setUseZip64(Zip64Mode.Never)
out.entryToDir(winX64DistDir.resolve("bin/idea.properties"), "bin/win")
out.entryToDir(linuxX64DistDir.resolve("bin/idea.properties"), "bin/linux")
out.entryToDir(macX64DistDir.resolve("bin/idea.properties"), "bin/mac")
out.entryToDir(macX64DistDir.resolve("bin/${executableName}.vmoptions"), "bin/mac")
out.entry("bin/mac/${executableName}64.vmoptions", macX64DistDir.resolve("bin/${executableName}.vmoptions"))
for ((p, f) in extraFiles) {
out.entry(p, f)
}
out.entry("product-info.json", productJson)
Files.newDirectoryStream(winX64DistDir.resolve("bin")).use {
for (file in it) {
val path = file.toString()
if (path.endsWith(".exe.vmoptions")) {
out.entryToDir(file, "bin/win")
}
else {
val fileName = file.fileName.toString()
if (fileName.startsWith("fsnotifier") && fileName.endsWith(".exe")) {
out.entry("bin/win/$fileName", file)
}
}
}
}
Files.newDirectoryStream(linuxX64DistDir.resolve("bin")).use {
for (file in it) {
val name = file.fileName.toString()
when {
name.endsWith(".vmoptions") -> out.entryToDir(file, "bin/linux")
name.endsWith(".sh") || name.endsWith(".py") -> out.entry("bin/${file.fileName}", file, unixMode = executableFileUnixMode)
name == "fsnotifier" -> out.entry("bin/linux/${name}", file, unixMode = executableFileUnixMode)
}
}
}
// At the moment, there is no ARM64 hardware suitable for painless IDEA plugin development,
// so corresponding artifacts are not packed in.
Files.newDirectoryStream(macX64DistDir.resolve("bin")).use {
for (file in it) {
if (file.toString().endsWith(".jnilib")) {
out.entry("bin/mac/${file.fileName.toString().removeSuffix(".jnilib")}.dylib", file)
}
else {
val fileName = file.fileName.toString()
if (fileName.startsWith("restarter") || fileName.startsWith("printenv")) {
out.entry("bin/$fileName", file, unixMode = executableFileUnixMode)
}
else if (fileName.startsWith("fsnotifier")) {
out.entry("bin/mac/$fileName", file, unixMode = executableFileUnixMode)
}
}
}
}
val patterns = executablePatterns.map {
FileSystems.getDefault().getPathMatcher("glob:$it")
}
val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, _, relativePathString ->
val relativePath = Path.of(relativePathString)
if (patterns.any { it.matches(relativePath) }) {
entry.unixMode = executableFileUnixMode
}
}
val commonFilter: (String) -> Boolean = { relPath ->
!relPath.startsWith("Info.plist") &&
!relPath.startsWith("bin/fsnotifier") &&
!relPath.startsWith("bin/repair") &&
!relPath.startsWith("bin/restart") &&
!relPath.startsWith("bin/printenv") &&
!(relPath.startsWith("bin/") && (relPath.endsWith(".sh") || relPath.endsWith(".vmoptions")) && relPath.count { it == '/' } == 1) &&
relPath != "bin/idea.properties" &&
!relPath.startsWith("help/")
}
val zipFileUniqueGuard = HashMap<String, Path>()
out.dir(distAllDir, "", fileFilter = { _, relPath -> relPath != "bin/idea.properties" }, entryCustomizer = entryCustomizer)
out.dir(macX64DistDir, "", fileFilter = { _, relativePath ->
commonFilter.invoke(relativePath) &&
filterFileIfAlreadyInZip(relativePath, macX64DistDir.resolve(relativePath), zipFileUniqueGuard)
}, entryCustomizer = entryCustomizer)
out.dir(macArm64DistDir, "", fileFilter = { _, relPath ->
commonFilter.invoke(relPath) &&
filterFileIfAlreadyInZip(relPath, macArm64DistDir.resolve(relPath), zipFileUniqueGuard)
}, entryCustomizer = entryCustomizer)
out.dir(linuxX64DistDir, "", fileFilter = { _, relPath ->
commonFilter.invoke(relPath) &&
filterFileIfAlreadyInZip(relPath, linuxX64DistDir.resolve(relPath), zipFileUniqueGuard)
}, entryCustomizer = entryCustomizer)
out.dir(startDir = winX64DistDir, prefix = "", fileFilter = { _, relativePath ->
commonFilter.invoke(relativePath) &&
!(relativePath.startsWith("bin/${executableName}") && relativePath.endsWith(".exe")) &&
filterFileIfAlreadyInZip(relativePath, winX64DistDir.resolve(relativePath), zipFileUniqueGuard)
}, entryCustomizer = entryCustomizer)
for (distFile in distFiles) {
// linux and windows: we don't add win and linux specific dist dirs for ARM, so, copy distFiles explicitly
// macOS: we don't copy dist files for macOS distribution to avoid extra copy operation
if (zipFileUniqueGuard.putIfAbsent(distFile.relativePath, distFile.file) == null) {
out.entry(distFile.relativePath, distFile.file)
}
}
}
}
}
fun getModulesToCompile(buildContext: BuildContext): Set<String> {
val productLayout = buildContext.productProperties.productLayout
val result = LinkedHashSet<String>()
result.addAll(productLayout.getIncludedPluginModules(java.util.Set.copyOf(productLayout.bundledPluginModules)))
PlatformModules.collectPlatformModules(result)
result.addAll(productLayout.productApiModules)
result.addAll(productLayout.productImplementationModules)
result.addAll(productLayout.additionalPlatformJars.values())
result.addAll(getToolModules())
result.addAll(buildContext.productProperties.additionalModulesToCompile)
result.add("intellij.idea.community.build.tasks")
result.add("intellij.platform.images.build")
result.removeAll(productLayout.excludedModuleNames)
return result
}
// Captures information about all available inspections in a JSON format as part of Inspectopedia project. This is later used by Qodana and other tools.
private suspend fun buildInspectopediaArtifacts(builder: DistributionJARsBuilder,
context: BuildContext) {
val ideClasspath = builder.createIdeClassPath(context)
val tempDir = context.paths.tempDir.resolve("inspectopedia-generator")
val inspectionsPath = tempDir.resolve("inspections-${context.applicationInfo.productCode.lowercase()}")
runApplicationStarter(context = context,
tempDir = tempDir,
ideClasspath = ideClasspath,
arguments = listOf("inspectopedia-generator", inspectionsPath.toAbsolutePath().toString()))
val targetFile = context.paths.artifactDir.resolve("inspections-${context.applicationInfo.productCode.lowercase()}.zip").toFile()
ZipOutputStream(FileOutputStream(targetFile)).use { zip ->
ZipUtil.addDirToZipRecursively(zip, targetFile, inspectionsPath.toFile(), "", null, null)
}
}
| apache-2.0 | 201009672bb273acf4fbfa0ae62761c8 | 47.748361 | 174 | 0.715283 | 5.211901 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/NodeAction.kt | 6 | 1654 | // 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.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAwareAction
import java.awt.datatransfer.StringSelection
import javax.swing.JTree
internal class CopyProblemDescriptionAction : NodeAction<Problem>() {
override fun getData(node: Any?) = (node as? ProblemNode)?.problem
override fun actionPerformed(data: Problem) = CopyPasteManager.getInstance().setContents(StringSelection(data.description ?: data.text))
}
internal abstract class NodeAction<Data> : DumbAwareAction() {
abstract fun getData(node: Any?): Data?
abstract fun actionPerformed(data: Data)
open fun isEnabled(data: Data) = true
override fun update(event: AnActionEvent) {
val data = getData(getSelectedNode(event))
event.presentation.isEnabledAndVisible = data != null && isEnabled(data)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(event: AnActionEvent) {
val data = getData(getSelectedNode(event))
if (data != null) actionPerformed(data)
}
}
private fun getSelectedNode(event: AnActionEvent): Any? {
val tree = event.getData(CONTEXT_COMPONENT) as? JTree
return tree?.selectionPath?.lastPathComponent
} | apache-2.0 | 9fe266bb46eb54424c29b3c84a1b4a81 | 39.365854 | 138 | 0.791415 | 4.594444 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRToolWindowTabViewModel.kt | 2 | 4043 | // 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.plugins.github.pullrequest.ui.toolwindow
import com.intellij.collaboration.async.combineState
import com.intellij.collaboration.async.mapStateScoped
import com.intellij.collaboration.util.URIUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.jetbrains.plugins.github.api.GHRepositoryConnection
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
internal class GHPRToolWindowTabViewModel(private val scope: CoroutineScope,
private val repositoriesManager: GHHostedRepositoriesManager,
private val accountManager: GHAccountManager,
private val connectionManager: GHRepositoryConnectionManager,
private val settings: GithubPullRequestsProjectUISettings) {
private val connectionState = MutableStateFlow<GHRepositoryConnection?>(null).apply {
scope.launch {
collectLatest {
if (it != null) {
it.awaitClose()
compareAndSet(it, null)
}
}
}
}
private val singleRepoAndAccountState: StateFlow<Pair<GHGitRepositoryMapping, GithubAccount>?> =
combineState(scope, repositoriesManager.knownRepositoriesState, accountManager.accountsState) { repos, accounts ->
repos.singleOrNull()?.let { repo ->
accounts.singleOrNull { URIUtil.equalWithoutSchema(it.server.toURI(), repo.repository.serverPath.toURI()) }?.let {
repo to it
}
}
}
val viewState: StateFlow<GHPRTabContentViewModel> = connectionState.mapStateScoped(scope) { scope, connection ->
if (connection != null) {
createConnectedVm(connection)
}
else {
createNotConnectedVm(scope)
}
}
private fun createNotConnectedVm(cs: CoroutineScope): GHPRTabContentViewModel.Selectors {
val selectorVm = GHRepositoryAndAccountSelectorViewModel(cs, repositoriesManager, accountManager, ::connect)
settings.selectedRepoAndAccount?.let { (repo, account) ->
with(selectorVm) {
repoSelectionState.value = repo
accountSelectionState.value = account
submitSelection()
}
}
cs.launch {
singleRepoAndAccountState.collect {
if (it != null) {
with(selectorVm) {
repoSelectionState.value = it.first
accountSelectionState.value = it.second
submitSelection()
}
}
}
}
return GHPRTabContentViewModel.Selectors(selectorVm)
}
private suspend fun connect(repo: GHGitRepositoryMapping, account: GithubAccount) {
connectionState.value = connectionManager.connect(scope, repo, account)
settings.selectedRepoAndAccount = repo to account
}
private fun createConnectedVm(connection: GHRepositoryConnection) = GHPRTabContentViewModel.PullRequests(connection)
fun canSelectDifferentRepoOrAccount(): Boolean {
return viewState.value is GHPRTabContentViewModel.PullRequests && singleRepoAndAccountState.value == null
}
fun selectDifferentRepoOrAccount() {
scope.launch {
settings.selectedRepoAndAccount = null
connectionState.value?.close()
}
}
}
internal sealed interface GHPRTabContentViewModel {
class Selectors(val selectorVm: GHRepositoryAndAccountSelectorViewModel) : GHPRTabContentViewModel
class PullRequests(val connection: GHRepositoryConnection) : GHPRTabContentViewModel
}
| apache-2.0 | d34ad74ab1b4c9f3d399937b606c60bc | 39.029703 | 122 | 0.730398 | 5.463514 | false | false | false | false |
ktorio/ktor | ktor-io/common/src/io/ktor/utils/io/internal/SequentialCopyTo.kt | 1 | 2011 | package io.ktor.utils.io.internal
import io.ktor.utils.io.ByteChannelSequentialBase
import io.ktor.utils.io.close
import io.ktor.utils.io.core.internal.ChunkBuffer
internal suspend fun ByteChannelSequentialBase.joinToImpl(dst: ByteChannelSequentialBase, closeOnEnd: Boolean) {
copyToSequentialImpl(dst, Long.MAX_VALUE)
if (closeOnEnd) dst.close()
}
/**
* Reads up to [limit] bytes from receiver channel and writes them to [dst] channel.
* Closes [dst] channel if fails to read or write with cause exception.
* @return a number of copied bytes
*/
internal suspend fun ByteChannelSequentialBase.copyToSequentialImpl(dst: ByteChannelSequentialBase, limit: Long): Long {
require(this !== dst)
if (closedCause != null) {
dst.close(closedCause)
return 0L
}
var remainingLimit = limit
while (remainingLimit > 0) {
if (!awaitInternalAtLeast1()) {
break
}
val transferred = transferTo(dst, remainingLimit)
val copied = if (transferred == 0L) {
val tail = copyToTail(dst, remainingLimit)
if (tail == 0L) {
break
}
tail
} else {
if (dst.availableForWrite == 0) {
dst.awaitAtLeastNBytesAvailableForWrite(1)
}
transferred
}
remainingLimit -= copied
if (copied > 0) {
dst.flush()
}
}
return limit - remainingLimit
}
private suspend fun ByteChannelSequentialBase.copyToTail(dst: ByteChannelSequentialBase, limit: Long): Long {
val lastPiece = ChunkBuffer.Pool.borrow()
try {
lastPiece.resetForWrite(limit.coerceAtMost(lastPiece.capacity.toLong()).toInt())
val rc = readAvailable(lastPiece)
if (rc == -1) {
lastPiece.release(ChunkBuffer.Pool)
return 0
}
dst.writeFully(lastPiece)
return rc.toLong()
} finally {
lastPiece.release(ChunkBuffer.Pool)
}
}
| apache-2.0 | e03c358fb69a17bb10391068ccd226eb | 27.323944 | 120 | 0.627051 | 4.488839 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt | 2 | 2040 | package eu.kanade.tachiyomi.ui.manga.track
import android.app.Dialog
import android.os.Bundle
import androidx.core.os.bundleOf
import com.bluelinelabs.conductor.Controller
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class SetTrackStatusDialog<T> : DialogController
where T : Controller {
private val item: TrackItem
private lateinit var listener: Listener
constructor(target: T, listener: Listener, item: TrackItem) : super(
bundleOf(KEY_ITEM_TRACK to item.track)
) {
targetController = target
this.listener = listener
this.item = item
}
@Suppress("unused")
constructor(bundle: Bundle) : super(bundle) {
val track = bundle.getSerializable(KEY_ITEM_TRACK) as Track
val service = Injekt.get<TrackManager>().getService(track.sync_id)!!
item = TrackItem(track, service)
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val statusList = item.service.getStatusList()
val statusString = statusList.map { item.service.getStatus(it) }
var selectedIndex = statusList.indexOf(item.track?.status)
return MaterialAlertDialogBuilder(activity!!)
.setTitle(R.string.status)
.setSingleChoiceItems(statusString.toTypedArray(), selectedIndex) { _, which ->
selectedIndex = which
}
.setPositiveButton(android.R.string.ok) { _, _ ->
listener.setStatus(item, selectedIndex)
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
interface Listener {
fun setStatus(item: TrackItem, selection: Int)
}
}
private const val KEY_ITEM_TRACK = "SetTrackStatusDialog.item.track"
| apache-2.0 | 09d8bef7ce93c68e1442a557f515e9b0 | 33.576271 | 91 | 0.691176 | 4.473684 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt | 2 | 7735 | package eu.kanade.tachiyomi.data.notification
import android.content.Context
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_DEFAULT
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_HIGH
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_LOW
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.buildNotificationChannel
import eu.kanade.tachiyomi.util.system.buildNotificationChannelGroup
/**
* Class to manage the basic information of all the notifications used in the app.
*/
object Notifications {
/**
* Common notification channel and ids used anywhere.
*/
const val CHANNEL_COMMON = "common_channel"
const val ID_DOWNLOAD_IMAGE = 2
/**
* Notification channel and ids used by the library updater.
*/
private const val GROUP_LIBRARY = "group_library"
const val CHANNEL_LIBRARY_PROGRESS = "library_progress_channel"
const val ID_LIBRARY_PROGRESS = -101
const val CHANNEL_LIBRARY_ERROR = "library_errors_channel"
const val ID_LIBRARY_ERROR = -102
/**
* Notification channel and ids used by the downloader.
*/
private const val GROUP_DOWNLOADER = "group_downloader"
const val CHANNEL_DOWNLOADER_PROGRESS = "downloader_progress_channel"
const val ID_DOWNLOAD_CHAPTER_PROGRESS = -201
const val CHANNEL_DOWNLOADER_COMPLETE = "downloader_complete_channel"
const val ID_DOWNLOAD_CHAPTER_COMPLETE = -203
const val CHANNEL_DOWNLOADER_ERROR = "downloader_error_channel"
const val ID_DOWNLOAD_CHAPTER_ERROR = -202
/**
* Notification channel and ids used by the library updater.
*/
const val CHANNEL_NEW_CHAPTERS = "new_chapters_channel"
const val ID_NEW_CHAPTERS = -301
const val GROUP_NEW_CHAPTERS = "eu.kanade.tachiyomi.NEW_CHAPTERS"
/**
* Notification channel and ids used by the backup/restore system.
*/
private const val GROUP_BACKUP_RESTORE = "group_backup_restore"
const val CHANNEL_BACKUP_RESTORE_PROGRESS = "backup_restore_progress_channel"
const val ID_BACKUP_PROGRESS = -501
const val ID_RESTORE_PROGRESS = -503
const val CHANNEL_BACKUP_RESTORE_COMPLETE = "backup_restore_complete_channel_v2"
const val ID_BACKUP_COMPLETE = -502
const val ID_RESTORE_COMPLETE = -504
/**
* Notification channel used for crash log file sharing.
*/
const val CHANNEL_CRASH_LOGS = "crash_logs_channel"
const val ID_CRASH_LOGS = -601
/**
* Notification channel used for Incognito Mode
*/
const val CHANNEL_INCOGNITO_MODE = "incognito_mode_channel"
const val ID_INCOGNITO_MODE = -701
/**
* Notification channel and ids used for app and extension updates.
*/
private const val GROUP_APK_UPDATES = "group_apk_updates"
const val CHANNEL_APP_UPDATE = "app_apk_update_channel"
const val ID_APP_UPDATER = 1
const val CHANNEL_EXTENSIONS_UPDATE = "ext_apk_update_channel"
const val ID_UPDATES_TO_EXTS = -401
const val ID_EXTENSION_INSTALLER = -402
private val deprecatedChannels = listOf(
"downloader_channel",
"backup_restore_complete_channel",
"library_channel",
"library_progress_channel",
"updates_ext_channel",
)
/**
* Creates the notification channels introduced in Android Oreo.
* This won't do anything on Android versions that don't support notification channels.
*
* @param context The application context.
*/
fun createChannels(context: Context) {
val notificationService = NotificationManagerCompat.from(context)
// Delete old notification channels
deprecatedChannels.forEach(notificationService::deleteNotificationChannel)
notificationService.createNotificationChannelGroupsCompat(
listOf(
buildNotificationChannelGroup(GROUP_BACKUP_RESTORE) {
setName(context.getString(R.string.label_backup))
},
buildNotificationChannelGroup(GROUP_DOWNLOADER) {
setName(context.getString(R.string.download_notifier_downloader_title))
},
buildNotificationChannelGroup(GROUP_LIBRARY) {
setName(context.getString(R.string.label_library))
},
buildNotificationChannelGroup(GROUP_APK_UPDATES) {
setName(context.getString(R.string.label_recent_updates))
},
)
)
notificationService.createNotificationChannelsCompat(
listOf(
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_common))
},
buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_NEW_CHAPTERS, IMPORTANCE_DEFAULT) {
setName(context.getString(R.string.channel_new_chapters))
},
buildNotificationChannel(CHANNEL_DOWNLOADER_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_COMPLETE, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_COMPLETE, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
setSound(null, null)
},
buildNotificationChannel(CHANNEL_CRASH_LOGS, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_crash_logs))
},
buildNotificationChannel(CHANNEL_INCOGNITO_MODE, IMPORTANCE_LOW) {
setName(context.getString(R.string.pref_incognito_mode))
},
buildNotificationChannel(CHANNEL_APP_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_app_updates))
},
buildNotificationChannel(CHANNEL_EXTENSIONS_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_ext_updates))
},
)
)
}
}
| apache-2.0 | bb69b763969c608c80de059e0811a316 | 41.734807 | 92 | 0.632062 | 5.045662 | false | false | false | false |
cfieber/orca | orca-qos/src/test/kotlin/com/netflix/spinnaker/orca/qos/ExecutionBufferActuatorTest.kt | 1 | 6833 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.qos
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.orca.ExecutionStatus.BUFFERED
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.events.BeforeInitialExecutionPersist
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.qos.BufferAction.BUFFER
import com.netflix.spinnaker.orca.qos.BufferAction.ENQUEUE
import com.netflix.spinnaker.orca.qos.BufferState.ACTIVE
import com.netflix.spinnaker.orca.qos.BufferState.INACTIVE
import com.netflix.spinnaker.orca.qos.bufferstate.BufferStateSupplierProvider
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.subject.SubjectSpek
class ExecutionBufferActuatorTest : SubjectSpek<ExecutionBufferActuator>({
val configService: DynamicConfigService = mock()
val bufferStateSupplier: BufferStateSupplier = mock()
val policy1: BufferPolicy = mock()
val policy2: BufferPolicy = mock()
subject(CachingMode.GROUP) {
ExecutionBufferActuator(
BufferStateSupplierProvider(listOf(bufferStateSupplier)),
configService, NoopRegistry(), listOf(policy1, policy2)
)
}
fun resetMocks() = reset(bufferStateSupplier, policy1, policy2)
describe("buffering executions") {
beforeGroup {
whenever(configService.isEnabled(eq("qos"), any())) doReturn true
whenever(configService.isEnabled(eq("qos.learningMode"), any())) doReturn false
}
afterGroup(::resetMocks)
given("buffer state is INACTIVE") {
val execution = pipeline {
application = "spintest"
status = NOT_STARTED
}
beforeGroup {
whenever(bufferStateSupplier.enabled()) doReturn true
whenever(bufferStateSupplier.get()) doReturn INACTIVE
}
afterGroup(::resetMocks)
on("before initial persist event") {
subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution))
}
it("does nothing") {
verify(policy1, never()).apply(execution)
verify(policy2, never()).apply(execution)
assert(execution.status == NOT_STARTED)
}
}
given("buffer state is ACTIVE and policies decide ENQUEUE") {
val execution = pipeline {
application = "spintest"
status = NOT_STARTED
}
beforeGroup {
whenever(bufferStateSupplier.enabled()) doReturn true
whenever(bufferStateSupplier.get()) doReturn ACTIVE
whenever(policy1.apply(any())) doReturn BufferResult(
action = ENQUEUE,
force = false,
reason = "Cannot determine action"
)
whenever(policy2.apply(any())) doReturn BufferResult(
action = ENQUEUE,
force = false,
reason = "Cannot determine action"
)
}
on("before initial persist event") {
subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution))
}
it("does nothing") {
verify(policy1, times(1)).apply(execution)
verify(policy2, times(1)).apply(execution)
assert(execution.status == NOT_STARTED)
}
}
given("buffer state is ACTIVE and policies decide BUFFER") {
val execution = pipeline {
application = "spintest"
status = NOT_STARTED
}
beforeGroup {
whenever(bufferStateSupplier.get()) doReturn ACTIVE
whenever(policy1.apply(any())) doReturn BufferResult(
action = BUFFER,
force = false,
reason = "Going to buffer"
)
whenever(policy2.apply(any())) doReturn BufferResult(
action = ENQUEUE,
force = false,
reason = "Cannot determine action"
)
}
on("before initial persist event") {
subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution))
}
it("does nothing") {
verify(policy1, times(1)).apply(execution)
verify(policy2, times(1)).apply(execution)
assert(execution.status == BUFFERED)
}
}
given("buffer state is ACTIVE and policy forces ENQUEUE") {
val execution = pipeline {
application = "spintest"
status = NOT_STARTED
}
beforeGroup {
whenever(bufferStateSupplier.get()) doReturn ACTIVE
whenever(policy1.apply(any())) doReturn BufferResult(
action = ENQUEUE,
force = true,
reason = "Going to buffer"
)
whenever(policy2.apply(any())) doReturn BufferResult(
action = BUFFER,
force = false,
reason = "Should buffer"
)
}
on("before initial persist event") {
subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution))
}
it("does nothing") {
verify(policy1, times(1)).apply(execution)
verify(policy2, times(1)).apply(execution)
assert(execution.status == NOT_STARTED)
}
}
given("in learning mode and buffer state is ACTIVE") {
val execution = pipeline {
application = "spintest"
status = NOT_STARTED
}
beforeGroup {
whenever(bufferStateSupplier.get()) doReturn ACTIVE
whenever(policy1.apply(any())) doReturn BufferResult(
action = BUFFER,
force = false,
reason = "Buffer"
)
whenever(policy2.apply(any())) doReturn BufferResult(
action = BUFFER,
force = false,
reason = "Should"
)
whenever(configService.isEnabled(any(), any())) doReturn true
}
on("before initial persist event") {
subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution))
}
it("does nothing") {
verify(policy1, times(1)).apply(execution)
verify(policy2, times(1)).apply(execution)
assert(execution.status == NOT_STARTED)
}
}
}
})
| apache-2.0 | 94b932c85ea7008dabc27daa880d272c | 31.383886 | 91 | 0.661642 | 4.676934 | false | false | false | false |
fabioCollini/ArchitectureComponentsDemo | uisearch/src/main/java/it/codingjam/github/ui/search/SearchUseCase.kt | 1 | 2464 | package it.codingjam.github.ui.search
import android.content.SharedPreferences
import com.nalulabs.prefs.string
import it.codingjam.github.FeatureAppScope
import it.codingjam.github.core.GithubInteractor
import it.codingjam.github.core.OpenForTesting
import it.codingjam.github.core.RepoId
import it.codingjam.github.util.*
import it.codingjam.github.vo.lce
import java.util.*
import javax.inject.Inject
@OpenForTesting
@FeatureAppScope
class SearchUseCase @Inject constructor(
private val githubInteractor: GithubInteractor,
prefs: SharedPreferences
) {
private var lastSearch by prefs.string("")
fun initialState() = SearchViewState(lastSearch)
fun setQuery(originalInput: String, state: SearchViewState): ActionsFlow<SearchViewState> {
lastSearch = originalInput
val input = originalInput.toLowerCase(Locale.getDefault()).trim { it <= ' ' }
return if (state.repos.data?.searchInvoked != true || input != state.query) {
reloadData(input)
} else
emptyActionsFlow()
}
fun loadNextPage(state: SearchViewState): ActionsFlow<SearchViewState> = actionsFlow<ReposViewState> {
state.repos.doOnData { (_, nextPage, _, loadingMore) ->
val query = state.query
if (query.isNotEmpty() && nextPage != null && !loadingMore) {
emit { copy(loadingMore = true) }
try {
val (items, newNextPage) = githubInteractor.searchNextPage(query, nextPage)
emit {
copy(list = list + items, nextPage = newNextPage, loadingMore = false)
}
} catch (t: Exception) {
emit { copy(loadingMore = false) }
emit(ErrorSignal(t))
}
}
}
}.mapActions { stateAction -> copy(repos = repos.map { stateAction(it) }) }
private fun reloadData(query: String): ActionsFlow<SearchViewState> = lce {
val (items, nextPage) = githubInteractor.search(query)
ReposViewState(items, nextPage, true)
}.mapActions { stateAction -> copy(repos = stateAction(repos), query = query) }
fun refresh(state: SearchViewState): ActionsFlow<SearchViewState> {
return if (state.query.isNotEmpty()) {
reloadData(state.query)
} else
emptyActionsFlow()
}
fun openRepoDetail(id: RepoId) = NavigationSignal("repo", id)
} | apache-2.0 | f9a115908245720b66e967098d311ba9 | 36.923077 | 106 | 0.640828 | 4.605607 | false | false | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/propertyelement/PropertyItemDataClass.kt | 1 | 1881 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.propertyelement
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.annotationprocessing.DateConverter
import java.util.Date
/**
* @author Hannes Dorfmann
*/
@Xml(name = "item")
data class PropertyItemDataClass(
@field:PropertyElement
@JvmField
var aString: String? = null,
@field:PropertyElement
@JvmField
var anInt: Int = 0,
@field:PropertyElement
@JvmField
var aBoolean: Boolean = false,
@field:PropertyElement
@JvmField
var aDouble: Double = 0.toDouble(),
@field:PropertyElement
@JvmField
var aLong: Long = 0,
@field:PropertyElement(converter = DateConverter::class)
@JvmField
var aDate: Date? = null,
@field:PropertyElement
@JvmField
var intWrapper: Int? = null,
@field:PropertyElement
@JvmField
var booleanWrapper: Boolean? = null,
@field:PropertyElement
@JvmField
var doubleWrapper: Double? = null,
@field:PropertyElement
@JvmField
var longWrapper: Long? = null
) | apache-2.0 | fa4aa3485736cb98270fca3b863e10ff | 29.852459 | 75 | 0.669325 | 4.554479 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewDiffPreviewProcessor.kt | 3 | 5511 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.diff.FrameDiffTool
import com.intellij.diff.util.DiffPlaces
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.*
import com.intellij.openapi.vcs.changes.actions.diff.lst.LocalChangeListDiffTool.ALLOW_EXCLUDE_FROM_COMMIT
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserChangeListNode
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode.MODIFIED_WITHOUT_EDITING_TAG
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.changes.ui.TagChangesBrowserNode
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.commit.EditedCommitDetails
import com.intellij.vcs.commit.EditedCommitNode
import one.util.streamex.StreamEx
import java.util.*
import java.util.stream.Stream
private fun wrap(project: Project, changesNodes: Stream<ChangesBrowserNode<*>>, unversioned: Stream<FilePath>): Stream<Wrapper> =
Stream.concat(
changesNodes.map { wrapNode(project, it) }.filter(Objects::nonNull),
unversioned.map { UnversionedFileWrapper(it) }
)
private fun wrapNode(project: Project, node: ChangesBrowserNode<*>): Wrapper? {
return when (val nodeObject = node.userObject) {
is Change -> ChangeWrapper(nodeObject, node.let(::wrapNodeToTag))
is VirtualFile -> if (findTagNode(node)?.userObject == MODIFIED_WITHOUT_EDITING_TAG) wrapHijacked(project, nodeObject) else null
else -> null
}
}
private fun wrapHijacked(project: Project, file: VirtualFile): Wrapper? {
return ChangesListView.toHijackedChange(project, file)
?.let { c -> ChangeWrapper(c, MODIFIED_WITHOUT_EDITING_TAG) }
}
private fun wrapNodeToTag(node: ChangesBrowserNode<*>): ChangesBrowserNode.Tag? {
return findChangeListNode(node)?.let { ChangeListWrapper(it.userObject) }
?: findAmendNode(node)?.let { AmendChangeWrapper(it.userObject) }
}
private fun findTagNode(node: ChangesBrowserNode<*>): TagChangesBrowserNode? = findNodeOfType(node)
private fun findChangeListNode(node: ChangesBrowserNode<*>): ChangesBrowserChangeListNode? = findNodeOfType(node)
private fun findAmendNode(node: ChangesBrowserNode<*>): EditedCommitNode? = findNodeOfType(node)
private inline fun <reified T : ChangesBrowserNode<*>> findNodeOfType(node: ChangesBrowserNode<*>): T? {
if (node is T) return node
var parent = node.parent
while (parent != null) {
if (parent is T) return parent
parent = parent.parent
}
return null
}
private class ChangesViewDiffPreviewProcessor(private val changesView: ChangesListView,
private val isInEditor: Boolean)
: ChangeViewDiffRequestProcessor(changesView.project, if (isInEditor) DiffPlaces.DEFAULT else DiffPlaces.CHANGES_VIEW) {
init {
putContextUserData(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, true)
}
override fun shouldAddToolbarBottomBorder(toolbarComponents: FrameDiffTool.ToolbarComponents): Boolean {
return !isInEditor || super.shouldAddToolbarBottomBorder(toolbarComponents)
}
override fun getSelectedChanges(): Stream<Wrapper> =
wrap(project, StreamEx.of(changesView.selectedChangesNodes.iterator()), StreamEx.of(changesView.selectedUnversionedFiles.iterator()))
override fun getAllChanges(): Stream<Wrapper> = wrap(project, StreamEx.of(changesView.changesNodes.iterator()), changesView.unversionedFiles)
override fun showAllChangesForEmptySelection(): Boolean = false
override fun selectChange(change: Wrapper) {
val tag = (change.tag as? ChangesViewUserObjectTag)?.userObject
val treePath = changesView.findNodePathInTree(change.userObject, tag) ?: return
TreeUtil.selectPath(changesView, treePath, false)
}
fun setAllowExcludeFromCommit(value: Boolean) {
if (DiffUtil.isUserDataFlagSet(ALLOW_EXCLUDE_FROM_COMMIT, context) == value) return
context.putUserData(ALLOW_EXCLUDE_FROM_COMMIT, value)
fireDiffSettingsChanged()
}
fun fireDiffSettingsChanged() {
dropCaches()
updateRequest(true)
}
}
private class AmendChangeWrapper(override val userObject: EditedCommitDetails) : ChangesViewUserObjectTag {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AmendChangeWrapper
if (userObject.commit.id != other.userObject.commit.id) return false
return true
}
override fun toString(): String = userObject.commit.subject
override fun hashCode(): Int = userObject.commit.id.hashCode()
}
private class ChangeListWrapper(override val userObject: ChangeList) : ChangesViewUserObjectTag {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ChangeListWrapper
if (userObject.name != other.userObject.name) return false
return true
}
override fun hashCode(): Int = userObject.name.hashCode()
override fun toString(): String = userObject.name
}
interface ChangesViewUserObjectTag : ChangesBrowserNode.Tag {
val userObject: Any
}
| apache-2.0 | 2970fdbf3f8cde850dac970c5adaee3e | 38.647482 | 158 | 0.770822 | 4.332547 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/app/log/LoggerTree.kt | 1 | 1075 | package soutvoid.com.DsrWeatherApp.app.log
import android.util.Log
import timber.log.Timber
/**
* логгирует в logcat
* логи уровня DEBUG и выше логируется в [RemoteLogger]
*/
class LoggerTree @JvmOverloads constructor(private val mLogPriority: Int = Log.DEBUG) : Timber.DebugTree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
super.log(priority, tag, message, t)
try {
if (priority >= mLogPriority) {
RemoteLogger.logMessage(String.format(REMOTE_LOGGER_LOG_FORMAT, tag, message))
if (t != null && priority >= Log.ERROR) {
RemoteLogger.logError(t)
}
}
} catch (e: Exception) {
super.log(priority, tag, "Remote logger error", t)
}
}
companion object {
val REMOTE_LOGGER_LOG_FORMAT = "%s: %s"
val REMOTE_LOGGER_SEND_LOG_ERROR = "error sending to RemoteLogger"
}
}
/**
* приоритет по умолчанию - DEBUG
*/
| apache-2.0 | 8f9eaec02bbd938ebb4719951331d5a0 | 27.305556 | 108 | 0.600589 | 3.705455 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityToParentImpl.kt | 2 | 5943 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class AttachedEntityToParentImpl: AttachedEntityToParent, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField var _data: String? = null
override val data: String
get() = _data!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: AttachedEntityToParentData?): ModifiableWorkspaceEntityBase<AttachedEntityToParent>(), AttachedEntityToParent.Builder {
constructor(): this(AttachedEntityToParentData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity AttachedEntityToParent is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isDataInitialized()) {
error("Field AttachedEntityToParent#data should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field AttachedEntityToParent#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): AttachedEntityToParentData = result ?: super.getEntityData() as AttachedEntityToParentData
override fun getEntityClass(): Class<AttachedEntityToParent> = AttachedEntityToParent::class.java
}
}
class AttachedEntityToParentData : WorkspaceEntityData<AttachedEntityToParent>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<AttachedEntityToParent> {
val modifiable = AttachedEntityToParentImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): AttachedEntityToParent {
val entity = AttachedEntityToParentImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return AttachedEntityToParent::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as AttachedEntityToParentData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as AttachedEntityToParentData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | apache-2.0 | 26247a8b4622ffb2ba09b067a46fc7f0 | 35.024242 | 149 | 0.660104 | 6.190625 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesOrderTable.kt | 12 | 2866 | // 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.profile.codeInspection.ui.table
import com.intellij.analysis.AnalysisBundle
import com.intellij.psi.search.scope.packageSet.NamedScope
import com.intellij.ui.OffsetIcon
import com.intellij.ui.table.TableView
import com.intellij.util.ui.ColumnInfo
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.ListTableModel
import com.intellij.util.ui.table.IconTableCellRenderer
import javax.swing.Icon
import javax.swing.JTable
import javax.swing.ListSelectionModel
import javax.swing.table.TableCellRenderer
class ScopesOrderTable : TableView<NamedScope>() {
private val model = ListTableModel<NamedScope>(IconColumn, NameColumn, SetColumn)
init {
setModelAndUpdateColumns(model)
rowSelectionAllowed = true
columnSelectionAllowed = false
setShowGrid(false)
tableHeader.reorderingAllowed = false
setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
getColumnModel().getColumn(0).apply {
maxWidth = JBUI.scale(34)
minWidth = JBUI.scale(34)
}
getColumnModel().getColumn(1).apply {
preferredWidth = JBUI.scale(200)
}
}
fun updateItems(scopes: Collection<NamedScope>) {
while (model.rowCount > 0) model.removeRow(0)
model.addRows(scopes)
}
fun getScopeAt(i: Int): NamedScope? {
return model.getItem(i)
}
fun moveUp() {
if (selectedRow > 0) move(-1)
}
fun moveDown() {
if (selectedRow + 1 < rowCount) move(1)
}
private fun move(offset: Int) {
val selected = selectedRow
model.exchangeRows(selected, selected + offset)
selectionModel.apply {
clearSelection()
addSelectionInterval(selected + offset, selected + offset)
}
scrollRectToVisible(getCellRect(selectedRow, 0, true))
repaint()
}
private object IconColumn : ColumnInfo<NamedScope, String?>("") {
override fun valueOf(item: NamedScope): String = ""
override fun getRenderer(item: NamedScope?): TableCellRenderer {
return object : IconTableCellRenderer<String>() {
override fun getIcon(value: String, table: JTable?, row: Int): Icon? {
when (item?.icon) {
is OffsetIcon -> return (item.icon as OffsetIcon).icon
else -> return item?.icon
}
}
override fun isCenterAlignment(): Boolean = true
}
}
}
private object NameColumn : ColumnInfo<NamedScope, String>(AnalysisBundle.message("inspections.settings.scopes.name")) {
override fun valueOf(item: NamedScope): String = item.presentableName
}
private object SetColumn : ColumnInfo<NamedScope, String>(AnalysisBundle.message("inspections.settings.scopes.pattern")) {
override fun valueOf(item: NamedScope): String = item.value?.text ?: ""
}
} | apache-2.0 | c85ded81c94e7908abd9e6a331bdc0a9 | 31.213483 | 140 | 0.714236 | 4.303303 | false | false | false | false |
android/privacy-codelab | PhotoLog_start/src/main/java/com/example/photolog_start/PhotoSaverRepository.kt | 1 | 2783 | /*
* 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
*
* 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.example.photolog_start
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
class PhotoSaverRepository(context: Context, private val contentResolver: ContentResolver) {
private val _photos = mutableListOf<File>()
fun getPhotos() = _photos.toList()
fun isEmpty() = _photos.isEmpty()
fun canAddPhoto() = _photos.size < MAX_LOG_PHOTOS_LIMIT
private val cacheFolder = File(context.cacheDir, "photos").also { it.mkdir() }
val photoFolder = File(context.filesDir, "photos").also { it.mkdir() }
private fun generateFileName() = "${System.currentTimeMillis()}.jpg"
private fun generatePhotoLogFile() = File(photoFolder, generateFileName())
fun generatePhotoCacheFile() = File(cacheFolder, generateFileName())
fun cacheCapturedPhoto(photo: File) {
if (_photos.size + 1 > MAX_LOG_PHOTOS_LIMIT) {
return
}
_photos += photo
}
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun cacheFromUri(uri: Uri) {
withContext(Dispatchers.IO) {
if (_photos.size + 1 > MAX_LOG_PHOTOS_LIMIT) {
return@withContext
}
contentResolver.openInputStream(uri)?.use { input ->
val cachedPhoto = generatePhotoCacheFile()
cachedPhoto.outputStream().use { output ->
input.copyTo(output)
_photos += cachedPhoto
}
}
}
}
suspend fun cacheFromUris(uris: List<Uri>) {
uris.forEach {
cacheFromUri(it)
}
}
suspend fun removeFile(photo: File) {
withContext(Dispatchers.IO) {
photo.delete()
_photos -= photo
}
}
suspend fun savePhotos(): List<File> {
return withContext(Dispatchers.IO) {
val savedPhotos = _photos.map { it.copyTo(generatePhotoLogFile()) }
_photos.forEach { it.delete() }
_photos.clear()
savedPhotos
}
}
} | apache-2.0 | 60aef14633deafb9d5089f1731ea2ce5 | 29.933333 | 92 | 0.63816 | 4.495961 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/MainController.kt | 1 | 6164 | package top.zbeboy.isy.web
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.LocaleResolver
import org.springframework.web.servlet.ModelAndView
import top.zbeboy.isy.annotation.logging.RecordSystemLogging
import top.zbeboy.isy.config.ISYProperties
import top.zbeboy.isy.config.Workbook
import top.zbeboy.isy.service.common.UploadService
import top.zbeboy.isy.service.system.AuthoritiesService
import top.zbeboy.isy.web.util.AjaxUtils
import java.io.File
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by zbeboy 2017-11-03 .
**/
@Controller
open class MainController {
@Resource
open lateinit var localeResolver: LocaleResolver
@Resource
open lateinit var authoritiesService: AuthoritiesService
@Autowired
open lateinit var isyProperties: ISYProperties
@Resource
open lateinit var uploadService: UploadService
/**
* main page
*
* @return main page
*/
@RequestMapping("/")
fun root(): String {
return "index"
}
/**
* Home page.
*
* @return home page
*/
@RequestMapping("/index")
fun index(): String {
return "index"
}
/**
* 登录页
*
* @return 登录页.
*/
@RequestMapping(value = ["/login"], method = [(RequestMethod.GET)])
fun login(): String {
return if (!authoritiesService.isAnonymousAuthenticated()) {
"redirect:/web/menu/backstage"
} else {
"login"
}
}
/**
* 注册页
*
* @param type 注册类型(学生,教职工)
* @return 注册页
*/
@RequestMapping(value = ["/register"], method = [(RequestMethod.GET)])
fun register(@RequestParam("type") type: String): String {
// 注册学生
if (type.equals(Workbook.STUDENT_REGIST, ignoreCase = true)) {
return "student_register"
}
// 注册教师
return if (type.equals(Workbook.STAFF_REGIST, ignoreCase = true)) {
"staff_register"
} else "login"
}
/**
* 注册完成时,但并不是成功
*
* @param modelMap 页面对象
* @return 完成页面
*/
@RequestMapping(value = ["/register/finish"], method = [(RequestMethod.GET)])
fun registerFinish(modelMap: ModelMap): String {
modelMap["msg"] = "验证邮件已发送至您的邮箱,请登录邮箱进行验证!"
return "msg"
}
/**
* 忘记密码
*
* @return 忘记密码页面
*/
@RequestMapping(value = ["/user/login/password/forget"], method = [(RequestMethod.GET)])
fun loginPasswordForget(): String {
return "forget_password"
}
/**
* 忘记密码完成时,但并不是成功
*
* @param modelMap 页面对象
* @return 完成页面
*/
@RequestMapping(value = ["/user/login/password/forget/finish"], method = [(RequestMethod.GET)])
fun loginPasswordForgetFinish(modelMap: ModelMap): String {
modelMap["msg"] = "密码重置邮件已发送至您的邮箱。"
return "msg"
}
/**
* 密码重置成功
*
* @param modelMap 页面对象
* @return 重置成功页面
*/
@RequestMapping(value = ["/user/login/password/reset/finish"], method = [(RequestMethod.GET)])
fun passwordResetFinish(modelMap: ModelMap): String {
modelMap["msg"] = "密码重置成功。"
return "msg"
}
/**
* 后台欢迎页
*
* @return 后台欢迎页
*/
@RecordSystemLogging(module = "Main", methods = "backstage", description = "访问系统主页")
@RequestMapping(value = ["/web/menu/backstage"], method = [(RequestMethod.GET)])
open fun backstage(request: HttpServletRequest): String {
return "backstage"
}
/**
* 语言切换,暂时不用
*
* @param request 请求对象
* @param response 响应对象
* @param language 语言
* @return 重置页面
*/
@RequestMapping("/language")
fun language(request: HttpServletRequest, response: HttpServletResponse, language: String): ModelAndView {
val languageLowerCase = language.toLowerCase()
if (languageLowerCase == "") {
return ModelAndView("redirect:/")
} else {
when (languageLowerCase) {
"zh_cn" -> localeResolver.setLocale(request, response, Locale.CHINA)
"en" -> localeResolver.setLocale(request, response, Locale.ENGLISH)
else -> localeResolver.setLocale(request, response, Locale.CHINA)
}
}
return ModelAndView("redirect:/")
}
/**
* 用于集群时,对服务器心跳检测
*
* @return 服务器是否正常运行
*/
@RequestMapping(value = ["/server/probe"], method = [(RequestMethod.GET)])
@ResponseBody
fun serverHealthCheck(): AjaxUtils<*> {
return AjaxUtils.of<Any>().success().msg("Server is running ...")
}
/**
* let's encrypt certificate check.
*
* @param request 请求
* @param response 响应
*/
@RequestMapping(value = ["/.well-known/acme-challenge/*"], method = [(RequestMethod.GET)])
fun letUsEncryptCertificateCheck(request: HttpServletRequest, response: HttpServletResponse) {
val uri = request.requestURI.replace("/", "\\")
//文件路径自行替换一下就行,就是上图中生成验证文件的路径,因为URI中已经包含了/.well-known/acme-challenge/,所以这里不需要
val file = File(isyProperties.getCertificate().place + uri)
uploadService.download("验证文件", file, response, request)
}
} | mit | 7588fc5022fe60a6919bd6897411e92b | 27.144279 | 110 | 0.629774 | 4.069065 | false | false | false | false |
google/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ReplaceBySourceTest.kt | 1 | 3113 | // 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.workspaceModel.ide
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.workspaceModel.ide.impl.jps.serialization.toConfigLocation
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.junit.*
class ReplaceBySourceTest {
@Rule
@JvmField
val projectModel = ProjectModelRule()
private lateinit var virtualFileManager: VirtualFileUrlManager
@Before
fun setUp() {
virtualFileManager = VirtualFileUrlManager.getInstance(projectModel.project)
}
@Test
fun checkOrderAtReplaceBySourceNotDependsOnExecutionCount() {
val expectedResult = mutableListOf<String>()
for (i in 1..100) {
val builder = createBuilder()
val storage = MutableEntityStorage.create()
storage.replaceBySource({ entitySource -> entitySource is JpsFileEntitySource }, builder)
val contentRootEntity = storage.entities(ContentRootEntity::class.java).first()
if (i == 1) {
contentRootEntity.sourceRoots.forEach { expectedResult.add(it.url.toString()) }
} else {
Assert.assertArrayEquals(expectedResult.toTypedArray(), contentRootEntity.sourceRoots.map { it.url.toString() }.toList().toTypedArray())
}
}
}
private fun createBuilder(): MutableEntityStorage {
val fileUrl = "/user/opt/app/a.txt"
val fileUrl2 = "/user/opt/app/b.txt"
val fileUrl3 = "/user/opt/app/c.txt"
val fileUrl4 = "/user/opt/app/d.txt"
val fileUrl5 = "/user/opt/app/e.txt"
val builder = MutableEntityStorage.create()
val baseDir = projectModel.baseProjectDir.rootPath.resolve("test")
val iprFile = baseDir.resolve("testProject.ipr")
val configLocation = toConfigLocation(iprFile, virtualFileManager)
val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation)
val moduleEntity = builder.addModuleEntity("name", emptyList(), source)
val contentRootEntity = builder.addContentRootEntity(virtualFileManager.fromUrl(fileUrl), emptyList(), emptyList(), moduleEntity)
builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl2), "", source)
builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl3), "", source)
builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl4), "", source)
builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl5), "", source)
return builder
}
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
} | apache-2.0 | cdb9905f7d3b2b324b4f0f34fb06637a | 43.485714 | 144 | 0.774173 | 5.053571 | false | true | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/FragmentSelectionsBuilder.kt | 1 | 1610 | package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder
import com.apollographql.apollo3.compiler.ir.IrNamedFragment
import com.apollographql.apollo3.compiler.codegen.kotlin.selections.CompiledSelectionsBuilder
import com.squareup.kotlinpoet.ClassName
class FragmentSelectionsBuilder(
val context: KotlinContext,
val fragment: IrNamedFragment,
val schema: Schema,
val allFragmentDefinitions: Map<String, GQLFragmentDefinition>,
) : CgOutputFileBuilder {
private val packageName = context.layout.fragmentResponseFieldsPackageName(fragment.filePath)
private val simpleName = context.layout.fragmentSelectionsName(fragment.name)
override fun prepare() {
context.resolver.registerFragmentSelections(
fragment.name,
ClassName(packageName, simpleName)
)
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = simpleName,
typeSpecs = listOf(
CompiledSelectionsBuilder(
context = context,
allFragmentDefinitions = allFragmentDefinitions,
schema = schema
).build(fragment.selections, simpleName, fragment.typeCondition)
)
)
}
} | mit | 7055ec9d94906cd790c595563b87ed15 | 37.357143 | 95 | 0.763354 | 4.680233 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt | 1 | 7317 | // 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.result
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.MapTransformation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
class MaxOrMinTransformation(
loop: KtForExpression,
initialization: VariableInitialization,
private val isMax: Boolean
) : AssignToVariableResultTransformation(loop, initialization) {
override val presentation: String
get() = if (isMax) "maxOrNull()" else "minOrNull()"
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val call = chainedCallGenerator.generate(presentation)
return KtPsiFactory(call.project).createExpressionByPattern(
"$0\n ?: $1", call, initialization.initializer,
reformat = chainedCallGenerator.reformat
)
}
/**
* Matches:
* val variable = <initial>
* for (...) {
* ...
* if (variable > <input variable>) { // or '<' or operands swapped
* variable = <input variable>
* }
* }
*
* or
*
* val variable = <initial>
* for (...) {
* ...
* // or '<', '<=', '>=' or operands swapped
* variable = if (variable > <input variable>) <input variable> else variable
* }
* }
* or
*
* val variable = <initial>
* for (...) {
* ...
* // or Math.min or operands swapped
* variable = Math.max(variable, <expression>)
* }
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = true
override fun match(state: MatchingState): TransformationMatch.Result? {
return matchIfAssign(state)
?: matchAssignIf(state)
?: matchMathMaxOrMin(state)
}
private fun matchIfAssign(state: MatchingState): TransformationMatch.Result? {
val ifExpression = state.statements.singleOrNull() as? KtIfExpression ?: return null
if (ifExpression.`else` != null) return null
val then = ifExpression.then ?: return null
val statement = then.blockExpressionsOrSingle().singleOrNull() as? KtBinaryExpression ?: return null
if (statement.operationToken != KtTokens.EQ) return null
return match(ifExpression.condition, statement.left, statement.right, null, state.inputVariable, state.outerLoop)
}
private fun matchAssignIf(state: MatchingState): TransformationMatch.Result? {
val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null
if (assignment.operationToken != KtTokens.EQ) return null
val ifExpression = assignment.right as? KtIfExpression ?: return null
return match(
ifExpression.condition,
assignment.left,
ifExpression.then,
ifExpression.`else`,
state.inputVariable,
state.outerLoop
)
}
private fun matchMathMaxOrMin(state: MatchingState): TransformationMatch.Result? {
val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null
if (assignment.operationToken != KtTokens.EQ) return null
val variableInitialization =
assignment.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false)
?: return null
return matchMathMaxOrMin(variableInitialization, assignment, state, isMax = true)
?: matchMathMaxOrMin(variableInitialization, assignment, state, isMax = false)
}
private fun matchMathMaxOrMin(
variableInitialization: VariableInitialization,
assignment: KtBinaryExpression,
state: MatchingState,
isMax: Boolean
): TransformationMatch.Result? {
val functionName = if (isMax) "max" else "min"
val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null
if (arguments.size != 2) return null
val value = when {
arguments[0].isVariableReference(variableInitialization.variable) -> arguments[1] ?: return null
arguments[1].isVariableReference(variableInitialization.variable) -> arguments[0] ?: return null
else -> return null
}
val mapTransformation = if (value.isVariableReference(state.inputVariable))
null
else
MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, value, mapNotNull = false)
val transformation = MaxOrMinTransformation(state.outerLoop, variableInitialization, isMax)
return TransformationMatch.Result(transformation, listOfNotNull(mapTransformation))
}
private fun match(
condition: KtExpression?,
assignmentTarget: KtExpression?,
valueAssignedIfTrue: KtExpression?,
valueAssignedIfFalse: KtExpression?,
inputVariable: KtCallableDeclaration,
loop: KtForExpression
): TransformationMatch.Result? {
if (condition !is KtBinaryExpression) return null
val comparison = condition.operationToken
if (comparison !in setOf(KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ)) return null
val left = condition.left as? KtNameReferenceExpression ?: return null
val right = condition.right as? KtNameReferenceExpression ?: return null
val otherHand = when {
left.isVariableReference(inputVariable) -> right
right.isVariableReference(inputVariable) -> left
else -> return null
}
val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false)
?: return null
if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null
val valueToBeVariable = when {
valueAssignedIfTrue.isVariableReference(inputVariable) -> valueAssignedIfFalse
valueAssignedIfFalse.isVariableReference(inputVariable) -> valueAssignedIfTrue
else -> return null
}
if (valueToBeVariable != null && !valueToBeVariable.isVariableReference(variableInitialization.variable)) return null
val isMax = (comparison == KtTokens.GT || comparison == KtTokens.GTEQ) xor (otherHand == left)
val transformation = MaxOrMinTransformation(loop, variableInitialization, isMax)
return TransformationMatch.Result(transformation)
}
}
} | apache-2.0 | 6d63d381584dc2a08615fc221c9aef6f | 42.820359 | 158 | 0.632226 | 5.637134 | false | false | false | false |
ursjoss/sipamato | core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/code/HidingInternalsCodeAggregator.kt | 1 | 2875 | package ch.difty.scipamato.core.sync.code
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
private const val AGGR_5ABC = "5abc"
/**
* HARDCODED consider moving aggregation into some table in scipamato-core (see also CodeSyncConfig#selectSql)
*/
private val codeAggregation: Map<String, String> = setOf("5A", "5B", "5C").associateWith { AGGR_5ABC }
private val populationCodeMapper: Map<String, Short> = (
setOf("3A", "3B").associateWith { 1 } +
setOf("3C").associateWith { 2 }
).map { it.key to it.value.toShort() }.toMap()
private val studyDesignCodeMapper: Map<String, Short> = (
setOf(AGGR_5ABC).associateWith { 1 } +
setOf("5E", "5F", "5G", "5H", "5I").associateWith { 2 } +
setOf("5U", "5M").associateWith { 3 }
).map { it.key to it.value.toShort() }.toMap()
/**
* The [HidingInternalsCodeAggregator] has the purpose of
*
* * Providing aggregated codes by
* * Enriching codes with aggregated codes
* * Filtering out internal codes
*
* * providing the aggregated
* * codesPopulation values
* * codesStudyDesign values
*/
@Component
@Scope("prototype")
class HidingInternalsCodeAggregator : CodeAggregator {
private val _internalCodes: MutableList<String> = ArrayList()
private val _codes: MutableList<String> = ArrayList()
private val _codesPopulation: MutableList<Short> = ArrayList()
private val _codesStudyDesign: MutableList<Short> = ArrayList()
override fun setInternalCodes(internalCodes: List<String>) {
this._internalCodes.clear()
this._internalCodes.addAll(internalCodes)
}
override fun load(codes: Array<String>) {
clearAll()
this._codes.addAll(aggregateCodes(codes))
_codesPopulation.addAll(gatherCodesPopulation())
_codesStudyDesign.addAll(gatherCodesStudyDesign())
}
private fun clearAll() {
_codes.clear()
_codesPopulation.clear()
_codesStudyDesign.clear()
}
private fun aggregateCodes(codeArray: Array<String>): List<String> =
filterAndEnrich(codeArray).sorted()
private fun filterAndEnrich(codeArray: Array<String>): List<String> =
codeArray
.map { codeAggregation[it] ?: it }
.filterNot { it in _internalCodes }
.distinct()
private fun gatherCodesPopulation(): List<Short> =
_codes.mapNotNull { populationCodeMapper[it] }.distinct()
private fun gatherCodesStudyDesign(): List<Short> =
_codes.mapNotNull { studyDesignCodeMapper[it] }.distinct()
override val aggregatedCodes: Array<String>
get() = _codes.toTypedArray()
override val codesPopulation: Array<Short>
get() = _codesPopulation.toTypedArray()
override val codesStudyDesign: Array<Short>
get() = _codesStudyDesign.toTypedArray()
}
| gpl-3.0 | e6f35459ba9b23d7d69f3e84e5a78a56 | 32.823529 | 110 | 0.67687 | 4.089616 | false | false | false | false |
neo4j-graphql/neo4j-graphql | src/main/kotlin/org/neo4j/graphql/GraphQLResource.kt | 1 | 4701 | package org.neo4j.graphql
import graphql.ExecutionInput
import graphql.schema.idl.SchemaPrinter
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.logging.Log
import org.neo4j.logging.LogProvider
import java.io.PrintWriter
import java.io.StringWriter
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.HttpHeaders
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
/**
* @author mh
* @since 30.10.16
*/
@Path("")
class GraphQLResource(@Context val provider: LogProvider, @Context val db: GraphDatabaseService) {
val log: Log
init {
log = provider.getLog(GraphQLResourceExperimental::class.java)
}
companion object {
val OBJECT_MAPPER = com.fasterxml.jackson.databind.ObjectMapper()
}
@Path("")
@OPTIONS
fun options(@Context headers: HttpHeaders) = Response.ok().build()
@Path("")
@GET
fun get(@QueryParam("query") query: String?, @QueryParam("variables") variableParam: String?): Response {
if (query == null) return Response.noContent().build()
return executeQuery(hashMapOf("query" to query, "variables" to (variableParam ?: emptyMap<String,Any>())))
}
@Path("")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
fun executeOperation(body: String): Response {
return executeQuery(parseMap(body))
}
@Path("/idl")
@POST
fun storeIdl(schema: String): Response {
try {
val text = if (schema.trim().startsWith('{')) {
parseMap(schema).get("query")?.toString() ?: throw IllegalArgumentException("Can't read schema as JSON despite starting with '{'")
} else {
if (schema.trim().let { it.startsWith('"') && it.endsWith('"') }) schema.trim('"', ' ', '\t', '\n') else schema
}
val metaDatas = GraphSchemaScanner.storeIdl(db, text)
return Response.ok().entity(OBJECT_MAPPER.writeValueAsString(metaDatas)).build()
} catch(e: Exception) {
return Response.serverError().entity(OBJECT_MAPPER.writeValueAsString(mapOf("error" to e.message,"trace" to e.stackTraceAsString()))).build()
}
}
@Path("/idl")
@DELETE
fun deleteIdl(): Response {
GraphSchemaScanner.deleteIdl(db)
return Response.ok().build() // todo JSON
}
@Path("/idl")
@GET
fun getIdl(): Response {
val schema = GraphQLSchemaBuilder.buildSchema(db!!)
val printed = SchemaPrinter().print(schema)
return Response.ok().entity(printed).build() // todo JSON
}
private fun executeQuery(params: Map<String, Any>): Response {
val query = params["query"] as String
val variables = getVariables(params)
if (log.isDebugEnabled()) log.debug("Executing {} with {}", query, variables)
val tx = db.beginTx()
try {
val ctx = GraphQLContext(db, log, variables)
val graphQL = GraphSchema.getGraphQL(db)
val execution = ExecutionInput.Builder()
.query(query).variables(variables).context(ctx).root(ctx) // todo proper mutation root
params.get("operationName")?.let { execution.operationName(it.toString()) }
val executionResult = graphQL.execute(execution.build())
val result = linkedMapOf("data" to executionResult.getData<Any>())
if (ctx.backLog.isNotEmpty()) {
result["extensions"]=ctx.backLog
}
if (executionResult.errors.isNotEmpty()) {
log.warn("Errors: {}", executionResult.errors)
result.put("errors", executionResult.errors)
tx.failure()
} else {
tx.success()
}
return Response.ok().entity(formatMap(result)).build()
} finally {
tx.close()
}
}
@Suppress("UNCHECKED_CAST")
private fun getVariables(requestBody: Map<String, Any?>): Map<String, Any> {
val varParam = requestBody["variables"]
return when (varParam) {
is String -> parseMap(varParam)
is Map<*, *> -> varParam as Map<String, Any>
else -> emptyMap()
}
}
private fun formatMap(result: Map<String, Any>) = OBJECT_MAPPER.writeValueAsString(result)
@Suppress("UNCHECKED_CAST")
private fun parseMap(value: String?): Map<String, Any> =
if (value == null || value.isNullOrBlank()|| value == "null") emptyMap()
else {
val v = value.trim('"',' ','\t','\n','\r')
OBJECT_MAPPER.readValue(v, Map::class.java) as Map<String, Any>
}
}
| apache-2.0 | 10ba624618676875f5a38fd0326afd02 | 34.885496 | 153 | 0.610508 | 4.293151 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/GoToParentOrChildAction.kt | 1 | 3351 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.data.LoadingDetails
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import java.awt.event.KeyEvent
open class GoToParentOrChildAction(val parent: Boolean) : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val ui = e.getData(VcsLogInternalDataKeys.LOG_UI_EX)
if (ui == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
if (e.inputEvent is KeyEvent) {
e.presentation.isEnabled = ui.table.isFocusOwner
}
else {
e.presentation.isEnabled = getRowsToJump(ui).isNotEmpty()
}
}
override fun actionPerformed(e: AnActionEvent) {
triggerUsage(e)
val ui = e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_EX)
val rows = getRowsToJump(ui)
if (rows.isEmpty()) {
// can happen if the action was invoked by shortcut
return
}
if (rows.size == 1) {
ui.jumpToRow(rows.single(), false)
}
else {
val popup = JBPopupFactory.getInstance().createActionGroupPopup("Select ${if (parent) "Parent" else "Child"} to Navigate",
createGroup(ui, rows), e.dataContext,
JBPopupFactory.ActionSelectionAid.NUMBERING, false)
popup.showInBestPositionFor(e.dataContext)
}
}
private fun createGroup(ui: VcsLogUiEx, rows: List<Int>): ActionGroup {
val actions = rows.mapTo(mutableListOf()) { row ->
val text = getActionText(ui.table.model.getCommitMetadata(row))
object : DumbAwareAction(text, "Navigate to $text", null) {
override fun actionPerformed(e: AnActionEvent) {
triggerUsage(e)
ui.jumpToRow(row, false)
}
}
}
return DefaultActionGroup(actions)
}
private fun DumbAwareAction.triggerUsage(e: AnActionEvent) {
VcsLogUsageTriggerCollector.triggerUsage(e, this) { data -> data.addData("parent_commit", parent) }
}
private fun getActionText(commitMetadata: VcsCommitMetadata): String {
var text = commitMetadata.id.toShortString()
if (commitMetadata !is LoadingDetails) {
text += " " + CommitPresentationUtil.getShortSummary(commitMetadata, false, 40)
}
return text
}
private fun getRowsToJump(ui: VcsLogUiEx): List<Int> {
val selectedRows = ui.table.selectedRows
if (selectedRows.size != 1) return emptyList()
return ui.dataPack.visibleGraph.getRowInfo(selectedRows.single()).getAdjacentRows(parent).sorted()
}
}
class GoToParentRowAction : GoToParentOrChildAction(true)
class GoToChildRowAction : GoToParentOrChildAction(false) | apache-2.0 | b887274538baac40e75cc21a08d6d145 | 35.835165 | 140 | 0.702477 | 4.444297 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/libraries/libraries/LegacyBridgeLibraryImpl.kt | 1 | 8486 | package com.intellij.workspace.legacyBridge.libraries.libraries
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.RootProvider.RootSetChangedListener
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.TraceableDisposable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.workspace.api.*
import com.intellij.workspace.ide.WorkspaceModel
import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeFilePointerProviderImpl
import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModuleLibraryTable
import com.intellij.workspace.legacyBridge.typedModel.library.LibraryViaTypedEntity
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
interface LegacyBridgeLibrary : LibraryEx {
val libraryId: LibraryId
@ApiStatus.Internal
fun getModifiableModel(builder: TypedEntityStorageBuilder): LibraryEx.ModifiableModelEx
}
@ApiStatus.Internal
internal class LegacyBridgeLibraryImpl(
private val libraryTable: LibraryTable,
val project: Project,
initialId: LibraryId,
initialEntityStore: TypedEntityStore,
parent: Disposable
) : LegacyBridgeLibrary, RootProvider, TraceableDisposable(true) {
companion object {
private const val UNNAMED_LIBRARY_NAME_PREFIX = "#"
private const val UNIQUE_INDEX_LIBRARY_NAME_SUFFIX = "-d1a6f608-UNIQUE-INDEX-f29c-4df6-"
fun getLegacyLibraryName(libraryId: LibraryId): String? {
if (libraryId.name.startsWith(UNNAMED_LIBRARY_NAME_PREFIX)) return null
if (libraryId.name.contains(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX)) return libraryId.name.substringBefore(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX)
return libraryId.name
}
fun generateLibraryEntityName(legacyLibraryName: String?, exists: (String) -> Boolean): String {
if (legacyLibraryName == null) {
// TODO Make it O(1) if required
var index = 1
while (true) {
val candidate = "$UNNAMED_LIBRARY_NAME_PREFIX$index"
if (!exists(candidate)) {
return candidate
}
index++
}
@Suppress("UNREACHABLE_CODE")
error("Unable to suggest unique name for unnamed module library")
}
if (!exists(legacyLibraryName)) return legacyLibraryName
var index = 1
while (true) {
val candidate = "$legacyLibraryName${UNIQUE_INDEX_LIBRARY_NAME_SUFFIX}$index"
if (!exists(candidate)) {
return candidate
}
index++
}
}
}
override fun getModule(): Module? = (libraryTable as? LegacyBridgeModuleLibraryTable)?.module
init {
Disposer.register(parent, this)
}
val filePointerProvider = LegacyBridgeFilePointerProviderImpl().also { Disposer.register(this, it) }
var entityStore: TypedEntityStore = initialEntityStore
internal set(value) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
field = value
}
var entityId: LibraryId = initialId
internal set(value) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
field = value
}
private var disposed = false
// null to update project model via ProjectModelUpdater
var modifiableModelFactory: ((LibraryViaTypedEntity, TypedEntityStorageBuilder) -> LegacyBridgeLibraryModifiableModelImpl)? = null
private val dispatcher = EventDispatcher.create(RootSetChangedListener::class.java)
private val libraryEntityValue = CachedValueWithParameter { storage, id: LibraryId ->
storage.resolve(id)
}
internal val libraryEntity
get() = entityStore.cachedValue(libraryEntityValue, entityId)
internal val snapshotValue = CachedValueWithParameter { storage, id: LibraryId ->
LibraryViaTypedEntity(
libraryImpl = this,
libraryEntity = storage.resolve(id) ?: object : LibraryEntity {
override val entitySource: EntitySource
get() = throw NotImplementedError()
override fun hasEqualProperties(e: TypedEntity): Boolean {
return e is LibraryEntity && e.name == name && e.roots.isEmpty() && e.excludedRoots.isEmpty()
}
override val tableId: LibraryTableId
get() = throw NotImplementedError()
override val name: String
get() = id.name
override val roots: List<LibraryRoot>
get() = emptyList()
override val excludedRoots: List<VirtualFileUrl>
get() = emptyList()
override fun <R : TypedEntity> referrers(entityClass: Class<R>, propertyName: String) = emptySequence<R>()
},
storage = storage,
libraryTable = libraryTable,
filePointerProvider = filePointerProvider,
modifiableModelFactory = modifiableModelFactory ?: { librarySnapshot, diff ->
LegacyBridgeLibraryModifiableModelImpl(
originalLibrary = this,
originalLibrarySnapshot = librarySnapshot,
diff = diff,
committer = { _, diffBuilder ->
WorkspaceModel.getInstance(project).updateProjectModel {
it.addDiff(diffBuilder)
}
})
}
)
}
private val snapshot: LibraryViaTypedEntity
get() {
checkDisposed()
return entityStore.cachedValue(snapshotValue, entityId)
}
override val libraryId: LibraryId
get() = entityId
override fun getTable(): LibraryTable? = if (libraryTable is LegacyBridgeModuleLibraryTable) null else libraryTable
override fun getRootProvider(): RootProvider = this
override fun getModifiableModel(): LibraryEx.ModifiableModelEx = snapshot.modifiableModel
override fun getModifiableModel(builder: TypedEntityStorageBuilder): LibraryEx.ModifiableModelEx = snapshot.getModifiableModel(builder)
override fun getSource(): Library? = null
override fun getExternalSource(): ProjectModelExternalSource? = snapshot.externalSource
override fun getInvalidRootUrls(type: OrderRootType): List<String> = snapshot.getInvalidRootUrls(type)
override fun getKind(): PersistentLibraryKind<*>? = snapshot.kind
override fun getName(): String? = getLegacyLibraryName(entityId)
override fun getUrls(rootType: OrderRootType): Array<String> = snapshot.getUrls(rootType)
override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = snapshot.getFiles(rootType)
override fun getProperties(): LibraryProperties<*>? = snapshot.properties
override fun getExcludedRoots(): Array<VirtualFile> = snapshot.excludedRoots
override fun getExcludedRootUrls(): Array<String> = snapshot.excludedRootUrls
override fun isJarDirectory(url: String): Boolean = snapshot.isJarDirectory(url)
override fun isJarDirectory(url: String, rootType: OrderRootType): Boolean = snapshot.isJarDirectory(url, rootType)
override fun isValid(url: String, rootType: OrderRootType): Boolean = snapshot.isValid(url, rootType)
override fun readExternal(element: Element?) = throw NotImplementedError()
override fun writeExternal(element: Element) = snapshot.writeExternal(element)
override fun addRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.addListener(listener)
override fun addRootSetChangedListener(listener: RootSetChangedListener, parentDisposable: Disposable) {
dispatcher.addListener(listener, parentDisposable)
}
override fun removeRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.removeListener(listener)
override fun isDisposed(): Boolean = disposed
override fun dispose() {
checkDisposed()
disposed = true
kill(null)
}
private fun checkDisposed() {
if (isDisposed) {
throwDisposalError("library $entityId already disposed: $stackTrace")
}
}
override fun equals(other: Any?): Boolean {
val otherLib = other as? LegacyBridgeLibraryImpl ?: return false
return libraryEntity == otherLib.libraryEntity
}
override fun hashCode(): Int = libraryEntity.hashCode()
}
| apache-2.0 | 69523d7e95b4f5e9b8848178eda8a8a9 | 38.469767 | 140 | 0.746524 | 5.209331 | false | false | false | false |
bitsydarel/DBWeather | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/WeatherLocalConverters.kt | 1 | 2509 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.proxies.local
import android.arch.persistence.room.TypeConverter
import android.support.annotation.RestrictTo
import com.dbeginc.dbweatherdata.proxies.local.weather.LocalAlert
import com.dbeginc.dbweatherdata.proxies.local.weather.LocalDailyData
import com.dbeginc.dbweatherdata.proxies.local.weather.LocalHourlyData
import com.dbeginc.dbweatherdata.proxies.local.weather.LocalMinutelyData
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Created by darel on 16.09.17.
*
* Local Converters
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
class WeatherLocalConverters {
@TypeConverter
fun jsonStringToMinutelyData(json: String): List<LocalMinutelyData>? {
return if (json.isNotEmpty()) Gson().fromJson(json, object : TypeToken<List<LocalMinutelyData>>() {}.type)
else null
}
@TypeConverter
fun minutelyDataToJson(list: List<LocalMinutelyData>?): String = if (list != null) Gson().toJson(list) else ""
@TypeConverter
fun jsonStringToHourlyData(json: String): List<LocalHourlyData> =
Gson().fromJson(json, object : TypeToken<List<LocalHourlyData>>() {}.type)
@TypeConverter
fun hourlyDataToJson(list: List<LocalHourlyData>): String = Gson().toJson(list)
@TypeConverter
fun jsonStringToDailyData(json: String): List<LocalDailyData> =
Gson().fromJson(json, object : TypeToken<List<LocalDailyData>>() {}.type)
@TypeConverter
fun dailyDataToJson(dailyData: List<LocalDailyData>): String = Gson().toJson(dailyData)
@TypeConverter
fun jsonStringToAlerts(json: String): List<LocalAlert>? {
return if (json.isNotEmpty()) Gson().fromJson(json, object : TypeToken<List<LocalAlert>>() {}.type)
else null
}
@TypeConverter
fun alertsToJson(alerts: List<LocalAlert>?): String = if (alerts != null) Gson().toJson(alerts) else ""
} | gpl-3.0 | 8b9a2ae3b785c71457a86812131093ae | 37.030303 | 114 | 0.732961 | 4.223906 | false | false | false | false |
AndroidX/androidx | lint-checks/src/main/java/androidx/build/lint/NullabilityAnnotationsDetector.kt | 3 | 3806 | /*
* 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.build.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.isJava
import org.jetbrains.uast.UAnnotation
/**
* Checks for usages of JetBrains nullability annotations in Java code.
*/
class NullabilityAnnotationsDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes() = listOf(UAnnotation::class.java)
override fun createUastHandler(context: JavaContext): UElementHandler {
return AnnotationChecker(context)
}
private inner class AnnotationChecker(val context: JavaContext) : UElementHandler() {
override fun visitAnnotation(node: UAnnotation) {
if (isJava(node.sourcePsi)) {
checkForAnnotation(node, "NotNull", "NonNull")
checkForAnnotation(node, "Nullable", "Nullable")
}
}
/**
* Check if the node is org.jetbrains.annotations.$jetBrainsAnnotation, replace with
* androidx.annotation.$androidxAnnotation if so.
*/
private fun checkForAnnotation(
node: UAnnotation,
jetBrainsAnnotation: String,
androidxAnnotation: String
) {
val incorrectAnnotation = "org.jetbrains.annotations.$jetBrainsAnnotation"
val replacementAnnotation = "androidx.annotation.$androidxAnnotation"
val patternToReplace = "(?:org\\.jetbrains\\.annotations\\.)?$jetBrainsAnnotation"
if (node.qualifiedName == incorrectAnnotation) {
val lintFix = fix().name("Replace with `@$replacementAnnotation`")
.replace()
.pattern(patternToReplace)
.with(replacementAnnotation)
.shortenNames()
.autoFix(true, true)
.build()
val incident = Incident(context)
.issue(ISSUE)
.fix(lintFix)
.location(context.getNameLocation(node))
.message("Use `@$replacementAnnotation` instead of `@$incorrectAnnotation`")
.scope(node)
context.report(incident)
}
}
}
companion object {
val ISSUE = Issue.create(
"NullabilityAnnotationsDetector",
"Replace usages of JetBrains nullability annotations with androidx " +
"versions in Java code",
"The androidx nullability annotations should be used in androidx libraries " +
"instead of JetBrains annotations.",
Category.CORRECTNESS, 5, Severity.ERROR,
Implementation(NullabilityAnnotationsDetector::class.java, Scope.JAVA_FILE_SCOPE)
)
}
}
| apache-2.0 | fcdcfae82fb743942367bbc24d6aa117 | 40.369565 | 96 | 0.65712 | 4.936446 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/VideoBadges.kt | 1 | 548 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Video badges data.
*
* @param hdr Whether the video has an HDR-compatible transcode.
* @param live Live data.
* @param weekendChallenge Whether the video is a Vimeo Weekend Challenge.
*/
@JsonClass(generateAdapter = true)
data class VideoBadges(
@Json(name = "hdr")
val hdr: Boolean? = null,
@Json(name = "live")
val live: Live? = null,
@Json(name = "weekendChallenge")
val weekendChallenge: Boolean? = null
)
| mit | d4b919d46d15814379ce011c0dedab22 | 21.833333 | 74 | 0.69708 | 3.581699 | false | false | false | false |
android/compose-samples | Reply/app/src/main/java/com/example/reply/ui/ReplyApp.kt | 1 | 12291 | /*
* 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.example.reply.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.PermanentNavigationDrawer
import androidx.compose.material3.rememberDrawerState
import androidx.compose.material3.windowsizeclass.WindowHeightSizeClass
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.window.layout.DisplayFeature
import androidx.window.layout.FoldingFeature
import com.example.reply.ui.navigation.ModalNavigationDrawerContent
import com.example.reply.ui.navigation.PermanentNavigationDrawerContent
import com.example.reply.ui.navigation.ReplyBottomNavigationBar
import com.example.reply.ui.navigation.ReplyNavigationActions
import com.example.reply.ui.navigation.ReplyNavigationRail
import com.example.reply.ui.navigation.ReplyRoute
import com.example.reply.ui.navigation.ReplyTopLevelDestination
import com.example.reply.ui.utils.DevicePosture
import com.example.reply.ui.utils.ReplyContentType
import com.example.reply.ui.utils.ReplyNavigationContentPosition
import com.example.reply.ui.utils.ReplyNavigationType
import com.example.reply.ui.utils.isBookPosture
import com.example.reply.ui.utils.isSeparating
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReplyApp(
windowSize: WindowSizeClass,
displayFeatures: List<DisplayFeature>,
replyHomeUIState: ReplyHomeUIState,
closeDetailScreen: () -> Unit = {},
navigateToDetail: (Long, ReplyContentType) -> Unit = { _, _ -> }
) {
/**
* This will help us select type of navigation and content type depending on window size and
* fold state of the device.
*/
val navigationType: ReplyNavigationType
val contentType: ReplyContentType
/**
* We are using display's folding features to map the device postures a fold is in.
* In the state of folding device If it's half fold in BookPosture we want to avoid content
* at the crease/hinge
*/
val foldingFeature = displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull()
val foldingDevicePosture = when {
isBookPosture(foldingFeature) ->
DevicePosture.BookPosture(foldingFeature.bounds)
isSeparating(foldingFeature) ->
DevicePosture.Separating(foldingFeature.bounds, foldingFeature.orientation)
else -> DevicePosture.NormalPosture
}
when (windowSize.widthSizeClass) {
WindowWidthSizeClass.Compact -> {
navigationType = ReplyNavigationType.BOTTOM_NAVIGATION
contentType = ReplyContentType.SINGLE_PANE
}
WindowWidthSizeClass.Medium -> {
navigationType = ReplyNavigationType.NAVIGATION_RAIL
contentType = if (foldingDevicePosture != DevicePosture.NormalPosture) {
ReplyContentType.DUAL_PANE
} else {
ReplyContentType.SINGLE_PANE
}
}
WindowWidthSizeClass.Expanded -> {
navigationType = if (foldingDevicePosture is DevicePosture.BookPosture) {
ReplyNavigationType.NAVIGATION_RAIL
} else {
ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER
}
contentType = ReplyContentType.DUAL_PANE
}
else -> {
navigationType = ReplyNavigationType.BOTTOM_NAVIGATION
contentType = ReplyContentType.SINGLE_PANE
}
}
/**
* Content inside Navigation Rail/Drawer can also be positioned at top, bottom or center for
* ergonomics and reachability depending upon the height of the device.
*/
val navigationContentPosition = when (windowSize.heightSizeClass) {
WindowHeightSizeClass.Compact -> {
ReplyNavigationContentPosition.TOP
}
WindowHeightSizeClass.Medium,
WindowHeightSizeClass.Expanded -> {
ReplyNavigationContentPosition.CENTER
}
else -> {
ReplyNavigationContentPosition.TOP
}
}
ReplyNavigationWrapper(
navigationType = navigationType,
contentType = contentType,
displayFeatures = displayFeatures,
navigationContentPosition = navigationContentPosition,
replyHomeUIState = replyHomeUIState,
closeDetailScreen = closeDetailScreen,
navigateToDetail = navigateToDetail
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ReplyNavigationWrapper(
navigationType: ReplyNavigationType,
contentType: ReplyContentType,
displayFeatures: List<DisplayFeature>,
navigationContentPosition: ReplyNavigationContentPosition,
replyHomeUIState: ReplyHomeUIState,
closeDetailScreen: () -> Unit,
navigateToDetail: (Long, ReplyContentType) -> Unit
) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
val navController = rememberNavController()
val navigationActions = remember(navController) {
ReplyNavigationActions(navController)
}
val navBackStackEntry by navController.currentBackStackEntryAsState()
val selectedDestination =
navBackStackEntry?.destination?.route ?: ReplyRoute.INBOX
if (navigationType == ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER) {
// TODO check on custom width of PermanentNavigationDrawer: b/232495216
PermanentNavigationDrawer(drawerContent = {
PermanentNavigationDrawerContent(
selectedDestination = selectedDestination,
navigationContentPosition = navigationContentPosition,
navigateToTopLevelDestination = navigationActions::navigateTo,
)
}) {
ReplyAppContent(
navigationType = navigationType,
contentType = contentType,
displayFeatures = displayFeatures,
navigationContentPosition = navigationContentPosition,
replyHomeUIState = replyHomeUIState,
navController = navController,
selectedDestination = selectedDestination,
navigateToTopLevelDestination = navigationActions::navigateTo,
closeDetailScreen = closeDetailScreen,
navigateToDetail = navigateToDetail
)
}
} else {
ModalNavigationDrawer(
drawerContent = {
ModalNavigationDrawerContent(
selectedDestination = selectedDestination,
navigationContentPosition = navigationContentPosition,
navigateToTopLevelDestination = navigationActions::navigateTo,
onDrawerClicked = {
scope.launch {
drawerState.close()
}
}
)
},
drawerState = drawerState
) {
ReplyAppContent(
navigationType = navigationType,
contentType = contentType,
displayFeatures = displayFeatures,
navigationContentPosition = navigationContentPosition,
replyHomeUIState = replyHomeUIState,
navController = navController,
selectedDestination = selectedDestination,
navigateToTopLevelDestination = navigationActions::navigateTo,
closeDetailScreen = closeDetailScreen,
navigateToDetail = navigateToDetail
) {
scope.launch {
drawerState.open()
}
}
}
}
}
@Composable
fun ReplyAppContent(
modifier: Modifier = Modifier,
navigationType: ReplyNavigationType,
contentType: ReplyContentType,
displayFeatures: List<DisplayFeature>,
navigationContentPosition: ReplyNavigationContentPosition,
replyHomeUIState: ReplyHomeUIState,
navController: NavHostController,
selectedDestination: String,
navigateToTopLevelDestination: (ReplyTopLevelDestination) -> Unit,
closeDetailScreen: () -> Unit,
navigateToDetail: (Long, ReplyContentType) -> Unit,
onDrawerClicked: () -> Unit = {}
) {
Row(modifier = modifier.fillMaxSize()) {
AnimatedVisibility(visible = navigationType == ReplyNavigationType.NAVIGATION_RAIL) {
ReplyNavigationRail(
selectedDestination = selectedDestination,
navigationContentPosition = navigationContentPosition,
navigateToTopLevelDestination = navigateToTopLevelDestination,
onDrawerClicked = onDrawerClicked,
)
}
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.inverseOnSurface)
) {
ReplyNavHost(
navController = navController,
contentType = contentType,
displayFeatures = displayFeatures,
replyHomeUIState = replyHomeUIState,
navigationType = navigationType,
closeDetailScreen = closeDetailScreen,
navigateToDetail = navigateToDetail,
modifier = Modifier.weight(1f),
)
AnimatedVisibility(visible = navigationType == ReplyNavigationType.BOTTOM_NAVIGATION) {
ReplyBottomNavigationBar(
selectedDestination = selectedDestination,
navigateToTopLevelDestination = navigateToTopLevelDestination
)
}
}
}
}
@Composable
private fun ReplyNavHost(
navController: NavHostController,
contentType: ReplyContentType,
displayFeatures: List<DisplayFeature>,
replyHomeUIState: ReplyHomeUIState,
navigationType: ReplyNavigationType,
closeDetailScreen: () -> Unit,
navigateToDetail: (Long, ReplyContentType) -> Unit,
modifier: Modifier = Modifier,
) {
NavHost(
modifier = modifier,
navController = navController,
startDestination = ReplyRoute.INBOX,
) {
composable(ReplyRoute.INBOX) {
ReplyInboxScreen(
contentType = contentType,
replyHomeUIState = replyHomeUIState,
navigationType = navigationType,
displayFeatures = displayFeatures,
closeDetailScreen = closeDetailScreen,
navigateToDetail = navigateToDetail,
)
}
composable(ReplyRoute.DM) {
EmptyComingSoon()
}
composable(ReplyRoute.ARTICLES) {
EmptyComingSoon()
}
composable(ReplyRoute.GROUPS) {
EmptyComingSoon()
}
}
}
| apache-2.0 | dcea82667e00aad107ac3029d577c456 | 38.268371 | 99 | 0.682206 | 6.242255 | false | false | false | false |
smmribeiro/intellij-community | platform/testFramework/src/com/intellij/project/IntelliJProjectConfiguration.kt | 2 | 4574 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.project
import com.intellij.application.options.PathMacrosImpl
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryDescription
import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryService
import org.jetbrains.jps.model.library.JpsLibraryCollection
import org.jetbrains.jps.model.library.JpsOrderRootType
import org.jetbrains.jps.model.serialization.JpsSerializationManager
import org.jetbrains.jps.util.JpsPathUtil
import org.junit.Assert
import java.io.File
/**
* Provides access to IntelliJ project configuration so the tests from IntelliJ project sources may locate project and module libraries without
* hardcoding paths to their JARs.
*/
class IntelliJProjectConfiguration {
private val projectHome = PathManager.getHomePath()
private val projectLibraries: Map<String, LibraryRoots>
private val moduleLibraries: Map<String, Map<String, LibraryRoots>>
private val remoteRepositoryDescriptions : List<JpsRemoteRepositoryDescription>
init {
val project = loadIntelliJProject(projectHome)
fun extractLibrariesRoots(collection: JpsLibraryCollection) = collection.libraries.associateBy({ it.name }, {
LibraryRoots(SmartList(it.getFiles(JpsOrderRootType.COMPILED)), SmartList(it.getFiles(JpsOrderRootType.SOURCES)))
})
projectLibraries = extractLibrariesRoots(project.libraryCollection)
moduleLibraries = project.modules.associateBy({it.name}, {
val libraries = extractLibrariesRoots(it.libraryCollection)
if (libraries.isNotEmpty()) libraries else emptyMap()
})
remoteRepositoryDescriptions = JpsRemoteRepositoryService.getInstance().getRemoteRepositoriesConfiguration(project)!!.repositories
}
companion object {
private val instance by lazy { IntelliJProjectConfiguration() }
@JvmStatic
fun getRemoteRepositoryDescriptions() : List<JpsRemoteRepositoryDescription> {
return instance.remoteRepositoryDescriptions
}
@JvmStatic
fun getProjectLibraryClassesRootPaths(libraryName: String): List<String> {
return getProjectLibrary(libraryName).classesPaths
}
@JvmStatic
fun getProjectLibraryClassesRootUrls(libraryName: String): List<String> {
return getProjectLibrary(libraryName).classesUrls
}
@JvmStatic
fun getProjectLibrary(libraryName: String): LibraryRoots {
return instance.projectLibraries[libraryName]
?: throw IllegalArgumentException("Cannot find project library '$libraryName' in ${instance.projectHome}")
}
@JvmStatic
fun getModuleLibrary(moduleName: String, libraryName: String): LibraryRoots {
val moduleLibraries = instance.moduleLibraries[moduleName]
?: throw IllegalArgumentException("Cannot find module '$moduleName' in ${instance.projectHome}")
return moduleLibraries[libraryName]
?: throw IllegalArgumentException("Cannot find module library '$libraryName' in $moduleName")
}
@JvmStatic
fun getJarFromSingleJarProjectLibrary(projectLibraryName: String): VirtualFile {
val jarUrl = UsefulTestCase.assertOneElement(getProjectLibraryClassesRootUrls(projectLibraryName))
val jarRoot = VirtualFileManager.getInstance().refreshAndFindFileByUrl(jarUrl)
Assert.assertNotNull(jarRoot)
return jarRoot!!
}
@JvmStatic
fun loadIntelliJProject(projectHome: String): JpsProject {
val m2Repo = FileUtil.toSystemIndependentName(File(SystemProperties.getUserHome(), ".m2/repository").absolutePath)
return JpsSerializationManager.getInstance().loadProject(projectHome, mapOf(PathMacrosImpl.MAVEN_REPOSITORY to m2Repo), true)
}
}
class LibraryRoots(val classes: List<File>, val sources: List<File>) {
val classesPaths: List<String>
get() = classes.map { FileUtil.toSystemIndependentName(it.absolutePath) }
val classesUrls: List<String>
get() = classes.map { JpsPathUtil.getLibraryRootUrl(it) }
val sourcesUrls: List<String>
get() = sources.map { JpsPathUtil.getLibraryRootUrl(it) }
}
}
| apache-2.0 | 74f583521007e959b8335239292f22ec | 42.980769 | 158 | 0.775251 | 5.116331 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/remote/DeferredRemoteProcess.kt | 11 | 5070 | // 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.remote
import com.google.common.net.HostAndPort
import com.intellij.openapi.diagnostic.logger
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.isPending
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.system.measureNanoTime
/**
* Asynchronous adapter for synchronous process callers. Intended for usage in cases when blocking calls like [ProcessBuilder.start]
* are called in EDT and it's uneasy to refactor. **Anyway, better to not call blocking methods in EDT rather than use this class.**
*
* **Beware!** Note that [DeferredRemoteProcess] is created even if underlying one fails to. Take care to make sure that such cases really
* look to users like underlying process not started, not like it started and died silently (see IDEA-265188). It would help a lot with
* future troubleshooting, reporting and investigation.
*/
class DeferredRemoteProcess(private val promise: Promise<RemoteProcess>) : RemoteProcess() {
override fun getOutputStream(): OutputStream =
DeferredOutputStream()
override fun getInputStream(): InputStream =
DeferredInputStream { it.inputStream }
override fun getErrorStream(): InputStream =
DeferredInputStream { it.errorStream }
override fun waitFor(): Int = get().waitFor()
override fun waitFor(timeout: Long, unit: TimeUnit): Boolean {
val process: RemoteProcess?
val nanosSpent = measureNanoTime {
process = promise.blockingGet(timeout.toInt(), unit)
}
val restTimeoutNanos = max(0, TimeUnit.NANOSECONDS.convert(timeout, unit) - nanosSpent)
return process?.waitFor(restTimeoutNanos, TimeUnit.NANOSECONDS) ?: false
}
override fun exitValue(): Int =
tryGet()?.exitValue()
?: throw IllegalStateException("Process is not terminated")
override fun destroy() {
runNowOrSchedule {
it.destroy()
}
}
override fun killProcessTree(): Boolean =
runNowOrSchedule {
it.killProcessTree()
}
?: false
override fun isDisconnected(): Boolean =
tryGet()?.isDisconnected
?: false
override fun getLocalTunnel(remotePort: Int): HostAndPort? =
get().getLocalTunnel(remotePort)
override fun destroyForcibly(): Process =
runNowOrSchedule {
it.destroyForcibly()
}
?: this
override fun supportsNormalTermination(): Boolean = true
override fun isAlive(): Boolean =
tryGet()?.isAlive
?: true
override fun onExit(): CompletableFuture<Process> =
CompletableFuture<Process>().also {
promise.then(it::complete)
}
private fun get(): RemoteProcess =
promise.blockingGet(Int.MAX_VALUE)!!
private fun tryGet(): RemoteProcess? =
promise.takeUnless { it.isPending }?.blockingGet(0)
private fun <T> runNowOrSchedule(handler: (RemoteProcess) -> T): T? {
val process = tryGet()
return if (process != null) {
handler(process)
}
else {
val cause = Throwable("Initially called from this context.")
promise.then {
try {
it?.let(handler)
}
catch (err: Throwable) {
err.addSuppressed(cause)
LOG.info("$this: Got an error that nothing could catch: ${err.message}", err)
}
}
null
}
}
private inner class DeferredOutputStream : OutputStream() {
override fun close() {
runNowOrSchedule {
it.outputStream.close()
}
}
override fun flush() {
tryGet()?.outputStream?.flush()
}
override fun write(b: Int) {
get().outputStream.write(b)
}
override fun write(b: ByteArray) {
get().outputStream.write(b)
}
override fun write(b: ByteArray, off: Int, len: Int) {
get().outputStream.write(b, off, len)
}
}
private inner class DeferredInputStream(private val streamGetter: (RemoteProcess) -> InputStream) : InputStream() {
override fun close() {
runNowOrSchedule {
streamGetter(it).close()
}
}
override fun read(): Int =
streamGetter(get()).read()
override fun read(b: ByteArray): Int =
streamGetter(get()).read(b)
override fun read(b: ByteArray, off: Int, len: Int): Int =
streamGetter(get()).read(b, off, len)
override fun readAllBytes(): ByteArray =
streamGetter(get()).readAllBytes()
override fun readNBytes(len: Int): ByteArray =
streamGetter(get()).readNBytes(len)
override fun readNBytes(b: ByteArray, off: Int, len: Int): Int =
streamGetter(get()).readNBytes(b, off, len)
override fun skip(n: Long): Long =
streamGetter(get()).skip(n)
override fun available(): Int =
tryGet()?.let(streamGetter)?.available() ?: 0
override fun markSupported(): Boolean = false
}
private companion object {
private val LOG = logger<DeferredRemoteProcess>()
}
} | apache-2.0 | c496d29ec8ee77cab3063f4f81dbd6e6 | 28.654971 | 140 | 0.681065 | 4.584087 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/FrequentlyAskedQuestionsViewHolderViewModel.kt | 1 | 2204 | package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.utils.DateTimeUtils
import com.kickstarter.models.ProjectFaq
import com.kickstarter.ui.viewholders.FrequentlyAskedQuestionsViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface FrequentlyAskedQuestionsViewHolderViewModel {
interface Inputs {
/** Configure the view model with the [ProjectFaq]. */
fun configureWith(projectFaq: ProjectFaq)
}
interface Outputs {
/** Emits the String for the question */
fun question(): Observable<String>
/** Emits the String for the answer */
fun answer(): Observable<String>
/** Emits the String for the updatedDate */
fun updatedDate(): Observable<String>
}
class ViewModel(@NonNull val environment: Environment) :
ActivityViewModel<FrequentlyAskedQuestionsViewHolder>(environment), Inputs, Outputs {
val inputs: Inputs = this
val outputs: Outputs = this
private val projectFaqInput = PublishSubject.create<ProjectFaq>()
private val question = BehaviorSubject.create<String>()
private val answer = BehaviorSubject.create<String>()
private val updatedDate = BehaviorSubject.create<String>()
init {
val projectFaqInput = this.projectFaqInput
projectFaqInput
.map { it.question }
.subscribe(this.question)
projectFaqInput
.map { it.answer }
.subscribe(this.answer)
projectFaqInput
.map { requireNotNull(it.createdAt) }
.map { DateTimeUtils.longDate(it) }
.subscribe(this.updatedDate)
}
override fun configureWith(projectFaq: ProjectFaq) = this.projectFaqInput.onNext(projectFaq)
override fun question(): Observable<String> = this.question
override fun answer(): Observable<String> = this.answer
override fun updatedDate(): Observable<String> = this.updatedDate
}
}
| apache-2.0 | 0f90631a0eab7a05b5335c53f78b89d9 | 33.984127 | 100 | 0.675136 | 5.310843 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/WrongMenuIdFormatDetectorTest.kt | 1 | 2904 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.tools.lint.checks.infrastructure.TestFiles.xml
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Test
class WrongMenuIdFormatDetectorTest {
@Test fun idLowerCamelCase() {
lint()
.files(
xml(
"res/menu/ids.xml",
"""
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/lowerCamelCase"/>
</menu>
""",
).indented(),
)
.issues(ISSUE_WRONG_MENU_ID_FORMAT)
.run()
.expectClean()
}
@Test fun idDefinedLowerCamelCase() {
lint()
.files(
xml(
"res/menu/ids.xml",
"""
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@id/lowerCamelCase"/>
</menu>
""",
).indented(),
)
.issues(ISSUE_WRONG_MENU_ID_FORMAT)
.run()
.expectClean()
}
@Test fun idCamelCase() {
lint()
.files(
xml(
"res/menu/ids.xml",
"""
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/CamelCase"/>
</menu>
""",
).indented(),
)
.issues(ISSUE_WRONG_MENU_ID_FORMAT)
.run()
.expect(
"""
|res/menu/ids.xml:2: Warning: Id is not in lowerCamelCaseFormat [WrongMenuIdFormat]
| <item android:id="@+id/CamelCase"/>
| ~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin(),
)
.expectFixDiffs(
"""
|Fix for res/menu/ids.xml line 1: Convert to lowerCamelCase:
|@@ -2 +2
|- <item android:id="@+id/CamelCase"/>
|+ <item android:id="@+id/camelCase"/>
""".trimMargin(),
)
}
@Test fun idSnakeCase() {
lint()
.files(
xml(
"res/menu/ids.xml",
"""
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/snake_case"/>
</menu>
""",
).indented(),
)
.issues(ISSUE_WRONG_MENU_ID_FORMAT)
.run()
.expect(
"""
|res/menu/ids.xml:2: Warning: Id is not in lowerCamelCaseFormat [WrongMenuIdFormat]
| <item android:id="@+id/snake_case"/>
| ~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin(),
)
.expectFixDiffs(
"""
|Fix for res/menu/ids.xml line 1: Convert to lowerCamelCase:
|@@ -2 +2
|- <item android:id="@+id/snake_case"/>
|+ <item android:id="@+id/snakeCase"/>
""".trimMargin(),
)
}
}
| apache-2.0 | 2ca2587614a43cf21658008bdd85a7f1 | 26.140187 | 93 | 0.495523 | 3.989011 | false | true | false | false |
mdaniel/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/config/wizard/BuildSystemGroovyNewProjectWizardData.kt | 8 | 1123 | // 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.plugins.groovy.config.wizard
import com.intellij.ide.wizard.BuildSystemNewProjectWizardData
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.roots.ui.distribution.DistributionInfo
import com.intellij.openapi.util.Key
interface BuildSystemGroovyNewProjectWizardData: BuildSystemNewProjectWizardData {
val groovySdkProperty : GraphProperty<DistributionInfo?>
var groovySdk : DistributionInfo?
companion object {
@JvmStatic val KEY = Key.create<BuildSystemGroovyNewProjectWizardData>(BuildSystemGroovyNewProjectWizardData::class.java.name)
@JvmStatic val NewProjectWizardStep.buildSystemData get() = data.getUserData(KEY)!!
@JvmStatic val NewProjectWizardStep.buildSystemProperty get() = buildSystemData.buildSystemProperty
@JvmStatic var NewProjectWizardStep.buildSystem get() = buildSystemData.buildSystem; set(it) { buildSystemData.buildSystem = it }
}
} | apache-2.0 | 505efee0be951792025de450fad21a82 | 45.833333 | 133 | 0.826358 | 5.127854 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluatorBuilder.kt | 1 | 30087 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.engine.evaluation.expression.*
import com.intellij.debugger.engine.jdi.StackFrameProxy
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbService
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.sun.jdi.*
import com.sun.jdi.Value
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.eval4j.*
import org.jetbrains.eval4j.jdi.JDIEval
import org.jetbrains.eval4j.jdi.asJdiValue
import org.jetbrains.eval4j.jdi.asValue
import org.jetbrains.eval4j.jdi.makeInitialFrame
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.util.caching.ConcurrentFactoryCache
import org.jetbrains.kotlin.idea.core.util.analyzeInlinedFunctions
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl
import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus.EvaluationContextLanguage
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.isEvaluationEntryPoint
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.*
import org.jetbrains.kotlin.idea.debugger.evaluate.compilingEvaluator.ClassLoadingResult
import org.jetbrains.kotlin.idea.debugger.evaluate.compilingEvaluator.loadClassesSafely
import org.jetbrains.kotlin.idea.debugger.evaluate.variables.EvaluatorValueConverter
import org.jetbrains.kotlin.idea.debugger.evaluate.variables.VariableFinder
import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation
import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod
import org.jetbrains.kotlin.idea.debugger.base.util.safeVisibleVariableByName
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.attachmentByPsiFile
import org.jetbrains.kotlin.idea.util.application.merge
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.AnalyzingUtils
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.tree.ClassNode
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import org.jetbrains.eval4j.Value as Eval4JValue
internal val LOG = Logger.getInstance(KotlinEvaluator::class.java)
object KotlinEvaluatorBuilder : EvaluatorBuilder {
override fun build(codeFragment: PsiElement, position: SourcePosition?): ExpressionEvaluator {
if (codeFragment !is KtCodeFragment) {
return EvaluatorBuilderImpl.getInstance().build(codeFragment, position)
}
val context = codeFragment.context
val file = context?.containingFile
if (file != null && file !is KtFile) {
reportError(codeFragment, position, "Unknown context${codeFragment.context?.javaClass}")
evaluationException(KotlinDebuggerEvaluationBundle.message("error.bad.context"))
}
return ExpressionEvaluatorImpl(KotlinEvaluator(codeFragment, position))
}
}
class KotlinEvaluator(val codeFragment: KtCodeFragment, private val sourcePosition: SourcePosition?) : Evaluator {
override fun evaluate(context: EvaluationContextImpl): Any? {
if (codeFragment.text.isEmpty()) {
return context.debugProcess.virtualMachineProxy.mirrorOfVoid()
}
val status = EvaluationStatus()
val evaluationType = codeFragment.getUserData(KotlinCodeFragmentFactory.EVALUATION_TYPE)
if (evaluationType != null) {
status.evaluationType(evaluationType)
}
val language = runReadAction {
when {
codeFragment.getCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) != null -> EvaluationContextLanguage.Java
codeFragment.context?.language == KotlinLanguage.INSTANCE -> EvaluationContextLanguage.Kotlin
else -> EvaluationContextLanguage.Other
}
}
status.contextLanguage(language)
try {
return evaluateWithStatus(context, status)
} finally {
status.send()
}
}
private fun evaluateWithStatus(context: EvaluationContextImpl, status: EvaluationStatus): Any? {
runReadAction {
if (DumbService.getInstance(codeFragment.project).isDumb) {
status.error(EvaluationError.DumbMode)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.dumb.mode"))
}
}
if (!context.debugProcess.isAttached) {
status.error(EvaluationError.DebuggerNotAttached)
throw EvaluateExceptionUtil.PROCESS_EXITED
}
val frameProxy = context.frameProxy ?: run {
status.error(EvaluationError.NoFrameProxy)
throw EvaluateExceptionUtil.NULL_STACK_FRAME
}
val operatingThread = context.suspendContext.thread ?: run {
status.error(EvaluationError.ThreadNotAvailable)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.thread.unavailable"))
}
if (!operatingThread.isSuspended) {
status.error(EvaluationError.ThreadNotSuspended)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.thread.not.suspended"))
}
try {
val executionContext = ExecutionContext(context, frameProxy)
return evaluateSafe(executionContext, status)
} catch (e: CodeFragmentCodegenException) {
status.error(EvaluationError.BackendException)
evaluationException(e.reason)
} catch (e: EvaluateException) {
val error = if (e.exceptionFromTargetVM != null) {
EvaluationError.ExceptionFromEvaluatedCode
} else {
EvaluationError.EvaluateException
}
status.error(error)
throw e
} catch (e: ProcessCanceledException) {
status.error(EvaluationError.ProcessCancelledException)
evaluationException(e)
} catch (e: Eval4JInterpretingException) {
status.error(EvaluationError.InterpretingException)
evaluationException(e.cause)
} catch (e: Exception) {
val isSpecialException = isSpecialException(e)
if (isSpecialException) {
status.error(EvaluationError.SpecialException)
evaluationException(e)
}
status.error(EvaluationError.GenericException)
reportError(codeFragment, sourcePosition, e.message ?: KotlinDebuggerEvaluationBundle.message("error.exception.occurred"), e)
val cause = if (e.message != null) ": ${e.message}" else ""
evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.evaluate") + cause)
}
}
private fun evaluateSafe(context: ExecutionContext, status: EvaluationStatus): Any? {
val compiledData = getCompiledCodeFragment(context, status)
val classLoadingResult = loadClassesSafely(context, compiledData.classes)
val classLoaderRef = (classLoadingResult as? ClassLoadingResult.Success)?.classLoader
if (classLoadingResult is ClassLoadingResult.Failure) {
status.classLoadingFailed()
}
val result = if (classLoaderRef != null) {
try {
status.usedEvaluator(EvaluationStatus.EvaluatorType.Bytecode)
return evaluateWithCompilation(context, compiledData, classLoaderRef, status)
} catch (e: Throwable) {
status.compilingEvaluatorFailed()
LOG.warn("Compiling evaluator failed: " + e.message, e)
status.usedEvaluator(EvaluationStatus.EvaluatorType.Eval4j)
evaluateWithEval4J(context, compiledData, classLoaderRef, status)
}
} else {
status.usedEvaluator(EvaluationStatus.EvaluatorType.Eval4j)
evaluateWithEval4J(context, compiledData, null, status)
}
return result.toJdiValue(context, status)
}
private fun getCompiledCodeFragment(context: ExecutionContext, status: EvaluationStatus): CompiledCodeFragmentData {
val contextElement = codeFragment.context ?: return compileCodeFragment(context, status)
val cache = runReadAction {
CachedValuesManager.getCachedValue(contextElement) {
val storage = ConcurrentHashMap<String, CompiledCodeFragmentData>()
CachedValueProvider.Result(ConcurrentFactoryCache(storage), PsiModificationTracker.MODIFICATION_COUNT)
}
}
val key = buildString {
appendLine(codeFragment.importsToString())
append(codeFragment.text)
}
return cache.get(key) {
compileCodeFragment(context, status)
}
}
private fun compileCodeFragment(context: ExecutionContext, status: EvaluationStatus): CompiledCodeFragmentData {
val debugProcess = context.debugProcess
var analysisResult = analyze(codeFragment, status, debugProcess)
val codeFragmentWasEdited = KotlinCodeFragmentEditor(codeFragment)
.withToStringWrapper(analysisResult.bindingContext)
.withSuspendFunctionWrapper(
analysisResult.bindingContext,
context,
isCoroutineScopeAvailable(context.frameProxy)
)
.editCodeFragment()
if (codeFragmentWasEdited) {
// Repeat analysis for edited code fragment
analysisResult = analyze(codeFragment, status, debugProcess)
}
analysisResult.illegalSuspendFunCallDiagnostic?.let {
reportErrorDiagnostic(it, status)
}
val (bindingContext, filesToCompile) = runReadAction {
val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment)
try {
val filesToCompile = if (!CodeFragmentCompiler.useIRFragmentCompiler()) {
analyzeInlinedFunctions(
resolutionFacade,
codeFragment,
analyzeOnlyReifiedInlineFunctions = false,
analysisResult.bindingContext
).second
} else {
// The IR Evaluator is sensitive to the analysis order of files in fragment compilation:
// The codeFragment must be passed _last_ to analysis such that the result is stacked at
// the _bottom_ of the composite analysis result.
//
// The situation as seen from here is as follows:
// 1) `analyzeWithAllCompilerChecks` analyze each individual file passed to it separately.
// 2) The individual results are "stacked" on top of each other.
// 3) With distinct files, "stacking on top" is equivalent to "side by side" - there is
// no overlap in what is analyzed, so the order doesn't matter: the composite analysis
// result is just a look-up mechanism for convenience.
// 4) Code Fragments perform partial analysis of the context of the fragment, e.g. a
// breakpoint in a function causes partial analysis of the surrounding function.
// 5) If the surrounding function is _also_ included in the `filesToCompile`, that
// function will be analyzed more than once: in particular, fresh symbols will be
// allocated anew upon repeated analysis.
// 6) Now the order of composition is significant: layering the fragment at the bottom
// ensures code that needs a consistent view of the entire function (i.e. psi2ir)
// does not mix the fresh, partial view of the function in the fragment analysis with
// the complete analysis from the separate analysis of the entire file included in the
// compilation.
//
fun <T> MutableList<T>.moveToLast(element: T) {
removeAll(listOf(element))
add(element)
}
gatherProjectFilesDependedOnByFragment(
codeFragment,
analysisResult.bindingContext
).toMutableList().apply {
moveToLast(codeFragment)
}
}
val analysis = resolutionFacade.analyzeWithAllCompilerChecks(filesToCompile)
Pair(analysis.bindingContext, filesToCompile)
} catch (e: IllegalArgumentException) {
status.error(EvaluationError.ErrorElementOccurred)
evaluationException(e.message ?: e.toString())
}
}
val moduleDescriptor = analysisResult.moduleDescriptor
val result = CodeFragmentCompiler(context, status).compile(codeFragment, filesToCompile, bindingContext, moduleDescriptor)
if (@Suppress("TestOnlyProblems") LOG_COMPILATIONS) {
LOG.debug("Compile bytecode for ${codeFragment.text}")
}
return createCompiledDataDescriptor(result)
}
private fun isCoroutineScopeAvailable(frameProxy: StackFrameProxy) =
if (frameProxy is CoroutineStackFrameProxyImpl)
frameProxy.isCoroutineScopeAvailable()
else
false
private data class ErrorCheckingResult(
val bindingContext: BindingContext,
val moduleDescriptor: ModuleDescriptor,
val files: List<KtFile>,
val illegalSuspendFunCallDiagnostic: Diagnostic?
)
private fun analyze(codeFragment: KtCodeFragment, status: EvaluationStatus, debugProcess: DebugProcessImpl): ErrorCheckingResult {
val result = ReadAction.nonBlocking<Result<ErrorCheckingResult>> {
try {
Result.success(doAnalyze(codeFragment, status, debugProcess))
} catch (ex: ProcessCanceledException) {
throw ex // Restart the action
} catch (ex: Exception) {
Result.failure(ex)
}
}.executeSynchronously()
return result.getOrThrow()
}
private fun doAnalyze(codeFragment: KtCodeFragment, status: EvaluationStatus, debugProcess: DebugProcessImpl): ErrorCheckingResult {
try {
AnalyzingUtils.checkForSyntacticErrors(codeFragment)
} catch (e: IllegalArgumentException) {
status.error(EvaluationError.ErrorElementOccurred)
evaluationException(e.message ?: e.toString())
}
val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment)
DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels()
val analysisResult = resolutionFacade.analyzeWithAllCompilerChecks(codeFragment)
if (analysisResult.isError()) {
status.error(EvaluationError.FrontendException)
evaluationException(analysisResult.error)
}
val bindingContext = analysisResult.bindingContext
reportErrorDiagnosticIfAny(status, bindingContext)
return ErrorCheckingResult(
bindingContext,
analysisResult.moduleDescriptor,
Collections.singletonList(codeFragment),
bindingContext.diagnostics.firstOrNull {
it.isIllegalSuspendFunCallInCodeFragment()
}
)
}
private fun reportErrorDiagnosticIfAny(status: EvaluationStatus, bindingContext: BindingContext) =
bindingContext.diagnostics
.filter { it.factory !in IGNORED_DIAGNOSTICS }
.firstOrNull { it.severity == Severity.ERROR && it.psiElement.containingFile == codeFragment }
?.let { reportErrorDiagnostic(it, status) }
private fun reportErrorDiagnostic(diagnostic: Diagnostic, status: EvaluationStatus) {
status.error(EvaluationError.ErrorsInCode)
evaluationException(DefaultErrorMessages.render(diagnostic))
}
private fun Diagnostic.isIllegalSuspendFunCallInCodeFragment() =
severity == Severity.ERROR && psiElement.containingFile == codeFragment &&
factory == Errors.ILLEGAL_SUSPEND_FUNCTION_CALL
private fun evaluateWithCompilation(
context: ExecutionContext,
compiledData: CompiledCodeFragmentData,
classLoader: ClassLoaderReference,
status: EvaluationStatus
): Value? {
return runEvaluation(context, compiledData, classLoader, status) { args ->
val mainClassType = context.findClass(GENERATED_CLASS_NAME, classLoader) as? ClassType
?: error("Can not find class \"$GENERATED_CLASS_NAME\"")
val mainMethod = mainClassType.methods().single { isEvaluationEntryPoint(it.name()) }
val returnValue = context.invokeMethod(mainClassType, mainMethod, args)
EvaluatorValueConverter.unref(returnValue)
}
}
private fun evaluateWithEval4J(
context: ExecutionContext,
compiledData: CompiledCodeFragmentData,
classLoader: ClassLoaderReference?,
status: EvaluationStatus
): InterpreterResult {
val mainClassBytecode = compiledData.mainClass.bytes
val mainClassAsmNode = ClassNode().apply { ClassReader(mainClassBytecode).accept(this, 0) }
val mainMethod = mainClassAsmNode.methods.first { it.isEvaluationEntryPoint }
return runEvaluation(context, compiledData, classLoader ?: context.evaluationContext.classLoader, status) { args ->
val vm = context.vm.virtualMachine
val thread = context.suspendContext.thread?.threadReference?.takeIf { it.isSuspended }
?: error("Can not find a thread to run evaluation on")
val eval = object : JDIEval(vm, classLoader, thread, context.invokePolicy) {
override fun jdiInvokeStaticMethod(type: ClassType, method: Method, args: List<Value?>, invokePolicy: Int): Value? {
return context.invokeMethod(type, method, args)
}
override fun jdiInvokeStaticMethod(type: InterfaceType, method: Method, args: List<Value?>, invokePolicy: Int): Value? {
return context.invokeMethod(type, method, args)
}
override fun jdiInvokeMethod(obj: ObjectReference, method: Method, args: List<Value?>, policy: Int): Value? {
return context.invokeMethod(obj, method, args, ObjectReference.INVOKE_NONVIRTUAL)
}
}
interpreterLoop(mainMethod, makeInitialFrame(mainMethod, args.map { it.asValue() }), eval)
}
}
private fun <T> runEvaluation(
context: ExecutionContext,
compiledData: CompiledCodeFragmentData,
classLoader: ClassLoaderReference?,
status: EvaluationStatus,
block: (List<Value?>) -> T
): T {
// Preload additional classes
compiledData.classes
.filter { !it.isMainClass }
.forEach { context.findClass(it.className, classLoader) }
for (parameterType in compiledData.mainMethodSignature.parameterTypes) {
context.findClass(parameterType, classLoader)
}
val variableFinder = VariableFinder(context)
val args = calculateMainMethodCallArguments(variableFinder, compiledData, status)
val result = block(args)
for (wrapper in variableFinder.refWrappers) {
updateLocalVariableValue(variableFinder.evaluatorValueConverter, wrapper)
}
return result
}
private fun updateLocalVariableValue(converter: EvaluatorValueConverter, ref: VariableFinder.RefWrapper) {
val frameProxy = converter.context.frameProxy
val newValue = EvaluatorValueConverter.unref(ref.wrapper)
val variable = frameProxy.safeVisibleVariableByName(ref.localVariableName)
if (variable != null) {
try {
frameProxy.setValue(variable, newValue)
} catch (e: InvalidTypeException) {
LOG.error("Cannot update local variable value: expected type ${variable.type}, actual type ${newValue?.type()}", e)
}
} else if (frameProxy is CoroutineStackFrameProxyImpl) {
frameProxy.updateSpilledVariableValue(ref.localVariableName, newValue)
}
}
private fun calculateMainMethodCallArguments(
variableFinder: VariableFinder,
compiledData: CompiledCodeFragmentData,
status: EvaluationStatus
): List<Value?> {
val asmValueParameters = compiledData.mainMethodSignature.parameterTypes
val valueParameters = compiledData.parameters
require(asmValueParameters.size == valueParameters.size)
val args = valueParameters.zip(asmValueParameters)
return args.map { (parameter, asmType) ->
val result = variableFinder.find(parameter, asmType)
if (result == null) {
val name = parameter.debugString
val frameProxy = variableFinder.context.frameProxy
fun isInsideDefaultInterfaceMethod(): Boolean {
val method = frameProxy.safeLocation()?.safeMethod() ?: return false
val desc = method.signature()
return method.name().endsWith("\$default") && DEFAULT_METHOD_MARKERS.any { desc.contains("I${it.descriptor})") }
}
if (parameter.kind == CodeFragmentParameter.Kind.COROUTINE_CONTEXT) {
status.error(EvaluationError.CoroutineContextUnavailable)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.coroutine.context.unavailable"))
} else if (parameter in compiledData.crossingBounds) {
status.error(EvaluationError.ParameterNotCaptured)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.not.captured", name))
} else if (parameter.kind == CodeFragmentParameter.Kind.FIELD_VAR) {
status.error(EvaluationError.BackingFieldNotFound)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.find.backing.field", parameter.name))
} else if (parameter.kind == CodeFragmentParameter.Kind.ORDINARY && isInsideDefaultInterfaceMethod()) {
status.error(EvaluationError.InsideDefaultMethod)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.parameter.evaluation.default.methods"))
} else if (parameter.kind == CodeFragmentParameter.Kind.ORDINARY && frameProxy is CoroutineStackFrameProxyImpl) {
status.error(EvaluationError.OptimisedVariable)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.variable.was.optimised"))
} else {
status.error(EvaluationError.CannotFindVariable)
evaluationException(KotlinDebuggerEvaluationBundle.message("error.cant.find.variable", name, asmType.className))
}
}
result.value
}
}
override fun getModifier() = null
companion object {
@get:TestOnly
@get:ApiStatus.Internal
var LOG_COMPILATIONS: Boolean = false
internal val IGNORED_DIAGNOSTICS: Set<DiagnosticFactory<*>> = Errors.INVISIBLE_REFERENCE_DIAGNOSTICS +
setOf(
Errors.OPT_IN_USAGE_ERROR,
Errors.MISSING_DEPENDENCY_SUPERCLASS,
Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS,
Errors.FIR_COMPILED_CLASS,
Errors.ILLEGAL_SUSPEND_FUNCTION_CALL
)
private val DEFAULT_METHOD_MARKERS = listOf(AsmTypes.OBJECT_TYPE, AsmTypes.DEFAULT_CONSTRUCTOR_MARKER)
private fun InterpreterResult.toJdiValue(context: ExecutionContext, status: EvaluationStatus): Value? {
val jdiValue = when (this) {
is ValueReturned -> result
is ExceptionThrown -> {
when (this.kind) {
ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE -> {
status.error(EvaluationError.ExceptionFromEvaluatedCode)
evaluationException(InvocationException(this.exception.value as ObjectReference))
}
ExceptionThrown.ExceptionKind.BROKEN_CODE ->
throw exception.value as Throwable
else -> {
status.error(EvaluationError.Eval4JUnknownException)
evaluationException(exception.toString())
}
}
}
is AbnormalTermination -> {
status.error(EvaluationError.Eval4JAbnormalTermination)
evaluationException(message)
}
else -> throw IllegalStateException("Unknown result value produced by eval4j")
}
val sharedVar = if ((jdiValue is AbstractValue<*>)) getValueIfSharedVar(jdiValue) else null
return sharedVar?.value ?: jdiValue.asJdiValue(context.vm.virtualMachine, jdiValue.asmType)
}
private fun getValueIfSharedVar(value: Eval4JValue): VariableFinder.Result? {
val obj = value.obj(value.asmType) as? ObjectReference ?: return null
return VariableFinder.Result(EvaluatorValueConverter.unref(obj))
}
}
}
private fun isSpecialException(th: Throwable): Boolean {
return when (th) {
is ClassNotPreparedException,
is InternalException,
is AbsentInformationException,
is ClassNotLoadedException,
is IncompatibleThreadStateException,
is InconsistentDebugInfoException,
is ObjectCollectedException,
is VMDisconnectedException -> true
else -> false
}
}
private fun reportError(codeFragment: KtCodeFragment, position: SourcePosition?, message: String, throwable: Throwable? = null) {
runReadAction {
val contextFile = codeFragment.context?.containingFile
val attachments = listOfNotNull(
attachmentByPsiFile(contextFile),
attachmentByPsiFile(codeFragment),
Attachment("breakpoint.info", "Position: " + position?.run { "${file.name}:$line" }),
Attachment("context.info", runReadAction { codeFragment.context?.text ?: "null" })
)
val decapitalizedMessage = message.replaceFirstChar { it.lowercase(Locale.getDefault()) }
LOG.error(
"Cannot evaluate a code fragment of type ${codeFragment::class.java}: $decapitalizedMessage",
throwable,
attachments.merge()
)
}
}
fun createCompiledDataDescriptor(result: CodeFragmentCompiler.CompilationResult): CompiledCodeFragmentData {
val localFunctionSuffixes = result.localFunctionSuffixes
val dumbParameters = ArrayList<CodeFragmentParameter.Dumb>(result.parameterInfo.parameters.size)
for (parameter in result.parameterInfo.parameters) {
val dumb = parameter.dumb
if (dumb.kind == CodeFragmentParameter.Kind.LOCAL_FUNCTION) {
val suffix = localFunctionSuffixes[dumb]
if (suffix != null) {
dumbParameters += dumb.copy(name = dumb.name + suffix)
continue
}
}
dumbParameters += dumb
}
return CompiledCodeFragmentData(
result.classes,
dumbParameters,
result.parameterInfo.crossingBounds,
result.mainMethodSignature
)
}
internal fun evaluationException(msg: String): Nothing = throw EvaluateExceptionUtil.createEvaluateException(msg)
internal fun evaluationException(e: Throwable): Nothing = throw EvaluateExceptionUtil.createEvaluateException(e)
internal fun getResolutionFacadeForCodeFragment(codeFragment: KtCodeFragment): ResolutionFacade {
val filesToAnalyze = listOf(codeFragment)
val kotlinCacheService = KotlinCacheService.getInstance(codeFragment.project)
return kotlinCacheService.getResolutionFacadeWithForcedPlatform(filesToAnalyze, JvmPlatforms.unspecifiedJvmPlatform)
}
| apache-2.0 | 24de9308268e39c7377f4f62b705fe4e | 45.646512 | 158 | 0.670755 | 5.637437 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/search/SearchFragment.kt | 1 | 10233 | @file:JvmName("SearchFragment") // ANALYTICS
package org.mtransit.android.ui.search
import android.content.Context
import android.location.Location
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import org.mtransit.android.R
import org.mtransit.android.common.repository.LocalPreferenceRepository
import org.mtransit.android.commons.KeyboardUtils.Companion.hideKeyboard
import org.mtransit.android.commons.ToastUtils
import org.mtransit.android.data.DataSourceType
import org.mtransit.android.data.POIArrayAdapter
import org.mtransit.android.data.POIArrayAdapter.TypeHeaderButtonsClickListener
import org.mtransit.android.databinding.FragmentSearchBinding
import org.mtransit.android.datasource.DataSourcesRepository
import org.mtransit.android.datasource.POIRepository
import org.mtransit.android.provider.FavoriteManager
import org.mtransit.android.provider.sensor.MTSensorManager
import org.mtransit.android.task.ServiceUpdateLoader
import org.mtransit.android.task.StatusLoader
import org.mtransit.android.ui.MTActivityWithLocation
import org.mtransit.android.ui.MTActivityWithLocation.UserLocationListener
import org.mtransit.android.ui.MainActivity
import org.mtransit.android.ui.fragment.ABFragment
import org.mtransit.android.ui.view.MTSearchView
import org.mtransit.android.ui.view.common.isAttached
import org.mtransit.android.ui.view.common.isVisible
import javax.inject.Inject
@AndroidEntryPoint
class SearchFragment : ABFragment(R.layout.fragment_search), UserLocationListener, TypeHeaderButtonsClickListener, OnItemSelectedListener {
companion object {
private val LOG_TAG = SearchFragment::class.java.simpleName
private const val TRACKING_SCREEN_NAME = "Search"
@JvmOverloads
@JvmStatic
fun newInstance(
optQuery: String? = null,
optTypeIdFilter: Int? = null
): SearchFragment {
return SearchFragment().apply {
arguments = bundleOf(
SearchViewModel.EXTRA_QUERY to (optQuery?.trim() ?: SearchViewModel.EXTRA_QUERY_DEFAULT),
SearchViewModel.EXTRA_TYPE_FILTER to optTypeIdFilter,
)
}
}
private const val DEV_QUERY = "MTDEV"
}
override fun getLogTag(): String = LOG_TAG
override fun getScreenName(): String = TRACKING_SCREEN_NAME
private val viewModel by viewModels<SearchViewModel>()
private val attachedViewModel
get() = if (isAttached()) viewModel else null
@Inject
lateinit var sensorManager: MTSensorManager
@Inject
lateinit var dataSourcesRepository: DataSourcesRepository
@Inject
lateinit var poiRepository: POIRepository
@Inject
lateinit var favoriteManager: FavoriteManager
@Inject
lateinit var statusLoader: StatusLoader
@Inject
lateinit var serviceUpdateLoader: ServiceUpdateLoader
@Inject
lateinit var lclPrefRepository: LocalPreferenceRepository
private var binding: FragmentSearchBinding? = null
private val adapter: POIArrayAdapter by lazy {
POIArrayAdapter(
this,
this.sensorManager,
this.dataSourcesRepository,
this.poiRepository,
this.favoriteManager,
this.statusLoader,
this.serviceUpdateLoader
).apply {
logTag = logTag
setOnTypeHeaderButtonsClickListener(this@SearchFragment)
setPois(emptyList()) // empty search = no result
}
}
private val typeFilterAdapter: SearchTypeFilterAdapter by lazy { SearchTypeFilterAdapter(requireContext()) }
override fun onAttach(context: Context) {
super.onAttach(context)
this.adapter.setActivity(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentSearchBinding.bind(view).apply {
listLayout.list.let { listView ->
listView.isVisible = adapter.isInitialized
adapter.setListView(listView)
}
typeFilters.apply {
onItemSelectedListener = this@SearchFragment
adapter = typeFilterAdapter
}
}
viewModel.query.observe(viewLifecycleOwner, { query ->
binding?.apply {
emptyLayout.isVisible = false // hide by default
emptyLayout.emptyText.text = if (query.isNullOrEmpty()) {
getString(R.string.search_hint)
} else {
getString(R.string.search_no_result_for_and_query, query)
}
if (query.isNullOrEmpty()) {
adapter.setPois(emptyList()) // empty search = no result
loadingLayout.isVisible = false // hide
listLayout.isVisible = false // hide
emptyLayout.isVisible = true // show
}
}
})
viewModel.loading.observe(viewLifecycleOwner, { loading ->
if (loading) {
adapter.clear() // mark not initialized == loading
binding?.apply {
listLayout.isVisible = false // hide
emptyLayout.isVisible = false // hide
loadingLayout.isVisible = true // show
}
}
})
viewModel.searchResults.observe(viewLifecycleOwner, { searchResults ->
adapter.setPois(searchResults)
adapter.updateDistanceNowAsync(viewModel.deviceLocation.value)
binding?.apply {
loadingLayout.isVisible = false
if (searchResults.isNullOrEmpty()) { // SHOW EMPTY
listLayout.isVisible = false
emptyLayout.isVisible = true
} else { // SHOW LIST
emptyLayout.isVisible = false
listLayout.isVisible = true
}
}
})
viewModel.deviceLocation.observe(viewLifecycleOwner, { deviceLocation ->
adapter.setLocation(deviceLocation)
})
viewModel.searchableDataSourceTypes.observe(viewLifecycleOwner, { dstList ->
typeFilterAdapter.setData(dstList)
})
viewModel.typeFilter.observe(viewLifecycleOwner, { dst ->
binding?.typeFilters?.apply {
setSelection(typeFilterAdapter.getPosition(dst))
isVisible = dst != null
}
adapter.setShowTypeHeader(if (dst == null) POIArrayAdapter.TYPE_HEADER_MORE else POIArrayAdapter.TYPE_HEADER_NONE)
})
}
override fun onTypeHeaderButtonClick(buttonId: Int, type: DataSourceType): Boolean {
if (buttonId == TypeHeaderButtonsClickListener.BUTTON_MORE) {
hideKeyboard(activity, view)
viewModel.setTypeFilter(type)
return true // handled
}
return false // not handled
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val dst = typeFilterAdapter.getItem(position)
viewModel.setTypeFilter(dst)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// DO NOTHING
}
override fun onResume() {
super.onResume()
adapter.onResume(this, viewModel.deviceLocation.value)
(activity as? MTActivityWithLocation)?.let { onUserLocationChanged(it.lastLocation) }
viewModel.onScreenVisible()
}
override fun onPause() {
super.onPause()
adapter.onPause()
}
override fun onUserLocationChanged(newLocation: Location?) {
attachedViewModel?.onDeviceLocationChanged(newLocation)
}
private var devEnabled: Boolean? = null
fun setSearchQuery(
query: String?,
@Suppress("UNUSED_PARAMETER") alreadyInSearchView: Boolean
) {
if (DEV_QUERY == query) {
devEnabled = devEnabled != true // flip
lclPrefRepository.saveAsync(LocalPreferenceRepository.PREFS_LCL_DEV_MODE_ENABLED, devEnabled)
ToastUtils.makeTextAndShowCentered(context, "DEV MODE: $devEnabled")
return
}
viewModel.onNewQuery(query)
}
override fun isABReady(): Boolean {
return searchView != null
}
override fun isABShowSearchMenuItem(): Boolean {
return false
}
override fun isABCustomViewFocusable(): Boolean {
return true
}
override fun isABCustomViewRequestFocus(): Boolean {
return searchHasFocus()
}
private fun searchHasFocus(): Boolean {
return refreshSearchHasFocus()
}
private fun refreshSearchHasFocus(): Boolean {
return searchView?.let {
val focus = it.hasFocus()
attachedViewModel?.setSearchHasFocus(focus)
focus
} ?: false
}
override fun getABCustomView(): View? {
return getSearchView()
}
private var searchView: MTSearchView? = null
private fun getSearchView(): MTSearchView? {
if (searchView == null) {
initSearchView()
}
return searchView
}
private fun initSearchView() {
val activity = activity ?: return
val mainActivity = activity as MainActivity
val supportActionBar = mainActivity.supportActionBar
val context = if (supportActionBar == null) mainActivity else supportActionBar.themedContext
searchView = MTSearchView(mainActivity, context).apply {
setQuery(attachedViewModel?.query?.value, false)
if (attachedViewModel?.searchHasFocus?.value == false) {
clearFocus()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onDestroy() {
super.onDestroy()
searchView = null // part of the activity
}
} | apache-2.0 | 9f417da22b155dff2e4c6400b8f0e3af | 33.691525 | 139 | 0.649272 | 5.302073 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddLabeledReturnInLambdaIntention.kt | 3 | 2255 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
class AddLabeledReturnInLambdaIntention : SelfTargetingRangeIntention<KtBlockExpression>(
KtBlockExpression::class.java,
KotlinBundle.lazyMessage("add.labeled.return.to.last.expression.in.a.lambda")
), LowPriorityAction {
override fun applicabilityRange(element: KtBlockExpression): TextRange? {
if (!isApplicableTo(element)) return null
val labelName = element.getParentLambdaLabelName() ?: return null
if (labelName == KtTokens.SUSPEND_KEYWORD.value) return null
setTextGetter(KotlinBundle.lazyMessage("add.return.at.0", labelName))
return element.statements.lastOrNull()?.textRange
}
override fun applyTo(element: KtBlockExpression, editor: Editor?) {
val labelName = element.getParentLambdaLabelName() ?: return
val lastStatement = element.statements.lastOrNull() ?: return
val newExpression = KtPsiFactory(element.project).createExpressionByPattern("return@$labelName $0", lastStatement)
lastStatement.replace(newExpression)
}
private fun isApplicableTo(block: KtBlockExpression): Boolean {
val lastStatement = block.statements.lastOrNull().takeIf { it !is KtReturnExpression } ?: return false
val bindingContext = lastStatement.safeAnalyzeNonSourceRootCode().takeIf { it != BindingContext.EMPTY } ?: return false
return lastStatement.isUsedAsExpression(bindingContext)
}
} | apache-2.0 | 7af4f57d15cd2818272de9bc0cc437de | 52.714286 | 158 | 0.785809 | 5.136674 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/OrderFilesTab_A2.kt | 1 | 18446 | package alraune
import vgrechka.*
import alraune.Ordering.*
import alraune.entity.*
import bolone.*
import bolone.rp.*
import pieces100.*
import kotlin.math.max
class OrderFilesTab_A2(val pedro: OrderPedro_A2) : EntityPageTemplate.Tab {
companion object {
val filesTabID = "Files"
}
var tampering by notNullOnce<OrderFilesTab_Tampering_A2>()
var searchFucker by notNullOnce<SearchFucker>()
val front_fileItems = mutableListOf<BoFrontFuns.InitOrderFilesPage.FileItem>()
override fun id() = filesTabID
override fun title() = t("Files", "Файлы")
val juan get() = pedro.juan
override fun willRender() {
tampering = OrderFilesTab_Tampering_A2(this)
}
override fun addTopRightControls(trc: TopRightControls) {
searchFucker = SearchFucker(juan.initialParams, trc)
trc.addOrderingSelect()
if (editable()) {
if (false) {
withNewSpaghettiDish(
before = tampering.tamperPreparePlusButton,
main = {
trc.addButton(FA.plus, AlDebugTag.topRightButton).whenDomReady_addOnClick(
jsBustOutModal(modalWithContext(composeFileModalContent_a2(juan.toLight(), null, FieldSource.Initial()))))
}
)
}
}
}
override fun render(): Renderable {
val tag = div().with {
if (searchFucker.sanitizedSearchString.isNotEmpty()) {
oo(div().style("""
margin-bottom: 1rem; padding-right: 0; padding-top: 0.5rem; padding-bottom: 1rem;
border-bottom: 3px dashed #9E9E9E;""").with {
oo(composeFlex_alignItemsCenter().with {
oo(FA.search())
oo(span().add(t("TOTE", "Это результаты поиска")).style("font-weight: bold; margin-left: 0.5em;"))
oo(ComposeChevronLink(
title = t("TOTE", "Не хочу поиск"),
href = makeUrlPart(SpitOrderPage.path, juan.initialParams.copy {
it.search.set(null)}))
.WithLeftMargin().replaceState())
})
})
}
// oo(!object : ComposePaginatedOrderFiles(
// req = juan.ept.requestSnapshot,
// order = juan.entity,
// spitPage = juan.ept.pedro.pageClass()) {
//
// init {
// orderingFrom(juan.initialParams)
// }
//
// override fun renderItem(item: Order_UA_V1.File) =
// composeOrderFileItem_a2(item, false, juan.ept)
// })
val pageSize = AlConst.pageSize
val order = juan.order
val orderData = order.data
oo(dance(object : ComposePaginatedShit<Order.File>(
object : PaginationPussy<Order.File> {
override fun pageSize() = pageSize
override fun selectItems(offset: Long): List<Order.File> {
val ordering = juan.initialParams.ordering.get()!!
val files = when (ordering) {
NewerFirst -> order.viewBucket().files.reversed()
OlderFirst -> order.viewBucket().files
}
val fromIndex = Math.toIntExact(offset)
val toIndex = Math.toIntExact(offset + pageSize)
val size = files.size
return files.subList(clamp(fromIndex, 0, max(size - 1, 0)), clamp(toIndex, 0, size))
}
override fun count() = order.viewBucket().files.size.toLong()
}) {
override fun initShitGivenItems(items: List<Order.File>) {}
override fun renderItem(item: Order.File, index: Int) = composeOrderFileItem_a2(juan.order, item, false, juan.toLight(),
tab = this@OrderFilesTab_A2)
override fun makePageHref(pageFrom1: Int): String {
return makeUrlPart(juan.ept.pedro.pagePath(),
GetParams().also {it.page.set(pageFrom1)},
keepCurrentParamsFrom = rctx0.req)
}
}))
}
!BoFrontFuns.InitOrderFilesPage(
userKind = rctx.maybeUser()?.kind,
editable = editable(),
orderHandle = juan.order.toHandle().toJsonizable(),
bucket = juan.order.viewBucket().name,
tabsTopRightContainerDomid = juan.tabsTopRightContainer.attrs.id,
reloadURL = juan.ept.reloadUrl(),
reloadToFirstPageURL = juan.ept.reloadToFirstPageUrl(),
storikanURL = alConfig.storikanUrl,
fileItems = front_fileItems)
return tag
}
fun editable() = pedro.canEditParams()
}
fun doUpdateOrderFile__killme(orderHandle: OrderHandle, viewBucket: String?, fileId: Long, fs: OrderFileFields__killme) {
!object : UpdateOrder(orderHandle, "Update order file") {
var file by notNullOnce<Order.File>()
override fun specificUpdates() {
file = order.bucket(postBucket(viewBucket)).fileByID(fileId)
populateEntityFromFields(file, fs)
file.updatedAt = now
}
override fun makeOperationData(template: Order.Operation) =
new_Order_Operation_File_Update(template, file)
}
}
fun doCreateOrderFile__killme(orderHandle: OrderHandle, viewBucket: String?, fs: OrderFileFields__killme): Long {
val fileFormValue = fs.file.value().meat!!
val fileId = dbNextSequenceValue(AlConst.orderFileIdSequence)
!object : UpdateOrder(orderHandle, shortDescription = "Create order file") {
var file by notNullOnce<Order.File>()
override fun specificUpdates() {
val fileUuid = largeUUID()
file = Order.File().fill(
id = fileId, createdAt = now, updatedAt = now, uuid = fileUuid,
state = Order.File.State.Unknown,
title = fs.title.sanitized(),
details = fs.details.sanitized(),
adminNotes = null, toBeFixed = null,
resource = Order.Resource().fill(
name = fileFormValue.name,
size = fileFormValue.size,
downloadUrl = fileFormValue.downloadUrl,
secretKeyBase64 = fileFormValue.secretKeyBase64))
val postBucket = postBucket(viewBucket)
order.bucket(postBucket).files.add(file)
if (postBucket == AlSite.BoloneCustomer.name) {
fun addToWriterBucket() = order.bucket(AlSite.BoloneWriter.name).files.add(file)
fun checkIsAdmin_addToWriterBucket() {
check(isAdmin())
addToWriterBucket()
}
exhaustive=when (order.state) {
Order.State.CustomerDraft -> addToWriterBucket()
Order.State.LookingForWriters -> checkIsAdmin_addToWriterBucket()
Order.State.WaitingPayment -> checkIsAdmin_addToWriterBucket()
Order.State.WaitingAdminApproval -> checkIsAdmin_addToWriterBucket()
Order.State.ReturnedToCustomerForFixing -> addToWriterBucket()
Order.State.WorkInProgress -> {}
}
}
}
override fun makeOperationData(template: Order.Operation) =
new_Order_Operation_File_Create(template, file)
}
return fileId
}
fun postBucket(viewBucket: String?) = when {
rctx0.al.site() == AlSite.BoloneAdmin -> viewBucket!!
else -> {
check(viewBucket == null)
rctx0.al.site().name
}
}
private fun composeFileModalContent_a2(lej: LightEptJuan,
fileId: Long?,
source: FieldSource): MainAndTieKnots<Renderable, Context1> {
return MainAndTieKnots(
main = {
dance(ComposeModalContent().also {
it.title = when {
fileId == null -> t("TOTE", "Файл")
else -> t("TOTE", "Файл №" + fileId)
}
it.blueLeftMargin()
it.body = composeFileModalBody_a2(source)
it.footer = dance(ButtonBarWithTicker()
.tickerLocation(Rightness.Left)
.addSubmitFormButton(MinimalButtonShit(
when {
fileId == null -> AlText.create
else -> AlText.save
},
AlButtonStyle.Primary,
freakingServant(postCreateOrUpdateFile(lej, fileId))))
.addCloseModalButton())
})
},
tieKnots = {c1 ->
c1.filePicker.shitIntoJsAfterStatusChanged.add {buf, status ->
buf.appendln(when (status) {
FilePicker.Status.Uploading -> """
${c1.buttonBars.joinToString(";") {it.jsCodeToSetMeEnabled(false)}}
${jsByIdSingle(c1.titleInput.controlDomid)}.focus()"""
else -> """
${c1.buttonBars.joinToString(";") {it.jsCodeToSetMeEnabled(true)}}"""
})
}
c1.filePicker.errorBannerDomid = c1.errorBannerDomid
}
)
}
private fun composeFileModalBody_a2(source: FieldSource) = div().with {
val fields = useFieldsSkippingAdminOnesIfNecessary(OrderFileFields__killme(), source)
oo(fields.file.compose())
oo(fields.title.begin()
.also {Context1.get().titleInput = it}
.focused()
.compose())
oo(fields.details.compose())
// fields.adminNotes.ifUsed {oo(it.compose())}
}
fun postCreateOrUpdateFile(lej: LightEptJuan, fileId: Long? = null) = fun() {
val fs = useFieldsSkippingAdminOnesIfNecessary(OrderFileFields__killme(), FieldSource.Post())
if (anyFieldErrors(fs)) {
val swc = withNewContext1(composeFileModalContent_a2(lej, fileId, FieldSource.Post()))
btfEval {s ->
jsReplaceElement(
ComposeModalContent.defaultModalDialogDomid,
swc.shit,
swc.context.onDomReadyPlusOnShown()
)}
return
}
if (fileId == null) {
doCreateOrderFile__killme(lej.handle, lej.viewBucket, fs)
btfRemoveModalAndProgressyNavigate(lej.reloadToFirstPageUrl, replaceState = true)
}
else {
doUpdateOrderFile__killme(lej.handle, lej.viewBucket, fileId, fs)
btfEval(lej.jsReload())
}
}
private fun composeOrderFileItem_a2(order: Order,
file: Order.File,
fuckIn: Boolean,
lej: LightEptJuan,
tab: OrderFilesTab_A2): Renderable {
var editTriggerDomid: String? = null
var titleBar by once<ooItemTitle>()
val tag = div().id(fileItemDomid_a2(file.id)).with {
if (fuckIn) {
currentTag().className(AlCSS.fuckIn.className)
}
titleBar = ooItemTitle(
title = file.title,
tinySubtitle = AlText.numString(file.id),
addIcons = {icons->
addDownloadOrderFileIcon(icons, file)
if (tab.editable()) {
val iconDomid = nextDomid()
editTriggerDomid = iconDomid
// bustOutModalOnDomidClick(iconDomid, modalWithContext(
// composeFileModalContent_a2(lej, file.id, FieldSource.DB(file))))
icons.item(FA.pencil, t("Edit", "Изменить")).id(iconDomid).appendStyle("margin-top: 1px;")
}
},
belowTitle = div().with {
if (isAdmin()) {
val iconStyle = "margin-left: 40px; margin-right: 0.5em; color: #616161;"
val copies = findFileCopies(file, order)
if (copies.isNotEmpty()) {
oo(div().with {
oo(FA.signIn().style(iconStyle))
oo(span(t("TOTE", "Скопирован в ")).style("font-weight: bold;"))
oo(copies.joinToString(", ") {it.display()})
})
}
file.copiedFrom?.let {src->
val srcDeleted = order.maybeBucketAndFileByID(src.fileID) == null
oo(div().with {
oo(FA.filesO().style(iconStyle))
oo(span(t("TOTE", "скопирован из ")).style("font-weight: bold;"))
oo(span(src.display()).style(srcDeleted.thenElseEmpty {"text-decoration: line-through;"}))
})
}
}
}
)
ooOrderFileItemBody_part1(file)
rctx0.somethingDrawn = false
if (AlFeatures.markSpecificFilesAsNeedingFix) {
file.toBeFixed?.let {
oo(div().style("background-color: #fbe9e7; border-radius: 5px; padding: 5px; margin-bottom: 0.5rem; position: relative;").with {
oo(DetailsRow().title(t("TOTE", "Что необходимо исправить")).content(it.what).noMarginBottom())
val detailsForAdmin = it.detailsForAdmin
if (!detailsForAdmin.isNullOrBlank() && rctx0.al.pretending == AlUserKind.Admin) {
oo(div().style("border-top: 2px dashed white; margin-top: 0.5rem; padding-top: 0.5rem;").with {
oo(DetailsRow().title(t("TOTE", "Админские заметки на этот счет")).content(detailsForAdmin).noMarginBottom())})
}
// run { // Bug menu
// val clsPosition = nextJSIdentifier()
// val clsIcon = nextJSIdentifier()
// val clsIconAdmin = nextJSIdentifier()
// oo(rawHtml("""<style>
// .$clsPosition {
// position: absolute;
// right: 5px;
// top: 5px;
// }
// .$clsIcon {
// color: #bf360c;
// font-size: 150%;
// transform: rotate(25deg);
// }
// .$clsIcon.$clsIconAdmin:hover {
// cursor: pointer;
// color: #e64a19;
// }
// </style>"""))
// val icon = FA.bug()
// exhaustive=when {
// isPretendingAdmin() -> ooDropdown(icon.appendClassName("$clsIcon $clsIconAdmin"), containerClass = clsPosition) {
// it.item(t("TOTE", "Пофикшено"), FA.checkSquareO) {domid->
// bustOutModalOnDomidClick(
// domid = domid,
// title = t("TOTE", "Файл №${file.id} считать пофикшеным?"),
// composeBody = {composeDescriptionOfEntityToBeOperatedOnInModal(file.title)},
// submitButtonServant = ept.servantHandle(ServeConsiderFileFixed_A2().fill(file))
// ).thunk()
// }
// it.item(t("TOTE", "Редактировать"), FA.pencil) {domid->
// attachWhatShouldBeFixedModal_a2(domid, file, ept)
// }
// }
// else -> oo(icon.appendClassName("$clsIcon $clsPosition"))
// }
// }
})
}
}
AlRender2.drawAdminNotes_ifAny_andPretendingAdmin(file.adminNotes)
ooOrderFileItemBody_part2(file)
}
tab.front_fileItems += BoFrontFuns.InitOrderFilesPage.FileItem(
id = file.id,
file = file,
editTriggerDomid = editTriggerDomid,
rightIconsContainerDomid = titleBar.rightIconsContainer.attrs.id,
fields = new_OrderFileFields(
file = FileField.noError(new_FileField_Value(
name = file.resource.name,
size = file.resource.size,
downloadURL = file.resource.downloadUrl,
secretKeyBase64 = file.resource.secretKeyBase64)),
title = TextField.noError(file.title),
details = TextField.noError(file.details)),
copiedTo = findFileCopies(file, order))
return tag
}
fun findFileCopies(file: Order.File, order: Order) = l<Order.File.Reference>{ist->
for (bucket in order.data.buckets) {
for (otherFile in bucket.files) {
if (otherFile.copiedFrom?.fileID == file.id) {
ist += new_Order_File_Reference(
bucketName = bucket.name,
fileID = otherFile.id)
}
}
}
}
private fun fileItemDomid_a2(id: Long) = "fileItem-$id"
fun doDeleteFile__killme(lej: LightEptJuan, fileId: Long) = {
!object : UpdateOrder(lej.handle, "Delete order file") {
var file by notNullOnce<Order.File>()
override fun specificUpdates() {
val bucket = order.bucket(postBucket(lej.viewBucket))
file = bucket.fileByID(fileId)
bucket.files.remove(file)
}
override fun makeOperationData(template: Order.Operation) =
new_Order_Operation_File_Delete(template, file)
}
btfEval(lej.jsReload())
}
| apache-2.0 | 57b50f6ca494a58e6bea8ee3d45abcf9 | 37.640592 | 144 | 0.515074 | 4.653004 | false | false | false | false |
androidx/androidx | camera/integration-tests/camerapipetestapp/src/main/java/androidx/camera/integration/camera2/pipe/CameraPipeActivity.kt | 3 | 5209 | /*
* 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.camera.integration.camera2.pipe
import android.Manifest
import android.hardware.camera2.CameraCharacteristics
import android.os.Bundle
import android.os.Trace
import android.util.Log
import android.view.View
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CameraPipe
import kotlinx.coroutines.runBlocking
/**
* This is the main activity for the CameraPipe test application.
*/
class CameraPipeActivity : CameraPermissionActivity() {
private lateinit var cameraPipe: CameraPipe
private lateinit var dataVisualizations: DataVisualizations
private lateinit var ui: CameraPipeUi
private var lastCameraId: CameraId? = null
private var currentCamera: SimpleCamera? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i("CXCP-App", "Activity onCreate")
cameraPipe = (applicationContext as CameraPipeApplication).cameraPipe
// This adjusts the UI to make the activity run a a full screen application.
configureFullScreenCameraWindow(this)
// Inflate the main ui for the camera activity.
Trace.beginSection("CXCP-App#inflate")
ui = CameraPipeUi.inflate(this)
// Configure and wire up basic UI behaviors.
ui.disableButton(ui.captureButton)
ui.disableButton(ui.infoButton)
ui.viewfinderText.visibility = View.VISIBLE
ui.switchButton.setOnClickListener { startNextCamera() }
Trace.endSection()
// TODO: Update this to work with newer versions of the visualizations and to accept
// the CameraPipeUi object as a parameter.
dataVisualizations = DataVisualizations(this)
}
override fun onStart() {
super.onStart()
Log.i("CXCP-App", "Activity onStart")
checkPermissionsAndRun(
setOf(
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
)
) {
val camera = currentCamera
if (camera == null) {
startNextCamera()
} else {
camera.start()
}
}
}
override fun onResume() {
super.onResume()
Log.i("CXCP-App", "Activity onResume")
}
override fun onPause() {
super.onPause()
Log.i("CXCP-App", "Activity onPause")
}
override fun onStop() {
super.onStop()
Log.i("CXCP-App", "Activity onStop")
currentCamera?.stop()
}
override fun onDestroy() {
super.onDestroy()
Log.i("CXCP-App", "Activity onDestroy")
currentCamera?.close()
dataVisualizations.close()
}
private fun startNextCamera() {
Trace.beginSection("CXCP-App#startNextCamera")
Trace.beginSection("CXCP-App#stopCamera")
var camera = currentCamera
camera?.stop()
Trace.endSection()
Trace.beginSection("CXCP-App#findNextCamera")
val cameraId = runBlocking { findNextCamera(lastCameraId) }
Trace.endSection()
Trace.beginSection("CXCP-App#startCameraGraph")
camera = SimpleCamera.create(cameraPipe, cameraId, ui.viewfinder, listOf())
Trace.endSection()
currentCamera = camera
lastCameraId = cameraId
ui.viewfinderText.text = camera.cameraInfoString()
camera.start()
Trace.endSection()
Trace.endSection()
}
private suspend fun findNextCamera(lastCameraId: CameraId?): CameraId {
val cameras: List<CameraId> = cameraPipe.cameras().ids()
// By default, open the first back facing camera if no camera was previously configured.
if (lastCameraId == null) {
return cameras.firstOrNull {
cameraPipe.cameras().getMetadata(it)[CameraCharacteristics.LENS_FACING] ==
CameraCharacteristics.LENS_FACING_BACK
} ?: cameras.first()
}
// If a camera was previously open, select the next camera in the list of all cameras. It is
// possible that the list of cameras contains only one camera, in which case this will return
// the same camera as "currentCameraId"
val lastCameraIndex = cameras.indexOf(lastCameraId)
if (cameras.isEmpty() || lastCameraIndex == -1) {
Log.e("CXCP-App", "Failed to find matching camera!")
return cameras.first()
}
// When we reach the end of the list of cameras, loop.
return cameras[(lastCameraIndex + 1) % cameras.size]
}
} | apache-2.0 | 6ed7cd59b24ee830243a99c1b56ba72f | 32.831169 | 101 | 0.655596 | 4.787684 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/color/ViewColorSet.kt | 1 | 1515 | package org.thoughtcrime.securesms.color
import android.content.Context
import android.os.Parcelable
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import kotlinx.parcelize.Parcelize
import org.thoughtcrime.securesms.R
/**
* Represents a set of colors to be applied to the foreground and background of a view.
*
* Supports mixing color ints and color resource ids.
*/
@Parcelize
data class ViewColorSet(
val foreground: ViewColor,
val background: ViewColor
) : Parcelable {
companion object {
val PRIMARY = ViewColorSet(
foreground = ViewColor.ColorResource(R.color.signal_colorOnPrimary),
background = ViewColor.ColorResource(R.color.signal_colorPrimary)
)
fun forCustomColor(@ColorInt customColor: Int): ViewColorSet {
return ViewColorSet(
foreground = ViewColor.ColorResource(R.color.signal_colorOnCustom),
background = ViewColor.ColorValue(customColor)
)
}
}
@Parcelize
sealed class ViewColor : Parcelable {
@ColorInt
abstract fun resolve(context: Context): Int
@Parcelize
data class ColorValue(@ColorInt val colorInt: Int) : ViewColor() {
override fun resolve(context: Context): Int {
return colorInt
}
}
@Parcelize
data class ColorResource(@ColorRes val colorRes: Int) : ViewColor() {
override fun resolve(context: Context): Int {
return ContextCompat.getColor(context, colorRes)
}
}
}
}
| gpl-3.0 | d3d994bc4a39aee0ecfc4c9b95b80a27 | 26.545455 | 87 | 0.720792 | 4.577039 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/di/NetworkModule.kt | 1 | 2709 | package de.droidcon.berlin2018.di
import android.content.Context
import com.tickaroo.tikxml.TikXml
import com.tickaroo.tikxml.converter.htmlescape.HtmlEscapeStringConverter
import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory
import dagger.Module
import dagger.Provides
import de.droidcon.berlin2018.BuildConfig
import de.droidcon.berlin2018.schedule.backend.BackendScheduleAdapter
import de.droidcon.berlin2018.schedule.backend.DroidconBerlinBackend2018
import de.droidcon.berlin2018.schedule.backend.DroidconBerlinBackendScheduleAdapter2018
import de.droidcon.berlin2018.schedule.backend.data2018.InstantTimeTypeConverter
import de.droidcon.berlin2018.schedule.backend.data2018.MyHtmlEscapeConverter
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level
import org.threeten.bp.Instant
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
/**
* @author Hannes Dorfmann
*/
@Module
open class NetworkModule(context: Context) {
private val retrofit: Retrofit
private val okHttp: OkHttpClient
private val backendAdapter: BackendScheduleAdapter
init {
val builder = OkHttpClient.Builder()
.cache(okhttp3.Cache(context.cacheDir, 48 * 1024 * 1024))
if (BuildConfig.DEBUG) {
val logging = HttpLoggingInterceptor()
logging.level = Level.HEADERS
builder.addInterceptor(logging)
}
okHttp = builder.build()
/*
val moshi = Moshi.Builder()
.add(HtmlStringTypeAdapter.newFactory())
.add(InstantIsoTypeConverter())
.build()
*/
retrofit = Retrofit.Builder()
.client(okHttp)
.baseUrl("https://cfp.droidcon.de")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(
TikXmlConverterFactory.create(
TikXml.Builder()
.exceptionOnUnreadXml(false)
.addTypeConverter(Instant::class.java, InstantTimeTypeConverter())
.addTypeConverter(String::class.java, MyHtmlEscapeConverter()) // HtmlEscapeStringConverter encode / decode html characters. This class ships as optional dependency
.build()
)
)
.build()
val backend = retrofit.create(DroidconBerlinBackend2018::class.java)
backendAdapter = DroidconBerlinBackendScheduleAdapter2018(backend)
}
@Provides
fun provideOkHttp(): OkHttpClient = okHttp
@Provides
fun provideBackendAdapter(): BackendScheduleAdapter = backendAdapter
}
| apache-2.0 | c47bcd999057bd0f702268e30edeebec | 34.181818 | 188 | 0.709118 | 5.054104 | false | false | false | false |
androidx/androidx | compose/animation/animation-graphics/src/androidMain/kotlin/androidx/compose/animation/graphics/vector/compat/XmlPullParserUtils.android.kt | 3 | 2293 | /*
* 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.compose.animation.graphics.vector.compat
import android.content.res.Resources
import android.content.res.TypedArray
import android.util.AttributeSet
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
internal fun XmlPullParser.isAtEnd(): Boolean =
eventType == XmlPullParser.END_DOCUMENT ||
(depth < 1 && eventType == XmlPullParser.END_TAG)
/**
* Helper method to seek to the first tag within the VectorDrawable xml asset
*/
@Throws(XmlPullParserException::class)
internal fun XmlPullParser.seekToStartTag(): XmlPullParser {
var type = next()
while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
// Empty loop
type = next()
}
if (type != XmlPullParser.START_TAG) {
throw XmlPullParserException("No start tag found")
}
return this
}
/**
* Assuming that we are at the [XmlPullParser.START_TAG start] of the specified [tag], iterates
* though the events until we see a corresponding [XmlPullParser.END_TAG].
*/
internal inline fun XmlPullParser.forEachChildOf(
tag: String,
action: XmlPullParser.() -> Unit
) {
next()
while (!isAtEnd()) {
if (eventType == XmlPullParser.END_TAG && name == tag) {
break
}
action()
next()
}
}
internal inline fun <T> AttributeSet.attrs(
res: Resources,
theme: Resources.Theme?,
styleable: IntArray,
body: (a: TypedArray) -> T
): T {
val a = theme?.obtainStyledAttributes(this, styleable, 0, 0)
?: res.obtainAttributes(this, styleable)
try {
return body(a)
} finally {
a.recycle()
}
}
| apache-2.0 | e4a8a8b27c8f20276d1aff3f265de639 | 29.171053 | 95 | 0.684693 | 4.238447 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/pointer/PointerInteropFilterAndroidViewOffsetsTest.kt | 3 | 5825 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.pointer
import android.content.Context
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_UP
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.test.TestActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.nhaarman.mockitokotlin2.clearInvocations
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
// Tests that pointer offsets are correct when a pointer is dispatched from Android through
// Compose and back into Android and each layer offsets the pointer during dispatch.
@MediumTest
@RunWith(AndroidJUnit4::class)
class PointerInteropFilterAndroidViewOffsetsTest {
private lateinit var five: View
private val theHitListener: () -> Unit = mock()
@get:Rule
val rule = createAndroidComposeRule<TestActivity>()
@Before
fun setup() {
rule.activityRule.scenario.onActivity { activity ->
// one: Android View that is the touch target, inside
// two: Android View with 1x2 padding, inside
// three: Compose Box with 2x12 padding, inside
// four: Android View with 3x13 padding, inside
// five: Android View with 4x14 padding
//
// With all of the padding, "one" is at 10 x 50 relative to "five" and the tests
// dispatch MotionEvents to "five".
val one = CustomView(activity).apply {
layoutParams = ViewGroup.LayoutParams(1, 1)
hitListener = theHitListener
}
val two = FrameLayout(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setPadding(1, 11, 0, 0)
addView(one)
}
val four = ComposeView(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setPadding(3, 13, 0, 0)
setContent {
with(LocalDensity.current) {
// Box is "three"
Box(
Modifier.padding(start = (2f / density).dp, top = (12f / density).dp)
) {
AndroidView({ two })
}
}
}
}
five = FrameLayout(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setPadding(4, 14, 0, 0)
addView(four)
}
activity.setContentView(five)
}
}
@Test
fun uiClick_inside_hits() {
uiClick(10, 50, true)
}
@Test
fun uiClick_justOutside_misses() {
uiClick(9, 50, false)
uiClick(10, 49, false)
uiClick(11, 50, false)
uiClick(10, 51, false)
}
// Gets reused to should always clean up state.
private fun uiClick(x: Int, y: Int, hits: Boolean) {
clearInvocations(theHitListener)
rule.activityRule.scenario.onActivity {
val down =
MotionEvent(
0,
ACTION_DOWN,
1,
0,
arrayOf(PointerProperties(1)),
arrayOf(PointerCoords(x.toFloat(), y.toFloat())),
five
)
val up =
MotionEvent(
10,
ACTION_UP,
1,
0,
arrayOf(PointerProperties(1)),
arrayOf(PointerCoords(x.toFloat(), y.toFloat())),
five
)
five.dispatchTouchEvent(down)
five.dispatchTouchEvent(up)
}
if (hits) {
verify(theHitListener, times(2)).invoke()
} else {
verify(theHitListener, never()).invoke()
}
}
}
private class CustomView(context: Context) : View(context) {
lateinit var hitListener: () -> Unit
override fun onTouchEvent(event: MotionEvent?): Boolean {
hitListener()
return true
}
} | apache-2.0 | 1de4e7e863c872330d3f2995984653da | 32.291429 | 97 | 0.593648 | 4.907329 | false | true | false | false |
androidx/androidx | compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/ComposeLayoutInspector.kt | 3 | 17360 | /*
* 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.compose.ui.inspection
import android.view.View
import android.view.inspector.WindowInspector
import androidx.compose.ui.inspection.compose.AndroidComposeViewWrapper
import androidx.compose.ui.inspection.compose.convertToParameterGroup
import androidx.compose.ui.inspection.compose.flatten
import androidx.compose.ui.inspection.framework.flatten
import androidx.compose.ui.inspection.inspector.InspectorNode
import androidx.compose.ui.inspection.inspector.LayoutInspectorTree
import androidx.compose.ui.inspection.inspector.NodeParameterReference
import androidx.compose.ui.inspection.proto.StringTable
import androidx.compose.ui.inspection.proto.convert
import androidx.compose.ui.inspection.proto.toComposableRoot
import androidx.compose.ui.inspection.util.ThreadUtils
import androidx.compose.ui.unit.IntOffset
import androidx.inspection.Connection
import androidx.inspection.Inspector
import androidx.inspection.InspectorEnvironment
import androidx.inspection.InspectorFactory
import com.google.protobuf.ByteString
import com.google.protobuf.InvalidProtocolBufferException
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.Command
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetAllParametersCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetAllParametersResponse
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetComposablesCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetComposablesResponse
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParameterDetailsCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParameterDetailsResponse
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParametersCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParametersResponse
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.Response
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UnknownCommandResponse
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UpdateSettingsCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UpdateSettingsResponse
private const val LAYOUT_INSPECTION_ID = "layoutinspector.compose.inspection"
private const val MAX_RECURSIONS = 2
private const val MAX_ITERABLE_SIZE = 5
// created by java.util.ServiceLoader
class ComposeLayoutInspectorFactory :
InspectorFactory<ComposeLayoutInspector>(LAYOUT_INSPECTION_ID) {
override fun createInspector(
connection: Connection,
environment: InspectorEnvironment
): ComposeLayoutInspector {
return ComposeLayoutInspector(connection, environment)
}
}
class ComposeLayoutInspector(
connection: Connection,
environment: InspectorEnvironment
) : Inspector(connection) {
/** Cache data which allows us to reuse previously queried inspector nodes */
private class CacheData(
val rootView: View,
val trees: List<CacheTree>
) {
/** The cached nodes as a map from node id to InspectorNode */
val lookup: Map<Long, InspectorNode>
get() = _lookup ?: trees.flatMap { it.nodes }
.flatMap { it.flatten() }
.associateBy { it.id }
.also { _lookup = it }
private var _lookup: Map<Long, InspectorNode>? = null
}
/** Cache data for a tree of [InspectorNode]s under a [viewParent] */
internal class CacheTree(
val viewParent: View,
val nodes: List<InspectorNode>,
val viewsToSkip: List<Long>
)
private val layoutInspectorTree = LayoutInspectorTree()
private val recompositionHandler = RecompositionHandler(environment.artTooling())
private var delayParameterExtractions = false
// Sidestep threading concerns by only ever accessing cachedNodes on the inspector thread
private val inspectorThread = Thread.currentThread()
private val _cachedNodes = mutableMapOf<Long, CacheData>()
private var cachedGeneration = 0
private var cachedSystemComposablesSkipped = false
private var cachedHasAllParameters = false
private val cachedNodes: MutableMap<Long, CacheData>
get() {
check(Thread.currentThread() == inspectorThread)
return _cachedNodes
}
override fun onReceiveCommand(data: ByteArray, callback: CommandCallback) {
val command = try {
Command.parseFrom(data)
} catch (ignored: InvalidProtocolBufferException) {
handleUnknownCommand(data, callback)
return
}
when (command.specializedCase) {
Command.SpecializedCase.GET_COMPOSABLES_COMMAND -> {
handleGetComposablesCommand(command.getComposablesCommand, callback)
}
Command.SpecializedCase.GET_PARAMETERS_COMMAND -> {
handleGetParametersCommand(command.getParametersCommand, callback)
}
Command.SpecializedCase.GET_ALL_PARAMETERS_COMMAND -> {
handleGetAllParametersCommand(command.getAllParametersCommand, callback)
}
Command.SpecializedCase.GET_PARAMETER_DETAILS_COMMAND -> {
handleGetParameterDetailsCommand(command.getParameterDetailsCommand, callback)
}
Command.SpecializedCase.UPDATE_SETTINGS_COMMAND -> {
handleUpdateSettingsCommand(command.updateSettingsCommand, callback)
}
else -> handleUnknownCommand(data, callback)
}
}
private fun handleUnknownCommand(commandBytes: ByteArray, callback: CommandCallback) {
callback.reply {
unknownCommandResponse = UnknownCommandResponse.newBuilder().apply {
this.commandBytes = ByteString.copyFrom(commandBytes)
}.build()
}
}
private fun handleGetComposablesCommand(
getComposablesCommand: GetComposablesCommand,
callback: CommandCallback
) {
val data = getComposableNodes(
getComposablesCommand.rootViewId,
getComposablesCommand.skipSystemComposables,
getComposablesCommand.extractAllParameters || !delayParameterExtractions,
getComposablesCommand.generation,
getComposablesCommand.generation == 0
)
val location = IntArray(2)
data?.rootView?.getLocationOnScreen(location)
val windowPos = IntOffset(location[0], location[1])
val stringTable = StringTable()
val trees = data?.trees ?: emptyList()
val roots = trees.map { it.toComposableRoot(stringTable, windowPos, recompositionHandler) }
callback.reply {
getComposablesResponse = GetComposablesResponse.newBuilder().apply {
addAllStrings(stringTable.toStringEntries())
addAllRoots(roots)
}.build()
}
}
private fun handleGetParametersCommand(
getParametersCommand: GetParametersCommand,
callback: CommandCallback
) {
val foundComposable = if (delayParameterExtractions && !cachedHasAllParameters) {
getComposableFromAnchor(getParametersCommand.anchorHash)
} else {
getComposableNodes(
getParametersCommand.rootViewId,
getParametersCommand.skipSystemComposables,
true,
getParametersCommand.generation
)?.lookup?.get(getParametersCommand.composableId)
}
val semanticsNode = getCachedComposableNodes(
getParametersCommand.rootViewId
)?.lookup?.get(getParametersCommand.composableId)
callback.reply {
getParametersResponse = if (foundComposable != null) {
val stringTable = StringTable()
GetParametersResponse.newBuilder().apply {
parameterGroup = foundComposable.convertToParameterGroup(
semanticsNode ?: foundComposable,
layoutInspectorTree,
getParametersCommand.rootViewId,
getParametersCommand.maxRecursions.orElse(MAX_RECURSIONS),
getParametersCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE),
stringTable
)
addAllStrings(stringTable.toStringEntries())
}.build()
} else {
GetParametersResponse.getDefaultInstance()
}
}
}
private fun handleGetAllParametersCommand(
getAllParametersCommand: GetAllParametersCommand,
callback: CommandCallback
) {
val allComposables =
getComposableNodes(
getAllParametersCommand.rootViewId,
getAllParametersCommand.skipSystemComposables,
true,
getAllParametersCommand.generation
)?.lookup?.values ?: emptyList()
callback.reply {
val stringTable = StringTable()
val parameterGroups = allComposables.map { composable ->
composable.convertToParameterGroup(
composable,
layoutInspectorTree,
getAllParametersCommand.rootViewId,
getAllParametersCommand.maxRecursions.orElse(MAX_RECURSIONS),
getAllParametersCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE),
stringTable
)
}
getAllParametersResponse = GetAllParametersResponse.newBuilder().apply {
rootViewId = getAllParametersCommand.rootViewId
addAllParameterGroups(parameterGroups)
addAllStrings(stringTable.toStringEntries())
}.build()
}
}
private fun handleGetParameterDetailsCommand(
getParameterDetailsCommand: GetParameterDetailsCommand,
callback: CommandCallback
) {
val reference = NodeParameterReference(
getParameterDetailsCommand.reference.composableId,
getParameterDetailsCommand.reference.anchorHash,
getParameterDetailsCommand.reference.kind.convert(),
getParameterDetailsCommand.reference.parameterIndex,
getParameterDetailsCommand.reference.compositeIndexList
)
val foundComposable = if (delayParameterExtractions && !cachedHasAllParameters) {
getComposableFromAnchor(reference.anchorId)
} else {
getComposableNodes(
getParameterDetailsCommand.rootViewId,
getParameterDetailsCommand.skipSystemComposables,
true,
getParameterDetailsCommand.generation
)?.lookup?.get(reference.nodeId)
}
val semanticsNode = getCachedComposableNodes(
getParameterDetailsCommand.rootViewId
)?.lookup?.get(getParameterDetailsCommand.reference.composableId)
val expanded = foundComposable?.let { composable ->
layoutInspectorTree.expandParameter(
getParameterDetailsCommand.rootViewId,
semanticsNode ?: composable,
reference,
getParameterDetailsCommand.startIndex,
getParameterDetailsCommand.maxElements,
getParameterDetailsCommand.maxRecursions.orElse(MAX_RECURSIONS),
getParameterDetailsCommand.maxInitialIterableSize.orElse(MAX_ITERABLE_SIZE),
)
}
callback.reply {
getParameterDetailsResponse = if (expanded != null) {
val stringTable = StringTable()
GetParameterDetailsResponse.newBuilder().apply {
rootViewId = getParameterDetailsCommand.rootViewId
parameter = expanded.convert(stringTable)
addAllStrings(stringTable.toStringEntries())
}.build()
} else {
GetParameterDetailsResponse.getDefaultInstance()
}
}
}
private fun handleUpdateSettingsCommand(
updateSettingsCommand: UpdateSettingsCommand,
callback: CommandCallback
) {
recompositionHandler.changeCollectionMode(
updateSettingsCommand.includeRecomposeCounts,
updateSettingsCommand.keepRecomposeCounts
)
delayParameterExtractions = updateSettingsCommand.delayParameterExtractions
callback.reply {
updateSettingsResponse = UpdateSettingsResponse.newBuilder().apply {
canDelayParameterExtractions = true
}.build()
}
}
/**
* Get all [InspectorNode]s found under the layout tree rooted by [rootViewId]. They will be
* mapped with their ID as the key.
*
* This will return cached data if possible, but may request new data otherwise, blocking the
* current thread potentially.
*/
private fun getComposableNodes(
rootViewId: Long,
skipSystemComposables: Boolean,
includeAllParameters: Boolean,
generation: Int,
forceRegeneration: Boolean = false
): CacheData? {
if (!forceRegeneration && generation == cachedGeneration &&
skipSystemComposables == cachedSystemComposablesSkipped &&
(!includeAllParameters || cachedHasAllParameters)
) {
return cachedNodes[rootViewId]
}
val data = ThreadUtils.runOnMainThread {
layoutInspectorTree.resetAccumulativeState()
layoutInspectorTree.includeAllParameters = includeAllParameters
val composeViews = getAndroidComposeViews(rootViewId, skipSystemComposables, generation)
val composeViewsByRoot = composeViews.groupBy { it.rootView.uniqueDrawingId }
val data = composeViewsByRoot.mapValues { (_, composeViews) ->
CacheData(
composeViews.first().rootView,
composeViews.map { CacheTree(it.viewParent, it.createNodes(), it.viewsToSkip) }
)
}
layoutInspectorTree.resetAccumulativeState()
data
}.get()
cachedNodes.clear()
cachedNodes.putAll(data)
cachedGeneration = generation
cachedSystemComposablesSkipped = skipSystemComposables
cachedHasAllParameters = includeAllParameters
return cachedNodes[rootViewId]
}
/**
* Return the cached [InspectorNode]s found under the layout tree rooted by [rootViewId].
*/
private fun getCachedComposableNodes(rootViewId: Long): CacheData? =
cachedNodes[rootViewId]
/**
* Find an [InspectorNode] with extracted parameters that represent the composable with the
* specified anchor hash.
*/
private fun getComposableFromAnchor(anchorId: Int): InspectorNode? =
ThreadUtils.runOnMainThread {
layoutInspectorTree.resetAccumulativeState()
layoutInspectorTree.includeAllParameters = false
val composeViews = getAndroidComposeViews(-1L, false, 1)
composeViews.firstNotNullOfOrNull { it.findParameters(anchorId) }
}.get()
/**
* Get all AndroidComposeView instances found within the layout tree rooted by [rootViewId].
*/
private fun getAndroidComposeViews(
rootViewId: Long,
skipSystemComposables: Boolean,
generation: Int
): List<AndroidComposeViewWrapper> {
ThreadUtils.assertOnMainThread()
val roots = WindowInspector.getGlobalWindowViews()
.asSequence()
.filter { root ->
root.visibility == View.VISIBLE && root.isAttachedToWindow &&
(generation > 0 || root.uniqueDrawingId == rootViewId)
}
val wrappers = mutableListOf<AndroidComposeViewWrapper>()
roots.forEach { root ->
root.flatten().mapNotNullTo(wrappers) { view ->
AndroidComposeViewWrapper.tryCreateFor(
layoutInspectorTree,
root,
view,
skipSystemComposables
)
}
}
return wrappers
}
}
private fun Inspector.CommandCallback.reply(initResponse: Response.Builder.() -> Unit) {
val response = Response.newBuilder()
response.initResponse()
reply(response.build().toByteArray())
}
// Provide default for older version:
private fun Int.orElse(defaultValue: Int): Int =
if (this == 0) defaultValue else this
| apache-2.0 | f85fb592f3e71d9b9d7762b3d26d7dd6 | 40.932367 | 100 | 0.677016 | 6.04878 | false | false | false | false |