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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
goldmansachs/obevo | obevo-db/src/test/java/com/gs/obevo/db/testutil/ParamReader.kt | 2 | 5232 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.db.testutil
import com.gs.obevo.api.appdata.PhysicalSchema
import com.gs.obevo.api.factory.XmlFileConfigReader
import com.gs.obevo.db.api.appdata.DbEnvironment
import com.gs.obevo.db.api.factory.DbEnvironmentXmlEnricher
import com.gs.obevo.db.api.platform.DbDeployerAppContext
import com.gs.obevo.db.impl.core.jdbc.JdbcDataSourceFactory
import com.gs.obevo.util.inputreader.Credential
import com.gs.obevo.util.vfs.FileRetrievalMode
import org.apache.commons.configuration2.BaseHierarchicalConfiguration
import org.apache.commons.configuration2.HierarchicalConfiguration
import org.apache.commons.configuration2.ImmutableHierarchicalConfiguration
import org.apache.commons.configuration2.tree.ImmutableNode
import org.apache.commons.lang3.StringUtils
import org.eclipse.collections.api.block.function.primitive.IntToObjectFunction
import org.slf4j.LoggerFactory
import java.sql.Driver
import javax.sql.DataSource
/**
* Utility for reading in the test suite parameters from an input property file.
*/
class ParamReader(
private val rootConfig: HierarchicalConfiguration<ImmutableNode>
) {
private constructor(configPath: String) : this(getFromPath(configPath))
private val sysConfigs: List<ImmutableHierarchicalConfiguration>
get() = rootConfig.immutableConfigurationsAt("environments.environment")
val appContextParams: Collection<Array<Any>>
get() = sysConfigs.map(Companion::getAppContext).map { arrayOf(it as Any) }
val appContextAndJdbcDsParams: Collection<Array<Any>>
get() = getAppContextAndJdbcDsParams(1)
val jdbcDsAndSchemaParams: Collection<Array<Any>>
get() = getJdbcDsAndSchemaParams(1)
fun getJdbcDsAndSchemaParams(numConnections: Int): Collection<Array<Any>> {
return sysConfigs.map { config ->
getAppContext(config).valueOf(1).setupEnvInfra() // setup the environment upfront, since the calling tests here do not require the schema
arrayOf(getJdbcDs(config, numConnections), PhysicalSchema.parseFromString(config.getString("metaschema")))
}
}
private fun getAppContextAndJdbcDsParams(numConnections: Int): Collection<Array<Any>> {
return sysConfigs.map { arrayOf(getAppContext(it), getJdbcDs(it, numConnections)) }
}
companion object {
private val LOG = LoggerFactory.getLogger(ParamReader::class.java)
@JvmStatic
fun fromPath(configPath: String?, defaultPath: String): ParamReader {
return fromPath(if (!configPath.isNullOrBlank()) configPath!! else defaultPath)
}
@JvmStatic
fun fromPath(configPath: String): ParamReader {
return ParamReader(configPath)
}
private fun getFromPath(configPath: String): HierarchicalConfiguration<ImmutableNode> {
val configFile = FileRetrievalMode.CLASSPATH.resolveSingleFileObject(configPath)
if (configFile != null && configFile.exists()) {
return XmlFileConfigReader().getConfig(configFile) as HierarchicalConfiguration<ImmutableNode>
} else {
LOG.info("Test parameter file {} not found; will not run tests", configPath)
return BaseHierarchicalConfiguration()
}
}
private fun getAppContext(config: ImmutableHierarchicalConfiguration): IntToObjectFunction<DbDeployerAppContext> {
return IntToObjectFunction { stepNumber -> replaceStepNumber(config.getString("sourcePath"), stepNumber, config).buildAppContext() }
}
private fun getJdbcDs(config: ImmutableHierarchicalConfiguration, numConnections: Int): DataSource {
val jdbcUrl = config.getString("jdbcUrl")
val username = config.getString("defaultUserId")
val password = config.getString("defaultPassword")
val driver = config.getString("driverClass")
return JdbcDataSourceFactory.createFromJdbcUrl(
Class.forName(driver) as Class<out Driver>,
jdbcUrl,
Credential(username, password),
numConnections)
}
private fun replaceStepNumber(input: String, stepNumber: Int, config: ImmutableHierarchicalConfiguration): DbEnvironment {
val stepPath = input.replace("\${stepNumber}", stepNumber.toString())
val sourcePath = FileRetrievalMode.CLASSPATH.resolveSingleFileObject(stepPath)
checkNotNull(sourcePath, { "Could not find directory path $stepPath" })
return DbEnvironmentXmlEnricher().readEnvironment(config, sourcePath)
}
}
}
| apache-2.0 | 928c04948d9f0124c2f23e767e8e7b29 | 44.495652 | 150 | 0.722095 | 4.752044 | false | true | false | false |
google/ide-perf | src/main/java/com/google/idea/perf/tracer/TracerController.kt | 1 | 8979 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.tracer
import com.google.idea.perf.AgentLoader
import com.google.idea.perf.tracer.ui.TracerPanel
import com.google.idea.perf.util.ExecutorWithExceptionLogging
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.Disposer
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.TestOnly
import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import java.lang.instrument.UnmodifiableClassException
import javax.imageio.ImageIO
// Things to improve:
// - Audit overall overhead and memory usage.
// - Make sure CPU overhead is minimal when the tracer window is not showing.
// - Add some logging.
// - Detect repeated instrumentation requests with the same spec.
// - Add a proper progress indicator (subclass of ProgressIndicator) which displays text status.
// - Add visual indicator in UI if agent is not available.
// - Make sure we're handling inner classes correctly (and lambdas, etc.)
// - Try to reduce the overhead of transforming classes by batching or parallelizing.
// - Support line-number-based tracepoints.
// - Corner case: classes may being loaded *during* a request to instrument a method.
// - Cancelable progress indicator for class retransformations.
class TracerController(
private val view: TracerPanel, // Access from EDT only.
parentDisposable: Disposable
) : Disposable {
companion object {
private val LOG = Logger.getInstance(TracerController::class.java)
}
// For simplicity we run all tasks in a single-thread executor.
// Most methods are assumed to run only on this executor.
private val executor = ExecutorWithExceptionLogging("Tracer", 1)
init {
Disposer.register(parentDisposable, this)
// Install tracer instrumentation hooks.
executor.execute {
if (!AgentLoader.ensureTracerHooksInstalled) {
displayWarning("Failed to install instrumentation agent (see idea.log)")
}
}
}
override fun dispose() {
// TODO: Should we wait for tasks to finish (under a modal progress dialog)?
executor.shutdownNow()
}
fun handleRawCommandFromEdt(text: String) {
getApplication().assertIsDispatchThread()
if (text.isBlank()) return
val cmd = text.trim()
if (cmd.startsWith("save")) {
// Special case: handle this command while we're still on the EDT.
val path = cmd.substringAfter("save").trim()
savePngFromEdt(path)
}
else {
executor.execute { handleCommand(cmd) }
}
}
private fun handleCommand(commandString: String) {
val command = parseMethodTracerCommand(commandString)
val errors = command.errors
if (errors.isNotEmpty()) {
displayWarning(errors.joinToString("\n"))
return
}
handleCommand(command)
}
private fun handleCommand(command: TracerCommand) {
when (command) {
is TracerCommand.Clear -> {
CallTreeManager.clearCallTrees()
}
is TracerCommand.Reset -> {
runWithProgress { progress ->
val oldRequests = TracerConfig.clearAllRequests()
val affectedClasses = TracerConfigUtil.getAffectedClasses(oldRequests)
retransformClasses(affectedClasses, progress)
CallTreeManager.clearCallTrees()
}
}
is TracerCommand.Trace -> {
val countOnly = command.traceOption == TraceOption.COUNT_ONLY
when (command.target) {
is TraceTarget.All -> {
when {
command.enable -> displayWarning("Cannot trace all classes")
else -> handleCommand(TracerCommand.Reset)
}
}
is TraceTarget.Method -> {
runWithProgress { progress ->
val clazz = command.target.className
val method = command.target.methodName ?: "*"
val methodPattern = MethodFqName(clazz, method, "*")
val config = MethodConfig(
enabled = command.enable,
countOnly = countOnly,
tracedParams = command.target.parameterIndexes!!
)
val request = TracerConfigUtil.appendTraceRequest(methodPattern, config)
val affectedClasses = TracerConfigUtil.getAffectedClasses(listOf(request))
retransformClasses(affectedClasses, progress)
CallTreeManager.clearCallTrees()
}
}
null -> {
displayWarning("Expected a trace target")
}
}
}
else -> {
displayWarning("Command not implemented")
}
}
}
private fun retransformClasses(classes: Collection<Class<*>>, progress: ProgressIndicator) {
if (classes.isEmpty()) return
val instrumentation = AgentLoader.instrumentation ?: return
LOG.info("Retransforming ${classes.size} classes")
progress.isIndeterminate = classes.size <= 5
var count = 0.0
for (clazz in classes) {
// Retransforming classes tends to lock up all threads, so to keep
// the UI responsive it helps to flush the EDT queue in between.
invokeAndWaitIfNeeded {}
progress.checkCanceled()
try {
instrumentation.retransformClasses(clazz)
}
catch (e: UnmodifiableClassException) {
LOG.info("Cannot instrument non-modifiable class: ${clazz.name}")
}
catch (e: Throwable) {
LOG.error("Failed to retransform class: ${clazz.name}", e)
}
if (!progress.isIndeterminate) {
progress.fraction = ++count / classes.size
}
}
progress.isIndeterminate = true
}
/** Saves a png of the current view. */
private fun savePngFromEdt(path: String) {
if (!path.endsWith(".png")) {
displayWarning("Destination file must be a .png file; instead got $path")
return
}
val file = File(path)
if (!file.isAbsolute) {
displayWarning("Must specify destination file with an absolute path; instead got $path")
return
}
val img = UIUtil.createImage(view, view.width, view.height, BufferedImage.TYPE_INT_RGB)
view.paintAll(img.createGraphics())
getApplication().executeOnPooledThread {
try {
ImageIO.write(img, "png", file)
}
catch (e: IOException) {
displayWarning("Failed to write png to $path", e)
}
}
}
private fun displayWarning(warning: String, e: Throwable? = null) {
LOG.warn(warning, e)
invokeLater {
view.showCommandLinePopup(warning, MessageType.WARNING)
}
}
private fun <T> runWithProgress(action: (ProgressIndicator) -> T): T {
val indicator = view.createProgressIndicator()
val computable = Computable { action(indicator) }
return ProgressManager.getInstance().runProcess(computable, indicator)
}
@TestOnly
fun handleCommandFromTest(cmd: String) {
check(!getApplication().isDispatchThread) { "Do not run on EDT; deadlock imminent" }
invokeAndWaitIfNeeded { handleRawCommandFromEdt(cmd) }
executor.submit {}.get() // Await quiescence.
}
}
| apache-2.0 | 4c08dbaa1c5b11327f13012485676570 | 38.555066 | 102 | 0.613765 | 5.122076 | false | false | false | false |
groupon/kmond | src/main/kotlin/com/groupon/aint/kmond/output/NagiosHandler.kt | 1 | 6991 | /**
* Copyright 2015 Groupon 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.groupon.aint.kmond.output
import com.arpnetworking.metrics.MetricsFactory
import com.groupon.aint.kmond.Metrics
import com.groupon.aint.kmond.config.NagiosClusterLoader
import com.groupon.aint.kmond.config.model.NagiosClusters
import com.groupon.vertx.utils.Logger
import io.vertx.core.Handler
import io.vertx.core.Vertx
import io.vertx.core.eventbus.Message
import io.vertx.core.http.HttpClient
import io.vertx.core.http.HttpClientOptions
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonObject
import java.util.HashMap
import java.util.concurrent.TimeUnit
/**
* Output handler for sending events to Nagios.
*
* @param appMetricsFactory Used to create metrics that instrument KMonD itself; unrelated to the metrics being forwarded to Nagios.
*
* @author fsiegrist (fsiegrist at groupon dot com)
*/
class NagiosHandler(val vertx: Vertx, val appMetricsFactory: MetricsFactory, val clusterId: String, val httpClientConfig: JsonObject = JsonObject()): Handler<Message<Metrics>> {
private val httpClientsMap = HashMap<String, HttpClient>()
private val APP_METRICS_PREFIX = "downstream/nagios"
companion object {
private val log = Logger.getLogger(NagiosHandler::class.java)
private const val SEMI = ";"
private const val EQUAL = "="
private const val DEFAULT_REQUEST_TIMEOUT = 1000L
}
override fun handle(event: Message<Metrics>) {
val metrics = event.body()
if (!metrics.hasAlert) {
return event.reply(JsonObject()
.put("status", "success")
.put("code", 200)
.put("message", "No alert present"))
}
val nagiosHost = getNagiosHost(clusterId, metrics.host) ?: return
val httpClient = httpClientsMap[nagiosHost] ?: createHttpClient(nagiosHost)
val appMetrics: com.arpnetworking.metrics.Metrics = appMetricsFactory.create()
appMetrics.resetCounter(APP_METRICS_PREFIX + "/metrics_count")
appMetrics.incrementCounter(APP_METRICS_PREFIX + "/metrics_count", metrics.metrics.size.toLong())
val timer = appMetrics.createTimer(APP_METRICS_PREFIX + "/request")
val httpRequest = httpClient.request(HttpMethod.POST, "/nagios/cmd.php", {
timer.stop()
attachStatusMetrics(appMetrics, it.statusCode())
appMetrics.close()
event.reply(JsonObject()
.put("status", getRequestStatus(it.statusCode()))
.put("code", it.statusCode())
.put("message", it.statusMessage())
)
})
httpRequest.exceptionHandler({
appMetrics.close()
log.error("handle", "exception", "unknown", it)
event.reply(JsonObject()
.put("status", "error")
.put("code", 500)
.put("message", it.message))
})
httpRequest.putHeader("X-Remote-User", "nagios_messagebus_consumer")
httpRequest.putHeader("Content-type", "text/plain")
httpRequest.setTimeout(httpClientConfig.getLong("requestTimeout", DEFAULT_REQUEST_TIMEOUT))
httpRequest.end(buildPayload(event.body()), "UTF-8")
}
private fun createHttpClient(host: String) : HttpClient {
val httpOptions = HttpClientOptions(httpClientConfig)
httpOptions.defaultHost = host
val httpClient = vertx.createHttpClient(httpOptions)
httpClientsMap[host] = httpClient
return httpClient
}
private fun getRequestStatus(statusCode: Int) : String {
return if (statusCode < 300) {
"success"
} else {
"fail"
}
}
private fun buildPayload(metric: Metrics) : String {
val timestamp = metric.timestamp
val hostname = metric.host
val runEvery = metric.runInterval
val prefix = metric.cluster + ":"
val serviceDescription = if (arrayOf("splunk", "splunk-staging").contains(hostname) &&
!metric.monitor.startsWith(prefix)) {
prefix + metric.monitor
} else {
metric.monitor
}
val delay = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - timestamp
val outputMessage = if ((runEvery == 0 && delay > 3600) || (runEvery != 0 && delay > 10 * runEvery)) {
"(lagged " + TimeUnit.MINUTES.convert(delay, TimeUnit.SECONDS) + "mins) " + metric.output
} else {
metric.output
}
return buildString {
append("[")
append(timestamp).append("] PROCESS_SERVICE_CHECK_RESULT;")
append(hostname)
append(SEMI)
append(serviceDescription)
append(SEMI)
append(metric.status)
append(SEMI)
append(outputMessage)
append("|")
if (metric.metrics.isNotEmpty()) {
metric.metrics.forEach({
append(it.key)
append(EQUAL)
append(it.value)
append(SEMI)
})
removeSuffix(SEMI)
}
}
}
private fun getNagiosHost(cluster: String, host: String) : String? {
val bucket = calculateBucket(host)
val nagiosClusterConfig = vertx.sharedData().getLocalMap<String, NagiosClusters?>("configs").get(NagiosClusterLoader.NAME)
return nagiosClusterConfig?.getHost(cluster, bucket)
}
private fun calculateBucket(host: String) : Int {
return host.toByteArray(Charsets.UTF_8).sum() % 100
}
private fun attachStatusMetrics(metric: com.arpnetworking.metrics.Metrics, statusCode: Int) {
var count2xx: Long = 0
var count4xx: Long = 0
var count5xx: Long = 0
var countOther: Long = 0
when (statusCode) {
in 200..299 -> count2xx = 1
in 400..499 -> count4xx = 1
in 500..599 -> count5xx = 1
else -> countOther = 1
}
metric.incrementCounter(APP_METRICS_PREFIX + "/status/2xx", count2xx)
metric.incrementCounter(APP_METRICS_PREFIX + "/status/4xx", count4xx)
metric.incrementCounter(APP_METRICS_PREFIX + "/status/5xx", count5xx)
metric.incrementCounter(APP_METRICS_PREFIX + "/status/other", countOther)
}
}
| apache-2.0 | ad06384630ae06b332a1202ad3a7b8d0 | 37.202186 | 177 | 0.629524 | 4.430292 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/backup/MyBackupDataInput.kt | 1 | 7842 | /*
* Copyright (C) 2014-2019 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.backup
import android.app.backup.BackupDataInput
import android.content.Context
import androidx.documentfile.provider.DocumentFile
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyStorage
import org.andstatus.app.util.DocumentFileUtils
import org.andstatus.app.util.JsonUtils
import org.andstatus.app.util.MyLog
import org.json.JSONObject
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
class MyBackupDataInput {
private val context: Context
private var myContext: MyContext? = null
private var backupDataInput: BackupDataInput? = null
private var docFolder: DocumentFile? = null
private val headers: MutableSet<BackupHeader> = TreeSet()
private var keysIterator: MutableIterator<BackupHeader>? = null
private var mHeaderReady = false
private var dataOffset = 0
private var header = BackupHeader.getEmpty()
internal class BackupHeader(var key: String, var ordinalNumber: Long, var dataSize: Int, var fileExtension: String) : Comparable<BackupHeader> {
override fun compareTo(other: BackupHeader): Int {
return java.lang.Long.compare(ordinalNumber, other.ordinalNumber)
}
override fun hashCode(): Int {
val prime = 31
var result = 1
result = prime * result + dataSize
result = prime * result + fileExtension.hashCode()
result = prime * result + key.hashCode()
result = prime * result + (ordinalNumber xor (ordinalNumber ushr 32)).toInt()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is BackupHeader) {
return false
}
if (dataSize != other.dataSize) {
return false
}
if (fileExtension != other.fileExtension) {
return false
}
if (key != other.key) {
return false
}
return if (ordinalNumber != other.ordinalNumber) {
false
} else true
}
override fun toString(): String {
return ("BackupHeader [key=" + key + ", ordinalNumber=" + ordinalNumber + ", dataSize="
+ dataSize + "]")
}
companion object {
fun getEmpty(): BackupHeader {
return BackupHeader("", 0, 0, "")
}
fun fromJson(jso: JSONObject): BackupHeader {
return BackupHeader(
JsonUtils.optString(jso, MyBackupDataOutput.KEY_KEYNAME),
jso.optLong(MyBackupDataOutput.KEY_ORDINAL_NUMBER, 0),
jso.optInt(MyBackupDataOutput.KEY_DATA_SIZE, 0),
JsonUtils.optString(jso, MyBackupDataOutput.KEY_FILE_EXTENSION,
MyBackupDataOutput.DATA_FILE_EXTENSION_DEFAULT))
}
}
}
internal constructor(context: Context, backupDataInput: BackupDataInput?) {
this.context = context
this.backupDataInput = backupDataInput
}
internal constructor(context: Context, fileFolder: DocumentFile) {
this.context = context
docFolder = fileFolder
for (file in fileFolder.listFiles()) {
val filename = file.name
if (filename != null && filename.endsWith(MyBackupDataOutput.HEADER_FILE_SUFFIX)) {
headers.add(BackupHeader.fromJson(DocumentFileUtils.getJSONObject(context, file)))
}
}
keysIterator = headers.iterator()
}
internal fun listKeys(): MutableSet<BackupHeader> {
return headers
}
/** [BackupDataInput.readNextHeader] */
fun readNextHeader(): Boolean {
return backupDataInput?.readNextHeader() ?: readNextHeader2()
}
private fun readNextHeader2(): Boolean {
mHeaderReady = false
dataOffset = 0
keysIterator?.takeIf { it.hasNext() }?.let { iterator ->
header = iterator.next()
mHeaderReady = if (header.dataSize > 0) {
true
} else {
throw FileNotFoundException("Header is invalid, $header")
}
}
return mHeaderReady
}
/** [BackupDataInput.getKey] */
fun getKey(): String {
return backupDataInput?.getKey() ?: getKey2()
}
private fun getKey2(): String {
return if (mHeaderReady) {
header.key
} else {
throw IllegalStateException(ENTITY_HEADER_NOT_READ)
}
}
/** [BackupDataInput.getDataSize] */
fun getDataSize(): Int {
return backupDataInput?.getDataSize() ?: getDataSize2()
}
private fun getDataSize2(): Int {
return if (mHeaderReady) {
header.dataSize
} else {
throw IllegalStateException(ENTITY_HEADER_NOT_READ)
}
}
/** [BackupDataInput.readEntityData] */
fun readEntityData(data: ByteArray, offset: Int, size: Int): Int {
return backupDataInput?.readEntityData(data, offset, size) ?: readEntityData2(data, offset, size)
}
private fun readEntityData2(data: ByteArray, offset: Int, size: Int): Int {
var bytesRead = 0
if (size > MyStorage.FILE_CHUNK_SIZE) {
throw FileNotFoundException("Size to read is too large: $size")
} else if (size < 1 || dataOffset >= header.dataSize) {
// skip
} else if (mHeaderReady) {
val readData = getBytes(size)
bytesRead = readData.size
System.arraycopy(readData, 0, data, offset, bytesRead)
} else {
throw IllegalStateException("Entity header not read")
}
MyLog.v(this, "key=" + header.key + ", offset=" + dataOffset + ", bytes read=" + bytesRead)
dataOffset += bytesRead
return bytesRead
}
private fun getBytes(size: Int): ByteArray {
val childName = header.key + MyBackupDataOutput.DATA_FILE_SUFFIX + header.fileExtension
val childDocFile = docFolder?.findFile(childName)
?: throw IOException("File '" + childName + "' not found in folder '" + docFolder?.getName() + "'")
return DocumentFileUtils.getBytes(context, childDocFile, dataOffset, size)
}
/** [BackupDataInput.skipEntityData] */
fun skipEntityData() {
backupDataInput?.skipEntityData() ?: skipEntityData2()
}
private fun skipEntityData2() {
mHeaderReady = if (mHeaderReady) {
false
} else {
throw IllegalStateException("Entity header not read")
}
}
fun getDataFolderName(): String {
return docFolder?.getUri()?.toString() ?: "(empty)"
}
fun setMyContext(myContext: MyContext) {
this.myContext = myContext
}
fun getMyContext(): MyContext {
return myContext ?: throw IllegalStateException("Context is null")
}
companion object {
private val ENTITY_HEADER_NOT_READ: String = "Entity header not read"
}
}
| apache-2.0 | 8630bc7e4cbb550036717179305c2130 | 34.008929 | 148 | 0.608901 | 4.957016 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/latisbooks/src/eu/kanade/tachiyomi/extension/en/latisbooks/Latisbooks.kt | 1 | 3875 | package eu.kanade.tachiyomi.extension.en.latisbooks
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import java.util.Calendar
@Nsfw
class Latisbooks : HttpSource() {
override val name = "Latis Books"
override val baseUrl = "https://www.latisbooks.com"
override val lang = "en"
override val supportsLatest = false
override val client: OkHttpClient = network.cloudflareClient
private fun createManga(response: Response): SManga {
return SManga.create().apply {
initialized = true
title = "Bodysuit 23"
url = "/archive/"
thumbnail_url = response.asJsoup().select("img.thumb-image").firstOrNull()?.attr("abs:data-src")
}
}
// Popular
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
return client.newCall(popularMangaRequest(page))
.asObservableSuccess()
.map { response ->
MangasPage(listOf(createManga(response)), false)
}
}
override fun popularMangaRequest(page: Int): Request {
return (GET("$baseUrl/archive/", headers))
}
override fun popularMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Latest
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Search
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = Observable.just(MangasPage(emptyList(), false))
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException("Not used")
override fun searchMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Details
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
createManga(response)
}
}
override fun mangaDetailsParse(response: Response): SManga = throw UnsupportedOperationException("Not used")
// Chapters
override fun chapterListParse(response: Response): List<SChapter> {
val cal: Calendar = Calendar.getInstance()
return response.asJsoup().select("ul.archive-item-list li a").map {
val date: List<String> = it.attr("abs:href").split("/")
cal.set(date[4].toInt(), date[5].toInt() - 1, date[6].toInt())
SChapter.create().apply {
name = it.text()
url = it.attr("abs:href")
date_upload = cal.timeInMillis
}
}
}
// Pages
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
return Observable.just(listOf(Page(0, chapter.url)))
}
override fun pageListParse(response: Response): List<Page> = throw UnsupportedOperationException("Not used")
override fun imageUrlParse(response: Response): String {
return response.asJsoup().select("div.content-wrapper img.thumb-image").attr("abs:data-src")
}
override fun getFilterList() = FilterList()
}
| apache-2.0 | 180bd28dd41bf7414497e94d1163bee0 | 33.292035 | 154 | 0.688 | 4.754601 | false | false | false | false |
googleads/googleads-mobile-android-examples | kotlin/advanced/APIDemo/app/src/main/java/com/google/android/gms/example/apidemo/MainActivity.kt | 1 | 2893 | package com.google.android.gms.example.apidemo
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.example.apidemo.databinding.ActivityMainBinding
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private lateinit var mainActivityBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainActivityBinding.root)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
// Initialize the Mobile Ads SDK with an empty completion listener.
MobileAds.initialize(this) {}
val toggle =
ActionBarDrawerToggle(
this,
mainActivityBinding.drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
mainActivityBinding.drawerLayout.addDrawerListener(toggle)
toggle.syncState()
mainActivityBinding.navView.setNavigationItemSelectedListener(this)
val trans = this.supportFragmentManager.beginTransaction()
trans.replace(R.id.container, AdMobAdListenerFragment())
trans.commit()
}
override fun onBackPressed() {
if (mainActivityBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
mainActivityBinding.drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val trans = this.supportFragmentManager.beginTransaction()
val newFragment =
when (item.itemId) {
R.id.nav_admob_adlistener -> AdMobAdListenerFragment()
R.id.nav_admob_adtargeting -> AdMobAdTargetingFragment()
R.id.nav_admob_bannersizes -> AdMobBannerSizesFragment()
R.id.nav_admob_custommute -> AdMobCustomMuteThisAdFragment()
R.id.nav_gam_adsizes -> AdManagerMultipleAdSizesFragment()
R.id.nav_gam_appevents -> AdManagerAppEventsFragment()
R.id.nav_gam_customtargeting -> AdManagerCustomTargetingFragment()
R.id.nav_gam_fluid -> AdManagerFluidSizeFragment()
R.id.nav_gam_ppid -> AdManagerPPIDFragment()
R.id.nav_gam_customcontrols -> AdManagerCustomControlsFragment()
else -> AdManagerCategoryExclusionFragment()
}
trans.replace(R.id.container, newFragment)
trans.commit()
mainActivityBinding.drawerLayout.closeDrawer(GravityCompat.START)
return true
}
companion object {
const val LOG_TAG = "APIDEMO"
}
}
| apache-2.0 | 3bf74500af32e14a7640d5a22e0faf50 | 35.1625 | 91 | 0.751815 | 4.742623 | false | false | false | false |
czyzby/ktx | style/src/test/kotlin/ktx/style/StyleTest.kt | 2 | 18246 | package ktx.style
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle
import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle
import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle
import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle
import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle
import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle
import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import io.kotlintest.matchers.shouldBe
import io.kotlintest.matchers.shouldNotBe
import io.kotlintest.mock.mock
import ktx.style.StyleTest.TestEnum.TEST
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
/**
* Tests [Skin] building utilities.
*/
class StyleTest {
@Test
fun `should use valid default style name`() {
val skin = Skin()
skin.add(defaultStyle, "Mock resource.")
// Calling getter without resource name - should default to "default":
val resource = skin[String::class.java]
resource shouldNotBe null
resource shouldBe "Mock resource."
// If this test fails, libGDX changed name of default resources or removed the unnamed resource getter.
}
@Test
fun `should create new skin`() {
val skin = skin()
skin shouldNotBe null
}
@Test
fun `should create new skin with init block`() {
val skin = skin {
add("mock", "Test.")
}
skin shouldNotBe null
skin.get("mock", String::class.java) shouldNotBe null
}
@Test
fun `should configure skin exactly once`() {
val variable: Int
skin {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should create new skin with TextureAtlas`() {
val skin = skin(TextureAtlas())
skin shouldNotBe null
}
@Test
fun `should create new skin with TextureAtlas and init block`() {
val skin = skin(TextureAtlas()) {
add("mock", "Test.")
}
skin shouldNotBe null
skin.get("mock", String::class.java) shouldNotBe null
}
@Test
fun `should configure skin with TextureAtlas exactly once`() {
val variable: Int
skin(TextureAtlas()) {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should register assets`() {
val skin = Skin()
skin.register {
add("mock", "Test.")
}
skin.get("mock", String::class.java) shouldNotBe null
}
@Test
fun `should register assets exactly once`() {
val skin = Skin()
val variable: Int
skin.register {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should extract resource with explicit reified type`() {
val skin = Skin()
skin.add("mock", "Test.")
val resource = skin.get<String>("mock")
resource shouldBe "Test."
}
@Test
fun `should extract resource with implicit reified type`() {
val skin = Skin()
skin.add("mock", "Test.")
val reified: String = skin["mock"]
reified shouldBe "Test."
}
@Test
fun `should extract optional resource with default style name`() {
val skin = Skin()
skin.add(defaultStyle, "Test.")
skin.optional<String>() shouldBe "Test."
}
@Test
fun `should extract optional resource`() {
val skin = Skin()
skin.add("mock", "Test.")
skin.optional<String>("mock") shouldBe "Test."
}
@Test
fun `should extract optional resource and return null`() {
val skin = Skin()
skin.add("asset", "Test.")
skin.optional<Color>("mock") shouldBe null
}
@Test
fun `should extract resource with default style name`() {
val skin = Skin()
skin[defaultStyle] = "Asset."
skin.get<String>() shouldBe "Asset."
}
@Test
fun `should add resources with brace operator`() {
val skin = Skin()
skin["name"] = "Asset."
skin.get<String>("name") shouldBe "Asset."
}
@Test
fun `should add resource with brace operator with enum name`() {
val skin = Skin()
skin[TEST] = "Test."
skin.get<String>("TEST") shouldBe "Test."
}
@Test
fun `should extract resource with brace operator with enum name`() {
val skin = Skin()
skin["TEST"] = "Test."
val resource: String = skin[TEST]
resource shouldBe "Test."
}
@Test
fun `should add and extract resource with brace operator with enum name`() {
val skin = Skin()
skin[TEST] = "Test."
val resource: String = skin[TEST]
resource shouldBe "Test."
}
@Test
fun `should add existing style to skin`() {
val skin = Skin()
val existing = LabelStyle()
skin.addStyle("mock", existing)
val style = skin.get<LabelStyle>("mock")
assertSame(existing, style)
}
@Test
fun `should add existing style to skin with init block`() {
val skin = Skin()
val existing = LabelStyle()
skin.addStyle("mock", existing) {
fontColor = Color.BLACK
}
val style = skin.get<LabelStyle>("mock")
assertSame(existing, style)
style.fontColor shouldBe Color.BLACK
}
@Test
fun `should add resource with default style name`() {
val skin = Skin()
skin.add("Test.")
skin.get<String>() shouldBe "Test."
}
@Test
fun `should add resource with default style name with plusAssign`() {
val skin = Skin()
skin += "Test."
skin.get<String>() shouldBe "Test."
}
@Test
fun `should remove resource with default style name`() {
val skin = Skin()
skin.add(defaultStyle, "Test.")
skin.remove<String>()
skin.has(defaultStyle, String::class.java) shouldBe false
}
@Test
fun `should remove resource`() {
val skin = Skin()
skin.add("mock", "Test.")
skin.remove<String>("mock")
skin.has("mock", String::class.java) shouldBe false
}
@Test
fun `should check if resource is present`() {
val skin = Skin()
skin.add("mock", "Test.")
skin.has<String>("mock") shouldBe true
skin.has<String>("mock-2") shouldBe false
}
@Test
fun `should check if resource with default style name is present`() {
val skin = Skin()
skin.add(defaultStyle, "Test.")
skin.has<String>() shouldBe true
}
@Test
fun `should return a map of all resources of a type`() {
val skin = Skin()
skin.add("mock-1", "Test.")
skin.add("mock-2", "Test 2.")
skin.getAll<String>()!!.size shouldBe 2
}
@Test
fun `should return null if resource is not in skin`() {
val skin = Skin()
skin.getAll<String>() shouldBe null
}
@Test
fun `should add color`() {
val skin = Skin()
skin.color("black", red = 0f, green = 0f, blue = 0f)
skin.getColor("black") shouldBe Color.BLACK
}
@Test
fun `should add ButtonStyle`() {
val skin = skin {
button {
pressedOffsetX = 1f
}
}
val style = skin.get<ButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend ButtonStyle`() {
val skin = skin {
button("base") {
pressedOffsetX = 1f
}
button("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<ButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add CheckBoxStyle`() {
val skin = skin {
checkBox {
pressedOffsetX = 1f
}
}
val style = skin.get<CheckBoxStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend CheckBoxStyle`() {
val skin = skin {
checkBox("base") {
pressedOffsetX = 1f
}
checkBox("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<CheckBoxStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add ImageButtonStyle`() {
val skin = skin {
imageButton {
pressedOffsetX = 1f
}
}
val style = skin.get<ImageButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend ImageButtonStyle`() {
val skin = skin {
imageButton("base") {
pressedOffsetX = 1f
}
imageButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<ImageButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add ImageTextButtonStyle`() {
val skin = skin {
imageTextButton {
pressedOffsetX = 1f
}
}
val style = skin.get<ImageTextButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend ImageTextButtonStyle`() {
val skin = skin {
imageTextButton("base") {
pressedOffsetX = 1f
}
imageTextButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<ImageTextButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add LabelStyle`() {
val skin = skin {
label {
fontColor = Color.BLACK
}
}
val style = skin.get<LabelStyle>(defaultStyle)
assertEquals(Color.BLACK, style.fontColor)
}
@Test
fun `should extend LabelStyle`() {
val skin = skin {
label("base") {
fontColor = Color.BLACK
}
label("new", extend = "base") {
}
}
val style = skin.get<LabelStyle>("new")
assertEquals(Color.BLACK, style.fontColor)
}
@Test
fun `should add ListStyle`() {
val skin = skin {
list {
fontColorSelected = Color.BLACK
}
}
val style = skin.get<ListStyle>(defaultStyle)
assertEquals(Color.BLACK, style.fontColorSelected)
}
@Test
fun `should extend ListStyle`() {
val skin = skin {
list("base") {
fontColorSelected = Color.BLACK
}
list("new", extend = "base") {
fontColorUnselected = Color.CYAN
}
}
val style = skin.get<ListStyle>("new")
assertEquals(Color.BLACK, style.fontColorSelected)
assertEquals(Color.CYAN, style.fontColorUnselected)
}
@Test
fun `should add ProgressBarStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
progressBar {
background = drawable
}
}
val style = skin.get<ProgressBarStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend ProgressBarStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
progressBar("base") {
background = drawable
}
progressBar("new", extend = "base") {
knob = drawable
}
}
val style = skin.get<ProgressBarStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.knob)
}
@Test
fun `should add ScrollPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
scrollPane {
background = drawable
}
}
val style: ScrollPaneStyle = skin.get()
assertEquals(drawable, style.background)
}
@Test
fun `should extend ScrollPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
scrollPane("base") {
background = drawable
}
scrollPane("new", extend = "base") {
corner = drawable
}
}
val style = skin.get<ScrollPaneStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.corner)
}
@Test
fun `should add SelectBoxStyle`() {
val skin = skin {
selectBox {
fontColor = Color.CYAN
}
}
val style = skin.get<SelectBoxStyle>(defaultStyle)
assertEquals(Color.CYAN, style.fontColor)
}
@Test
fun `should extend SelectBoxStyle`() {
val skin = skin {
list() // Necessary for copy constructor.
scrollPane()
selectBox("base") {
listStyle = it[defaultStyle]
scrollStyle = it[defaultStyle]
fontColor = Color.CYAN
}
selectBox("new", extend = "base") {
disabledFontColor = Color.BLACK
}
}
val style = skin.get<SelectBoxStyle>("new")
assertEquals(Color.CYAN, style.fontColor)
assertEquals(Color.BLACK, style.disabledFontColor)
}
@Test
fun `should add SliderStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
slider {
background = drawable
}
}
val style = skin.get<SliderStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend SliderStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
slider("base") {
background = drawable
}
slider("new", extend = "base") {
knob = drawable
}
}
val style = skin.get<SliderStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.knob)
}
@Test
fun `should add SplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
splitPane {
handle = drawable
}
}
val style = skin.get<SplitPaneStyle>(defaultStyle)
assertEquals(drawable, style.handle)
}
@Test
fun `should extend SplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
splitPane("base") {
handle = drawable
}
splitPane("new", extend = "base")
}
val style = skin.get<SplitPaneStyle>("new")
assertEquals(drawable, style.handle)
}
@Test
fun `should add TextButtonStyle`() {
val skin = skin {
textButton {
pressedOffsetX = 1f
}
}
val style = skin.get<TextButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend TextButtonStyle`() {
val skin = skin {
textButton("base") {
pressedOffsetX = 1f
}
textButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<TextButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add TextFieldStyle`() {
val skin = skin {
textField {
fontColor = Color.CYAN
}
}
val style = skin.get<TextFieldStyle>(defaultStyle)
assertEquals(Color.CYAN, style.fontColor)
}
@Test
fun `should extend TextFieldStyle`() {
val skin = skin {
textField("base") {
fontColor = Color.CYAN
}
textField("new", extend = "base") {
disabledFontColor = Color.BLACK
}
}
val style = skin.get<TextFieldStyle>("new")
assertEquals(Color.CYAN, style.fontColor)
assertEquals(Color.BLACK, style.disabledFontColor)
}
@Test
fun `should add TextTooltipStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
textTooltip {
background = drawable
}
}
val style = skin.get<TextTooltipStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend TextTooltipStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
textTooltip("base") {
label = it.label() // Necessary for copy constructor.
background = drawable
}
textTooltip("new", extend = "base") {
wrapWidth = 1f
}
}
val style = skin.get<TextTooltipStyle>("new")
assertEquals(drawable, style.background)
assertEquals(1f, style.wrapWidth)
}
@Test
fun `should add TouchpadStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
touchpad {
knob = drawable
}
}
val style = skin.get<TouchpadStyle>(defaultStyle)
assertEquals(drawable, style.knob)
}
@Test
fun `should extend TouchpadStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
touchpad("base") {
knob = drawable
}
touchpad("new", extend = "base") {
background = drawable
}
}
val style = skin.get<TouchpadStyle>("new")
assertEquals(drawable, style.knob)
assertEquals(drawable, style.background)
}
@Test
fun `should add TreeStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
tree {
plus = drawable
}
}
val style = skin.get<TreeStyle>(defaultStyle)
assertEquals(drawable, style.plus)
}
@Test
fun `should extend TreeStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
tree("base") {
plus = drawable
}
tree("new", extend = "base") {
minus = drawable
}
}
val style = skin.get<TreeStyle>("new")
assertEquals(drawable, style.plus)
assertEquals(drawable, style.minus)
}
@Test
fun `should add WindowStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
window {
background = drawable
}
}
val style = skin.get<WindowStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend WindowStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
window("base") {
background = drawable
}
window("new", extend = "base") {
stageBackground = drawable
}
}
val style = skin.get<WindowStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.stageBackground)
}
/** For [StyleTest] tests. */
internal enum class TestEnum {
TEST
}
}
| cc0-1.0 | 7409884621f38cc805c4f930e9aa6fd4 | 21.062878 | 107 | 0.624192 | 4.083706 | false | true | false | false |
ilya-g/kotlinx.collections.experimental | kotlinx-collections-experimental/benchmarks/src/main/kotlin/GroupCount.kt | 1 | 1482 | package kotlinx.collections.experimental.benchmarks
import kotlinx.collections.experimental.grouping.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.stream.Collectors
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
open class GroupCount {
@Param("100", "100000")
open var elements = 0
val buckets = 100
private lateinit var data: List<Element>
@Setup
fun createValues() {
data = generateElements(elements, buckets)
}
@Benchmark
fun naive() = data.groupBy { it.key }.mapValues { it.value.size }
@Benchmark
fun countGroup() = data.groupCountBy { it.key }
@Benchmark
fun countGrouping() = data.groupingBy { it.key }.eachCount()
@Benchmark
fun countGroupingAtomic() =
data.groupingBy { it.key }
.fold(AtomicInteger(0)) { acc, e -> acc.apply { incrementAndGet() }}
.mapValues { it.value.get() }
@Benchmark
fun countGroupingRef() = data.groupingBy { it.key }.eachCountRef()
@Benchmark
fun countGroupingRefInPlace() = data.groupingBy { it.key }.eachCountRefInPlace()
@Benchmark
fun countGroupingReducer() = data.groupingBy { it.key }.reduce(Count)
@Benchmark
fun countGroupingReducerRef() = data.groupingBy { it.key }.reduce(CountWithRef)
@Benchmark
fun countGroupingCollector() = data.groupingBy { it.key }.eachCollect(Collectors.counting())
}
| apache-2.0 | 908b656d7c26e935750cf5aa313324d5 | 25.464286 | 96 | 0.676113 | 4.283237 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/playground_access/AddPlaygroundAccess.kt | 1 | 981 | package de.westnordost.streetcomplete.quests.playground_access
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddPlaygroundAccess : OsmFilterQuestType<Boolean>() {
override val elementFilter = "nodes, ways, relations with leisure = playground and (!access or access = unknown)"
override val commitMessage = "Add playground access"
override val wikiLink = "Tag:leisure=playground"
override val icon = R.drawable.ic_quest_playground
override fun getTitle(tags: Map<String, String>) = R.string.quest_playground_access_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("access", if (answer) "yes" else "private")
}
}
| gpl-3.0 | a1a9b82a943b3a1a15cc1fe94e79d421 | 43.590909 | 117 | 0.783894 | 4.762136 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/upload/UploadController.kt | 1 | 1976 | package de.westnordost.streetcomplete.data.upload
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import javax.inject.Inject
import javax.inject.Singleton
/** Controls uploading */
@Singleton class UploadController @Inject constructor(
private val context: Context
): UploadProgressSource {
private var uploadServiceIsBound = false
private var uploadService: UploadService.Interface? = null
private val uploadServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
uploadService = service as UploadService.Interface
uploadService?.setProgressListener(uploadProgressRelay)
}
override fun onServiceDisconnected(className: ComponentName) {
uploadService = null
}
}
private val uploadProgressRelay = UploadProgressRelay()
override val isUploadInProgress: Boolean get() =
uploadService?.isUploadInProgress == true
init {
bindServices()
}
/** Collect and upload all changes made by the user */
fun upload() {
context.startService(UploadService.createIntent(context))
}
private fun bindServices() {
uploadServiceIsBound = context.bindService(
Intent(context, UploadService::class.java),
uploadServiceConnection, Context.BIND_AUTO_CREATE
)
}
private fun unbindServices() {
if (uploadServiceIsBound) context.unbindService(uploadServiceConnection)
uploadServiceIsBound = false
}
override fun addUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.addListener(listener)
}
override fun removeUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.removeListener(listener)
}
} | gpl-3.0 | fdb8963df9114e7bcf7392364c4c62c1 | 31.95 | 89 | 0.727733 | 5.811765 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_search/dialog/CourseSearchDialogFragment.kt | 1 | 13066 | package org.stepik.android.view.course_search.dialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.SearchView
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.core.presenters.SearchSuggestionsPresenter
import org.stepic.droid.core.presenters.contracts.SearchSuggestionsView
import org.stepic.droid.databinding.DialogCourseSearchBinding
import org.stepic.droid.model.SearchQuery
import org.stepic.droid.model.SearchQuerySource
import org.stepic.droid.ui.custom.AutoCompleteSearchView
import org.stepik.android.domain.course_search.analytic.CourseContentSearchScreenOpenedAnalyticEvent
import org.stepik.android.domain.course_search.model.CourseSearchResultListItem
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.presentation.course_search.CourseSearchFeature
import org.stepik.android.presentation.course_search.CourseSearchViewModel
import org.stepik.android.view.course_search.adapter.delegate.CourseSearchResultAdapterDelegate
import org.stepik.android.view.lesson.ui.activity.LessonActivity
import ru.nobird.android.core.model.PaginationDirection
import ru.nobird.android.presentation.redux.container.ReduxView
import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.delegate.ViewStateDelegate
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.setOnPaginationListener
import ru.nobird.android.view.redux.ui.extension.reduxViewModel
import javax.inject.Inject
class CourseSearchDialogFragment :
DialogFragment(),
ReduxView<CourseSearchFeature.State, CourseSearchFeature.Action.ViewAction>,
SearchSuggestionsView,
AutoCompleteSearchView.FocusCallback,
AutoCompleteSearchView.SuggestionClickCallback {
companion object {
const val TAG = "CourseSearchDialogFragment"
fun newInstance(courseId: Long, courseTitle: String): DialogFragment =
CourseSearchDialogFragment().apply {
this.courseId = courseId
this.courseTitle = courseTitle
}
}
@Inject
lateinit var analytic: Analytic
@Inject
lateinit var screenManager: ScreenManager
@Inject
lateinit var searchSuggestionsPresenter: SearchSuggestionsPresenter
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
private val courseSearchViewModel: CourseSearchViewModel by reduxViewModel(this) { viewModelFactory }
private val viewStateDelegate = ViewStateDelegate<CourseSearchFeature.State>()
private val courseSearchResultItemsAdapter = DefaultDelegateAdapter<CourseSearchResultListItem>()
private var courseId: Long by argument()
private var courseTitle: String by argument()
private val courseSearchBinding: DialogCourseSearchBinding by viewBinding(DialogCourseSearchBinding::bind)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
analytic.report(CourseContentSearchScreenOpenedAnalyticEvent(courseId, courseTitle))
setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.dialog_course_search, container, false)
private fun injectComponent() {
App.component()
.courseSearchComponentBuilder()
.courseId(courseId)
.build()
.inject(this)
}
private fun initViewStateDelegate() {
viewStateDelegate.addState<CourseSearchFeature.State.Idle>(courseSearchBinding.courseSearchIdle.courseSearchIdleContainer)
viewStateDelegate.addState<CourseSearchFeature.State.Error>(courseSearchBinding.courseSearchError.error)
viewStateDelegate.addState<CourseSearchFeature.State.Loading>(courseSearchBinding.courseSearchRecycler)
viewStateDelegate.addState<CourseSearchFeature.State.Empty>(courseSearchBinding.courseSearchEmpty.reportProblem)
viewStateDelegate.addState<CourseSearchFeature.State.Content>(courseSearchBinding.courseSearchRecycler)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupSearchBar()
initViewStateDelegate()
courseSearchResultItemsAdapter += adapterDelegate(
layoutResId = R.layout.item_course_search_result_loading,
isForViewType = { _, data -> data is CourseSearchResultListItem.Placeholder }
)
courseSearchResultItemsAdapter += CourseSearchResultAdapterDelegate(
onLogEventAction = { stepId, type ->
courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.CourseContentSearchResultClickedEventMessage(
courseId = courseId,
courseTitle = courseTitle,
query = courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString(),
type = type,
step = stepId
))
},
onOpenStepAction = { lesson, unit, section, stepPosition ->
val lessonData = LessonData(
lesson = lesson,
unit = unit,
section = section,
course = null,
stepPosition = stepPosition?.let { it - 1 } ?: 0
)
val intent = LessonActivity.createIntent(requireContext(), lessonData)
requireActivity().startActivity(intent)
},
onOpenCommentAction = { lesson, unit, section, stepPosition, discussionId ->
val lessonData = LessonData(
lesson = lesson,
unit = unit,
section = section,
course = null,
stepPosition = stepPosition?.let { it - 1 } ?: 0,
discussionId = discussionId
)
val intent = LessonActivity.createIntent(requireContext(), lessonData)
requireActivity().startActivity(intent)
}
)
with(courseSearchBinding.courseSearchRecycler) {
adapter = courseSearchResultItemsAdapter
itemAnimator = null
layoutManager = LinearLayoutManager(requireContext())
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
AppCompatResources.getDrawable(context, R.drawable.bg_divider_vertical_course_search)?.let(::setDrawable)
})
setOnPaginationListener { paginationDirection ->
if (paginationDirection == PaginationDirection.NEXT) {
courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.FetchNextPage(courseId, courseTitle, courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString()))
}
}
}
courseSearchBinding.courseSearchError.tryAgain.setOnClickListener {
onQueryTextSubmit(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString(), isSuggestion = false)
}
}
override fun onStart() {
super.onStart()
searchSuggestionsPresenter.attachView(this)
}
override fun onStop() {
searchSuggestionsPresenter.detachView(this)
super.onStop()
}
override fun onAction(action: CourseSearchFeature.Action.ViewAction) {
// no op
}
override fun render(state: CourseSearchFeature.State) {
viewStateDelegate.switchState(state)
if (state is CourseSearchFeature.State.Loading) {
courseSearchResultItemsAdapter.items = listOf(
CourseSearchResultListItem.Placeholder,
CourseSearchResultListItem.Placeholder,
CourseSearchResultListItem.Placeholder,
CourseSearchResultListItem.Placeholder,
CourseSearchResultListItem.Placeholder
)
}
if (state is CourseSearchFeature.State.Content) {
courseSearchResultItemsAdapter.items =
if (state.isLoadingNextPage) {
state.courseSearchResultListDataItems + CourseSearchResultListItem.Placeholder
} else {
state.courseSearchResultListDataItems
}
}
}
override fun setSuggestions(suggestions: List<SearchQuery>, source: SearchQuerySource) {
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setSuggestions(suggestions, source)
}
override fun onFocusChanged(hasFocus: Boolean) {
if (hasFocus) {
searchSuggestionsPresenter.onQueryTextChange(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString())
}
}
private fun setupSearchBar() {
courseSearchBinding.viewSearchToolbarBinding.viewCenteredToolbarBinding.centeredToolbar.isVisible = false
courseSearchBinding.viewSearchToolbarBinding.backIcon.isVisible = true
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.isVisible = true
(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, 0, 0)
setupSearchView(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar)
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setFocusCallback(this)
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setSuggestionClickCallback(this)
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setIconifiedByDefault(false)
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setBackgroundColor(0)
courseSearchBinding.viewSearchToolbarBinding.backIcon.setOnClickListener {
val hasFocus = courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.hasFocus()
if (hasFocus) {
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.clearFocus()
} else {
dismiss()
}
}
}
private fun setupSearchView(searchView: AutoCompleteSearchView) {
searchView.initSuggestions(courseSearchBinding.courseSearchContainer)
(searchView.findViewById(androidx.appcompat.R.id.search_mag_icon) as ImageView).setImageResource(0)
searchView.queryHint = getString(R.string.course_search_hint, courseTitle)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
onQueryTextSubmit(query, isSuggestion = false)
return true
}
override fun onQueryTextChange(query: String): Boolean {
courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setConstraint(query)
searchSuggestionsPresenter.onQueryTextChange(query)
return false
}
})
searchView.onActionViewExpanded()
searchView.clearFocus()
}
override fun onQueryTextSubmitSuggestion(query: String) {
onQueryTextSubmit(query, isSuggestion = true)
}
private fun onQueryTextSubmit(query: String, isSuggestion: Boolean) {
searchSuggestionsPresenter.onQueryTextSubmit(query)
with(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar) {
onActionViewCollapsed()
onActionViewExpanded()
clearFocus()
setQuery(query, false)
}
courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.CourseContentSearchedEventMessage(courseId, courseTitle, query, isSuggestion = isSuggestion))
courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.FetchCourseSearchResultsInitial(courseId, courseTitle, query, isSuggestion = isSuggestion))
}
} | apache-2.0 | af261eb8d1a0bf5e1398ac00a5f5ec99 | 44.849123 | 201 | 0.720113 | 6.071561 | false | false | false | false |
zlyne0/colonization | core/src/net/sf/freecol/common/model/ai/missions/pioneer/ReplaceColonyWorkerMission.kt | 1 | 3742 | package net.sf.freecol.common.model.ai.missions.pioneer
import net.sf.freecol.common.model.Colony
import net.sf.freecol.common.model.ColonyId
import net.sf.freecol.common.model.Game
import net.sf.freecol.common.model.Unit
import net.sf.freecol.common.model.UnitId
import net.sf.freecol.common.model.ai.missions.AbstractMission
import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer
import net.sf.freecol.common.model.ai.missions.UnitMissionsMapping
import net.sf.freecol.common.model.player.Player
import promitech.colonization.ai.CommonMissionHandler
import promitech.colonization.savegame.XmlNodeAttributes
import promitech.colonization.savegame.XmlNodeAttributesWriter
class ReplaceColonyWorkerMission : AbstractMission {
val colonyId: ColonyId
val colonyWorkerUnitId: UnitId
val replaceByUnit: Unit
constructor(colony: Colony, colonyWorkerUnit: Unit, replaceByUnit: Unit) : super(Game.idGenerator.nextId(ReplaceColonyWorkerMission::class.java)) {
this.colonyId = colony.id
this.colonyWorkerUnitId = colonyWorkerUnit.id
this.replaceByUnit = replaceByUnit
}
private constructor(missionId: String, replaceByUnit: Unit, colonyId: ColonyId, workerUnitId: UnitId) : super(missionId) {
this.replaceByUnit = replaceByUnit
this.colonyId = colonyId
this.colonyWorkerUnitId = workerUnitId
}
override fun blockUnits(unitMissionsMapping: UnitMissionsMapping) {
unitMissionsMapping.blockUnit(replaceByUnit, this)
unitMissionsMapping.blockUnit(colonyWorkerUnitId, this)
}
override fun unblockUnits(unitMissionsMapping: UnitMissionsMapping) {
unitMissionsMapping.unblockUnitFromMission(replaceByUnit, this)
unitMissionsMapping.unblockUnitFromMission(colonyWorkerUnitId, this)
}
internal fun isUnitExists(player: Player): Boolean {
return CommonMissionHandler.isUnitExists(player, replaceByUnit)
}
fun colony(): Colony {
return replaceByUnit.owner.settlements.getById(colonyId).asColony()
}
internal fun isWorkerExistsInColony(player: Player): Boolean {
val colony = player.settlements.getByIdOrNull(colonyId)
if (colony == null) {
return false
}
return colony.asColony().isUnitInColony(colonyWorkerUnitId)
}
override fun toString(): String {
return "ReplaceColonyWorkerMission: missionId: ${id}, replaceByUnit: ${replaceByUnit.id}, colonyId: ${colonyId}, workerUnitId: ${colonyWorkerUnitId}"
}
class Xml : AbstractMission.Xml<ReplaceColonyWorkerMission>() {
private val ATTR_UNIT = "unit"
private val ATTR_COLONY = "colony"
private val ATTR_WORKER = "worker"
override fun startElement(attr: XmlNodeAttributes) {
nodeObject = ReplaceColonyWorkerMission(
attr.id,
PlayerMissionsContainer.Xml.getPlayerUnit(attr.getStrAttribute(ATTR_UNIT)),
attr.getStrAttribute(ATTR_COLONY),
attr.getStrAttribute(ATTR_WORKER)
)
super.startElement(attr)
}
override fun startWriteAttr(mission: ReplaceColonyWorkerMission, attr: XmlNodeAttributesWriter) {
super.startWriteAttr(mission, attr)
attr.setId(mission)
attr.set(ATTR_UNIT, mission.replaceByUnit)
attr.set(ATTR_COLONY, mission.colonyId)
attr.set(ATTR_WORKER, mission.colonyWorkerUnitId)
}
override fun getTagName(): String {
return tagName()
}
companion object {
@JvmStatic
fun tagName(): String {
return "replaceColonyWorkerMission"
}
}
}
} | gpl-2.0 | 9d659ac4c86df36163aa9bd4fa708892 | 36.808081 | 157 | 0.703367 | 4.718789 | false | false | false | false |
MKA-Nigeria/MKAN-Report-Android | videos_module/src/main/java/com/abdulmujibaliu/koutube/data/models/deserializers/Deserializers.kt | 1 | 9601 | package com.abdulmujibaliu.koutube.data.models.deserializers
import android.util.Log
import com.abdulmujibaliu.koutube.data.KutConstants
import com.abdulmujibaliu.koutube.data.models.*
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import java.lang.reflect.Type
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
/**
* Created by abdulmujibaliu on 10/16/17.
*/
open abstract class BaseDeserializer : JsonDeserializer<BaseModelWrapper> {
val TAG = javaClass.simpleName
fun findDetails(json: JsonElement?, baseModel: BaseModel) {
baseModel.itemID = json!!.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString
if (json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET) != null && !json.asJsonObject.getAsJsonObject(KutConstants.SNIPPET).isJsonNull) {
val snippetObject: JsonElement? = json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET)
var dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
val dateTime = dtf.parseDateTime(snippetObject?.asJsonObject?.get(KutConstants.VIDEO_PUBSLISHED_AT)?.asString)
val title = snippetObject?.asJsonObject?.get(KutConstants.VIDEO_TITLE)?.asString
val desc = snippetObject?.asJsonObject?.get(KutConstants.VIDEO_DESCRIPTION)?.asString
if (snippetObject!!.asJsonObject.get(KutConstants.VIDEO_CHANNEL_NAME) != null) {
val channelName = snippetObject.asJsonObject.get(KutConstants.VIDEO_CHANNEL_TITLE).asString
baseModel.channelName = channelName
}
//Log.d(TAG, "VIDEO DATETIME $dateTime VIDNAME: $title DESC: $desc")
baseModel.datePublished = dateTime
baseModel.itemTitle = title
baseModel.itemDesc = desc
if (snippetObject?.asJsonObject?.getAsJsonObject(KutConstants.VIDEO_THUMBNAILS) != null &&
!snippetObject.asJsonObject?.getAsJsonObject(KutConstants.VIDEO_THUMBNAILS)!!.isJsonNull) {
val thumbNailsObj = snippetObject.asJsonObject?.get(KutConstants.VIDEO_THUMBNAILS)
if (thumbNailsObj != null) {
val standard = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_STANDARD)
val default = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_DEFAULT_IMG)
val maxRes = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_MAXRES_IMG)
val medium = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_MEDIUM_IMG)
val high = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_HIGH_IMG)
//Log.d(TAG, standard.toString())
var resURL: String? = null
when {
maxRes != null -> resURL = maxRes.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString
high != null -> resURL = high.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString
medium != null -> resURL = medium.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString
standard != null -> resURL = standard.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString
default != null -> resURL = default.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString
}
baseModel.itemImageURL = resURL
}
}
/*dtf = DateTimeFormat.forPattern("'PT'mm'M'ss'S'")
if (json.asJsonObject.get(KutConstants.KEY_CONTENT_DETAILS) != null) {
try {
val duration = dtf.parseLocalTime(json.asJsonObject.
get(KutConstants.KEY_CONTENT_DETAILS).asJsonObject.get(KutConstants.VIDEO_VIDEO_DURATION).asString)
baseModel.duration = duration
} catch (e: Exception) {
e.printStackTrace()
}
}
if (json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) != null) {
baseModel.numberOfViews = json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS)
.asJsonObject.get(KutConstants.VIDEO_VIDEO_VIEW_COUNT).asInt
}*/
}
}
}
class ChannelPlaylistsDeserializer : BaseDeserializer() {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): PlayListsResult {
val data = json?.getAsJsonObject()
val itemsList = mutableListOf<BaseModel>()
var playListResult: PlayListsResult? = null
if (data != null && !data.isJsonNull) {
playListResult = PlayListsResult(findIDs(data)!!)
for (jsonElement in data.asJsonObject.get(KutConstants.KEY_ITEMS).asJsonArray) {
val playList = PlayList()
findDetails(jsonElement, playList)
itemsList.add(playList)
}
playListResult.items = itemsList
}
return playListResult!!
}
fun findIDs(jsonObject: JsonObject): MutableList<String>? {
val jsonArray = jsonObject.get(KutConstants.KEY_ITEMS).getAsJsonArray()
var idList: MutableList<String>? = mutableListOf()
if (jsonArray != null && !jsonArray.isJsonNull() && !(jsonArray.size() == 0)) {
for (jsonElement in jsonArray) {
val itemID = jsonElement.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString.replace("\"", "")
Log.d(TAG, itemID)
idList?.add(itemID)
}
}
return idList
}
}
class PlaylistsItemsDeserializer : BaseDeserializer() {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): PlayListItemsResult {
val data = json?.getAsJsonObject()
val itemsList = mutableListOf<BaseModel>()
var playListItemWrapper: PlayListItemsResult? = null
if (data != null && !data.isJsonNull) {
playListItemWrapper = PlayListItemsResult(findVideoIDs(data)!!)
for (jsonElement in data.asJsonObject.get(KutConstants.KEY_ITEMS).asJsonArray) {
val playListItem = PlayListItem()
findDetails(jsonElement, playListItem)
itemsList.add(playListItem)
}
playListItemWrapper.items = itemsList
}
return playListItemWrapper!!
}
fun findVideoIDs(jsonObject: JsonObject): MutableList<String>? {
val jsonArray = jsonObject.get(KutConstants.KEY_ITEMS).getAsJsonArray()
var idList: MutableList<String>? = mutableListOf()
if (jsonArray != null && !jsonArray.isJsonNull() && !(jsonArray.size() == 0)) {
for (jsonElement in jsonArray) {
val itemID = jsonElement.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString.replace("\"", "")
Log.d(TAG, "PLAYLISTITEMID $itemID")
val snippet = jsonElement.asJsonObject.get(KutConstants.SNIPPET)
if (snippet != null) {
val contentDetails = snippet.asJsonObject.get(KutConstants.RECOURCE_ID)
val videoID = contentDetails.asJsonObject.get(KutConstants.KEY_VIDEO_ID).asString
Log.d(TAG, "VIDEO ID $videoID")
idList?.add(videoID)
}
}
}
return idList
}
}
class VideoDeserializer : BaseDeserializer() {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): VideoResult? {
val videos = mutableListOf<BaseModel>()
val data = json?.getAsJsonObject()
val videoResult = VideoResult()
for (jsonElement in data?.get(KutConstants.KEY_ITEMS)!!.asJsonArray) {
var videoItem = YoutubeVideo()
findDetails(jsonElement, videoItem)
videos.add(videoItem)
}
videoResult.items = videos
return videoResult
}
fun findDetails(json: JsonElement?, youtubeVideo: YoutubeVideo) {
super.findDetails(json, youtubeVideo)
youtubeVideo.videoID = json!!.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString
var dtf: DateTimeFormatter
if (json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET) != null && !json.asJsonObject.getAsJsonObject(KutConstants.SNIPPET).isJsonNull) {
dtf = DateTimeFormat.forPattern("'PT'mm'M'ss'S'")
val channelName = json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET)!!.asJsonObject.get(KutConstants.VIDEO_CHANNEL_TITLE).asString
youtubeVideo.channelName = channelName
if (json.asJsonObject.get(KutConstants.KEY_CONTENT_DETAILS) != null) {
try {
val duration = dtf.parseLocalTime(json.asJsonObject.
get(KutConstants.KEY_CONTENT_DETAILS).asJsonObject.get(KutConstants.VIDEO_VIDEO_DURATION).asString)
youtubeVideo.duration = duration
} catch (e: Exception) {
e.printStackTrace()
}
}
if (json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) != null) {
youtubeVideo.numberOfViews = json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS)
.asJsonObject.get(KutConstants.VIDEO_VIDEO_VIEW_COUNT).asInt
}
}
}
} | mit | 614dd3911d2f6d15ec26f4b856f04455 | 38.842324 | 150 | 0.629205 | 5.031971 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/admin/user/EditUserPresenter.kt | 1 | 2262 | package tr.xip.scd.tensuu.ui.admin.user
import android.os.Bundle
import android.text.Editable
import android.view.MenuItem
import tr.xip.scd.tensuu.App.Companion.context
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.realm.model.User
import tr.xip.scd.tensuu.realm.model.UserFields
import tr.xip.scd.tensuu.common.ui.mvp.RealmPresenter
class EditUserPresenter : RealmPresenter<EditUserView>() {
private var user: User? = null
fun loadWith(extras: Bundle?) {
if (extras == null) {
throw IllegalArgumentException("No extra passed to ${EditUserPresenter::class.java.simpleName}")
}
user = realm.where(User::class.java)
.equalTo(UserFields.EMAIL, extras.getString(EditUserActivity.ARG_USER_EMAIL))
.findFirst()
if (user != null) {
view?.setEmail(user?.email)
view?.setName(user?.name)
view?.setPassword(user?.password)
view?.setAdmin(user?.isAdmin ?: false)
view?.setCanModify(user?.isAdmin ?: false)
} else {
view?.showToast(context.getString(R.string.error_couldnt_find_user))
view?.die()
}
}
fun onEmailChanged(s: Editable?) {
if (s == null) return
realm.executeTransaction {
user?.email = s.toString()
}
}
fun onPasswordChanged(s: Editable?) {
if (s == null) return
realm.executeTransaction {
user?.password = s.toString()
}
}
fun onNameChanged(s: Editable?) {
if (s == null) return
realm.executeTransaction {
user?.name = s.toString()
}
}
fun onAdminChanged(isChecked: Boolean) {
realm.executeTransaction {
user?.isAdmin = isChecked
}
}
fun onCanModifyChanged(isChecked: Boolean) {
realm.executeTransaction {
user?.canModify = isChecked
}
}
fun onOptionsMenuItemSelected(item: MenuItem) {
when (item.itemId) {
R.id.action_delete -> realm.executeTransaction {
user?.deleteFromRealm()
if (!(user?.isValid ?: false)) {
view?.die()
}
}
}
}
} | gpl-3.0 | 0d6c691ca64c2c84713e5cc066930a0e | 27.64557 | 108 | 0.579134 | 4.29222 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/login/LoginView.kt | 1 | 523 | package tr.xip.scd.tensuu.ui.login
import com.hannesdorfmann.mosby3.mvp.MvpView
interface LoginView : MvpView {
fun setEmailError(error: String?)
fun setPasswordError(error: String?)
fun enableEmail(enable: Boolean = true)
fun enablePassword(enable: Boolean = true)
fun enableSignInButton(enable: Boolean = true)
fun showProgress(show: Boolean = true)
fun showSnackbar(text: String, actionText: String? = null, actionListener: (() -> Unit)? = null)
fun startMainActivity()
fun die()
} | gpl-3.0 | 9a05f5863ed06e118aeec49a876ab9aa | 31.75 | 100 | 0.717017 | 4.054264 | false | false | false | false |
Maccimo/intellij-community | build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.kt | 2 | 7198 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import kotlinx.collections.immutable.persistentListOf
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.intellij.build.impl.BaseLayout
import org.jetbrains.intellij.build.impl.BuildContextImpl
import java.nio.file.Path
internal fun createCommunityBuildContext(
communityHome: BuildDependenciesCommunityRoot,
options: BuildOptions = BuildOptions(),
projectHome: Path = communityHome.communityRoot,
): BuildContextImpl {
return BuildContextImpl.createContext(communityHome = communityHome,
projectHome = projectHome,
productProperties = IdeaCommunityProperties(communityHome),
options = options)
}
open class IdeaCommunityProperties(private val communityHome: BuildDependenciesCommunityRoot) : BaseIdeaProperties() {
init {
baseFileName = "idea"
platformPrefix = "Idea"
applicationInfoModule = "intellij.idea.community.resources"
additionalIDEPropertiesFilePaths = listOf(communityHome.communityRoot.resolve("build/conf/ideaCE.properties"))
toolsJarRequired = true
scrambleMainJar = false
useSplash = true
buildCrossPlatformDistribution = true
productLayout.failOnUnspecifiedPluginLayout = true
productLayout.productImplementationModules = listOf("intellij.platform.main")
productLayout.withAdditionalPlatformJar(BaseLayout.APP_JAR, "intellij.idea.community.resources")
productLayout.bundledPluginModules.addAll(BUNDLED_PLUGIN_MODULES)
productLayout.prepareCustomPluginRepositoryForPublishedPlugins = false
productLayout.buildAllCompatiblePlugins = false
productLayout.pluginLayouts = CommunityRepositoryModules.COMMUNITY_REPOSITORY_PLUGINS.addAll(listOf(
JavaPluginLayout.javaPlugin(),
CommunityRepositoryModules.androidPlugin(emptyMap()),
CommunityRepositoryModules.groovyPlugin(emptyList())
))
productLayout.addPlatformCustomizer { layout, _ ->
layout.withModule("intellij.platform.duplicates.analysis")
layout.withModule("intellij.platform.structuralSearch")
}
mavenArtifacts.forIdeModules = true
mavenArtifacts.additionalModules = listOf(
"intellij.platform.debugger.testFramework",
"intellij.platform.vcs.testFramework",
"intellij.platform.externalSystem.testFramework",
"intellij.maven.testFramework"
)
mavenArtifacts.squashedModules += listOf(
"intellij.platform.util.base",
"intellij.platform.util.zip",
)
versionCheckerConfig = CE_CLASS_VERSIONS
}
override fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) {
super.copyAdditionalFiles(context, targetDirectory)
FileSet(context.paths.communityHomeDir.communityRoot)
.include("LICENSE.txt")
.include("NOTICE.txt")
.copyToDir(Path.of(targetDirectory))
FileSet(context.paths.communityHomeDir.communityRoot.resolve("build/conf/ideaCE/common/bin"))
.includeAll()
.copyToDir(Path.of(targetDirectory, "bin"))
bundleExternalPlugins(context, targetDirectory)
}
protected open fun bundleExternalPlugins(context: BuildContext, targetDirectory: String) {
//temporary unbundle VulnerabilitySearch
//ExternalPluginBundler.bundle('VulnerabilitySearch',
// "$buildContext.paths.communityHome/build/dependencies",
// buildContext, targetDirectory)
}
override fun createWindowsCustomizer(projectHome: String): WindowsDistributionCustomizer {
return object : WindowsDistributionCustomizer() {
init {
icoPath = "${communityHome.communityRoot}/platform/icons/src/idea_CE.ico"
icoPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/win/images/idea_CE_EAP.ico"
installerImagesPath = "${communityHome.communityRoot}/build/conf/ideaCE/win/images"
fileAssociations = listOf("java", "groovy", "kt", "kts")
}
override fun getFullNameIncludingEdition(appInfo: ApplicationInfoProperties) = "IntelliJ IDEA Community Edition"
override fun getFullNameIncludingEditionAndVendor(appInfo: ApplicationInfoProperties) = "IntelliJ IDEA Community Edition"
override fun getUninstallFeedbackPageUrl(applicationInfo: ApplicationInfoProperties): String {
return "https://www.jetbrains.com/idea/uninstall/?edition=IC-${applicationInfo.majorVersion}.${applicationInfo.minorVersion}"
}
}
}
override fun createLinuxCustomizer(projectHome: String): LinuxDistributionCustomizer {
return object : LinuxDistributionCustomizer() {
init {
iconPngPath = "${communityHome.communityRoot}/build/conf/ideaCE/linux/images/icon_CE_128.png"
iconPngPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/linux/images/icon_CE_EAP_128.png"
snapName = "intellij-idea-community"
snapDescription =
"The most intelligent Java IDE. Every aspect of IntelliJ IDEA is specifically designed to maximize developer productivity. " +
"Together, powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience."
extraExecutables = persistentListOf(
"plugins/Kotlin/kotlinc/bin/kotlin",
"plugins/Kotlin/kotlinc/bin/kotlinc",
"plugins/Kotlin/kotlinc/bin/kotlinc-js",
"plugins/Kotlin/kotlinc/bin/kotlinc-jvm",
"plugins/Kotlin/kotlinc/bin/kotlin-dce-js"
)
}
override fun getRootDirectoryName(appInfo: ApplicationInfoProperties, buildNumber: String) = "idea-IC-$buildNumber"
}
}
override fun createMacCustomizer(projectHome: String): MacDistributionCustomizer {
return object : MacDistributionCustomizer() {
init {
icnsPath = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/idea.icns"
urlSchemes = listOf("idea")
associateIpr = true
fileAssociations = FileAssociation.from("java", "groovy", "kt", "kts")
bundleIdentifier = "com.jetbrains.intellij.ce"
dmgImagePath = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/dmg_background.tiff"
icnsPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/communityEAP.icns"
}
override fun getRootDirectoryName(appInfo: ApplicationInfoProperties, buildNumber: String): String {
return if (appInfo.isEAP) {
"IntelliJ IDEA ${appInfo.majorVersion}.${appInfo.minorVersionMainPart} CE EAP.app"
}
else {
"IntelliJ IDEA CE.app"
}
}
}
}
override fun getSystemSelector(appInfo: ApplicationInfoProperties, buildNumber: String): String {
return "IdeaIC${appInfo.majorVersion}.${appInfo.minorVersionMainPart}"
}
override fun getBaseArtifactName(appInfo: ApplicationInfoProperties, buildNumber: String) = "ideaIC-$buildNumber"
override fun getOutputDirectoryName(appInfo: ApplicationInfoProperties) = "idea-ce"
} | apache-2.0 | 87fe1cd066579259e9287e2738c8153f | 45.445161 | 143 | 0.730897 | 5.104965 | false | false | false | false |
mutcianm/android-dsl | src/ru/ifmo/rain/adsl/Generator.kt | 2 | 9908 | package ru.ifmo.rain.adsl;
import java.util.jar.JarEntry
import java.util.Enumeration
import java.util.jar.JarFile
import java.util.Collections
import org.objectweb.asm.*
import java.io.InputStream
import java.util.ArrayList
import java.util.TreeMap
import java.util.Arrays
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.InnerClassNode
import org.objectweb.asm.tree.MethodNode
open class DSLException(message: String = "") : Exception(message)
open class DSLGeneratorException(message: String = ""): DSLException(message)
class InvalidPropertyException(message: String = ""): DSLGeneratorException(message)
class NoListenerClassException(message: String = ""): DSLGeneratorException(message)
class Hook<T>(val predicate: ((_class: T) -> Boolean), val function: ((_class: T) -> Unit)) {
public fun run(_class: T) {
if (predicate(_class))
function(_class)
}
public fun invoke(_class: T) {
run(_class)
}
}
class PropertyData(var parentClass: ClassNode,
var propName: String,
var propType: Type?,
var getter: MethodNode?,
var setter: MethodNode?,
var valueType: Type?,
val isContainer: Boolean)
class Generator(val jarPath: String, val packageName: String,
val settings: BaseGeneratorSettings) {
private val propMap = TreeMap<String, PropertyData>()
private val classBlackList = settings.blackListedClasses
private val propBlackList = settings.blacklistedProperties
private val helperConstructors = settings.helperConstructors
private val explicitlyProcessedClasses = settings.explicitlyProcessedClasses
private val classTree: ClassTree = ClassTree()
private val dslWriter = DSLWriter(settings, classTree)
private val classHooks = Arrays.asList<Hook<ClassNode>>(
Hook({
isWidget(it) && !isBlacklistedClass(it) && !it.isAbstract() && !it.isInner() && !isContainer(it)
}, { genWidget(it) }),
Hook({
!isBlacklistedClass(it) && !it.isAbstract() && !it.isInner() && isContainer(it)
}, { genContainer(it) })
)
private val methodHooks = Arrays.asList<Hook<MethodNodeWithParent>>(
Hook({
isWidget(it.parent) && !isBlacklistedClass(it.parent) && it.child.isGetter() && !it.child.isProtected()
}, { genGetter(it) }),
Hook({
isWidget(it.parent) && !isBlacklistedClass(it.parent) && it.child.isSetter() && !it.child.isProtected()
}, { genSetter(it) }),
Hook({
it.child.name!!.startsWith("setOn") && it.child.name!!.endsWith("Listener") && !isBlacklistedClass(it.parent)
}, { genListenerHelper(it) })
)
private fun isBlacklistedClass(classInfo: ClassNode): Boolean {
return classInfo.cleanInternalName() in classBlackList
}
private fun isBlacklistedProperty(propertyName: String): Boolean {
return propertyName in propBlackList
}
private fun isContainer(widget: ClassNode): Boolean {
return classTree.isSuccessorOf(widget, settings.containerBaseClass)
}
public fun run() {
for (classData in extractClasses(jarPath, packageName)) {
classTree.add(processClassData(classData))
}
for (classInfo in classTree) {
classInfo.methods!!.forEach { method ->
methodHooks.forEach {
hook ->
hook(MethodNodeWithParent(classInfo, method))
}
}
classHooks.forEach { hook -> hook(classInfo) }
}
produceProperties()
dslWriter.write()
}
private fun produceProperties() {
for (prop in propMap.values()) {
if (!isBlacklistedProperty(prop.parentClass.cleanInternalName() + '.' + prop.propName))
if (prop.getter != null && prop.propType?.getSort() != Type.VOID)
dslWriter.produceProperty(prop)
}
}
private fun isWidget(classNode: ClassNode): Boolean {
return classTree.isSuccessorOf(classNode, settings.widgetBaseClass) ||
classNode.name in explicitlyProcessedClasses
}
private fun genListenerHelper(methodInfo: MethodNodeWithParent) {
val listenerType = methodInfo.child.arguments!![0]
val name = listenerType.getInternalName()
val node = classTree.findNode(name)
if (node == null)
throw NoListenerClassException("Listener class $name not found")
dslWriter.genListenerHelper(methodInfo, node.data)
}
private fun genSetter(methodInfo: MethodNodeWithParent) {
if(methodInfo.parent.isAbstract() && isContainer(methodInfo.parent)) return
if (!settings.generateSetters) return
val property = PropertyData(methodInfo.parent, methodInfo.child.toProperty(), null, null,
methodInfo.child, methodInfo.child.arguments!![0],isContainer(methodInfo.parent))
updateProperty(property)
}
private fun genGetter(methodInfo: MethodNodeWithParent) {
if(methodInfo.parent.isAbstract() && isContainer(methodInfo.parent)) return
if (!settings.generateGetters) return
val property = PropertyData(methodInfo.parent, methodInfo.child.toProperty(),
methodInfo.child.getReturnType(), methodInfo.child, null, null, isContainer(methodInfo.parent))
updateProperty(property)
}
private fun updateProperty(newProp: PropertyData) {
val prop = propMap[newProp.parentClass.cleanInternalName() + newProp.propName]
if (prop != null) {
with(prop) {
setter = updateIfNotNull(setter, newProp.setter)
getter = updateIfNotNull(getter, newProp.getter)
valueType = updateIfNotNull(valueType, newProp.valueType)
propType = updateIfNotNull(propType, newProp.propType)
}
} else {
propMap[newProp.parentClass.cleanInternalName() + newProp.propName] = newProp
}
}
private fun getHelperConstructors(classNode: ClassNode): List<List<PropertyData>> {
val constructors: List<List<String>>? = helperConstructors.get(classNode.cleanInternalName())
val res = ArrayList<ArrayList<PropertyData>>()
val defaultConstructor = ArrayList<PropertyData>()
res.add(defaultConstructor)
val className = classNode.cleanInternalName()
if (constructors == null || !settings.generateHelperConstructors) {
return res
} else {
for (constructor in constructors) {
val cons = ArrayList<PropertyData>()
for (argument in constructor) {
val _class = classTree.findParentWithProperty(classNode, argument)
if (_class == null)
throw InvalidPropertyException("Property $argument is not in $className hierarchy")
val property = propMap.get(_class.cleanInternalName() + argument)
if (property == null)
throw InvalidPropertyException("Property $argument in not a member of $className")
if (property.valueType == null)
throw InvalidPropertyException("Property $argument is read-only in $className")
cons.add(property)
}
res.add(cons)
}
return res
}
}
private fun genWidget(classNode: ClassNode) {
val cleanNameDecap = classNode.cleanNameDecap()
val cleanInternalName = classNode.cleanInternalName()
val constructors = getHelperConstructors(classNode)
for (constructor in constructors) {
dslWriter.makeWidget(classNode, cleanNameDecap, cleanInternalName, constructor)
}
}
private fun genContainer(classNode: ClassNode) {
if (classNode.signature != null)
println("${classNode.name} : ${classNode.signature}")
genContainerWidgetFun(classNode)
dslWriter.genContainerClass(classNode, extractLayoutParams(classNode))
dslWriter.genUIWidgetFun(classNode)
}
private fun extractLayoutParams(viewGroup: ClassNode): ClassNode? {
if (viewGroup.innerClasses == null)
return null
val innerClasses = (viewGroup.innerClasses as List<InnerClassNode>)
val lp = innerClasses.find { it.name!!.contains("LayoutParams") }
return classTree.findNode(lp?.name)?.data
}
private fun genContainerWidgetFun(classNode: ClassNode) {
val cleanNameDecap = classNode.cleanNameDecap()
val cleanName = classNode.cleanName()
val cleanInternalName = classNode.cleanInternalName()
dslWriter.makeContainerWidgetFun(classNode, cleanNameDecap, cleanName, cleanInternalName)
}
private fun processClassData(classData: InputStream?): ClassNode {
val cn = ClassNode()
try {
val cr = ClassReader(classData)
cr.accept(cn, 0)
} catch (e: Exception) {
//optionally log something here
} finally {
classData?.close()
}
return cn
}
private fun extractClasses(jarPath: String, packageName: String): Iterator<InputStream> {
// val packageName = packageName.replace('.', '/')
val jarFile = JarFile(jarPath)
return Collections.list(jarFile.entries() as Enumeration<JarEntry>)
.iterator()
.filter {
// (it.getName().startsWith(packageName) || it.getName() in explicitlyProcessedClasses) &&
it.getName().endsWith(".class")
}.map {
jarFile.getInputStream(it)!!
}
}
}
| apache-2.0 | 826c86214d1ed95cf79db895fd7806c9 | 38.31746 | 125 | 0.631308 | 5.02689 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/ReferenceConvolve.kt | 1 | 2129 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.renderscript_test
import com.google.android.renderscript.Range2d
/**
* Reference implementation of a Convolve operation.
*/
@ExperimentalUnsignedTypes
fun referenceConvolve(
inputArray: ByteArray,
vectorSize: Int,
sizeX: Int,
sizeY: Int,
coefficients: FloatArray,
restriction: Range2d?
): ByteArray {
val input = Vector2dArray(inputArray.asUByteArray(), vectorSize, sizeX, sizeY)
val radius = when (coefficients.size) {
9 -> 1
25 -> 2
else -> {
throw IllegalArgumentException("RenderScriptToolkit Convolve. Only 3x3 and 5x5 convolutions are supported. ${coefficients.size} coefficients provided.")
}
}
input.clipReadToRange = true
val output = input.createSameSized()
input.forEach(restriction) { x, y ->
output[x, y] = convolveOne(input, x, y, coefficients, radius)
}
return output.values.asByteArray()
}
@ExperimentalUnsignedTypes
private fun convolveOne(
inputAlloc: Vector2dArray,
x: Int,
y: Int,
coefficients: FloatArray,
radius: Int
): UByteArray {
var sum = FloatArray(paddedSize(inputAlloc.vectorSize))
var coefficientIndex = 0
for (deltaY in -radius..radius) {
for (deltaX in -radius..radius) {
val inputVector = inputAlloc[x + deltaX, y + deltaY]
sum += inputVector.toFloatArray() * coefficients[coefficientIndex]
coefficientIndex++
}
}
return sum.clampToUByte()
}
| apache-2.0 | 47974ba481d2c7d2a3b86e084ffd06f4 | 30.308824 | 164 | 0.686707 | 4.17451 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/interactors/qms/QmsInteractor.kt | 1 | 3259 | package forpdateam.ru.forpda.model.interactors.qms
import forpdateam.ru.forpda.entity.remote.editpost.AttachmentItem
import forpdateam.ru.forpda.entity.remote.others.user.ForumUser
import forpdateam.ru.forpda.entity.remote.qms.QmsChatModel
import forpdateam.ru.forpda.entity.remote.qms.QmsContact
import forpdateam.ru.forpda.entity.remote.qms.QmsMessage
import forpdateam.ru.forpda.entity.remote.qms.QmsThemes
import forpdateam.ru.forpda.model.data.remote.api.RequestFile
import forpdateam.ru.forpda.model.repository.events.EventsRepository
import forpdateam.ru.forpda.model.repository.qms.QmsRepository
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.disposables.Disposable
class QmsInteractor(
private val qmsRepository: QmsRepository,
private val eventsRepository: EventsRepository
) {
private var eventsDisposable: Disposable? = null
fun subscribeEvents() {
if (eventsDisposable != null) return
eventsDisposable = eventsRepository
.observeEventsTab()
.subscribe {
qmsRepository.handleEvent(it)
}
}
fun observeContacts(): Observable<List<QmsContact>> = qmsRepository
.observeContacts()
fun observeThemes(userId: Int): Observable<QmsThemes> = qmsRepository
.observeThemes(userId)
//Common
fun findUser(nick: String): Single<List<ForumUser>> = qmsRepository
.findUser(nick)
fun blockUser(nick: String): Single<List<QmsContact>> = qmsRepository
.blockUser(nick)
fun unBlockUsers(userId: Int): Single<List<QmsContact>> = qmsRepository
.unBlockUsers(userId)
//Contacts
fun getContactList(): Single<List<QmsContact>> = qmsRepository
.getContactList()
fun getBlackList(): Single<List<QmsContact>> = qmsRepository
.getBlackList()
fun deleteDialog(mid: Int): Single<String> = qmsRepository
.deleteDialog(mid)
//Themes
fun getThemesList(id: Int): Single<QmsThemes> = qmsRepository
.getThemesList(id)
fun deleteTheme(id: Int, themeId: Int): Single<QmsThemes> = qmsRepository
.deleteTheme(id, themeId)
//Chat
fun getChat(userId: Int, themeId: Int): Single<QmsChatModel> = qmsRepository
.getChat(userId, themeId)
fun sendNewTheme(nick: String, title: String, mess: String, files: List<AttachmentItem>): Single<QmsChatModel> = qmsRepository
.sendNewTheme(nick, title, mess, files)
fun sendMessage(userId: Int, themeId: Int, text: String, files: List<AttachmentItem>): Single<List<QmsMessage>> = qmsRepository
.sendMessage(userId, themeId, text, files)
fun getMessagesFromWs(themeId: Int, messageId: Int, afterMessageId: Int): Single<List<QmsMessage>> = qmsRepository
.getMessagesFromWs(themeId, messageId, afterMessageId)
fun getMessagesAfter(userId: Int, themeId: Int, afterMessageId: Int): Single<List<QmsMessage>> = qmsRepository
.getMessagesAfter(userId, themeId, afterMessageId)
fun uploadFiles(files: List<RequestFile>, pending: List<AttachmentItem>): Single<List<AttachmentItem>> = qmsRepository
.uploadFiles(files, pending)
} | gpl-3.0 | ac360c73abc6fd711c06df393163213a | 36.906977 | 131 | 0.709113 | 4.482806 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderPostUiStateBuilder.kt | 1 | 21810 | package org.wordpress.android.ui.reader.discover
import dagger.Reusable
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import org.wordpress.android.R
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.models.ReaderBlog
import org.wordpress.android.models.ReaderCardType.DEFAULT
import org.wordpress.android.models.ReaderCardType.GALLERY
import org.wordpress.android.models.ReaderCardType.PHOTO
import org.wordpress.android.models.ReaderCardType.VIDEO
import org.wordpress.android.models.ReaderPost
import org.wordpress.android.models.ReaderPostDiscoverData
import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.EDITOR_PICK
import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.OTHER
import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.SITE_PICK
import org.wordpress.android.models.ReaderTag
import org.wordpress.android.models.ReaderTagList
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.reader.ReaderConstants
import org.wordpress.android.ui.reader.ReaderTypes.ReaderPostListType
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestChipStyleColor
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleGreen
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleOrange
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStylePurple
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleYellow
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ReaderInterestUiState
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState.DiscoverLayoutUiState
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState.GalleryThumbnailStripData
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderRecommendedBlogsCardUiState
import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderRecommendedBlogsCardUiState.ReaderRecommendedBlogUiState
import org.wordpress.android.ui.reader.discover.ReaderPostCardAction.PrimaryAction
import org.wordpress.android.ui.reader.discover.ReaderPostCardAction.SecondaryAction
import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.BOOKMARK
import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.LIKE
import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.REBLOG
import org.wordpress.android.ui.reader.utils.ReaderImageScannerProvider
import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper
import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState
import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState.ReaderBlogSectionClickData
import org.wordpress.android.ui.utils.UiDimen.UIDimenRes
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringResWithParams
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.DateTimeUtilsWrapper
import org.wordpress.android.util.GravatarUtilsWrapper
import org.wordpress.android.util.SiteUtils
import org.wordpress.android.util.UrlUtilsWrapper
import org.wordpress.android.util.image.BlavatarShape.CIRCULAR
import org.wordpress.android.util.image.ImageType
import javax.inject.Inject
import javax.inject.Named
private const val READER_INTEREST_LIST_SIZE_LIMIT = 5
private const val READER_RECOMMENDED_BLOGS_LIST_SIZE_LIMIT = 3
@Reusable
class ReaderPostUiStateBuilder @Inject constructor(
private val accountStore: AccountStore,
private val urlUtilsWrapper: UrlUtilsWrapper,
private val gravatarUtilsWrapper: GravatarUtilsWrapper,
private val dateTimeUtilsWrapper: DateTimeUtilsWrapper,
private val readerImageScannerProvider: ReaderImageScannerProvider,
private val readerUtilsWrapper: ReaderUtilsWrapper,
private val readerPostTagsUiStateBuilder: ReaderPostTagsUiStateBuilder,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher
) {
@Suppress("LongParameterList")
suspend fun mapPostToUiState(
source: String,
post: ReaderPost,
isDiscover: Boolean = false,
photonWidth: Int,
photonHeight: Int,
postListType: ReaderPostListType,
onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit,
onItemClicked: (Long, Long) -> Unit,
onItemRendered: (ReaderCardUiState) -> Unit,
onDiscoverSectionClicked: (Long, Long) -> Unit,
onMoreButtonClicked: (ReaderPostUiState) -> Unit,
onMoreDismissed: (ReaderPostUiState) -> Unit,
onVideoOverlayClicked: (Long, Long) -> Unit,
onPostHeaderViewClicked: (Long, Long) -> Unit,
onTagItemClicked: (String) -> Unit,
moreMenuItems: List<SecondaryAction>? = null
): ReaderPostUiState {
return withContext(bgDispatcher) {
mapPostToUiStateBlocking(
source,
post,
isDiscover,
photonWidth,
photonHeight,
postListType,
onButtonClicked,
onItemClicked,
onItemRendered,
onDiscoverSectionClicked,
onMoreButtonClicked,
onMoreDismissed,
onVideoOverlayClicked,
onPostHeaderViewClicked,
onTagItemClicked,
moreMenuItems
)
}
}
@Suppress("LongParameterList")
fun mapPostToUiStateBlocking(
source: String,
post: ReaderPost,
isDiscover: Boolean = false,
photonWidth: Int,
photonHeight: Int,
postListType: ReaderPostListType,
onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit,
onItemClicked: (Long, Long) -> Unit,
onItemRendered: (ReaderCardUiState) -> Unit,
onDiscoverSectionClicked: (Long, Long) -> Unit,
onMoreButtonClicked: (ReaderPostUiState) -> Unit,
onMoreDismissed: (ReaderPostUiState) -> Unit,
onVideoOverlayClicked: (Long, Long) -> Unit,
onPostHeaderViewClicked: (Long, Long) -> Unit,
onTagItemClicked: (String) -> Unit,
moreMenuItems: List<ReaderPostCardAction>? = null
): ReaderPostUiState {
return ReaderPostUiState(
source = source,
postId = post.postId,
blogId = post.blogId,
feedId = post.feedId,
isFollowed = post.isFollowedByCurrentUser,
blogSection = buildBlogSection(post, onPostHeaderViewClicked, postListType, post.isP2orA8C),
excerpt = buildExcerpt(post),
title = buildTitle(post),
tagItems = buildTagItems(post, onTagItemClicked),
photoFrameVisibility = buildPhotoFrameVisibility(post),
photoTitle = buildPhotoTitle(post),
featuredImageUrl = buildFeaturedImageUrl(post, photonWidth, photonHeight),
featuredImageCornerRadius = UIDimenRes(R.dimen.reader_featured_image_corner_radius),
thumbnailStripSection = buildThumbnailStripUrls(post),
expandableTagsViewVisibility = buildExpandedTagsViewVisibility(post, isDiscover),
videoOverlayVisibility = buildVideoOverlayVisibility(post),
featuredImageVisibility = buildFeaturedImageVisibility(post),
moreMenuVisibility = accountStore.hasAccessToken(),
moreMenuItems = moreMenuItems,
fullVideoUrl = buildFullVideoUrl(post),
discoverSection = buildDiscoverSection(post, onDiscoverSectionClicked),
bookmarkAction = buildBookmarkSection(post, onButtonClicked),
likeAction = buildLikeSection(post, onButtonClicked),
reblogAction = buildReblogSection(post, onButtonClicked),
commentsAction = buildCommentsSection(post, onButtonClicked),
onItemClicked = onItemClicked,
onItemRendered = onItemRendered,
onMoreButtonClicked = onMoreButtonClicked,
onMoreDismissed = onMoreDismissed,
onVideoOverlayClicked = onVideoOverlayClicked
)
}
fun mapPostToBlogSectionUiState(
post: ReaderPost,
onBlogSectionClicked: (Long, Long) -> Unit
): ReaderBlogSectionUiState {
return buildBlogSection(post, onBlogSectionClicked)
}
fun mapPostToActions(
post: ReaderPost,
onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit
): ReaderPostActions {
return ReaderPostActions(
bookmarkAction = buildBookmarkSection(post, onButtonClicked),
likeAction = buildLikeSection(post, onButtonClicked),
reblogAction = buildReblogSection(post, onButtonClicked),
commentsAction = buildCommentsSection(post, onButtonClicked)
)
}
suspend fun mapTagListToReaderInterestUiState(
interests: ReaderTagList,
onClicked: ((String) -> Unit)
): ReaderInterestsCardUiState {
return withContext(bgDispatcher) {
val listSize = if (interests.size < READER_INTEREST_LIST_SIZE_LIMIT) {
interests.size
} else {
READER_INTEREST_LIST_SIZE_LIMIT
}
return@withContext ReaderInterestsCardUiState(interests.take(listSize).map { interest ->
ReaderInterestUiState(
interest = interest.tagTitle,
onClicked = onClicked,
chipStyle = buildChipStyle(interest, interests)
)
})
}
}
suspend fun mapRecommendedBlogsToReaderRecommendedBlogsCardUiState(
recommendedBlogs: List<ReaderBlog>,
onItemClicked: (Long, Long, Boolean) -> Unit,
onFollowClicked: (ReaderRecommendedBlogUiState) -> Unit
): ReaderRecommendedBlogsCardUiState = withContext(bgDispatcher) {
recommendedBlogs.take(READER_RECOMMENDED_BLOGS_LIST_SIZE_LIMIT)
.map {
ReaderRecommendedBlogUiState(
name = it.name,
url = urlUtilsWrapper.removeScheme(it.url),
blogId = it.blogId,
feedId = it.feedId,
description = it.description.ifEmpty { null },
iconUrl = it.imageUrl,
isFollowed = it.isFollowing,
onFollowClicked = onFollowClicked,
onItemClicked = onItemClicked
)
}.let { ReaderRecommendedBlogsCardUiState(it) }
}
private fun buildBlogSection(
post: ReaderPost,
onBlogSectionClicked: (Long, Long) -> Unit,
postListType: ReaderPostListType? = null,
isP2Post: Boolean = false
) = buildBlogSectionUiState(post, onBlogSectionClicked, postListType, isP2Post)
private fun buildBlogSectionUiState(
post: ReaderPost,
onBlogSectionClicked: (Long, Long) -> Unit,
postListType: ReaderPostListType?,
isP2Post: Boolean = false
): ReaderBlogSectionUiState {
return ReaderBlogSectionUiState(
postId = post.postId,
blogId = post.blogId,
blogName = buildBlogName(post, isP2Post),
blogUrl = buildBlogUrl(post),
dateLine = buildDateLine(post),
avatarOrBlavatarUrl = buildAvatarOrBlavatarUrl(post),
isAuthorAvatarVisible = isP2Post,
blavatarType = SiteUtils.getSiteImageType(isP2Post, CIRCULAR),
authorAvatarUrl = gravatarUtilsWrapper.fixGravatarUrlWithResource(
post.postAvatar,
R.dimen.avatar_sz_medium
),
blogSectionClickData = buildOnBlogSectionClicked(onBlogSectionClicked, postListType)
)
}
private fun buildOnBlogSectionClicked(
onBlogSectionClicked: (Long, Long) -> Unit,
postListType: ReaderPostListType?
): ReaderBlogSectionClickData? {
return if (postListType != ReaderPostListType.BLOG_PREVIEW) {
ReaderBlogSectionClickData(onBlogSectionClicked, android.R.attr.selectableItemBackground)
} else {
null
}
}
private fun buildBlogUrl(post: ReaderPost) = post
.takeIf { it.hasBlogUrl() }
?.blogUrl
?.let { urlUtilsWrapper.removeScheme(it) }
private fun buildDiscoverSection(post: ReaderPost, onDiscoverSectionClicked: (Long, Long) -> Unit) =
post.takeIf { post.isDiscoverPost && post.discoverData.discoverType != OTHER }
?.let { buildDiscoverSectionUiState(post.discoverData, onDiscoverSectionClicked) }
private fun buildFullVideoUrl(post: ReaderPost) =
post.takeIf { post.cardType == VIDEO }
?.let { post.featuredVideo }
private fun buildExpandedTagsViewVisibility(post: ReaderPost, isDiscover: Boolean) =
post.tags.isNotEmpty() && isDiscover
private fun buildTagItems(post: ReaderPost, onClicked: (String) -> Unit) =
readerPostTagsUiStateBuilder.mapPostTagsToTagUiStates(post, onClicked)
// TODO malinjir show overlay when buildFullVideoUrl != null
private fun buildVideoOverlayVisibility(post: ReaderPost) = post.cardType == VIDEO
private fun buildFeaturedImageVisibility(post: ReaderPost) =
(post.cardType == PHOTO || post.cardType == DEFAULT) && post.hasFeaturedImage() ||
post.cardType == VIDEO && post.hasFeaturedVideo()
private fun buildThumbnailStripUrls(post: ReaderPost) =
post.takeIf { it.cardType == GALLERY }
?.let { retrieveGalleryThumbnailUrls(post) }
private fun buildFeaturedImageUrl(post: ReaderPost, photonWidth: Int, photonHeight: Int): String? {
return post
.takeIf { (it.cardType == PHOTO || it.cardType == DEFAULT) && it.hasFeaturedImage() }
?.getFeaturedImageForDisplay(photonWidth, photonHeight)
}
private fun buildPhotoTitle(post: ReaderPost) =
post.takeIf { it.cardType == PHOTO && it.hasTitle() }?.title
private fun buildPhotoFrameVisibility(post: ReaderPost) =
(post.hasFeaturedVideo() || post.hasFeaturedImage()) &&
post.cardType != GALLERY
// TODO malinjir show title only when buildPhotoTitle == null
private fun buildTitle(post: ReaderPost): UiString? {
return if (post.cardType != PHOTO) {
post.takeIf { it.hasTitle() }?.title?.let { UiStringText(it) }
?: UiStringRes(R.string.untitled_in_parentheses)
} else {
null
}
}
// TODO malinjir show excerpt only when buildPhotoTitle == null
private fun buildExcerpt(post: ReaderPost) =
post.takeIf { post.cardType != PHOTO && post.hasExcerpt() }?.excerpt
private fun buildBlogName(post: ReaderPost, isP2Post: Boolean = false): UiString {
val blogName = post.takeIf { it.hasBlogName() }?.blogName?.let { UiStringText(it) }
?: UiStringRes(R.string.untitled_in_parentheses)
if (!isP2Post) {
return blogName
}
val authorName = if (post.hasAuthorFirstName()) {
UiStringText(post.authorFirstName)
} else {
UiStringText(post.authorName)
}
return UiStringResWithParams(R.string.reader_author_with_blog_name, listOf(authorName, blogName))
}
private fun buildAvatarOrBlavatarUrl(post: ReaderPost) =
post.takeIf { it.hasBlogImageUrl() }
?.blogImageUrl
?.let { gravatarUtilsWrapper.fixGravatarUrlWithResource(it, R.dimen.avatar_sz_medium) }
private fun buildDateLine(post: ReaderPost) =
dateTimeUtilsWrapper.javaDateToTimeSpan(post.getDisplayDate(dateTimeUtilsWrapper))
@Suppress("UseCheckOrError")
private fun buildDiscoverSectionUiState(
discoverData: ReaderPostDiscoverData,
onDiscoverSectionClicked: (Long, Long) -> Unit
): DiscoverLayoutUiState {
val discoverText = discoverData.attributionHtml
val discoverAvatarUrl = gravatarUtilsWrapper.fixGravatarUrlWithResource(
discoverData.avatarUrl,
R.dimen.avatar_sz_small
)
@Suppress("DEPRECATION") val discoverAvatarImageType = when (discoverData.discoverType) {
EDITOR_PICK -> ImageType.AVATAR
SITE_PICK -> ImageType.BLAVATAR
OTHER -> throw IllegalStateException("This could should be unreachable.")
else -> ImageType.AVATAR
}
return DiscoverLayoutUiState(discoverText, discoverAvatarUrl, discoverAvatarImageType, onDiscoverSectionClicked)
}
private fun retrieveGalleryThumbnailUrls(post: ReaderPost): GalleryThumbnailStripData {
// scan post content for images suitable in a gallery
val images = readerImageScannerProvider.createReaderImageScanner(post.text, post.isPrivate)
.getImageList(ReaderConstants.THUMBNAIL_STRIP_IMG_COUNT, ReaderConstants.MIN_GALLERY_IMAGE_WIDTH)
return GalleryThumbnailStripData(images, post.isPrivate, post.text)
}
private fun buildBookmarkSection(
post: ReaderPost,
onClicked: (Long, Long, ReaderPostCardActionType) -> Unit
): PrimaryAction {
val contentDescription = UiStringRes(
if (post.isBookmarked) {
R.string.reader_remove_bookmark
} else {
R.string.reader_add_bookmark
}
)
return if (post.postId != 0L && post.blogId != 0L) {
PrimaryAction(
isEnabled = true,
isSelected = post.isBookmarked,
contentDescription = contentDescription,
onClicked = onClicked,
type = BOOKMARK
)
} else {
PrimaryAction(isEnabled = false, contentDescription = contentDescription, type = BOOKMARK)
}
}
private fun buildLikeSection(
post: ReaderPost,
onClicked: (Long, Long, ReaderPostCardActionType) -> Unit
): PrimaryAction {
val likesEnabled = post.canLikePost() && accountStore.hasAccessToken()
return PrimaryAction(
isEnabled = likesEnabled,
isSelected = post.isLikedByCurrentUser,
contentDescription = UiStringText(
readerUtilsWrapper.getLongLikeLabelText(post.numLikes, post.isLikedByCurrentUser)
),
count = post.numLikes,
onClicked = if (likesEnabled) onClicked else null,
type = LIKE
)
}
private fun buildReblogSection(
post: ReaderPost,
onReblogClicked: (Long, Long, ReaderPostCardActionType) -> Unit
): PrimaryAction {
val canReblog = !post.isPrivate && accountStore.hasAccessToken()
return PrimaryAction(
isEnabled = canReblog,
contentDescription = UiStringRes(R.string.reader_view_reblog),
onClicked = if (canReblog) onReblogClicked else null,
type = REBLOG
)
}
private fun buildCommentsSection(
post: ReaderPost,
onCommentsClicked: (Long, Long, ReaderPostCardActionType) -> Unit
): PrimaryAction {
val showComments = when {
post.isDiscoverPost -> false
!accountStore.hasAccessToken() -> post.numReplies > 0
else -> post.isWP && (post.isCommentsOpen || post.numReplies > 0)
}
val contentDescription = UiStringRes(R.string.comments)
return if (showComments) {
PrimaryAction(
isEnabled = true,
count = post.numReplies,
contentDescription = contentDescription,
onClicked = onCommentsClicked,
type = ReaderPostCardActionType.COMMENTS
)
} else {
PrimaryAction(
isEnabled = false,
contentDescription = contentDescription,
type = ReaderPostCardActionType.COMMENTS
)
}
}
private fun buildChipStyle(readerTag: ReaderTag, readerTagList: ReaderTagList): ChipStyle {
val colorCount = ReaderInterestChipStyleColor.values().size
val index = readerTagList.indexOf(readerTag)
return when (index % colorCount) {
ReaderInterestChipStyleColor.GREEN.id -> ChipStyleGreen
ReaderInterestChipStyleColor.PURPLE.id -> ChipStylePurple
ReaderInterestChipStyleColor.YELLOW.id -> ChipStyleYellow
ReaderInterestChipStyleColor.ORANGE.id -> ChipStyleOrange
else -> ChipStyleGreen
}
}
}
| gpl-2.0 | f0847b3dd0e72a6ad8b4e0a9ebcecaf7 | 45.207627 | 128 | 0.666208 | 5.43213 | false | false | false | false |
edwardharks/Aircraft-Recognition | app/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/filter/FilterActivity.kt | 1 | 7400 | package com.edwardharker.aircraftrecognition.ui.filter
import android.graphics.Rect
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import com.edwardharker.aircraftrecognition.R
import com.edwardharker.aircraftrecognition.analytics.eventAnalytics
import com.edwardharker.aircraftrecognition.analytics.filterScreen
import com.edwardharker.aircraftrecognition.filter.picker.FilterPickerResetView
import com.edwardharker.aircraftrecognition.maths.mapFromPercent
import com.edwardharker.aircraftrecognition.maths.mapToPercent
import com.edwardharker.aircraftrecognition.perf.TracerFactory.filterActivityContentLoadTracer
import com.edwardharker.aircraftrecognition.perf.TracerFactory.filterPickerLoadTracer
import com.edwardharker.aircraftrecognition.ui.bind
import com.edwardharker.aircraftrecognition.ui.filter.picker.FilterPickerRecyclerView
import com.edwardharker.aircraftrecognition.ui.filter.picker.filterPickerResetPresenter
import com.edwardharker.aircraftrecognition.ui.filter.results.FilterResultsRecyclerView
import com.edwardharker.aircraftrecognition.ui.navigator
import com.edwardharker.aircraftrecognition.ui.search.launchSearchActivity
class FilterActivity : AppCompatActivity(), Toolbar.OnMenuItemClickListener,
FilterResultsRecyclerView.HiddenListener, FilterPickerResetView {
private val toolbar by bind<Toolbar>(R.id.toolbar)
private val bottomSheetView by bind<FilterResultsRecyclerView>(R.id.content_filter)
private val filterPicker by bind<FilterPickerRecyclerView>(R.id.filter_picker)
private val resultsHandleView by bind<ImageView>(R.id.results_handle)
private val resultsHandleContainer by bind<View>(R.id.results_handle_container)
private val dragHandleToArrowAnim by lazy {
AnimatedVectorDrawableCompat.create(this, R.drawable.ic_drag_handle_to_arrow_anim)
}
private val arrowToDragHandleAnim by lazy {
AnimatedVectorDrawableCompat.create(this, R.drawable.ic_arrow_to_drag_handle_anim)
}
private val pickerHeight by lazy {
resources.getDimensionPixelSize(R.dimen.filter_picker_height).toFloat()
}
private val rootView by lazy { findViewById<View>(R.id.root_view) }
private val rootViewBottom: Float
get() = rootView.bottom.toFloat()
private val resultHandleHeightVisible by lazy {
resources.getDimensionPixelSize(R.dimen.filter_results_handle_height_visible).toFloat()
}
private val resultHandleHeightHidden by lazy {
resources.getDimensionPixelSize(R.dimen.filter_results_handle_height_hidden).toFloat()
}
private val filterActivityContentLoadTracer = filterActivityContentLoadTracer()
private val filterPickerLoadTracer = filterPickerLoadTracer()
private val filterPickerResetPresenter = filterPickerResetPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
filterActivityContentLoadTracer.start()
filterPickerLoadTracer.start()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_filter)
toolbar.inflateMenu(R.menu.menu_filter_search)
toolbar.setOnMenuItemClickListener(this)
bottomSheetView.hiddenListener = this
bottomSheetView.viewTreeObserver.addOnPreDrawListener {
updateResultsHandle()
updateFilterPickerClipRect()
return@addOnPreDrawListener true
}
bottomSheetView.showAircraftListener = {
// clear the listener so we don't get called again
bottomSheetView.showAircraftListener = null
filterActivityContentLoadTracer.stop()
}
filterPicker.showFilterListener = {
// clear the listener so we don't get called again
filterPicker.showFilterListener = null
filterPickerLoadTracer.stop()
}
resultsHandleContainer.setOnClickListener { toggleBottomSheetHidden() }
resultsHandleContainer.setOnTouchListener { _, event ->
bottomSheetView.onTouchEvent(event)
updateBottomSheetToggle(hidden = false)
return@setOnTouchListener false
}
}
override fun onStart() {
super.onStart()
filterPickerResetPresenter.startPresenting(this)
eventAnalytics().logScreenView(filterScreen())
}
override fun onStop() {
super.onStop()
filterPickerResetPresenter.stopPresenting()
}
override fun onMenuItemClick(item: MenuItem): Boolean {
return when {
item.itemId == R.id.action_search -> {
navigator.launchSearchActivity()
true
}
item.itemId == R.id.action_reset -> {
filterPicker.clearFilters()
filterPickerResetPresenter.resetFilters()
true
}
else -> false
}
}
override fun onBackPressed() {
if (bottomSheetView.isHidden) {
bottomSheetView.showBottomSheet()
} else {
super.onBackPressed()
}
}
override fun onBottomSheetHiddenChanged(hidden: Boolean) {
updateBottomSheetToggle(hidden)
filterPicker.scrollOnSelection = !hidden
}
private fun toggleBottomSheetHidden() {
if (bottomSheetView.isHidden) {
bottomSheetView.showBottomSheet()
} else {
bottomSheetView.hideBottomSheet()
}
}
override fun showReset() {
toolbar.menu.clear()
toolbar.inflateMenu(R.menu.menu_filter_reset)
}
override fun hideReset() {
toolbar.menu.clear()
toolbar.inflateMenu(R.menu.menu_filter_search)
}
private fun updateBottomSheetToggle(hidden: Boolean) {
if (hidden) {
if (resultsHandleView.drawable != dragHandleToArrowAnim) {
resultsHandleView.setImageDrawable(dragHandleToArrowAnim)
dragHandleToArrowAnim?.start()
}
} else {
if (resultsHandleView.drawable != arrowToDragHandleAnim) {
resultsHandleView.setImageDrawable(arrowToDragHandleAnim)
arrowToDragHandleAnim?.start()
}
}
}
private fun updateFilterPickerClipRect() {
filterPicker.clipBounds = Rect(
filterPicker.left,
filterPicker.top,
filterPicker.right,
bottomSheetView.top
)
}
private fun updateResultsHandle() {
resultsHandleContainer.translationY = bottomSheetView.y - resultsHandleContainer.height
if (rootViewBottom > 0) {
val percent = mapToPercent(
resultsHandleContainer.translationY,
pickerHeight,
rootViewBottom
)
val handleContainerHeight = mapFromPercent(
percent,
resultHandleHeightVisible,
resultHandleHeightHidden
).toInt()
if (handleContainerHeight != resultsHandleContainer.height) {
resultsHandleContainer.layoutParams.height = handleContainerHeight
resultsHandleContainer.requestLayout()
}
}
}
}
| gpl-3.0 | 3cbeaffe2395688d0cac50d614eb5cab | 36.755102 | 95 | 0.697027 | 5.481481 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/PagesLinkHandler.kt | 1 | 1796 | package org.wordpress.android.ui.deeplinks.handlers
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction
import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenPages
import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenPagesForSite
import org.wordpress.android.ui.deeplinks.DeepLinkUriUtils
import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.HOST_WORDPRESS_COM
import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.SITE_DOMAIN
import org.wordpress.android.util.UriWrapper
import javax.inject.Inject
class PagesLinkHandler
@Inject constructor(private val deepLinkUriUtils: DeepLinkUriUtils) : DeepLinkHandler {
/**
* Returns true if the URI looks like `wordpress.com/pages`
*/
override fun shouldHandleUrl(uri: UriWrapper): Boolean {
return uri.host == HOST_WORDPRESS_COM &&
uri.pathSegments.firstOrNull() == PAGES_PATH
}
override fun buildNavigateAction(uri: UriWrapper): NavigateAction {
val targetHost: String = uri.lastPathSegment ?: ""
val site: SiteModel? = deepLinkUriUtils.hostToSite(targetHost)
return if (site != null) {
OpenPagesForSite(site)
} else {
// In other cases, launch pages with the current selected site.
OpenPages
}
}
override fun stripUrl(uri: UriWrapper): String {
return buildString {
append("$HOST_WORDPRESS_COM/$PAGES_PATH")
if (uri.pathSegments.size > 1) {
append("/$SITE_DOMAIN")
}
}
}
companion object {
private const val PAGES_PATH = "pages"
}
}
| gpl-2.0 | 96fc87370aa1d9fd96f5fa290e688ca8 | 38.043478 | 105 | 0.709911 | 4.65285 | false | false | false | false |
PKRoma/PocketHub | app/src/main/java/com/github/pockethub/android/ui/repo/RepositoryReadmeFragment.kt | 4 | 4543 | package com.github.pockethub.android.ui.repo
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.caverock.androidsvg.SVG
import com.github.pockethub.android.Intents
import com.github.pockethub.android.R
import com.github.pockethub.android.markwon.FontResolver
import com.github.pockethub.android.markwon.MarkwonUtils
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.ui.base.BaseFragment
import com.github.pockethub.android.util.ToastUtils
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.Repository
import com.meisolsson.githubsdk.service.repositories.RepositoryContentService
import com.uber.autodispose.SingleSubscribeProxy
import io.noties.markwon.Markwon
import io.noties.markwon.recycler.MarkwonAdapter
import io.noties.markwon.recycler.SimpleEntry
import io.noties.markwon.recycler.table.TableEntry
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.commonmark.ext.gfm.tables.TableBlock
import org.commonmark.node.FencedCodeBlock
import org.commonmark.node.HtmlBlock
import retrofit2.Response
class RepositoryReadmeFragment : BaseFragment() {
private lateinit var recyclerView: RecyclerView
private var data: String? = null
private var repo: Repository? = null
private var markwon: Markwon? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
repo = requireActivity().intent.getParcelableExtra(Intents.EXTRA_REPOSITORY)
val defaultBranch = if (repo!!.defaultBranch() == null) "master" else repo!!.defaultBranch()!!
val baseString = String.format("https://github.com/%s/%s/%s/%s/", repo!!.owner()!!.login(), repo!!.name(), "%s", defaultBranch)
SVG.registerExternalFileResolver(FontResolver(requireActivity().assets))
markwon = MarkwonUtils.createMarkwon(requireContext(), baseString)
loadReadMe()
}
private fun loadReadMe() {
ServiceGenerator.createService(activity, RepositoryContentService::class.java)
.getReadmeRaw(repo!!.owner()!!.login(), repo!!.name(), null)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`<SingleSubscribeProxy<Response<String?>>>(AutoDisposeUtils.bindToLifecycle(this))
.subscribe { response: Response<String?> ->
if (response.isSuccessful) {
setMarkdown(response.body())
} else {
ToastUtils.show(requireActivity(), R.string.error_rendering_markdown)
}
}
}
private fun setMarkdown(body: String?) {
data = body
if (!this::recyclerView.isInitialized) {
return
}
val adapter = MarkwonAdapter.builderTextViewIsRoot(R.layout.markwon_adapter)
.include(HtmlBlock::class.java, SimpleEntry.createTextViewIsRoot(R.layout.markwon_adapter_test))
.include(FencedCodeBlock::class.java, SimpleEntry.create(R.layout.adapter_fenced_code_block, R.id.text))
.include(TableBlock::class.java, TableEntry.create { builder: TableEntry.Builder ->
builder
.tableLayout(R.layout.markwon_table_block, R.id.table_layout)
.textLayoutIsRoot(R.layout.markwon_table_cell)
})
.build()
recyclerView.adapter = adapter
adapter.setMarkdown(markwon!!, body!!)
adapter.notifyDataSetChanged()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val recyclerView = RecyclerView(inflater.context)
recyclerView.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
recyclerView.layoutManager = LinearLayoutManager(inflater.context)
return recyclerView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view as RecyclerView
if (data != null) {
setMarkdown(data)
}
}
} | apache-2.0 | 592ce9e1e24ce17c074e16a88cb198e8 | 44.44 | 135 | 0.705041 | 4.807407 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt | 1 | 2695 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.checkers.ConstModifierChecker
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceJvmFieldWithConstFix(annotation: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotation) {
override fun getText(): String = KotlinBundle.message("replace.jvmfield.with.const")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val property = element?.getParentOfType<KtProperty>(false) ?: return
element?.delete()
property.addModifier(KtTokens.CONST_KEYWORD)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val annotation = diagnostic.psiElement as? KtAnnotationEntry ?: return null
val property = annotation.getParentOfType<KtProperty>(false) ?: return null
val propertyDescriptor = property.descriptor as? PropertyDescriptor ?: return null
if (!ConstModifierChecker.canBeConst(property, property, propertyDescriptor)) {
return null
}
val initializer = property.initializer ?: return null
if (!initializer.isConstantExpression()) {
return null
}
return ReplaceJvmFieldWithConstFix(annotation)
}
private fun KtExpression.isConstantExpression() =
ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL))?.let { !it.usesNonConstValAsConstant } ?: false
}
} | apache-2.0 | 6af7ce7e5c8a64000fbb2940bafc4d5d | 47.142857 | 158 | 0.76475 | 5.056285 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/dsls/embed/EmbedDSL.kt | 1 | 943 | package me.aberrantfox.hotbot.dsls.embed
import net.dv8tion.jda.core.EmbedBuilder
import net.dv8tion.jda.core.entities.MessageEmbed
class EmbedDSLHandle : EmbedBuilder() {
operator fun invoke(args: EmbedDSLHandle.() -> Unit) {}
fun title(title: String?) = this.setTitle(title)
fun description(descr: String?) = this.setDescription(descr)
fun field(construct: FieldStore.() -> Unit) {
val field = FieldStore()
field.construct()
addField(field.name, field.value, field.inline)
}
fun ifield(construct: FieldStore.() -> Unit) {
val field = FieldStore()
field.construct()
addField(field.name, field.value, true)
}
}
data class FieldStore(var name: String? = "", var value: String? = "", var inline: Boolean = true)
fun embed(construct: EmbedDSLHandle.() -> Unit): MessageEmbed {
val handle = EmbedDSLHandle()
handle.construct()
return handle.build()
} | mit | 0d419e3197f927e9834e29a162efceff | 27.606061 | 98 | 0.669141 | 3.929167 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/media/camera2/CameraResolver.kt | 1 | 1002 | package com.haishinkit.media.camera2
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.util.Size
class CameraResolver(private val manager: CameraManager) {
fun getCameraId(facing: Int): String? {
for (id in manager.cameraIdList) {
val chars = manager.getCameraCharacteristics(id)
if (chars.get(CameraCharacteristics.LENS_FACING) == facing) {
return id
}
}
return null
}
fun getFacing(characteristics: CameraCharacteristics): Int? {
return characteristics.get(CameraCharacteristics.LENS_FACING)
}
fun getCameraSize(characteristics: CameraCharacteristics?): Size {
val scm = characteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
val cameraSizes = scm?.getOutputSizes(SurfaceTexture::class.java) ?: return Size(0, 0)
return cameraSizes[0]
}
}
| bsd-3-clause | fd7b8243e58dfa42e8d583bf8b241175 | 34.785714 | 94 | 0.705589 | 4.817308 | false | false | false | false |
zhiayang/pew | core/src/main/kotlin/Items/Weapons/Fists.kt | 1 | 1077 | // Copyright (c) 2014 Orion Industries, [email protected]
// Licensed under the Apache License version 2.0
package Items.Weapons
import Abstractions.Entity
import Abstractions.Damageable
import Entities.CharacterEntity
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.Camera
import Utilities.DelayComponent
public class Fists : MeleeWeapon("fist.basic")
{
override val delay: DelayComponent = DelayComponent(1.0f)
override var animDelay: DelayComponent = DelayComponent(1.0f)
override val range: Float = 1.0f
override val maxStackSize: Int = 1
override var durability: Int = 1
override fun Use(e: Entity?)
{
}
override fun Attack(owner: Entity, target: Damageable?): Boolean
{
return if (owner is CharacterEntity && target != null && Utilities.isWithinRange(owner, target, this.range))
{
// deal damage
target.Damage(2)
true
}
else
{
false
}
}
override fun Render(spriteBatch: SpriteBatch, owner: Entity, delta: Float, camera: Camera)
{
// do nothing, since weapons are part of the sprite...
}
}
| apache-2.0 | 249c4bcf9d01bb436a0f0240a1f7e06c | 23.477273 | 110 | 0.741876 | 3.419048 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/lookups/TailTextProvider.kt | 3 | 2612 | // 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.completion.lookups
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol
import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType
import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor
import org.jetbrains.kotlin.idea.completion.impl.k2.KotlinCompletionImplK2Bundle
import org.jetbrains.kotlin.idea.completion.lookups.CompletionShortNamesRenderer.renderFunctionParameters
import org.jetbrains.kotlin.name.FqName
internal object TailTextProvider {
fun KtAnalysisSession.getTailText(symbol: KtCallableSymbol, substitutor: KtSubstitutor): String = buildString {
if (symbol is KtFunctionSymbol) {
if (insertLambdaBraces(symbol)) {
append(" {...}")
} else {
append(renderFunctionParameters(symbol, substitutor))
}
}
symbol.callableIdIfNonLocal
?.takeIf { it.className == null }
?.let { callableId ->
append(" (")
append(callableId.packageName.asStringForTailText())
append(")")
}
symbol.receiverType?.let { receiverType ->
val renderedType = receiverType.render(CompletionShortNamesRenderer.TYPE_RENDERING_OPTIONS)
append(KotlinCompletionImplK2Bundle.message("presentation.tail.for.0", renderedType))
}
}
fun KtAnalysisSession.getTailText(symbol: KtClassLikeSymbol): String = buildString {
symbol.classIdIfNonLocal?.let { classId ->
append(" (")
append(classId.asSingleFqName().parent().asStringForTailText())
append(")")
}
}
private fun FqName.asStringForTailText(): String =
if (isRoot) "<root>" else asString()
fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionSymbol): Boolean {
val singleParam = symbol.valueParameters.singleOrNull()
return singleParam != null && !singleParam.hasDefaultValue && singleParam.returnType is KtFunctionalType
}
fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionalType): Boolean {
val singleParam = symbol.parameterTypes.singleOrNull()
return singleParam != null && singleParam is KtFunctionalType
}
} | apache-2.0 | f1eb150b4cb9b07b32310018e70ed0f3 | 42.55 | 158 | 0.705207 | 5.091618 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/util/projectWizard/PanelBuilderSettingsStep.kt | 2 | 2029 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.projectWizard
import com.intellij.ide.wizard.NewProjectWizardBaseStep
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.Panel
import com.intellij.util.PathUtil
import java.io.File
import javax.swing.JComponent
class PanelBuilderSettingsStep(private val wizardContext: WizardContext,
private val builder: Panel,
private val baseStep: NewProjectWizardBaseStep) : SettingsStep {
override fun getContext(): WizardContext = wizardContext
override fun addSettingsField(label: String, field: JComponent) {
with(builder) {
row(label) {
cell(field).align(AlignX.FILL)
}.bottomGap(BottomGap.SMALL)
}
}
override fun addSettingsComponent(component: JComponent) {
with(builder) {
row("") {
cell(component).align(AlignX.FILL)
}.bottomGap(BottomGap.SMALL)
}
}
override fun addExpertPanel(panel: JComponent) {
addSettingsComponent(panel)
}
override fun addExpertField(label: String, field: JComponent) {
addSettingsField(label, field)
}
override fun getModuleNameLocationSettings(): ModuleNameLocationSettings {
return object : ModuleNameLocationSettings {
override fun getModuleName(): String = baseStep.name
override fun setModuleName(moduleName: String) {
baseStep.name = moduleName
}
override fun getModuleContentRoot(): String {
return FileUtil.toSystemDependentName(baseStep.path).trimEnd(File.separatorChar) + File.separatorChar + baseStep.name
}
override fun setModuleContentRoot(path: String) {
baseStep.path = PathUtil.getParentPath(path)
baseStep.name = PathUtil.getFileName(path)
}
}
}
} | apache-2.0 | 69cd6a8b6cdb05aad4eb6a936cbe909d | 32.833333 | 158 | 0.714145 | 4.580135 | false | false | false | false |
jk1/intellij-community | java/compiler/impl/src/com/intellij/compiler/chainsSearch/RefChainOperation.kt | 3 | 4623 | // 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.compiler.chainsSearch
import com.intellij.compiler.backwardRefs.CompilerReferenceServiceEx
import com.intellij.compiler.chainsSearch.context.ChainCompletionContext
import com.intellij.compiler.chainsSearch.context.ChainSearchTarget
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiUtil
import org.jetbrains.jps.backwardRefs.CompilerRef
import org.jetbrains.jps.backwardRefs.SignatureData
sealed class RefChainOperation {
abstract val qualifierRawName: String
abstract val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef
abstract val compilerRef: CompilerRef
}
class TypeCast(override val compilerRef: CompilerRef.CompilerClassHierarchyElementDef,
val castTypeRef: CompilerRef.CompilerClassHierarchyElementDef,
refService: CompilerReferenceServiceEx): RefChainOperation() {
override val qualifierRawName: String
get() = operandName.value
override val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef
get() = compilerRef
private val operandName = lazy(LazyThreadSafetyMode.NONE) {
refService.getName(compilerRef.name)
}
}
class MethodCall(override val compilerRef: CompilerRef.JavaCompilerMethodRef,
private val signatureData: SignatureData,
private val context: ChainCompletionContext): RefChainOperation() {
private companion object {
val CONSTRUCTOR_METHOD_NAME = "<init>"
}
override val qualifierRawName: String
get() = owner.value
override val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef
get() = compilerRef.owner
private val name = lazy(LazyThreadSafetyMode.NONE) {
context.refService.getName(compilerRef.name)
}
private val owner = lazy(LazyThreadSafetyMode.NONE) {
context.refService.getName(compilerRef.owner.name)
}
private val rawReturnType = lazy(LazyThreadSafetyMode.NONE) {
context.refService.getName(signatureData.rawReturnType)
}
val isStatic: Boolean
get() = signatureData.isStatic
fun resolve(): Array<PsiMethod> {
if (CONSTRUCTOR_METHOD_NAME == name.value) {
return PsiMethod.EMPTY_ARRAY
}
val aClass = context.resolvePsiClass(qualifierDef) ?: return PsiMethod.EMPTY_ARRAY
return aClass.findMethodsByName(name.value, true)
.filter { it.hasModifierProperty(PsiModifier.STATIC) == isStatic }
.filter { !it.isDeprecated }
.filter { context.accessValidator().test(it) }
.filter {
val returnType = it.returnType
when (signatureData.iteratorKind) {
SignatureData.ARRAY_ONE_DIM -> {
when (returnType) {
is PsiArrayType -> {
val componentType = returnType.componentType
componentType is PsiClassType && componentType.resolve()?.qualifiedName == rawReturnType.value
}
else -> false
}
}
SignatureData.ITERATOR_ONE_DIM -> {
val iteratorKind = ChainSearchTarget.getIteratorKind(PsiUtil.resolveClassInClassTypeOnly(returnType))
when {
iteratorKind != null -> PsiUtil.resolveClassInClassTypeOnly(PsiUtil.substituteTypeParameter(returnType, iteratorKind, 0, false))?.qualifiedName == rawReturnType.value
else -> false
}
}
SignatureData.ZERO_DIM -> returnType is PsiClassType && returnType.resolve()?.qualifiedName == rawReturnType.value
else -> throw IllegalStateException("kind is unsupported ${signatureData.iteratorKind}")
}
}
.sortedBy({ it.parameterList.parametersCount })
.toTypedArray()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as MethodCall
if (compilerRef.owner != other.compilerRef.owner) return false
if (compilerRef.name != other.compilerRef.name) return false
if (signatureData != other.signatureData) return false
return true
}
override fun hashCode(): Int {
var result = compilerRef.owner.hashCode()
result = 31 * result + compilerRef.name.hashCode()
result = 31 * result + signatureData.hashCode()
return result
}
override fun toString(): String {
return qualifierRawName + (if (isStatic) "." else "#") + name + "(" + compilerRef.parameterCount + ")"
}
}
| apache-2.0 | b948187105daa5f17315a9173e902364 | 36.585366 | 180 | 0.714039 | 4.997838 | false | false | false | false |
mihkels/graphite-client-kotlin | bash-script-executor/src/main/kotlin/com/mihkels/graphite/bash/SimpleBashExecutor.kt | 1 | 2422 | package com.mihkels.graphite.bash
import mu.KLogging
import org.zeroturnaround.exec.ProcessExecutor
import org.zeroturnaround.exec.stream.slf4j.Slf4jStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.streams.toList
interface BashExecutor {
fun runScript(scriptName: String): String
fun runDirectory(directoryName: String, callback: (String, String) -> Unit = {p1, p2 ->}): List<String>
}
class SimpleBashExecutor: BashExecutor {
companion object: KLogging()
private val fileHelpers = FileHelpers()
override fun runScript(scriptName: String): String {
val fullPath = fileHelpers.getPath(scriptName)
return executeScript(fullPath.normalize().toString())
}
override fun runDirectory(directoryName: String, callback: (outpput: String, scriptName: String) -> Unit): List<String> {
val output: MutableList<String> = mutableListOf()
fileHelpers.getFiles(directoryName).forEach {
logger.info { "Executing script: $it" }
val scriptOutput = executeScript(it)
output.add(scriptOutput)
callback(scriptOutput, it)
}
return output
}
private fun executeScript(fullPath: String): String {
return ProcessExecutor().command(fullPath)
.redirectOutput(Slf4jStream.of(javaClass).asInfo())
.readOutput(true).execute().outputUTF8()
}
}
internal class FileHelpers {
fun getPath(scriptName: String): Path {
var localScriptName = Paths.get(scriptName)
val resourceRoot = this::class.java.getResource("/")?.path
localScriptName = if (Files.exists(localScriptName)) localScriptName
else Paths.get("$resourceRoot/$scriptName")
if (Files.notExists(localScriptName)) {
throw IOException("No such file $localScriptName make sure the BASH script path is correct")
}
return localScriptName
}
fun getFiles(inputPath: String): List<String> {
val scriptDirectoryPath = getPath(inputPath)
var files: List<String> = emptyList()
Files.walk(scriptDirectoryPath).use { paths ->
files = paths.filter { path -> Files.isRegularFile(path) }
.map { it.toAbsolutePath().normalize().toString() }
.toList()
}
return files
}
}
| mit | a94706731d6d067ed4a7dd9d4db616bb | 32.178082 | 126 | 0.66474 | 4.411658 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/review/AddMessageDialogFragment.kt | 1 | 7807 | package org.thoughtcrime.securesms.mediasend.v2.review
import android.content.DialogInterface
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import org.signal.core.util.EditTextUtil
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.ComposeText
import org.thoughtcrime.securesms.components.InputAwareLayout
import org.thoughtcrime.securesms.components.KeyboardEntryDialogFragment
import org.thoughtcrime.securesms.components.emoji.EmojiToggle
import org.thoughtcrime.securesms.components.emoji.MediaKeyboard
import org.thoughtcrime.securesms.components.mention.MentionAnnotation
import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerFragment
import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerViewModel
import org.thoughtcrime.securesms.keyboard.KeyboardPage
import org.thoughtcrime.securesms.keyboard.KeyboardPagerViewModel
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.mediasend.v2.HudCommand
import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionViewModel
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.views.Stub
import org.thoughtcrime.securesms.util.visible
class AddMessageDialogFragment : KeyboardEntryDialogFragment(R.layout.v2_media_add_message_dialog_fragment) {
private val viewModel: MediaSelectionViewModel by viewModels(
ownerProducer = { requireActivity() }
)
private val keyboardPagerViewModel: KeyboardPagerViewModel by viewModels(
ownerProducer = { requireActivity() }
)
private val mentionsViewModel: MentionsPickerViewModel by viewModels(
ownerProducer = { requireActivity() },
factoryProducer = { MentionsPickerViewModel.Factory() }
)
private lateinit var input: ComposeText
private lateinit var emojiDrawerToggle: EmojiToggle
private lateinit var emojiDrawerStub: Stub<MediaKeyboard>
private lateinit var hud: InputAwareLayout
private lateinit var mentionsContainer: ViewGroup
private var requestedEmojiDrawer: Boolean = false
private val disposables = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val themeWrapper = ContextThemeWrapper(inflater.context, R.style.TextSecure_DarkTheme)
val themedInflater = LayoutInflater.from(themeWrapper)
return super.onCreateView(themedInflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
input = view.findViewById(R.id.add_a_message_input)
EditTextUtil.addGraphemeClusterLimitFilter(input, Stories.MAX_BODY_SIZE)
input.setText(requireArguments().getCharSequence(ARG_INITIAL_TEXT))
emojiDrawerToggle = view.findViewById(R.id.emoji_toggle)
emojiDrawerStub = Stub(view.findViewById(R.id.emoji_drawer_stub))
if (SignalStore.settings().isPreferSystemEmoji) {
emojiDrawerToggle.visible = false
} else {
emojiDrawerToggle.setOnClickListener { onEmojiToggleClicked() }
}
hud = view.findViewById(R.id.hud)
hud.setOnClickListener { dismissAllowingStateLoss() }
val confirm: View = view.findViewById(R.id.confirm_button)
confirm.setOnClickListener { dismissAllowingStateLoss() }
disposables.add(
viewModel.hudCommands.observeOn(AndroidSchedulers.mainThread()).subscribe {
when (it) {
HudCommand.OpenEmojiSearch -> openEmojiSearch()
HudCommand.CloseEmojiSearch -> closeEmojiSearch()
is HudCommand.EmojiKeyEvent -> onKeyEvent(it.keyEvent)
is HudCommand.EmojiInsert -> onEmojiSelected(it.emoji)
else -> Unit
}
}
)
initializeMentions()
}
override fun onResume() {
super.onResume()
requestedEmojiDrawer = false
ViewUtil.focusAndShowKeyboard(input)
}
override fun onPause() {
super.onPause()
ViewUtil.hideKeyboard(requireContext(), input)
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
viewModel.setMessage(input.text)
}
override fun onKeyboardHidden() {
if (!requestedEmojiDrawer) {
super.onKeyboardHidden()
}
}
override fun onDestroyView() {
super.onDestroyView()
disposables.dispose()
input.setMentionQueryChangedListener(null)
input.setMentionValidator(null)
}
private fun initializeMentions() {
val recipientId: RecipientId = viewModel.destination.getRecipientSearchKey()?.recipientId ?: return
mentionsContainer = requireView().findViewById(R.id.mentions_picker_container)
Recipient.live(recipientId).observe(viewLifecycleOwner) { recipient ->
mentionsViewModel.onRecipientChange(recipient)
input.setMentionQueryChangedListener { query ->
if (recipient.isPushV2Group) {
ensureMentionsContainerFilled()
mentionsViewModel.onQueryChange(query)
}
}
input.setMentionValidator { annotations ->
if (!recipient.isPushV2Group) {
annotations
} else {
val validRecipientIds: Set<String> = recipient.participants
.map { r -> MentionAnnotation.idToMentionAnnotationValue(r.id) }
.toSet()
annotations
.filter { !validRecipientIds.contains(it.value) }
.toList()
}
}
}
mentionsViewModel.selectedRecipient.observe(viewLifecycleOwner) { recipient ->
input.replaceTextWithMention(recipient.getDisplayName(requireContext()), recipient.id)
}
}
private fun ensureMentionsContainerFilled() {
val mentionsFragment = childFragmentManager.findFragmentById(R.id.mentions_picker_container)
if (mentionsFragment == null) {
childFragmentManager
.beginTransaction()
.replace(R.id.mentions_picker_container, MentionsPickerFragment())
.commitNowAllowingStateLoss()
}
}
private fun onEmojiToggleClicked() {
if (!emojiDrawerStub.resolved()) {
keyboardPagerViewModel.setOnlyPage(KeyboardPage.EMOJI)
emojiDrawerStub.get().setFragmentManager(childFragmentManager)
emojiDrawerToggle.attach(emojiDrawerStub.get())
}
if (hud.currentInput == emojiDrawerStub.get()) {
requestedEmojiDrawer = false
hud.showSoftkey(input)
} else {
requestedEmojiDrawer = true
hud.hideSoftkey(input) {
hud.post {
hud.show(input, emojiDrawerStub.get())
}
}
}
}
private fun openEmojiSearch() {
if (emojiDrawerStub.resolved()) {
emojiDrawerStub.get().onOpenEmojiSearch()
}
}
private fun closeEmojiSearch() {
if (emojiDrawerStub.resolved()) {
emojiDrawerStub.get().onCloseEmojiSearch()
}
}
private fun onEmojiSelected(emoji: String?) {
input.insertEmoji(emoji)
}
private fun onKeyEvent(keyEvent: KeyEvent?) {
input.dispatchKeyEvent(keyEvent)
}
companion object {
const val TAG = "ADD_MESSAGE_DIALOG_FRAGMENT"
private const val ARG_INITIAL_TEXT = "arg.initial.text"
fun show(fragmentManager: FragmentManager, initialText: CharSequence?) {
AddMessageDialogFragment().apply {
arguments = Bundle().apply {
putCharSequence(ARG_INITIAL_TEXT, initialText)
}
}.show(fragmentManager, TAG)
}
}
}
| gpl-3.0 | 718b9d42666643d43897b49667d226cf | 32.080508 | 113 | 0.745229 | 4.888541 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/settings/my/MyStorySettingsViewModel.kt | 1 | 1605 | package org.thoughtcrime.securesms.stories.settings.my
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.thoughtcrime.securesms.util.livedata.Store
class MyStorySettingsViewModel(private val repository: MyStorySettingsRepository) : ViewModel() {
private val store = Store(MyStorySettingsState())
private val disposables = CompositeDisposable()
val state: LiveData<MyStorySettingsState> = store.stateLiveData
override fun onCleared() {
disposables.clear()
}
fun refresh() {
disposables.clear()
disposables += repository.getHiddenRecipientCount()
.subscribe { count -> store.update { it.copy(hiddenStoryFromCount = count) } }
disposables += repository.getRepliesAndReactionsEnabled()
.subscribe { repliesAndReactionsEnabled -> store.update { it.copy(areRepliesAndReactionsEnabled = repliesAndReactionsEnabled) } }
}
fun setRepliesAndReactionsEnabled(repliesAndReactionsEnabled: Boolean) {
disposables += repository.setRepliesAndReactionsEnabled(repliesAndReactionsEnabled)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { refresh() }
}
class Factory(private val repository: MyStorySettingsRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(MyStorySettingsViewModel(repository)) as T
}
}
}
| gpl-3.0 | 79eecfc0b6ba7d40e9655e2ec8ec9e2d | 39.125 | 135 | 0.78567 | 5.111465 | false | false | false | false |
marius-m/wt4 | models/src/main/java/lt/markmerkk/entities/TicketCode.kt | 1 | 942 | package lt.markmerkk.entities
import lt.markmerkk.utils.LogUtils
data class TicketCode private constructor(
val codeProject: String,
val codeNumber: String
) {
val code: String = if (isEmpty()) "" else "$codeProject-$codeNumber"
fun isEmpty(): Boolean = codeProject.isEmpty()
&& codeNumber.isEmpty()
companion object {
fun asEmpty(): TicketCode = TicketCode(
codeProject = "",
codeNumber = ""
)
fun new(
code: String
): TicketCode {
val validTicketCode = LogUtils.validateTaskTitle(code)
if (validTicketCode.isEmpty()) {
return asEmpty()
}
return TicketCode(
codeProject = LogUtils.splitTaskTitle(validTicketCode),
codeNumber = LogUtils.splitTaskNumber(validTicketCode).toString()
)
}
}
} | apache-2.0 | 1e30e4caaf2f2dc0dbccc527c67bc9e3 | 26.735294 | 85 | 0.559448 | 5.119565 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchSettingsPreference.kt | 2 | 1102 | package eu.kanade.tachiyomi.widget.preference
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.preference.PreferenceViewHolder
import androidx.preference.SwitchPreferenceCompat
import eu.kanade.tachiyomi.R
class SwitchSettingsPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
SwitchPreferenceCompat(context, attrs) {
var onSettingsClick: View.OnClickListener? = null
init {
widgetLayoutResource = R.layout.pref_settings
}
@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
holder.findViewById(R.id.button).setOnClickListener {
onSettingsClick?.onClick(it)
}
// Disable swiping to align with SwitchPreferenceCompat
holder.findViewById(R.id.switchWidget).setOnTouchListener { _, event ->
event.actionMasked == MotionEvent.ACTION_MOVE
}
}
}
| apache-2.0 | 826b7dcd9c7730d6df62b234a31dd1d4 | 31.411765 | 105 | 0.750454 | 5.198113 | false | false | false | false |
KDE/kdeconnect-android | src/org/kde/kdeconnect/Plugins/ClibpoardPlugin/ClipboardTileService.kt | 1 | 1103 | /*
* SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
package org.kde.kdeconnect.Plugins.ClibpoardPlugin
import android.content.Intent
import android.os.Build
import android.service.quicksettings.TileService
import androidx.annotation.RequiresApi
import org.kde.kdeconnect.BackgroundService
@RequiresApi(Build.VERSION_CODES.N)
class ClipboardTileService : TileService() {
override fun onClick() {
super.onClick()
startActivityAndCollapse(Intent(this, ClipboardFloatingActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
var ids : List<String> = emptyList()
val service = BackgroundService.getInstance()
if (service != null) {
ids = service.devices.values
.filter { it.isReachable && it.isPaired }
.map { it.deviceId }
}
putExtra("connectedDeviceIds", ArrayList(ids))
})
}
}
| gpl-2.0 | c4769008c58edd0ff2ab5b5a6525af45 | 33.46875 | 92 | 0.669084 | 4.162264 | false | false | false | false |
saffih/ElmDroid | app/src/main/java/elmdroid/elmdroid/example1/hello/Turtle.kt | 1 | 3817 | package elmdroid.elmdroid.example1.hello
import elmdroid.elmdroid.example1.ExampleHelloWorldActivity
import kotlinx.android.synthetic.main.activity_helloworld.*
import saffih.elmdroid.ElmChild
/**
* Copyright Joseph Hartal (Saffi)
* Created by saffi on 9/05/17.
*/
// POJO
enum class ESpeed {
sleep,
slow,
fast,
rocket;
fun step(by: Int) = if (ordIn(ordinal + by)) ESpeed.values()[ordinal + by] else this
fun next() = step(1)
fun prev() = step(-1)
fun cnext() = cycle(ordinal + 1)
fun cprev() = cycle(ordinal - 1)
companion object {
fun ordIn(i: Int) = (i >= 0 && i < ESpeed.values().size)
fun cycle(i: Int) = ESpeed.values()[i % ESpeed.values().size]
}
}
// MODEL
data class Model(val speed: MSpeed = MSpeed(), val ui: MUIMode = MUIMode())
data class MSpeed(val speed: ESpeed = ESpeed.slow)
data class MUIMode(val faster: Boolean = true)
// MSG
sealed class Msg {
class Init : Msg()
sealed class ChangeSpeed : Msg() {
class Increase : ChangeSpeed()
class Decrease : ChangeSpeed()
class CycleUp : ChangeSpeed()
class Night : ChangeSpeed()
}
sealed class UI : Msg() {
class ToggleClicked : UI()
class NextSpeedClicked : UI()
}
}
abstract class Turtle(val me: ExampleHelloWorldActivity) :
ElmChild<Model, Msg>() {
override fun init(): Model{
dispatch( Msg.Init())
return Model()
}
private fun update(msg: Msg.Init, model: MSpeed): MSpeed{
return model
}
private fun update(msg: Msg.ChangeSpeed, model: MSpeed): MSpeed{
return when (msg) {
is Msg.ChangeSpeed.Increase -> model.copy(speed = model.speed.next())
is Msg.ChangeSpeed.Decrease -> model.copy(speed = model.speed.prev())
is Msg.ChangeSpeed.CycleUp -> model.copy(speed = model.speed.cnext())
is Msg.ChangeSpeed.Night -> model.copy(speed = ESpeed.sleep)
}
}
override fun update(msg: Msg, model: Model) : Model{
return when (msg) {
is Msg.Init -> {
val m = update(msg, model.speed)
val mu = update(msg, model.ui)
model.copy(speed = m, ui = mu)
}
is Msg.ChangeSpeed -> {
val m = update(msg, model.speed)
model.copy(speed = m)
}
is Msg.UI -> {
val m = update(msg, model.ui)
model.copy(ui = m)
}
}
}
private fun update(msg: Msg.UI, model: MUIMode) : MUIMode{
// return model)
return when (msg) {
is Msg.UI.ToggleClicked -> model.copy(faster = !model.faster)
is Msg.UI.NextSpeedClicked -> {
dispatch ( if (model.faster) Msg.ChangeSpeed.Increase() else Msg.ChangeSpeed.Decrease())
model
}
}
}
private fun update(msg: Msg.Init, model: MUIMode) : MUIMode{
return model
}
override fun view(model: Model, pre: Model?) {
val setup = {}
checkView(setup, model, pre) {
view(model.speed, pre?.speed)
view(model.ui, pre?.ui)
}
}
private fun view(model: MUIMode, pre: MUIMode?) {
val setup = {}
checkView(setup, model, pre) {
val mode = me.turtleFaster
mode.text = if (model.faster) "faster" else "slower"
mode.setOnClickListener { dispatch(Msg.UI.ToggleClicked()) }
}
}
private fun view(model: MSpeed, pre: MSpeed?) {
val setup = {}
checkView(setup, model, pre) {
val v = me.turtleSpeed
v.text = model.speed.name
v.setOnClickListener { dispatch(Msg.UI.NextSpeedClicked()) }
}
}
}
| apache-2.0 | a17fda87ba56271aac5e20a62fa6db28 | 27.066176 | 106 | 0.559602 | 3.906858 | false | false | false | false |
mdanielwork/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 1 | 22842 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.diagnostic.IdeErrorsDialog
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.plugins.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.service.fus.collectors.FUSApplicationUsageTrigger
import com.intellij.notification.*
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.LogUtil
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.loadElement
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import gnu.trove.THashMap
import org.jdom.JDOMException
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.collections.HashSet
import kotlin.collections.set
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker")
@JvmField val NOTIFICATIONS: NotificationGroup = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true)
private const val DISABLED_UPDATE = "disabled_update.txt"
private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL }
private var ourDisabledToUpdatePlugins: MutableSet<String>? = null
private val ourAdditionalRequestOptions = THashMap<String, String>()
private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>()
private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>()
/**
* Adding a plugin ID to this collection allows to exclude a plugin from a regular update check.
* Has no effect on non-bundled or "essential" (i.e. required for one of open projects) plugins.
*/
@Suppress("MemberVisibilityCanBePrivate")
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
val callback = ActionCallback()
ApplicationManager.getApplication().executeOnPooledThread {
doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback)
}
return callback
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action may pass customised update settings).
*/
@JvmStatic
fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) {
val settings = customSettings ?: UpdateSettings.getInstance()
val fromSettings = customSettings != null
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null)
override fun isConditionalModal(): Boolean = fromSettings
override fun shouldStartInBackground(): Boolean = !fromSettings
})
}
/**
* An immediate check for plugin updates for use from a command line (read "Toolbox").
*/
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
checkPluginsUpdate(UpdateSettings.getInstance(), EmptyProgressIndicator(), null, ApplicationInfo.getInstance().build)
private fun doUpdateAndShowResult(project: Project?,
fromSettings: Boolean,
manualCheck: Boolean,
updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
callback: ActionCallback?) {
// check platform update
indicator?.text = IdeBundle.message("updates.checking.platform")
val result = checkPlatformUpdate(updateSettings)
if (result.state == UpdateStrategy.State.CONNECTION_ERROR) {
val e = result.error
if (e != null) LOG.debug(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error"))
callback?.setRejected()
return
}
// check plugins update (with regard to potential platform update)
indicator?.text = IdeBundle.message("updates.checking.plugins")
val buildNumber: BuildNumber? = result.newBuild?.apiVersion
val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet() else null
val updatedPlugins: Collection<PluginDownloader>?
val externalUpdates: Collection<ExternalUpdate>?
try {
updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber)
externalUpdates = checkExternalUpdates(manualCheck, updateSettings, indicator)
}
catch (e: IOException) {
showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message))
callback?.setRejected()
return
}
// show result
UpdateSettings.getInstance().saveLastCheckedInfo()
ApplicationManager.getApplication().invokeLater({
showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck)
callback?.setDone()
}, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL)
}
private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult {
val updateInfo: UpdatesInfo?
try {
var updateUrl = Urls.newFromEncoded(updateUrl)
if (updateUrl.scheme != URLUtil.FILE_PROTOCOL) {
updateUrl = prepareUpdateCheckArgs(updateUrl, settings.packageManagerName)
}
LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl)
updateInfo = HttpRequests.request(updateUrl)
.forceHttps(settings.canUseSecureConnection())
.connect {
try {
if (settings.isPlatformUpdateEnabled)
UpdatesInfo(loadElement(it.reader))
else
null
}
catch (e: JDOMException) {
// corrupted content, don't bother telling user
LOG.info(e)
null
}
}
}
catch (e: Exception) {
LOG.info(e)
return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e)
}
if (updateInfo == null) {
return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null)
}
val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings)
return strategy.checkForUpdates()
}
@JvmStatic
@Throws(IOException::class)
fun getUpdatesInfo(settings: UpdateSettings): UpdatesInfo? {
val updateUrl = Urls.newFromEncoded(updateUrl)
LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl)
return HttpRequests.request(updateUrl)
.forceHttps(settings.canUseSecureConnection())
.connect {
try {
UpdatesInfo(loadElement(it.reader))
}
catch (e: JDOMException) {
// corrupted content, don't bother telling user
LOG.info(e)
null
}
}
}
private fun checkPluginsUpdate(updateSettings: UpdateSettings,
indicator: ProgressIndicator?,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
buildNumber: BuildNumber?): Collection<PluginDownloader>? {
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) return null
val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>()
val state = InstalledPluginsState.getInstance()
outer@ for (host in RepositoryHelper.getPluginHosts()) {
try {
val forceHttps = host == null && updateSettings.canUseSecureConnection()
val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator)
for (descriptor in list) {
val id = descriptor.pluginId
if (updateable.containsKey(id)) {
updateable.remove(id)
state.onDescriptorDownload(descriptor)
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps)
checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator)
if (updateable.isEmpty()) {
break@outer
}
}
}
}
catch (e: IOException) {
LOG.debug(e)
LOG.info("failed to load plugin descriptions from ${host ?: "default repository"}: ${e.message}")
}
}
return if (toUpdate.isEmpty) null else toUpdate.values
}
/**
* Returns a list of plugins which are currently installed or were installed in the previous installation from which
* we're importing the settings.
*/
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> {
val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>()
updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId }
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
FileUtil.loadLines(onceInstalled)
.map { line -> PluginId.getId(line.trim { it <= ' ' }) }
.filter { it !in updateable }
.forEach { updateable[it] = null }
}
catch (e: IOException) {
LOG.error(onceInstalled.path, e)
}
//noinspection SSBasedInspection
onceInstalled.deleteOnExit()
}
if (!excludedFromUpdateCheckPlugins.isEmpty()) {
val required = ProjectManager.getInstance().openProjects
.flatMap { ExternalDependenciesManager.getInstance(it).getDependencies(DependencyOnPlugin::class.java) }
.map { PluginId.getId(it.pluginId) }
.toSet()
excludedFromUpdateCheckPlugins.forEach {
val excluded = PluginId.getId(it)
if (excluded !in required) {
val plugin = updateable[excluded]
if (plugin != null && plugin.isBundled) {
updateable.remove(excluded)
}
}
}
}
return updateable
}
private fun checkExternalUpdates(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> {
val result = arrayListOf<ExternalUpdate>()
val manager = ExternalComponentManager.getInstance()
indicator?.text = IdeBundle.message("updates.external.progress")
for (source in manager.componentSources) {
indicator?.checkCanceled()
if (source.name in updateSettings.enabledExternalUpdateSources) {
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (!siteResult.isEmpty()) {
result += ExternalUpdate(siteResult, source)
}
}
catch (e: Exception) {
LOG.warn(e)
showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error"))
}
}
}
return result
}
@Throws(IOException::class)
@JvmStatic
fun checkAndPrepareToInstall(downloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?,
indicator: ProgressIndicator?) {
@Suppress("NAME_SHADOWING")
var downloader = downloader
val pluginId = downloader.pluginId
if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return
val pluginVersion = downloader.pluginVersion
val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId))
if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) {
var descriptor: IdeaPluginDescriptor?
val oldDownloader = ourUpdatedPlugins[pluginId]
if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
descriptor = downloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) {
descriptor = downloader.descriptor
}
ourUpdatedPlugins[pluginId] = downloader
}
}
else {
downloader = oldDownloader
descriptor = oldDownloader.descriptor
}
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[PluginId.getId(pluginId)] = downloader
}
}
// collect plugins which were not updated and would be incompatible with new version
if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled &&
!toUpdate.containsKey(installedPlugin.pluginId) &&
!PluginManagerCore.isCompatible(installedPlugin, downloader.buildNumber)) {
incompatiblePlugins += installedPlugin
}
}
private fun showErrorMessage(showDialog: Boolean, message: String) {
LOG.info(message)
if (showDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) }
}
}
private fun showUpdateResult(project: Project?,
checkForUpdateResult: CheckForUpdateResult,
updateSettings: UpdateSettings,
updatedPlugins: Collection<PluginDownloader>?,
incompatiblePlugins: Collection<IdeaPluginDescriptor>?,
externalUpdates: Collection<ExternalUpdate>?,
enableLink: Boolean,
alwaysShowResults: Boolean) {
val updatedChannel = checkForUpdateResult.updatedChannel
val newBuild = checkForUpdateResult.newBuild
if (updatedChannel != null && newBuild != null) {
val runnable = {
val patches = checkForUpdateResult.patches
val forceHttps = updateSettings.canUseSecureConnection()
UpdateInfoDialog(updatedChannel, newBuild, patches, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show()
}
ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.shown")
val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName)
showNotification(project, message, {
FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.clicked")
runnable()
}, NotificationUniqueType.PLATFORM)
}
return
}
var updateFound = false
if (updatedPlugins != null && !updatedPlugins.isEmpty()) {
updateFound = true
val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() }
ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName }
val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins)
showNotification(project, message, runnable, NotificationUniqueType.PLUGINS)
}
}
if (externalUpdates != null && !externalUpdates.isEmpty()) {
updateFound = true
ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (alwaysShowResults) {
runnable.invoke()
}
else {
val updates = update.components.joinToString(", ")
val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates)
showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL)
}
}
}
if (!updateFound && alwaysShowResults) {
NoUpdatesDialog(enableLink).show()
}
}
private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) {
val listener = NotificationListener { notification, _ ->
notification.expire()
action.invoke()
}
val title = IdeBundle.message("update.notifications.title")
val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener)
notification.whenExpired { ourShownNotifications.remove(notificationType, notification) }
notification.notify(project)
ourShownNotifications.putValue(notificationType, notification)
}
@JvmStatic
fun addUpdateRequestParameter(name: String, value: String) {
ourAdditionalRequestOptions[name] = value
}
private fun prepareUpdateCheckArgs(url: Url, packageManagerName: String?): Url {
addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString())
addUpdateRequestParameter("uid", PermanentInstallationID.get())
addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (packageManagerName != null) {
addUpdateRequestParameter("manager", packageManagerName)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
addUpdateRequestParameter("eap", "")
}
return url.addParameters(ourAdditionalRequestOptions)
}
@Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID"))
@JvmStatic
@Suppress("unused", "UNUSED_PARAMETER")
fun getInstallationUID(c: PropertiesComponent): String = PermanentInstallationID.get()
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() {
if (ourDisabledToUpdatePlugins == null) {
ourDisabledToUpdatePlugins = TreeSet()
if (!ApplicationManager.getApplication().isUnitTestMode) {
try {
val file = File(PathManager.getConfigPath(), DISABLED_UPDATE)
if (file.isFile) {
FileUtil.loadFile(file)
.split("[\\s]".toRegex())
.map { it.trim() }
.filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() }
}
}
catch (e: IOException) {
LOG.error(e)
}
}
}
return ourDisabledToUpdatePlugins!!
}
@JvmStatic
fun saveDisabledToUpdatePlugins() {
val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE)
try {
PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins)
}
catch (e: IOException) {
LOG.error(e)
}
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) {
val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
fun testPlatformUpdate(updateInfoText: String, patchFilePath: String?, forceUpdate: Boolean) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val channel: UpdateChannel?
val newBuild: BuildInfo?
val patches: UpdateChain?
if (forceUpdate) {
val node = loadElement(updateInfoText).getChild("product")?.getChild("channel") ?: throw IllegalArgumentException("//channel missing")
channel = UpdateChannel(node)
newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing")
patches = newBuild.patches.firstOrNull()?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
}
else {
val updateInfo = UpdatesInfo(loadElement(updateInfoText))
val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo)
val checkForUpdateResult = strategy.checkForUpdates()
channel = checkForUpdateResult.updatedChannel
newBuild = checkForUpdateResult.newBuild
patches = checkForUpdateResult.patches
}
if (channel != null && newBuild != null) {
val patchFile = if (patchFilePath != null) File(FileUtil.toSystemDependentName(patchFilePath)) else null
UpdateInfoDialog(channel, newBuild, patches, patchFile).show()
}
else {
NoUpdatesDialog(true).show()
}
}
} | apache-2.0 | e1a0bb60b1d9654db72f9befb36a1e21 | 39.216549 | 163 | 0.694072 | 5.40767 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.kt | 2 | 10998 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.IdeBundle
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.components.*
import com.intellij.openapi.editor.actions.CtrlYActionChooser
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.NaturalComparator
import com.intellij.ui.AppUIUtil
import com.intellij.util.ResourceUtil
import com.intellij.util.containers.ContainerUtil
import org.jdom.Element
import java.util.function.Function
import java.util.function.Predicate
const val KEYMAPS_DIR_PATH = "keymaps"
private const val ACTIVE_KEYMAP = "active_keymap"
private const val NAME_ATTRIBUTE = "name"
@State(name = "KeymapManager", storages = [(Storage(value = "keymap.xml", roamingType = RoamingType.PER_OS))],
additionalExportDirectory = KEYMAPS_DIR_PATH,
category = SettingsCategory.KEYMAP)
class KeymapManagerImpl : KeymapManagerEx(), PersistentStateComponent<Element> {
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<KeymapManagerListener>()
private val boundShortcuts = HashMap<String, String>()
private val schemeManager: SchemeManager<Keymap>
companion object {
@JvmStatic
var isKeymapManagerInitialized = false
private set
}
init {
schemeManager = SchemeManagerFactory.getInstance().create(KEYMAPS_DIR_PATH, object : LazySchemeProcessor<Keymap, KeymapImpl>() {
override fun createScheme(dataHolder: SchemeDataHolder<KeymapImpl>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean) = KeymapImpl(name, dataHolder)
override fun onCurrentSchemeSwitched(oldScheme: Keymap?,
newScheme: Keymap?,
processChangeSynchronously: Boolean) {
fireActiveKeymapChanged(newScheme, activeKeymap)
}
override fun reloaded(schemeManager: SchemeManager<Keymap>, schemes: Collection<Keymap>) {
if (schemeManager.activeScheme == null) {
// listeners expect that event will be fired in EDT
AppUIUtil.invokeOnEdt {
schemeManager.setCurrentSchemeName(DefaultKeymap.getInstance().defaultKeymapName, true)
}
}
}
})
val defaultKeymapManager = DefaultKeymap.getInstance()
val systemDefaultKeymap = WelcomeWizardUtil.getWizardMacKeymap() ?: defaultKeymapManager.defaultKeymapName
for (keymap in defaultKeymapManager.keymaps) {
schemeManager.addScheme(keymap)
if (keymap.name == systemDefaultKeymap) {
schemeManager.setCurrent(keymap, notify = false)
}
}
schemeManager.loadSchemes()
isKeymapManagerInitialized = true
if (ConfigImportHelper.isNewUser()) {
CtrlYActionChooser.askAboutShortcut()
}
fun removeKeymap(keymapName: String) {
val isCurrent = schemeManager.activeScheme?.name.equals(keymapName)
val keymap = schemeManager.removeScheme(keymapName)
if (keymap != null) {
fireKeymapRemoved(keymap)
}
DefaultKeymap.getInstance().removeKeymap(keymapName)
if (isCurrent) {
val activeKeymap = schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)
schemeManager.setCurrent(activeKeymap, notify = true, processChangeSynchronously = true)
fireActiveKeymapChanged(activeKeymap, activeKeymap)
}
}
BundledKeymapBean.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<BundledKeymapBean> {
override fun extensionAdded(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
val keymapName = getKeymapName(ep)
//if (!SystemInfo.isMac &&
// keymapName != KeymapManager.MAC_OS_X_KEYMAP &&
// keymapName != KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP &&
// DefaultKeymap.isBundledKeymapHidden(keymapName) &&
// schemeManager.findSchemeByName(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP) == null) return
val keymap = DefaultKeymap.getInstance().loadKeymap(keymapName, object : SchemeDataHolder<KeymapImpl> {
override fun read(): Element {
return JDOMUtil.load(ResourceUtil.getResourceAsBytes(getEffectiveFile(ep), pluginDescriptor.classLoader, true))
}
}, pluginDescriptor)
schemeManager.addScheme(keymap)
fireKeymapAdded(keymap)
// do no set current keymap here, consider: multi-keymap plugins, parent keymaps loading
}
override fun extensionRemoved(ep: BundledKeymapBean, pluginDescriptor: PluginDescriptor) {
removeKeymap(getKeymapName(ep))
}
}, null)
}
private fun fireKeymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapAdded(keymap)
for (listener in listeners) {
listener.keymapAdded(keymap)
}
}
private fun fireKeymapRemoved(keymap: Keymap) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).keymapRemoved(keymap)
for (listener in listeners) {
listener.keymapRemoved(keymap)
}
}
private fun fireActiveKeymapChanged(newScheme: Keymap?, activeKeymap: Keymap?) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).activeKeymapChanged(activeKeymap)
for (listener in listeners) {
listener.activeKeymapChanged(newScheme)
}
}
override fun getAllKeymaps(): Array<Keymap> = getKeymaps(null).toTypedArray()
fun getKeymaps(additionalFilter: Predicate<Keymap>?): List<Keymap> {
return schemeManager.allSchemes.filter { !it.presentableName.startsWith("$") && (additionalFilter == null || additionalFilter.test(it)) }
}
override fun getKeymap(name: String): Keymap? = schemeManager.findSchemeByName(name)
override fun getActiveKeymap(): Keymap {
return schemeManager.activeScheme
?: schemeManager.findSchemeByName(DefaultKeymap.getInstance().defaultKeymapName)
?: schemeManager.findSchemeByName(KeymapManager.DEFAULT_IDEA_KEYMAP)!!
}
override fun setActiveKeymap(keymap: Keymap) {
schemeManager.setCurrent(keymap)
}
override fun bindShortcuts(sourceActionId: String, targetActionId: String) {
boundShortcuts.put(targetActionId, sourceActionId)
}
override fun unbindShortcuts(targetActionId: String) {
boundShortcuts.remove(targetActionId)
}
override fun getBoundActions(): MutableSet<String> = boundShortcuts.keys
override fun getActionBinding(actionId: String): String? {
var visited: MutableSet<String>? = null
var id = actionId
while (true) {
val next = boundShortcuts.get(id) ?: break
if (visited == null) {
visited = HashSet()
}
id = next
if (!visited.add(id)) {
break
}
}
return if (id == actionId) null else id
}
override fun getSchemeManager(): SchemeManager<Keymap> = schemeManager
fun setKeymaps(keymaps: List<Keymap>, active: Keymap?, removeCondition: Predicate<Keymap>?) {
schemeManager.setSchemes(keymaps, active, removeCondition)
fireActiveKeymapChanged(active, activeKeymap)
}
override fun getState(): Element {
val result = Element("state")
schemeManager.activeScheme?.let {
if (it.name != DefaultKeymap.getInstance().defaultKeymapName) {
val e = Element(ACTIVE_KEYMAP)
e.setAttribute(NAME_ATTRIBUTE, it.name)
result.addContent(e)
}
}
return result
}
override fun loadState(state: Element) {
val child = state.getChild(ACTIVE_KEYMAP)
val activeKeymapName = child?.getAttributeValue(NAME_ATTRIBUTE)
if (!activeKeymapName.isNullOrBlank()) {
schemeManager.currentSchemeName = activeKeymapName
if (schemeManager.currentSchemeName != activeKeymapName) {
notifyAboutMissingKeymap(activeKeymapName, IdeBundle.message("notification.content.cannot.find.keymap", activeKeymapName), false)
}
}
}
@Suppress("OverridingDeprecatedMember")
override fun addKeymapManagerListener(listener: KeymapManagerListener, parentDisposable: Disposable) {
pollQueue()
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(KeymapManagerListener.TOPIC, listener)
}
private fun pollQueue() {
listeners.removeAll { it is WeakKeymapManagerListener && it.isDead }
}
@Suppress("OverridingDeprecatedMember")
override fun removeKeymapManagerListener(listener: KeymapManagerListener) {
pollQueue()
listeners.remove(listener)
}
override fun addWeakListener(listener: KeymapManagerListener) {
pollQueue()
listeners.add(WeakKeymapManagerListener(this, listener))
}
override fun removeWeakListener(listenerToRemove: KeymapManagerListener) {
listeners.removeAll { it is WeakKeymapManagerListener && it.isWrapped(listenerToRemove) }
}
}
internal val keymapComparator: Comparator<Keymap?> by lazy {
val defaultKeymapName = DefaultKeymap.getInstance().defaultKeymapName
Comparator { keymap1, keymap2 ->
if (keymap1 === keymap2) return@Comparator 0
if (keymap1 == null) return@Comparator - 1
if (keymap2 == null) return@Comparator 1
val parent1 = (if (!keymap1.canModify()) null else keymap1.parent) ?: keymap1
val parent2 = (if (!keymap2.canModify()) null else keymap2.parent) ?: keymap2
if (parent1 === parent2) {
when {
!keymap1.canModify() -> - 1
!keymap2.canModify() -> 1
else -> compareByName(keymap1, keymap2, defaultKeymapName)
}
}
else {
compareByName(parent1, parent2, defaultKeymapName)
}
}
}
private fun compareByName(keymap1: Keymap, keymap2: Keymap, defaultKeymapName: String): Int {
return when (defaultKeymapName) {
keymap1.name -> -1
keymap2.name -> 1
else -> NaturalComparator.INSTANCE.compare(keymap1.presentableName, keymap2.presentableName)
}
} | apache-2.0 | b99a1501c6eb482cf3df2f64b533fcea | 38.422939 | 141 | 0.723222 | 4.96748 | false | false | false | false |
spoptchev/kotlin-preconditions | src/test/kotlin/com/github/spoptchev/kotlin/preconditions/PreconditionDSLTest.kt | 1 | 3308 | package com.github.spoptchev.kotlin.preconditions
import com.github.spoptchev.kotlin.preconditions.matcher.*
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.fail
class PreconditionDSLTest {
@Test(expected = IllegalStateException::class)
fun `test invalid check`() {
checkThat("hello") { matches("olleh") }
fail("should not be executed")
}
@Test(expected = IllegalArgumentException::class)
fun `test invalid require`() {
requireThat(1) { isLt(0) }
fail("should not be executed")
}
@Test
fun `test check invalid with label`() {
try {
checkThat("x", "ID") { not(isEqualTo("x")) }
fail("should not be executed")
} catch (e: IllegalStateException) {
assertEquals("expected ID x not to be equal to 'x'", e.message)
}
}
@Test
fun `test labeled valid evaluation`() {
checkThat("y", "Should") { isEqualTo("y") }
}
@Test
fun `test shouldNotBe`() {
try {
requireThat(1) { isGt(0) }
} catch (e: IllegalArgumentException) {
assertEquals("expected 1 not to be > 0", e.message)
}
}
@Test
fun `test result value`() {
val result: Int = requireThat(1) { isGt(0) }
assertEquals(result, 1)
}
@Test
fun `test integration of all collection preconditions`() {
val list = listOf(1, 2)
requireThat(list) { hasSize(2) }
requireThat(list) { contains(1) or contains(3) and not(hasSize(3)) }
requireThat(list) { containsAll(1, 2) }
requireThat(list) { containsAll(list) }
requireThat(list) { isSorted() }
requireThat(list) { not(isEmpty()) }
}
@Test
fun `test integration of all comparable preconditions`() {
requireThat(1) { isLt(2) }
requireThat(1) { isLte(1) }
requireThat(1) { isGt(0) }
requireThat(1) { isGte(1) }
requireThat(1) { isBetween(0..2) }
}
@Test
fun `test integration of all map preconditions`() {
val map = mapOf(1 to "1")
requireThat(map) { hasKey(1) }
requireThat(map) { hasValue("1") }
requireThat(map) { contains(1, "1") }
}
@Test
fun `test integration of all string preconditions`() {
val value = "hello"
requireThat(value) { startsWith("he") and hasLength(5) and not(includes("io")) }
requireThat(value) { includes("ll") }
requireThat(value) { matches("hello") }
requireThat(value) { endsWith("lo") }
requireThat(value) { hasLength(5) }
requireThat(value) { not(isBlank()) }
requireThat(value) { not(isEmpty()) }
requireThat(value) { hasLengthBetween(1, 5) }
}
@Test
fun `test integration of all object preconditions`() {
val result = Result(true) { "" }
requireThat(result) { not(isNull()) }
requireThat(result) { isEqualTo(result) }
requireThat(result) { isSameInstanceAs(result) }
}
@Test
fun `test nested preconditions`() {
requireThat("hello") {
not(isNull()) and {
hasLength(6) or {
startsWith("he") and endsWith("llo")
}
}
}
}
}
| mit | ce16a1a5d7435dd66cc728b8248ddb40 | 27.033898 | 88 | 0.563482 | 4.04896 | false | true | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutinesUtils.kt | 1 | 15621 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.openapi.application.EDT
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.ProgressManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiFile
import com.intellij.util.flow.throttle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.future.await
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.time.Duration
import kotlin.time.TimedValue
import kotlin.time.measureTimedValue
internal fun <T> Flow<T>.onEach(context: CoroutineContext, action: suspend (T) -> Unit) =
onEach { withContext(context) { action(it) } }
internal fun <T, R> Flow<T>.map(context: CoroutineContext, action: suspend (T) -> R) =
map { withContext(context) { action(it) } }
internal fun <T> Flow<T>.replayOnSignals(vararg signals: Flow<Any>) = channelFlow {
var lastValue: T? = null
onEach { send(it) }
.onEach { lastValue = it }
.launchIn(this)
merge(*signals)
.onEach { lastValue?.let { send(it) } }
.launchIn(this)
}
suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend CoroutineScope.(T) -> R) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T> Iterable<T>.parallelFilterNot(transform: suspend (T) -> Boolean) =
channelFlow { parallelForEach { if (!transform(it)) send(it) } }.toList()
internal suspend fun <T, R> Iterable<T>.parallelMapNotNull(transform: suspend (T) -> R?) =
channelFlow { parallelForEach { transform(it)?.let { send(it) } } }.toList()
internal suspend fun <T> Iterable<T>.parallelForEach(action: suspend CoroutineScope.(T) -> Unit) = coroutineScope {
forEach { launch { action(it) } }
}
internal suspend fun <T, R, K> Map<T, R>.parallelMap(transform: suspend (Map.Entry<T, R>) -> K) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T, R> Iterable<T>.parallelFlatMap(transform: suspend (T) -> Iterable<R>) = coroutineScope {
map { async { transform(it) } }.flatMap { it.await() }
}
internal suspend inline fun <K, V> Map<K, V>.parallelUpdatedKeys(keys: Iterable<K>, crossinline action: suspend (K) -> V): Map<K, V> {
val map = toMutableMap()
keys.parallelForEach { map[it] = action(it) }
return map
}
internal fun timer(each: Duration, emitAtStartup: Boolean = true) = flow {
if (emitAtStartup) emit(Unit)
while (true) {
delay(each)
emit(Unit)
}
}
internal fun <T> Flow<T>.throttle(time: Duration) =
throttle(time.inWholeMilliseconds)
internal inline fun <reified T, reified R> Flow<T>.modifiedBy(
modifierFlow: Flow<R>,
crossinline transform: suspend (T, R) -> T
): Flow<T> = flow {
coroutineScope {
val queue = Channel<Any?>(capacity = 1)
val mutex = Mutex(locked = true)
[email protected] {
queue.send(it)
if (mutex.isLocked) mutex.unlock()
}.launchIn(this)
mutex.lock()
modifierFlow.onEach { queue.send(it) }.launchIn(this)
var currentState: T = queue.receive() as T
emit(currentState)
for (e in queue) {
when (e) {
is T -> currentState = e
is R -> currentState = transform(currentState, e)
else -> continue
}
emit(currentState)
}
}
}
internal fun <T, R> Flow<T>.mapLatestTimedWithLoading(
loggingContext: String,
loadingFlow: MutableStateFlow<Boolean>? = null,
transform: suspend CoroutineScope.(T) -> R
) =
mapLatest {
measureTimedValue {
loadingFlow?.emit(true)
val result = try {
coroutineScope { transform(it) }
} finally {
loadingFlow?.emit(false)
}
result
}
}.map {
logDebug(loggingContext) { "Took ${it.duration.absoluteValue} to process" }
it.value
}
internal fun <T> Flow<T>.catchAndLog(context: String, message: String? = null) =
catch {
if (message != null) {
logDebug(context, it) { message }
} else logDebug(context, it)
}
internal suspend inline fun <R> MutableStateFlow<Boolean>.whileLoading(action: () -> R): TimedValue<R> {
emit(true)
val r = measureTimedValue { action() }
emit(false)
return r
}
internal inline fun <reified T> Flow<T>.batchAtIntervals(duration: Duration) = channelFlow {
val mutex = Mutex()
val buffer = mutableListOf<T>()
var job: Job? = null
collect {
mutex.withLock { buffer.add(it) }
if (job == null || job?.isCompleted == true) {
job = launch {
delay(duration)
mutex.withLock {
send(buffer.toTypedArray())
buffer.clear()
}
}
}
}
}
internal suspend fun showBackgroundLoadingBar(
project: Project,
@Nls title: String,
@Nls upperMessage: String,
cancellable: Boolean = false,
isSafe: Boolean = true
): BackgroundLoadingBarController {
val syncSignal = Mutex(true)
val externalScopeJob = coroutineContext.job
val progressManager = ProgressManager.getInstance()
val progressController = BackgroundLoadingBarController(syncSignal)
progressManager.run(object : Task.Backgroundable(project, title, cancellable) {
override fun run(indicator: ProgressIndicator) {
if (isSafe && progressManager is ProgressManagerImpl && indicator is UserDataHolder) {
progressManager.markProgressSafe(indicator)
}
indicator.text = upperMessage // ??? why does it work?
runBlocking {
indicator.text = upperMessage // ??? why does it work?
val indicatorCancelledPollingJob = launch {
while (true) {
if (indicator.isCanceled) break
delay(50)
}
}
val internalJob = launch {
syncSignal.lock()
}
select {
internalJob.onJoin { }
externalScopeJob.onJoin {
internalJob.cancel()
indicatorCancelledPollingJob.cancel()
}
indicatorCancelledPollingJob.onJoin {
syncSignal.unlock()
progressController.triggerCallbacks()
}
}
indicatorCancelledPollingJob.cancel()
}
}
})
return progressController
}
internal class BackgroundLoadingBarController(private val syncMutex: Mutex) {
private val callbacks = mutableSetOf<() -> Unit>()
fun addOnComputationInterruptedCallback(callback: () -> Unit) {
callbacks.add(callback)
}
internal fun triggerCallbacks() = callbacks.forEach { it.invoke() }
fun clear() {
runCatching { syncMutex.unlock() }
}
}
suspend fun <R> writeAction(action: () -> R): R = withContext(Dispatchers.EDT) { action() }
internal fun ModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules)
}
internal fun AsyncModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules).await()
}
internal fun ModuleChangesSignalProvider.asCoroutine() = object : FlowModuleChangesSignalProvider {
override fun registerModuleChangesListener(project: Project) = callbackFlow {
val sub = registerModuleChangesListener(project) { trySend() }
awaitClose { sub.unsubscribe() }
}
}
internal fun ProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).toList()
}
internal fun AsyncProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).await().toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).await().toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).await().toList()
}
fun SendChannel<Unit>.trySend() = trySend(Unit)
fun ProducerScope<Unit>.trySend() = trySend(Unit)
suspend fun SendChannel<Unit>.send() = send(Unit)
suspend fun ProducerScope<Unit>.send() = send(Unit)
data class CombineLatest3<A, B, C>(val a: A, val b: B, val c: C)
fun <A, B, C, Z> combineLatest(
flowA: Flow<A>,
flowB: Flow<B>,
flowC: Flow<C>,
transform: suspend (CombineLatest3<A, B, C>) -> Z
) = combine(flowA, flowB, flowC) { a, b, c -> CombineLatest3(a, b, c) }
.mapLatest(transform)
| apache-2.0 | f983fb29bc7e75294b8d2ddd94915b13 | 40.879357 | 134 | 0.711478 | 4.863325 | false | false | false | false |
algra/pact-jvm | pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/generators/Generator.kt | 1 | 7787 | package au.com.dius.pact.model.generators
import au.com.dius.pact.model.PactSpecVersion
import com.mifmif.common.regex.Generex
import mu.KotlinLogging
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.RandomUtils
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import java.util.concurrent.ThreadLocalRandom
import kotlin.reflect.full.companionObject
import kotlin.reflect.full.companionObjectInstance
import kotlin.reflect.full.declaredMemberFunctions
private val logger = KotlinLogging.logger {}
fun lookupGenerator(generatorMap: Map<String, Any>): Generator? {
var generator: Generator? = null
try {
val generatorClass = Class.forName("au.com.dius.pact.model.generators.${generatorMap["type"]}Generator").kotlin
val fromMap = when {
generatorClass.companionObject != null ->
generatorClass.companionObjectInstance to generatorClass.companionObject?.declaredMemberFunctions?.find { it.name == "fromMap" }
generatorClass.objectInstance != null ->
generatorClass.objectInstance to generatorClass.declaredMemberFunctions.find { it.name == "fromMap" }
else -> null
}
if (fromMap?.second != null) {
generator = fromMap.second!!.call(fromMap.first, generatorMap) as Generator?
} else {
logger.warn { "Could not invoke generator class 'fromMap' for generator config '$generatorMap'" }
}
} catch (e: ClassNotFoundException) {
logger.warn(e) { "Could not find generator class for generator config '$generatorMap'" }
}
return generator
}
interface Generator {
fun generate(base: Any?): Any
fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any>
}
data class RandomIntGenerator(val min: Int, val max: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomInt", "min" to min, "max" to max)
}
override fun generate(base: Any?): Any {
return RandomUtils.nextInt(min, max)
}
companion object {
fun fromMap(map: Map<String, Any>): RandomIntGenerator {
val min = if (map["min"] is Number) {
(map["min"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for min: '${map["min"]}'" }
0
}
val max = if (map["max"] is Number) {
(map["max"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for max: '${map["max"]}'" }
Int.MAX_VALUE
}
return RandomIntGenerator(min, max)
}
}
}
data class RandomDecimalGenerator(val digits: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomDecimal", "digits" to digits)
}
override fun generate(base: Any?): Any = BigDecimal(RandomStringUtils.randomNumeric(digits))
companion object {
fun fromMap(map: Map<String, Any>): RandomDecimalGenerator {
val digits = if (map["digits"] is Number) {
(map["digits"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for digits: '${map["digits"]}'" }
10
}
return RandomDecimalGenerator(digits)
}
}
}
data class RandomHexadecimalGenerator(val digits: Int) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomHexadecimal", "digits" to digits)
}
override fun generate(base: Any?): Any = RandomStringUtils.random(digits, "0123456789abcdef")
companion object {
fun fromMap(map: Map<String, Any>): RandomHexadecimalGenerator {
val digits = if (map["digits"] is Number) {
(map["digits"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for digits: '${map["digits"]}'" }
10
}
return RandomHexadecimalGenerator(digits)
}
}
}
data class RandomStringGenerator(val size: Int = 20) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomString", "size" to size)
}
override fun generate(base: Any?): Any {
return RandomStringUtils.randomAlphanumeric(size)
}
companion object {
fun fromMap(map: Map<String, Any>): RandomStringGenerator {
val size = if (map["size"] is Number) {
(map["size"] as Number).toInt()
} else {
logger.warn { "Ignoring invalid value for size: '${map["size"]}'" }
10
}
return RandomStringGenerator(size)
}
}
}
data class RegexGenerator(val regex: String) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "Regex", "regex" to regex)
}
override fun generate(base: Any?): Any = Generex(regex).random()
companion object {
fun fromMap(map: Map<String, Any>) = RegexGenerator(map["regex"]!! as String)
}
}
object UuidGenerator : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "Uuid")
}
override fun generate(base: Any?): Any {
return UUID.randomUUID().toString()
}
@Suppress("UNUSED_PARAMETER")
fun fromMap(map: Map<String, Any>): UuidGenerator {
return UuidGenerator
}
}
data class DateGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "Date", "format" to this.format)
}
return mapOf("type" to "Date")
}
override fun generate(base: Any?): Any {
return if (format != null) {
OffsetDateTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalDate.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): DateGenerator {
return DateGenerator(map["format"] as String?)
}
}
}
data class TimeGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "Time", "format" to this.format)
}
return mapOf("type" to "Time")
}
override fun generate(base: Any?): Any {
return if (format != null) {
OffsetTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalTime.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): TimeGenerator {
return TimeGenerator(map["format"] as String?)
}
}
}
data class DateTimeGenerator(val format: String? = null) : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
if (format != null) {
return mapOf("type" to "DateTime", "format" to this.format)
}
return mapOf("type" to "DateTime")
}
override fun generate(base: Any?): Any {
return if (format != null) {
ZonedDateTime.now().format(DateTimeFormatter.ofPattern(format))
} else {
LocalDateTime.now().toString()
}
}
companion object {
fun fromMap(map: Map<String, Any>): DateTimeGenerator {
return DateTimeGenerator(map["format"] as String?)
}
}
}
object RandomBooleanGenerator : Generator {
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> {
return mapOf("type" to "RandomBoolean")
}
override fun generate(base: Any?): Any {
return ThreadLocalRandom.current().nextBoolean()
}
override fun equals(other: Any?) = other is RandomBooleanGenerator
@Suppress("UNUSED_PARAMETER")
fun fromMap(map: Map<String, Any>): RandomBooleanGenerator {
return RandomBooleanGenerator
}
}
| apache-2.0 | e9e45ae705ae26dfb8c1347709651916 | 29.65748 | 136 | 0.676641 | 4.100579 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddWhenRemainingBranchesIntention.kt | 1 | 2143 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.diagnostics.WhenMissingCase
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntentionWithContext
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddRemainingWhenBranchesUtils
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddRemainingWhenBranchesUtils.addRemainingWhenBranches
import org.jetbrains.kotlin.psi.KtWhenExpression
internal class AddWhenRemainingBranchesIntention
: AbstractKotlinApplicableIntentionWithContext<KtWhenExpression, AddRemainingWhenBranchesUtils.Context>(KtWhenExpression::class) {
override fun getFamilyName(): String = AddRemainingWhenBranchesUtils.familyAndActionName(false)
override fun getActionName(element: KtWhenExpression, context: AddRemainingWhenBranchesUtils.Context): String = familyName
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtWhenExpression> = ApplicabilityRanges.SELF
override fun isApplicableByPsi(element: KtWhenExpression): Boolean = true
context(KtAnalysisSession)
override fun prepareContext(element: KtWhenExpression): AddRemainingWhenBranchesUtils.Context? {
val whenMissingCases = element.getMissingCases().takeIf {
it.isNotEmpty() && it.singleOrNull() != WhenMissingCase.Unknown
} ?: return null
return AddRemainingWhenBranchesUtils.Context(whenMissingCases, enumToStarImport = null)
}
override fun apply(element: KtWhenExpression, context: AddRemainingWhenBranchesUtils.Context, project: Project, editor: Editor?) {
addRemainingWhenBranches(element, context)
}
} | apache-2.0 | 8ce4a82f5291570d170a7dea7113f6bb | 56.945946 | 134 | 0.825478 | 5.439086 | false | false | false | false |
chetdeva/recyclerview-bindings | app/src/main/java/com/fueled/recyclerviewbindings/widget/scroll/RecyclerViewScrollCallback.kt | 1 | 4327 | package com.fueled.recyclerviewbindings.widget.scroll
import android.support.v7.widget.RecyclerView
class RecyclerViewScrollCallback(private val visibleThreshold: Int, private val layoutManager: RecyclerView.LayoutManager)
: RecyclerView.OnScrollListener() {
// The minimum amount of items to have below your current scroll position
// before loading more.
// The current offset index of data you have loaded
private var currentPage = 0
// The total number of items in the dataset after the last load
private var previousTotalItemCount = 0
// True if we are still waiting for the last set of data to load.
private var loading = true
// Sets the starting page index
private val startingPageIndex = 0
lateinit var layoutManagerType: LayoutManagerType
lateinit var onScrolledListener: OnScrolledListener
constructor(builder: Builder) : this(builder.visibleThreshold, builder.layoutManager) {
this.layoutManagerType = builder.layoutManagerType
this.onScrolledListener = builder.onScrolledListener
if (builder.resetLoadingState) {
resetState()
}
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
override fun onScrolled(view: RecyclerView?, dx: Int, dy: Int) {
val lastVisibleItemPosition = RecyclerViewUtil.getLastVisibleItemPosition(layoutManager, layoutManagerType)
val totalItemCount = layoutManager.itemCount
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = totalItemCount
if (totalItemCount == 0) {
this.loading = true
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && totalItemCount > previousTotalItemCount) {
loading = false
previousTotalItemCount = totalItemCount
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) {
currentPage++
onScrolledListener.onScrolledToBottom(currentPage)
loading = true
}
}
// Call this method whenever performing new searches
private fun resetState() {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = 0
this.loading = true
}
interface OnScrolledListener {
fun onScrolledToBottom(page: Int)
}
class Builder(internal val layoutManager: RecyclerView.LayoutManager) {
internal var visibleThreshold = 7
internal var layoutManagerType = LayoutManagerType.LINEAR
internal lateinit var onScrolledListener: OnScrolledListener
internal var resetLoadingState: Boolean = false
fun visibleThreshold(value: Int): Builder {
visibleThreshold = value
return this
}
fun onScrolledListener(value: OnScrolledListener): Builder {
onScrolledListener = value
return this
}
fun resetLoadingState(value: Boolean): Builder {
resetLoadingState = value
return this
}
fun build(): RecyclerViewScrollCallback {
layoutManagerType = RecyclerViewUtil.computeLayoutManagerType(layoutManager)
visibleThreshold = RecyclerViewUtil.computeVisibleThreshold(
layoutManager, layoutManagerType, visibleThreshold)
return RecyclerViewScrollCallback(this)
}
}
} | mit | 3cefae655673b3e052ed37e8be4447be | 40.980583 | 122 | 0.681471 | 5.665793 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/activity/ImagePreviewActivity.kt | 1 | 6185 | package com.glodanif.bluetoothchat.ui.activity
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import androidx.transition.Transition
import androidx.transition.TransitionManager
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.ViewCompat
import android.util.ArrayMap
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.ImageView
import com.github.chrisbanes.photoview.PhotoView
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.data.entity.MessageFile
import com.glodanif.bluetoothchat.ui.presenter.ImagePreviewPresenter
import com.glodanif.bluetoothchat.ui.view.ImagePreviewView
import com.glodanif.bluetoothchat.ui.viewmodel.ChatMessageViewModel
import com.glodanif.bluetoothchat.utils.argument
import com.glodanif.bluetoothchat.utils.bind
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
import java.io.File
import java.lang.Exception
import java.lang.ref.WeakReference
class ImagePreviewActivity : SkeletonActivity(), ImagePreviewView {
private val messageId: Long by argument(EXTRA_MESSAGE_ID, -1L)
private val imagePath: String? by argument(EXTRA_IMAGE_PATH)
private val own: Boolean by argument(EXTRA_OWN, false)
private val presenter: ImagePreviewPresenter by inject {
parametersOf(messageId, File(imagePath), this)
}
private val imageView: PhotoView by bind(R.id.pv_preview)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_preview, ActivityType.CHILD_ACTIVITY)
supportPostponeEnterTransition()
ViewCompat.setTransitionName(imageView, messageId.toString())
toolbar?.setTitleTextAppearance(this, R.style.ActionBar_TitleTextStyle)
toolbar?.setSubtitleTextAppearance(this, R.style.ActionBar_SubTitleTextStyle)
imageView.minimumScale = .75f
imageView.maximumScale = 2f
presenter.loadImage()
}
override fun displayImage(fileUrl: String) {
val callback = object : Callback {
override fun onSuccess() {
supportStartPostponedEnterTransition()
}
override fun onError(e: Exception?) {
supportStartPostponedEnterTransition()
}
}
Picasso.get()
.load(fileUrl)
.config(Bitmap.Config.RGB_565)
.noFade()
.into(imageView, callback)
}
override fun showFileInfo(name: String, readableSize: String) {
title = name
toolbar?.subtitle = readableSize
}
override fun close() {
finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (!own) {
menuInflater.inflate(R.menu.menu_image_preview, menu)
}
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_remove -> {
confirmFileRemoval()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun confirmFileRemoval() {
AlertDialog.Builder(this)
.setMessage(getString(R.string.images__removal_confirmation))
.setPositiveButton(getString(R.string.general__yes)) { _, _ ->
presenter.removeFile()
}
.setNegativeButton(getString(R.string.general__no), null)
.show()
}
override fun onDestroy() {
super.onDestroy()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return
}
//Fixes https://issuetracker.google.com/issues/37042900
val transitionManagerClass = TransitionManager::class.java
try {
val runningTransitionsField = transitionManagerClass.getDeclaredField("sRunningTransitions")
runningTransitionsField.isAccessible = true
val runningTransitions = runningTransitionsField.get(transitionManagerClass)
as ThreadLocal<WeakReference<ArrayMap<ViewGroup, ArrayList<Transition>>>>
if (runningTransitions.get() == null || runningTransitions.get().get() == null) {
return
}
val map = runningTransitions.get().get()
val decorView = window.decorView
if (map != null && map.containsKey(decorView)) {
map.remove(decorView)
}
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
companion object {
const val EXTRA_MESSAGE_ID = "extra.message_id"
const val EXTRA_IMAGE_PATH = "extra.image_path"
const val EXTRA_OWN = "extra.own"
fun start(activity: Activity, transitionView: ImageView, message: MessageFile) {
start(activity, transitionView, message.uid, message.filePath ?: "unknown", message.own)
}
fun start(activity: Activity, transitionView: ImageView, message: ChatMessageViewModel) {
start(activity, transitionView, message.uid, message.imagePath
?: "unknown", message.own)
}
fun start(activity: Activity, transitionView: ImageView, messageId: Long, imagePath: String, ownMessage: Boolean) {
val intent = Intent(activity, ImagePreviewActivity::class.java)
.putExtra(EXTRA_MESSAGE_ID, messageId)
.putExtra(EXTRA_IMAGE_PATH, imagePath)
.putExtra(EXTRA_OWN, ownMessage)
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity, transitionView, messageId.toString())
activity.startActivity(intent, options.toBundle())
}
}
}
| apache-2.0 | 164aaec80558cc15fee9e45847238dd0 | 33.943503 | 123 | 0.661762 | 4.920446 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/utils/UrlParser.kt | 1 | 4824 | package no.skatteetaten.aurora.boober.utils
import no.skatteetaten.aurora.boober.model.PortNumbers
import no.skatteetaten.aurora.boober.service.UrlValidationException
import java.net.URI
class UrlParser(val url: String) {
private val uri: URI? = if (isJdbcUrl()) null else URI(url)
private val jdbcUri: JdbcUri? = when {
isPostgresJdbcUrl() -> PostgresJdbcUri(url)
isOracleJdbcUrl() -> OracleJdbcUri(url)
else -> null
}
val hostName: String get() {
assertIsValid()
return uri?.host ?: jdbcUri!!.hostName
}
val port: Int get() {
assertIsValid()
return uri?.givenOrDefaultPort() ?: jdbcUri!!.port
}
val suffix: String get() {
assertIsValid()
return uri?.suffix() ?: jdbcUri!!.suffix
}
private fun isJdbcUrl() = url.startsWith("jdbc:")
private fun isOracleJdbcUrl() = url.startsWith("jdbc:oracle:thin:@")
private fun isPostgresJdbcUrl() = url.startsWith("jdbc:postgresql:")
fun isValid(): Boolean = (if (isJdbcUrl()) jdbcUri?.isValid() else uri?.isValid()) ?: false
fun assertIsValid() = if (!isValid()) {
throw UrlValidationException("The format of the URL \"$url\" is not supported")
} else { null }
fun makeString(
modifiedHostName: String = hostName,
modifiedPort: Int = port,
modifiedSuffix: String = suffix
): String {
assertIsValid()
return if (isJdbcUrl()) {
jdbcUri!!.makeString(modifiedHostName, modifiedPort, modifiedSuffix)
} else {
uri!!.makeString(modifiedHostName, modifiedPort, modifiedSuffix)
}
}
fun withModifiedHostName(newHostName: String) = UrlParser(makeString(modifiedHostName = newHostName))
fun withModifiedPort(newPort: Int) = UrlParser(makeString(modifiedPort = newPort))
}
private abstract class JdbcUri {
abstract val hostName: String
abstract val port: Int
abstract val suffix: String
abstract fun isValid(): Boolean
abstract fun makeString(
modifiedHostName: String = hostName,
modifiedPort: Int = port,
modifiedSuffix: String = suffix
): String
}
private class PostgresJdbcUri(postgresJdbcUrl: String) : JdbcUri() {
val uri = URI(
if (postgresJdbcUrl.startsWith("jdbc:postgresql://")) {
postgresJdbcUrl
} else {
// If hostname is not given, it should default to localhost
postgresJdbcUrl.replaceFirst("sql:", "sql://localhost/")
}.removePrefix("jdbc:")
)
override val hostName: String get() = uri.host
override val port: Int get() = uri.givenOrDefaultPort()
override val suffix: String get() = uri.suffix()
override fun isValid(): Boolean = uri.isValid()
override fun makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "jdbc:postgresql://$modifiedHostName:$modifiedPort$modifiedSuffix"
}
private class OracleJdbcUri(private val oracleJdbcUrl: String) : JdbcUri() {
override val hostName: String get() = oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.substringBefore('?')
.substringBefore('/')
.substringBefore(':')
override val port: Int get() = Regex("^[0-9]+")
.find(
oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.removePrefix("$hostName:")
)
?.value
?.toInt()
?: PortNumbers.DEFAULT_ORACLE_PORT
override val suffix: String get() = oracleJdbcUrl
.removeEverythingBeforeHostnameFromOracleJdbcUrl()
.removePrefix(hostName)
.replace(Regex("^:[0-9]+"), "")
val protocol: String get() =
Regex("(?<=^jdbc:oracle:thin:@)([a-z]+:\\/\\/|\\/\\/)").find(oracleJdbcUrl)?.value ?: ""
override fun isValid(): Boolean = hostName.isNotEmpty()
override fun makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "jdbc:oracle:thin:@$protocol$modifiedHostName:$modifiedPort$modifiedSuffix"
private fun String.removeEverythingBeforeHostnameFromOracleJdbcUrl() =
replace(Regex("^jdbc:oracle:thin:@([a-z]+:\\/\\/|\\/\\/)?"), "")
}
private fun URI.givenOrDefaultPort() = if (port == -1) when (scheme) {
"https" -> PortNumbers.HTTPS_PORT
"postgresql" -> PortNumbers.DEFAULT_POSTGRES_PORT
else -> PortNumbers.HTTP_PORT
} else port
private fun URI.suffix() = path + (if (query != null) "?$query" else "")
private fun URI.isValid() = !scheme.isNullOrEmpty() && !host.isNullOrEmpty()
private fun URI.makeString(
modifiedHostName: String,
modifiedPort: Int,
modifiedSuffix: String
) = "$scheme://$modifiedHostName:$modifiedPort$modifiedSuffix"
| apache-2.0 | 62e8941a552ea5226737260fb750cb28 | 30.324675 | 105 | 0.6449 | 4.611855 | false | false | false | false |
ursjoss/sipamato | core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/search/SearchConditionTest.kt | 1 | 35875 | package ch.difty.scipamato.core.entity.search
import ch.difty.scipamato.common.entity.CodeClassId
import ch.difty.scipamato.core.entity.Code
import ch.difty.scipamato.core.entity.IdScipamatoEntity.IdScipamatoEntityFields.ID
import ch.difty.scipamato.core.entity.Paper.PaperFields.DOI
import ch.difty.scipamato.core.entity.Paper.PaperFields.FIRST_AUTHOR_OVERRIDDEN
import ch.difty.scipamato.core.entity.Paper.PaperFields.NUMBER
import ch.difty.scipamato.core.entity.newsletter.NewsletterTopic
import io.mockk.every
import io.mockk.mockk
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldContainAll
import org.amshove.kluent.shouldContainSame
import org.amshove.kluent.shouldHaveSize
import org.amshove.kluent.shouldNotBeEqualTo
import org.amshove.kluent.shouldThrow
import org.amshove.kluent.withMessage
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
private const val SEARCH_CONDITION_ID: Long = 1
private const val X = "x"
@Suppress("LargeClass", "SpellCheckingInspection")
internal class SearchConditionTest {
private val sc1 = SearchCondition(SEARCH_CONDITION_ID)
private val sc2 = SearchCondition()
@Test
fun allStringSearchTerms() {
sc1.doi = X
sc1.authors = X
sc1.firstAuthor = X
sc1.title = X
sc1.location = X
sc1.goals = X
sc1.population = X
sc1.populationPlace = X
sc1.populationParticipants = X
sc1.populationDuration = X
sc1.exposureAssessment = X
sc1.exposurePollutant = X
sc1.methods = X
sc1.methodStudyDesign = X
sc1.methodOutcome = X
sc1.methodStatistics = X
sc1.methodConfounders = X
sc1.result = X
sc1.resultExposureRange = X
sc1.resultEffectEstimate = X
sc1.resultMeasuredOutcome = X
sc1.conclusion = X
sc1.comment = X
sc1.intern = X
sc1.originalAbstract = X
sc1.mainCodeOfCodeclass1 = X
sc1.stringSearchTerms shouldHaveSize 26
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun allIntegerSearchTerms() {
sc1.id = "3"
sc1.pmId = "6"
sc1.number = "30"
sc1.publicationYear = "2017"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 4
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
sc1.number shouldBeEqualTo "30"
}
@Test
fun allBooleanSearchTerms() {
sc1.isFirstAuthorOverridden = true
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
sc1.auditSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue.shouldBeNull()
sc1.modifiedDisplayValue.shouldBeNull()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun allAuditSearchTerms() {
sc1.createdDisplayValue = X
sc1.modifiedDisplayValue = X + X
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.auditSearchTerms shouldHaveSize 4
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun id_extensiveTest() {
sc1.id.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.id = "5"
sc1.id shouldBeEqualTo "5"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo ID.fieldName
st.rawSearchTerm shouldBeEqualTo "5"
sc1.id = "10"
sc1.id shouldBeEqualTo "10"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo ID.fieldName
st.rawSearchTerm shouldBeEqualTo "10"
sc1.id = null
sc1.id.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun number_extensiveTest() {
sc1.number.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.number = "50"
sc1.number shouldBeEqualTo "50"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo NUMBER.fieldName
st.rawSearchTerm shouldBeEqualTo "50"
sc1.number = "100"
sc1.number shouldBeEqualTo "100"
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms shouldHaveSize 1
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.integerSearchTerms.first()
st.fieldName shouldBeEqualTo NUMBER.fieldName
st.rawSearchTerm shouldBeEqualTo "100"
sc1.number = null
sc1.number.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun doi_extensiveTest() {
sc1.doi.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.doi = "101111"
sc1.doi shouldBeEqualTo "101111"
sc1.stringSearchTerms shouldHaveSize 1
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
var st = sc1.stringSearchTerms.first()
st.fieldName shouldBeEqualTo DOI.fieldName
st.rawSearchTerm shouldBeEqualTo "101111"
sc1.doi = "102222"
sc1.doi shouldBeEqualTo "102222"
sc1.stringSearchTerms shouldHaveSize 1
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
st = sc1.stringSearchTerms.first()
st.fieldName shouldBeEqualTo DOI.fieldName
st.rawSearchTerm shouldBeEqualTo "102222"
sc1.doi = null
sc1.doi.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.searchConditionId shouldBeEqualTo SEARCH_CONDITION_ID
}
@Test
fun pmId() {
sc1.pmId.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.pmId = "6"
sc1.pmId shouldBeEqualTo "6"
sc1.integerSearchTerms shouldHaveSize 1
sc1.pmId = null
sc1.pmId.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
}
@Test
fun authors() {
sc1.authors.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.authors = X
sc1.authors shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.authors = null
sc1.authors.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun firstAuthor() {
sc1.firstAuthor.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.firstAuthor = X
sc1.firstAuthor shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.firstAuthor = null
sc1.firstAuthor.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun firstAuthorOverridden_extensiveTest() {
sc1.isFirstAuthorOverridden.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.isFirstAuthorOverridden = true
(sc1.isFirstAuthorOverridden == true).shouldBeTrue()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
var st = sc1.booleanSearchTerms.first()
st.fieldName shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN.fieldName
st.rawSearchTerm shouldBeEqualTo "true"
st.value.shouldBeTrue()
sc1.isFirstAuthorOverridden = false
(sc1.isFirstAuthorOverridden == true).shouldBeFalse()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms shouldHaveSize 1
st = sc1.booleanSearchTerms.first()
st.fieldName shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN.fieldName
st.rawSearchTerm shouldBeEqualTo "false"
st.value.shouldBeFalse()
sc1.isFirstAuthorOverridden = null
sc1.isFirstAuthorOverridden.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.booleanSearchTerms.shouldBeEmpty()
}
@Test
fun title() {
sc1.title.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.title = X
sc1.title shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.title = null
sc1.title.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun location() {
sc1.location.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.location = X
sc1.location shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.location = null
sc1.location.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun publicationYear() {
sc1.publicationYear.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.publicationYear = "2016"
sc1.publicationYear shouldBeEqualTo "2016"
sc1.integerSearchTerms shouldHaveSize 1
sc1.publicationYear = null
sc1.publicationYear.shouldBeNull()
sc1.integerSearchTerms.shouldBeEmpty()
}
@Test
fun goals() {
sc1.goals.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.goals = X
sc1.goals shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.goals = null
sc1.goals.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun population() {
sc1.population.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.population = X
sc1.population shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.population = null
sc1.population.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationPlace() {
sc1.populationPlace.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationPlace = X
sc1.populationPlace shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationPlace = null
sc1.populationPlace.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationParticipants() {
sc1.populationParticipants.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationParticipants = X
sc1.populationParticipants shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationParticipants = null
sc1.populationParticipants.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun populationDuration() {
sc1.populationDuration.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.populationDuration = X
sc1.populationDuration shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.populationDuration = null
sc1.populationDuration.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun exposurePollutant() {
sc1.exposurePollutant.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.exposurePollutant = X
sc1.exposurePollutant shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.exposurePollutant = null
sc1.exposurePollutant.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun exposureAssessment() {
sc1.exposureAssessment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.exposureAssessment = X
sc1.exposureAssessment shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.exposureAssessment = null
sc1.exposureAssessment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methods() {
sc1.methods.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methods = X
sc1.methods shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methods = null
sc1.methods.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodStudyDesign() {
sc1.methodStudyDesign.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodStudyDesign = X
sc1.methodStudyDesign shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodStudyDesign = null
sc1.methodStudyDesign.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodOutcome() {
sc1.methodOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodOutcome = X
sc1.methodOutcome shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodOutcome = null
sc1.methodOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodStatistics() {
sc1.methodStatistics.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodStatistics = X
sc1.methodStatistics shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodStatistics = null
sc1.methodStatistics.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun methodConfounders() {
sc1.methodConfounders.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.methodConfounders = X
sc1.methodConfounders shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.methodConfounders = null
sc1.methodConfounders.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun result() {
sc1.result.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.result = X
sc1.result shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.result = null
sc1.result.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultExposureRange() {
sc1.resultExposureRange.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultExposureRange = X
sc1.resultExposureRange shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultExposureRange = null
sc1.resultExposureRange.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultEffectEstimate() {
sc1.resultEffectEstimate.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultEffectEstimate = X
sc1.resultEffectEstimate shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultEffectEstimate = null
sc1.resultEffectEstimate.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun resultMeasuredOutcome() {
sc1.resultMeasuredOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.resultMeasuredOutcome = X
sc1.resultMeasuredOutcome shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.resultMeasuredOutcome = null
sc1.resultMeasuredOutcome.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun conclusion() {
sc1.conclusion.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.conclusion = X
sc1.conclusion shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.conclusion = null
sc1.conclusion.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun comment() {
sc1.comment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.comment = X
sc1.comment shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.comment = null
sc1.comment.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun intern() {
sc1.intern.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.intern = X
sc1.intern shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.intern = null
sc1.intern.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun originalAbstract() {
sc1.originalAbstract.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.originalAbstract = X
sc1.originalAbstract shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.originalAbstract = null
sc1.originalAbstract.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun mainCodeOfClass1() {
sc1.mainCodeOfCodeclass1.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.mainCodeOfCodeclass1 = X
sc1.mainCodeOfCodeclass1 shouldBeEqualTo X
sc1.stringSearchTerms shouldHaveSize 1
sc1.mainCodeOfCodeclass1 = null
sc1.mainCodeOfCodeclass1.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun createdDisplayValue() {
sc1.createdDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.createdDisplayValue = X
sc1.createdDisplayValue shouldBeEqualTo X
sc1.created shouldBeEqualTo X
sc1.createdBy shouldBeEqualTo X
sc1.lastModified.shouldBeNull()
sc1.lastModifiedBy.shouldBeNull()
sc1.stringSearchTerms shouldHaveSize 0
sc1.createdDisplayValue = null
sc1.createdDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun modifiedDisplayValue() {
sc1.modifiedDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
sc1.modifiedDisplayValue = X
sc1.modifiedDisplayValue shouldBeEqualTo X
sc1.lastModified shouldBeEqualTo X
sc1.lastModifiedBy shouldBeEqualTo X
sc1.created.shouldBeNull()
sc1.createdBy.shouldBeNull()
sc1.stringSearchTerms shouldHaveSize 0
sc1.modifiedDisplayValue = null
sc1.modifiedDisplayValue.shouldBeNull()
sc1.stringSearchTerms.shouldBeEmpty()
}
@Test
fun testDisplayValue_withSingleStringSearchTerms_returnsIt() {
sc1.authors = "hoops"
sc1.displayValue shouldBeEqualTo "hoops"
}
@Test
fun testDisplayValue_withTwoStringSearchTerms_joinsThemUsingAnd() {
sc1.authors = "rag"
sc1.methodConfounders = "bones"
sc1.displayValue shouldBeEqualTo "rag AND bones"
}
@Test
fun testDisplayValue_forBooleanSearchTermsBeginFalse() {
sc1.isFirstAuthorOverridden = false
sc1.displayValue shouldBeEqualTo "-firstAuthorOverridden"
}
@Test
fun testDisplayValue_forIntegerSearchTerms() {
sc1.publicationYear = "2017"
sc1.displayValue shouldBeEqualTo "2017"
}
@Test
fun testDisplayValue_forAuditSearchTermsForAuthorSearch() {
sc1.createdDisplayValue = "mkj"
sc1.displayValue shouldBeEqualTo "mkj"
}
@Test
fun testDisplayValue_forAuditSearchTermsForDateSearch() {
sc1.createdDisplayValue = ">2017-01-23"
sc1.displayValue shouldBeEqualTo ">2017-01-23"
}
@Test
fun testDisplayValue_forAuditSearchTermsForCombinedSearch() {
sc1.modifiedDisplayValue = "rk >=2017-01-23"
sc1.displayValue shouldBeEqualTo "rk >=2017-01-23"
}
@Test
fun testDisplayValue_withHasAttachment() {
sc1.hasAttachments = true
sc1.displayValue shouldBeEqualTo "attachment=true"
sc1.hasAttachments = false
sc1.displayValue shouldBeEqualTo "attachment=false"
}
@Test
fun testDisplayValue_withAttachmentMask_displaysItRegardlessOfHasAttachment() {
// attachmentNameMask is not considered if hasAttachment is set to non-null
sc1.attachmentNameMask = "foo"
sc1.hasAttachments = true
sc1.displayValue shouldBeEqualTo "attachment=foo"
sc1.hasAttachments = false
sc1.displayValue shouldBeEqualTo "attachment=foo"
sc1.hasAttachments = null
sc1.displayValue shouldBeEqualTo "attachment=foo"
}
@Test
fun testDisplayValue_withMultipleSearchTerms_joinsThemAllUsingAND() {
sc1.authors = "fooAuth"
sc1.methodStudyDesign = "bar"
sc1.doi = "baz"
sc1.publicationYear = "2016"
sc1.isFirstAuthorOverridden = true
sc1.displayValue shouldBeEqualTo "fooAuth AND bar AND baz AND 2016 AND firstAuthorOverridden"
}
@Test
fun testDisplayValue_withCodesOnly() {
sc1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
sc1.addCode(Code("5H", "C5H", "", false, 5, "CC5", "", 0))
sc1.displayValue shouldBeEqualTo "1F&5H"
}
@Test
fun testDisplayValue_withSearchTermsAndCodes() {
sc1.authors = "foobar"
sc1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
sc1.addCode(Code("5H", "C5H", "", false, 5, "CC5", "", 0))
sc1.displayValue shouldBeEqualTo "foobar AND 1F&5H"
}
@Test
fun testDisplayValue_withNewsletterHeadlineOnly() {
sc1.newsletterHeadline = "foo"
sc1.displayValue shouldBeEqualTo "headline=foo"
}
@Test
fun testDisplayValue_withNewsletterTopicOnly() {
sc1.setNewsletterTopic(NewsletterTopic(1, "t1"))
sc1.displayValue shouldBeEqualTo "topic=t1"
}
@Test
fun testDisplayValue_withNewsletterIssueOnly() {
sc1.newsletterIssue = "2018/06"
sc1.displayValue shouldBeEqualTo "issue=2018/06"
}
@Test
fun testDisplayValue_withNewsletterHeadlinePlusSomethingElse() {
sc1.authors = "foobar"
sc1.newsletterHeadline = "foo"
sc1.displayValue shouldBeEqualTo "foobar AND headline=foo"
}
@Test
fun testDisplayValue_withNewsletterTopicPlusSomethingElse() {
sc1.authors = "foobar"
sc1.setNewsletterTopic(NewsletterTopic(1, "t1"))
sc1.displayValue shouldBeEqualTo "foobar AND topic=t1"
}
@Test
fun testDisplayValue_withNewsletterIssuePlusSomethingElse() {
sc1.authors = "foobar"
sc1.newsletterIssue = "2018/04"
sc1.displayValue shouldBeEqualTo "foobar AND issue=2018/04"
}
@Test
fun testDisplayValue_withAllNewsletterRelatedFields() {
sc1.newsletterHeadline = "foobar"
sc1.newsletterIssue = "2018/02"
sc1.setNewsletterTopic(NewsletterTopic(10, "t2"))
sc1.displayValue shouldBeEqualTo "issue=2018/02 AND headline=foobar AND topic=t2"
}
@Test
fun testDisplayValue_withNewsletterTopicNull_() {
sc1.newsletterHeadline = "foobar"
sc1.newsletterIssue = "2018/02"
sc1.setNewsletterTopic(null)
sc1.displayValue shouldBeEqualTo "issue=2018/02 AND headline=foobar"
}
@Test
fun equalsAndHash1_ofFieldSc() {
(sc1 == sc1).shouldBeTrue()
}
@Test
fun equalsAndHash2_withEmptySearchConditions() {
val f1 = SearchCondition()
val f2 = SearchCondition()
assertEquality(f1, f2)
}
private fun assertEquality(f1: SearchCondition, f2: SearchCondition) {
f1.hashCode() shouldBeEqualTo f2.hashCode()
((f1 == f2)).shouldBeTrue()
((f2 == f1)).shouldBeTrue()
}
@Test
fun equalsAndHash3_withSingleAttribute() {
val f1 = SearchCondition()
f1.authors = "foo"
val f2 = SearchCondition()
f2.authors = "foo"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash4_withManyAttributes() {
val f1 = SearchCondition()
f1.authors = "foo"
f1.comment = "bar"
f1.publicationYear = "2014"
f1.firstAuthor = "baz"
f1.isFirstAuthorOverridden = true
f1.methodOutcome = "blup"
val f2 = SearchCondition()
f2.authors = "foo"
f2.comment = "bar"
f2.publicationYear = "2014"
f2.firstAuthor = "baz"
f2.isFirstAuthorOverridden = true
f2.methodOutcome = "blup"
assertEquality(f1, f2)
f2.methodOutcome = "blup2"
((f1 == f2)).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
f2.methodOutcome = "blup"
f2.methodStatistics = "bloop"
((f1 == f2)).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
}
@Test
fun equalsAndHash5_withDifferentSearchConditionIds() {
val f1 = SearchCondition()
f1.authors = "foo"
val f2 = SearchCondition()
f2.authors = "foo"
assertEquality(f1, f2)
f1.searchConditionId = 3L
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f2.searchConditionId = 4L
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f2.searchConditionId = 3L
assertEquality(f1, f2)
}
@Test
fun equalsAndHash6_withCreatedDisplayValue() {
val f1 = SearchCondition()
f1.createdDisplayValue = "foo"
val f2 = SearchCondition()
(f1 == f2).shouldBeFalse()
f2.createdDisplayValue = "foo"
assertEquality(f1, f2)
f2.createdDisplayValue = "bar"
(f1 == f2).shouldBeFalse()
f1.createdDisplayValue = null
(f2 == f1).shouldBeFalse()
}
@Test
fun equalsAndHash7_withModifiedDisplayValue() {
val f1 = SearchCondition()
f1.modifiedDisplayValue = "foo"
val f2 = SearchCondition()
(f1 == f2).shouldBeFalse()
f2.modifiedDisplayValue = "foo"
assertEquality(f1, f2)
f2.modifiedDisplayValue = "bar"
(f1 == f2).shouldBeFalse()
f1.createdDisplayValue = null
(f2 == f1).shouldBeFalse()
}
@Test
fun equalsAndHash8_withDifferentBooleanSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newBooleanSearchTerm("f1", "false"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newBooleanSearchTerm("f1", "true"))
assertInequality(f1, f2)
}
private fun assertInequality(f1: SearchCondition, f2: SearchCondition) {
(f1 == f2).shouldBeFalse()
(f2 == f1).shouldBeFalse()
f1.hashCode() shouldNotBeEqualTo f2.hashCode()
}
@Test
fun equalsAndHash8_withDifferentIntegerSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newIntegerSearchTerm("f1", "1"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newIntegerSearchTerm("f1", "2"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash9_withDifferentStringSearchTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newStringSearchTerm("f1", "foo"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newStringSearchTerm("f1", "bar"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash10_withDifferentStringAuditTerms() {
val f1 = SearchCondition()
f1.addSearchTerm(SearchTerm.newAuditSearchTerm("f1", "foo"))
val f2 = SearchCondition()
f2.addSearchTerm(SearchTerm.newAuditSearchTerm("f1", "bar"))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash11_withDifferentCodes() {
val f1 = SearchCondition()
f1.addCode(Code("1F", "C1F", "", false, 1, "CC1", "", 0))
val f2 = SearchCondition()
f2.addCode(Code("1G", "C1G", "", false, 1, "CC1", "", 0))
assertInequality(f1, f2)
}
@Test
fun equalsAndHash12_withDifferentNewsletterTopics_notDifferent() {
val f1 = SearchCondition()
f1.setNewsletterTopic(NewsletterTopic(1, "foo"))
val f2 = SearchCondition()
f2.setNewsletterTopic(NewsletterTopic(2, "foo"))
assertEquality(f1, f2)
}
@Test
fun equalsAndHash13_withDifferentNewsletterHeadlines_notDifferent() {
val f1 = SearchCondition()
f1.newsletterHeadline = "foo"
val f2 = SearchCondition()
f2.newsletterHeadline = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash14_withDifferentNewsletterIssue_notDifferent() {
val f1 = SearchCondition()
f1.newsletterIssue = "foo"
val f2 = SearchCondition()
f2.newsletterIssue = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash15_withDifferentNewsletterTopics_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.setNewsletterTopic(null)
val f2 = SearchCondition()
f2.setNewsletterTopic(NewsletterTopic(2, "foo"))
assertEquality(f1, f2)
}
@Test
fun equalsAndHash16_withDifferentNewsletterHeadlines_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.newsletterHeadline = null
val f2 = SearchCondition()
f2.newsletterHeadline = "bar"
assertEquality(f1, f2)
}
@Test
fun equalsAndHash17_withDifferentNewsletterIssue_firstNull_notDifferent() {
val f1 = SearchCondition()
f1.newsletterIssue = null
val f2 = SearchCondition()
f2.newsletterIssue = "bar"
assertEquality(f1, f2)
}
@Test
fun newSearchCondition_hasEmptyRemovedKeys() {
SearchCondition().removedKeys.shouldBeEmpty()
}
@Test
fun addingSearchTerms_leavesRemovedKeysEmpty() {
sc2.authors = "foo"
sc2.publicationYear = "2014"
sc2.isFirstAuthorOverridden = true
sc2.removedKeys.shouldBeEmpty()
}
@Test
fun removingSearchTerms_addsThemToRemovedKeys() {
sc2.authors = "foo"
sc2.publicationYear = "2014"
sc2.goals = "bar"
sc2.publicationYear = null
sc2.removedKeys shouldContainSame listOf("publicationYear")
}
@Test
fun addingSearchTerm_afterRemovingIt_removesItFromRemovedKeys() {
sc2.publicationYear = "2014"
sc2.publicationYear = null
sc2.publicationYear = "2015"
sc2.removedKeys.shouldBeEmpty()
}
@Test
fun clearingRemovedKeys_removesAllPresent() {
sc1.authors = "foo"
sc1.authors = null
sc1.publicationYear = "2014"
sc1.publicationYear = null
sc1.removedKeys shouldHaveSize 2
sc1.clearRemovedKeys()
sc1.removedKeys.shouldBeEmpty()
}
@Test
fun addingBooleanSearchTerm() {
sc2.addSearchTerm(SearchTerm.newBooleanSearchTerm("fn", "rst"))
sc2.booleanSearchTerms shouldHaveSize 1
sc2.integerSearchTerms.shouldBeEmpty()
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingIntegerTerm() {
sc2.addSearchTerm(SearchTerm.newIntegerSearchTerm("fn", "1"))
sc2.booleanSearchTerms.shouldBeEmpty()
sc2.integerSearchTerms shouldHaveSize 1
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingStringSearchTerm() {
sc1.addSearchTerm(SearchTerm.newStringSearchTerm("fn", "rst"))
sc1.booleanSearchTerms.shouldBeEmpty()
sc1.integerSearchTerms.shouldBeEmpty()
sc1.stringSearchTerms shouldHaveSize 1
sc1.auditSearchTerms.shouldBeEmpty()
}
@Test
fun addingAuditSearchTerm() {
sc2.addSearchTerm(SearchTerm.newAuditSearchTerm("fn", "rst"))
sc2.booleanSearchTerms.shouldBeEmpty()
sc2.integerSearchTerms.shouldBeEmpty()
sc2.stringSearchTerms.shouldBeEmpty()
sc2.auditSearchTerms shouldHaveSize 1
}
@Test
fun addingUnsupportedSearchTerm() {
val stMock = mockk<SearchTerm> {
every { searchTermType } returns SearchTermType.UNSUPPORTED
}
invoking { sc2.addSearchTerm(stMock) } shouldThrow AssertionError::class withMessage "SearchTermType.UNSUPPORTED is not supported"
}
@Test
fun addingCodes() {
val c1 = Code("c1", "c1", "", false, 1, "cc1", "", 0)
val c2 = Code("c2", "c2", "", false, 2, "cc2", "", 0)
val c3 = Code("c3", "c3", "", false, 3, "cc3", "", 0)
val c4 = Code("c4", "c4", "", false, 3, "cc3", "", 0)
sc2.addCodes(listOf(c1, c2, c3, c4))
sc2.codes shouldHaveSize 4
sc2.getCodesOf(CodeClassId.CC3) shouldContainAll listOf(c3, c4)
sc2.clearCodesOf(CodeClassId.CC3)
sc2.codes shouldHaveSize 2
sc2.clearCodes()
sc2.codes.shouldBeEmpty()
}
@Test
fun settingAndResettingNewsletterHeadline() {
sc1.newsletterHeadline.shouldBeNull()
sc1.newsletterHeadline = "foo"
sc1.newsletterHeadline shouldBeEqualTo "foo"
sc1.newsletterHeadline = null
sc1.newsletterHeadline.shouldBeNull()
}
@Test
fun settingAndResettingNewsletterTopic() {
sc1.newsletterTopicId.shouldBeNull()
sc1.setNewsletterTopic(NewsletterTopic(1, "tp1"))
sc1.newsletterTopicId shouldBeEqualTo 1
sc1.setNewsletterTopic(null)
sc1.newsletterTopicId.shouldBeNull()
}
@Test
fun settingAndResettingNewsletterIssue() {
sc1.newsletterIssue.shouldBeNull()
sc1.newsletterIssue = "foo"
sc1.newsletterIssue shouldBeEqualTo "foo"
sc1.newsletterIssue = null
sc1.newsletterIssue.shouldBeNull()
}
@Test
fun hasAttachments() {
sc1.hasAttachments.shouldBeNull()
sc1.hasAttachments = true
sc1.hasAttachments?.shouldBeTrue() ?: fail("should not be null")
sc1.hasAttachments = false
sc1.hasAttachments?.shouldBeFalse() ?: fail("should not be null")
sc1.hasAttachments = null
sc1.hasAttachments.shouldBeNull()
}
@Test
fun attachmentNameMas() {
sc1.attachmentNameMask.shouldBeNull()
sc1.attachmentNameMask = "foo"
sc1.attachmentNameMask shouldBeEqualTo "foo"
sc1.attachmentNameMask = null
sc1.attachmentNameMask.shouldBeNull()
}
}
| gpl-3.0 | ce7f41e51f886e30f565909dc979f205 | 29.248735 | 138 | 0.660293 | 4.735348 | false | true | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/history/GitCommitRequirements.kt | 3 | 2166 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.history
import com.intellij.openapi.util.registry.Registry
data class GitCommitRequirements(private val includeRootChanges: Boolean = true,
val diffRenameLimit: DiffRenameLimit = DiffRenameLimit.GIT_CONFIG,
val diffInMergeCommits: DiffInMergeCommits = DiffInMergeCommits.COMBINED_DIFF) {
fun configParameters(): List<String> {
val result = mutableListOf<String>()
when (diffRenameLimit) {
DiffRenameLimit.INFINITY -> result.add(renameLimit(0))
DiffRenameLimit.REGISTRY -> result.add(renameLimit(Registry.intValue("git.diff.renameLimit")))
DiffRenameLimit.NO_RENAMES -> result.add("diff.renames=false")
else -> {
}
}
if (!includeRootChanges) {
result.add("log.showRoot=false")
}
return result
}
fun commandParameters(): List<String> {
val result = mutableListOf<String>()
if (diffRenameLimit != DiffRenameLimit.NO_RENAMES) {
result.add("-M")
}
when (diffInMergeCommits) {
DiffInMergeCommits.DIFF_TO_PARENTS -> result.add("-m")
DiffInMergeCommits.COMBINED_DIFF -> result.add("-c")
DiffInMergeCommits.NO_DIFF -> {
}
}
return result
}
private fun renameLimit(limit: Int): String {
return "diff.renameLimit=$limit"
}
enum class DiffRenameLimit {
/**
* Use zero value
*/
INFINITY,
/**
* Use value set in registry (usually 1000)
*/
REGISTRY,
/**
* Use value set in users git.config
*/
GIT_CONFIG,
/**
* Disable renames detection
*/
NO_RENAMES
}
enum class DiffInMergeCommits {
/**
* Do not report changes for merge commits
*/
NO_DIFF,
/**
* Report combined changes (same as `git log -c`)
*/
COMBINED_DIFF,
/**
* Report changes to all of the parents (same as `git log -m`)
*/
DIFF_TO_PARENTS
}
companion object {
@JvmField
val DEFAULT = GitCommitRequirements()
}
}
| apache-2.0 | 14ae7bbf5e932a046b30fcb1dc499183 | 25.414634 | 140 | 0.627424 | 4.349398 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/file/ModuleNameIndex.kt | 1 | 2598 | package org.purescript.file
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.*
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.annotations.NonNls
class ModuleNameIndex : ScalarIndexExtension<String>() {
override fun getName(): ID<String, Void?> {
return NAME
}
override fun getIndexer(): DataIndexer<String, Void?, FileContent> {
return DataIndexer<String, Void?, FileContent> {
when (val file = it.psiFile) {
is PSFile -> file.module?.name?.let { mapOf(it to null) }
?: emptyMap()
else -> emptyMap()
}
}
}
override fun getKeyDescriptor(): KeyDescriptor<String> =
EnumeratorStringDescriptor.INSTANCE
override fun getVersion(): Int = 0
override fun getInputFilter(): FileBasedIndex.InputFilter =
DefaultFileTypeSpecificInputFilter(PSFileType.INSTANCE)
override fun dependsOnFileContent(): Boolean = true
companion object {
@NonNls
val NAME =
ID.create<String, Void?>("org.purescript.file.ModuleNameIndex")
fun fileContainingModule(
project: Project,
moduleName: String
): PSFile? {
val fileBasedIndex = FileBasedIndex.getInstance()
return ReadAction.compute<PSFile?, Throwable> {
val files = fileBasedIndex.getContainingFiles(
NAME,
moduleName,
GlobalSearchScope.allScope(project)
)
files
//.filter { it.isValid }
.map { PsiManager.getInstance(project).findFile(it) }
.filterIsInstance(PSFile::class.java)
.firstOrNull()
}
}
fun getAllModuleNames(project: Project): List<String> {
val fileBasedIndex = FileBasedIndex.getInstance()
return fileBasedIndex.getAllKeys(NAME, project)
.filter { fileContainingModule(project, it) != null }
.toList()
}
fun getModuleNameFromFile(project: Project,file: VirtualFile) =
FileBasedIndex
.getInstance()
.getFileData(NAME, file, project)
.keys
.firstOrNull()
}
} | bsd-3-clause | b2fcdbe1253b7145c028d2959665a616 | 32.753247 | 75 | 0.603541 | 5.302041 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/features/PSFindUsageProvider.kt | 1 | 5510 | package org.purescript.features
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.tree.TokenSet
import org.purescript.lexer.PSLexer
import org.purescript.parser.ARROW
import org.purescript.parser.BACKSLASH
import org.purescript.parser.CHAR
import org.purescript.parser.COMMA
import org.purescript.parser.DARROW
import org.purescript.parser.DCOLON
import org.purescript.parser.DDOT
import org.purescript.parser.DOC_COMMENT
import org.purescript.parser.DOT
import org.purescript.parser.EQ
import org.purescript.parser.FLOAT
import org.purescript.parser.IDENT
import org.purescript.parser.LARROW
import org.purescript.parser.LDARROW
import org.purescript.parser.MLCOMMENT
import org.purescript.parser.MODULE_PREFIX
import org.purescript.parser.NATURAL
import org.purescript.parser.OPERATOR
import org.purescript.parser.OPTIMISTIC
import org.purescript.parser.PIPE
import org.purescript.parser.PROPER_NAME
import org.purescript.parser.SEMI
import org.purescript.parser.SLCOMMENT
import org.purescript.parser.STRING
import org.purescript.parser.STRING_ERROR
import org.purescript.parser.STRING_ESCAPED
import org.purescript.parser.STRING_GAP
import org.purescript.psi.PSForeignDataDeclaration
import org.purescript.psi.PSForeignValueDeclaration
import org.purescript.psi.PSModule
import org.purescript.psi.binder.PSVarBinder
import org.purescript.psi.classes.PSClassDeclaration
import org.purescript.psi.classes.PSClassMember
import org.purescript.psi.data.PSDataConstructor
import org.purescript.psi.data.PSDataDeclaration
import org.purescript.psi.declaration.PSFixityDeclaration
import org.purescript.psi.declaration.PSValueDeclaration
import org.purescript.psi.imports.PSImportAlias
import org.purescript.psi.newtype.PSNewTypeConstructor
import org.purescript.psi.newtype.PSNewTypeDeclaration
import org.purescript.psi.typesynonym.PSTypeSynonymDeclaration
class PSFindUsageProvider : FindUsagesProvider {
override fun canFindUsagesFor(psiElement: PsiElement): Boolean =
psiElement is PSValueDeclaration
|| psiElement is PSVarBinder
|| psiElement is PSModule
|| psiElement is PSForeignValueDeclaration
|| psiElement is PSNewTypeDeclaration
|| psiElement is PSNewTypeConstructor
|| psiElement is PSImportAlias
|| psiElement is PSDataDeclaration
|| psiElement is PSDataConstructor
|| psiElement is PSClassDeclaration
|| psiElement is PSTypeSynonymDeclaration
|| psiElement is PSClassMember
|| psiElement is PSFixityDeclaration
|| psiElement is PSForeignDataDeclaration
override fun getWordsScanner(): WordsScanner {
val psWordScanner = DefaultWordsScanner(
PSLexer(),
TokenSet.create(IDENT, PROPER_NAME, MODULE_PREFIX),
TokenSet.create(MLCOMMENT, SLCOMMENT, DOC_COMMENT),
TokenSet.create(
STRING,
STRING_ERROR,
STRING_ESCAPED,
STRING_GAP,
CHAR,
NATURAL,
FLOAT
),
TokenSet.EMPTY,
TokenSet.create(
OPERATOR,
ARROW,
BACKSLASH, // maybe?!
COMMA,
DARROW,
DCOLON,
DDOT,
DOT,
EQ, // maybe?!
LARROW,
LDARROW,
OPTIMISTIC,
PIPE,
SEMI,
)
)
return psWordScanner
}
override fun getHelpId(psiElement: PsiElement): String? {
return null
}
override fun getType(element: PsiElement): String {
return when (element) {
is PSValueDeclaration -> "value"
is PSVarBinder -> "parameter"
is PSModule -> "module"
is PSNewTypeDeclaration -> "newtype"
is PSNewTypeConstructor -> "newtype constructor"
is PSImportAlias -> "import alias"
is PSDataDeclaration -> "data"
is PSDataConstructor -> "data constructor"
is PSClassDeclaration -> "class"
is PSForeignValueDeclaration -> "foreign value"
is PSForeignDataDeclaration -> "foreign data"
is PSTypeSynonymDeclaration -> "type synonym"
is PSClassMember -> "class member"
is PSFixityDeclaration -> "operator"
else -> "unknown"
}
}
override fun getDescriptiveName(element: PsiElement): String {
when (element) {
is PSValueDeclaration -> {
return "${element.module?.name}.${element.name}"
}
is PsiNamedElement -> {
val name = element.name
if (name != null) {
return name
}
}
}
return ""
}
override fun getNodeText(
element: PsiElement,
useFullName: Boolean
): String {
if (useFullName) {
return getDescriptiveName(element)
} else if (element is PsiNamedElement) {
val name = element.name
if (name != null) {
return name
}
}
return ""
}
}
| bsd-3-clause | 1e799bf0fe357dc73751f9b1ca40704f | 34.095541 | 68 | 0.648457 | 4.981917 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrMapConstructorPropertyReference.kt | 1 | 2404 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrConstructorCall
import org.jetbrains.plugins.groovy.lang.resolve.api.*
class GrMapConstructorPropertyReference(element: GrArgumentLabel) : GroovyPropertyWriteReferenceBase<GrArgumentLabel>(element) {
override val receiverArgument: Argument?
get() {
val label: GrArgumentLabel = element
val namedArgument: GrNamedArgument = label.parent as GrNamedArgument // hard cast because reference must be checked before
val constructorReference: GroovyConstructorReference = requireNotNull(getConstructorReference(namedArgument))
val resolveResult: GroovyResolveResult = constructorReference.resolveClass() ?: return null
val clazz: PsiClass = resolveResult.element as? PsiClass ?: return null
val type: PsiClassType = JavaPsiFacade.getElementFactory(label.project).createType(clazz, resolveResult.substitutor)
return JustTypeArgument(type)
}
override val propertyName: String get() = requireNotNull(element.name)
override val argument: Argument? get() = (element.parent as GrNamedArgument).expression?.let(::ExpressionArgument)
companion object {
@JvmStatic
fun getConstructorReference(argument: GrNamedArgument): GroovyConstructorReference? {
val parent: PsiElement? = argument.parent
if (parent is GrListOrMap) {
return parent.constructorReference
}
else if (parent is GrArgumentList) {
val grandParent: PsiElement? = parent.getParent()
if (grandParent is GrConstructorCall) {
return grandParent.constructorReference
}
}
return null
}
}
}
| apache-2.0 | 9f60f68e194d6955d508cc19b94343cf | 47.08 | 140 | 0.779534 | 4.916155 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectStatus.kt | 1 | 5918 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.INTERNAL
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.*
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectState.*
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.max
class ProjectStatus(private val debugName: String? = null) {
private var state = AtomicReference(Synchronized(-1) as ProjectState)
fun isDirty() = state.get() is Dirty
fun isUpToDate() = when (state.get()) {
is Modified, is Dirty, is Broken -> false
is Synchronized, is Reverted -> true
}
fun getModificationType() = when (val state = state.get()) {
is Dirty -> state.type
is Modified -> state.type
else -> null
}
fun markBroken(stamp: Long): ProjectState {
return update(Break(stamp))
}
fun markDirty(stamp: Long, type: ModificationType = INTERNAL): ProjectState {
return update(Invalidate(stamp, type))
}
fun markModified(stamp: Long, type: ModificationType = INTERNAL): ProjectState {
return update(Modify(stamp, type))
}
fun markReverted(stamp: Long): ProjectState {
return update(Revert(stamp))
}
fun markSynchronized(stamp: Long): ProjectState {
return update(Synchronize(stamp))
}
fun update(event: ProjectEvent): ProjectState {
val oldState = AtomicReference<ProjectState>()
val newState = state.updateAndGet { currentState ->
oldState.set(currentState)
when (currentState) {
is Synchronized -> when (event) {
is Synchronize -> event.withFuture(currentState, ::Synchronized)
is Invalidate -> event.ifFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.ifFuture(currentState) { Modified(it, event.type) }
is Revert -> event.ifFuture(currentState, ::Reverted)
is Break -> event.ifFuture(currentState, ::Broken)
}
is Dirty -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Modify -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Revert -> event.withFuture(currentState) { Dirty(it, currentState.type) }
is Break -> event.withFuture(currentState) { Dirty(it, currentState.type) }
}
is Modified -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, currentState.type.merge(event.type)) }
is Modify -> event.withFuture(currentState) { Modified(it, currentState.type.merge(event.type)) }
is Revert -> event.ifFuture(currentState, ::Reverted)
is Break -> event.withFuture(currentState) { Dirty(it, currentState.type) }
}
is Reverted -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.ifFuture(currentState) { Modified(it, event.type) }
is Revert -> event.withFuture(currentState, ::Reverted)
is Break -> event.ifFuture(currentState, ::Broken)
}
is Broken -> when (event) {
is Synchronize -> event.ifFuture(currentState, ::Synchronized)
is Invalidate -> event.withFuture(currentState) { Dirty(it, event.type) }
is Modify -> event.withFuture(currentState) { Dirty(it, event.type) }
is Revert -> event.withFuture(currentState, ::Broken)
is Break -> event.withFuture(currentState, ::Broken)
}
}
}
debug(newState, oldState.get(), event)
return newState
}
private fun debug(newState: ProjectState, oldState: ProjectState, event: ProjectEvent) {
if (LOG.isDebugEnabled) {
val debugPrefix = if (debugName == null) "" else "$debugName: "
LOG.debug("${debugPrefix}$oldState -> $newState by $event")
}
}
private fun ProjectEvent.withFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState {
return action(max(stamp, state.stamp))
}
private fun ProjectEvent.ifFuture(state: ProjectState, action: (Long) -> ProjectState): ProjectState {
return if (stamp > state.stamp) action(stamp) else state
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
enum class ModificationType {
EXTERNAL, INTERNAL;
fun merge(other: ModificationType): ModificationType {
return when (this) {
INTERNAL -> INTERNAL
EXTERNAL -> other
}
}
}
sealed class ProjectEvent {
abstract val stamp: Long
data class Synchronize(override val stamp: Long) : ProjectEvent()
data class Invalidate(override val stamp: Long, val type: ModificationType) : ProjectEvent()
data class Modify(override val stamp: Long, val type: ModificationType) : ProjectEvent()
data class Revert(override val stamp: Long) : ProjectEvent()
data class Break(override val stamp: Long) : ProjectEvent()
}
sealed class ProjectState {
abstract val stamp: Long
data class Synchronized(override val stamp: Long) : ProjectState()
data class Dirty(override val stamp: Long, val type: ModificationType) : ProjectState()
data class Modified(override val stamp: Long, val type: ModificationType) : ProjectState()
data class Reverted(override val stamp: Long) : ProjectState()
data class Broken(override val stamp: Long) : ProjectState()
}
}
| apache-2.0 | 521c97c5a67e4346d92ccb877d02e096 | 40.384615 | 140 | 0.68655 | 4.552308 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenWrapperSupport.kt | 7 | 8217 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.server
import com.intellij.build.FilePosition
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.isDirectory
import org.jetbrains.idea.maven.buildtool.MavenSyncConsole
import org.jetbrains.idea.maven.execution.SyncBundle
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenUtil
import java.io.*
import java.math.BigInteger
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermissions
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
@State(name = "MavenWrapperMapping",
storages = [Storage(value = "maven.wrapper.mapping.xml", roamingType = RoamingType.PER_OS)],
category = SettingsCategory.TOOLS)
internal class MavenWrapperMapping : PersistentStateComponent<MavenWrapperMapping.State> {
internal var myState = State()
class State {
@JvmField
val mapping = ConcurrentHashMap<String, String>()
}
override fun getState() = myState
override fun loadState(state: State) {
myState.mapping.putAll(state.mapping)
}
companion object {
@JvmStatic
fun getInstance(): MavenWrapperMapping {
return ApplicationManager.getApplication().getService(MavenWrapperMapping::class.java)
}
}
}
private const val DISTS_DIR = "wrapper/dists"
internal class MavenWrapperSupport {
@Throws(IOException::class)
fun downloadAndInstallMaven(urlString: String, indicator: ProgressIndicator?): MavenDistribution {
val current = getCurrentDistribution(urlString)
if (current != null) return current
val zipFile = getZipFile(urlString)
if (!zipFile.isFile) {
val partFile = File(zipFile.parentFile, "${zipFile.name}.part-${System.currentTimeMillis()}")
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.downloading.from", urlString) }
try {
HttpRequests.request(urlString)
.forceHttps(false)
.connectTimeout(30_000)
.readTimeout(30_000)
.saveToFile(partFile, indicator)
}
catch (t: Throwable) {
if (t is ControlFlowException) throw RuntimeException(SyncBundle.message("maven.sync.wrapper.downloading.canceled"))
}
FileUtil.rename(partFile, zipFile)
}
if (!zipFile.isFile) {
throw RuntimeException(SyncBundle.message("cannot.download.zip.from", urlString))
}
val home = unpackZipFile(zipFile, indicator).canonicalFile
MavenWrapperMapping.getInstance().myState.mapping[urlString] = home.absolutePath
return LocalMavenDistribution(home.toPath(), urlString)
}
private fun unpackZipFile(zipFile: File, indicator: ProgressIndicator?): File {
unzip(zipFile, indicator)
val dirs = zipFile.parentFile.listFiles { it -> it.isDirectory }
if (dirs == null || dirs.size != 1) {
MavenLog.LOG.warn("Expected exactly 1 top level dir in Maven distribution, found: " + dirs?.asList())
throw IllegalStateException(SyncBundle.message("zip.is.not.correct", zipFile.absoluteFile))
}
val mavenHome = dirs[0]
if (!SystemInfo.isWindows) {
makeMavenBinRunnable(mavenHome)
}
return mavenHome
}
private fun makeMavenBinRunnable(mavenHome: File?) {
val mvnExe = File(mavenHome, "bin/mvn").canonicalFile
val permissions = PosixFilePermissions.fromString("rwxr-xr-x")
Files.setPosixFilePermissions(mvnExe.toPath(), permissions)
}
private fun unzip(zip: File, indicator: ProgressIndicator?) {
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.unpacking") }
val unpackDir = zip.parentFile
val destinationCanonicalPath = unpackDir.canonicalPath
var errorUnpacking = true
try {
ZipFile(zip).use { zipFile ->
val entries: Enumeration<*> = zipFile.entries()
while (entries.hasMoreElements()) {
val entry = entries.nextElement() as ZipEntry
val destFile = File(unpackDir, entry.name)
val canonicalPath = destFile.canonicalPath
if (!canonicalPath.startsWith(destinationCanonicalPath)) {
FileUtil.delete(zip)
throw RuntimeException("Directory traversal attack detected, zip file is malicious and IDEA dropped it")
}
if (entry.isDirectory) {
destFile.mkdirs()
}
else {
destFile.parentFile.mkdirs()
BufferedOutputStream(FileOutputStream(destFile)).use {
StreamUtil.copy(zipFile.getInputStream(entry), it)
}
}
}
}
errorUnpacking = false
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.unpacked.into", destinationCanonicalPath) }
}
finally {
if (errorUnpacking) {
indicator?.apply { text = SyncBundle.message("maven.sync.wrapper.failure") }
zip.parentFile.listFiles { it -> it.name != zip.name }?.forEach { FileUtil.delete(it) }
}
}
}
private fun getZipFile(distributionUrl: String): File {
val baseName: String = getDistName(distributionUrl)
val distName: String = FileUtil.getNameWithoutExtension(baseName)
val md5Hash: String = getMd5Hash(distributionUrl)
val m2dir = MavenUtil.resolveM2Dir()
val distsDir = File(m2dir, DISTS_DIR)
return File(File(File(distsDir, distName), md5Hash), baseName).absoluteFile
}
private fun getDistName(distUrl: String): String {
val p = distUrl.lastIndexOf("/")
return if (p < 0) distUrl else distUrl.substring(p + 1)
}
private fun getMd5Hash(string: String): String {
return try {
val messageDigest = MessageDigest.getInstance("MD5")
val bytes = string.toByteArray()
messageDigest.update(bytes)
BigInteger(1, messageDigest.digest()).toString(32)
}
catch (var4: Exception) {
throw RuntimeException("Could not hash input string.", var4)
}
}
companion object {
val DISTRIBUTION_URL_PROPERTY = "distributionUrl"
@JvmStatic
fun getWrapperDistributionUrl(baseDir: VirtualFile?): String? {
val wrapperProperties = getWrapperProperties(baseDir) ?: return null
val properties = Properties()
val stream = ByteArrayInputStream(wrapperProperties.contentsToByteArray(true))
properties.load(stream)
return properties.getProperty(DISTRIBUTION_URL_PROPERTY)
}
@JvmStatic
fun showUnsecureWarning(console: MavenSyncConsole, mavenProjectMultimodulePath: VirtualFile?) {
val properties = getWrapperProperties(mavenProjectMultimodulePath)
val line = properties?.inputStream?.bufferedReader(properties.charset)?.readLines()?.indexOfFirst {
it.startsWith(DISTRIBUTION_URL_PROPERTY)
} ?: -1
val position = properties?.let { FilePosition(it.toNioPath().toFile(), line, 0) }
console.addWarning(SyncBundle.message("maven.sync.wrapper.http.title"),
SyncBundle.message("maven.sync.wrapper.http.description"),
position)
}
@JvmStatic
fun getCurrentDistribution(urlString: String): MavenDistribution? {
val mapping = MavenWrapperMapping.getInstance()
val cachedHome = mapping.myState.mapping.get(urlString)
if (cachedHome != null) {
val path = Path.of(cachedHome)
if (path.isDirectory()) {
return LocalMavenDistribution(path, urlString)
}
else {
mapping.myState.mapping.remove(urlString)
}
}
return null
}
@JvmStatic
fun getWrapperProperties(baseDir: VirtualFile?) =
baseDir?.findChild(".mvn")?.findChild("wrapper")?.findChild("maven-wrapper.properties")
}
} | apache-2.0 | 72f35223c667bbf307202851d74f34b9 | 36.018018 | 140 | 0.708166 | 4.507405 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/notification/impl/NotificationsToolWindow.kt | 1 | 53159 | // 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.notification.impl
import com.intellij.UtilBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.LafManagerListener
import com.intellij.idea.ActionsBundle
import com.intellij.notification.ActionCenter
import com.intellij.notification.EventLog
import com.intellij.notification.LogModel
import com.intellij.notification.Notification
import com.intellij.notification.impl.ui.NotificationsUtil
import com.intellij.notification.impl.widget.IdeNotificationArea
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Divider
import com.intellij.openapi.ui.NullableComponent
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Clock
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Alarm
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.*
import java.util.*
import java.util.function.Consumer
import javax.accessibility.AccessibleContext
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.HyperlinkEvent
import javax.swing.event.PopupMenuEvent
import javax.swing.text.JTextComponent
internal class NotificationsToolWindowFactory : ToolWindowFactory, DumbAware {
companion object {
const val ID = "Notifications"
internal const val CLEAR_ACTION_ID = "ClearAllNotifications"
internal val myModel = ApplicationNotificationModel()
fun addNotification(project: Project?, notification: Notification) {
if (ActionCenter.isEnabled() && notification.canShowFor(project) && NotificationsConfigurationImpl.getSettings(
notification.groupId).isShouldLog) {
myModel.addNotification(project, notification)
}
}
fun expire(notification: Notification) {
myModel.expire(notification)
}
fun expireAll() {
myModel.expireAll()
}
fun clearAll(project: Project?) {
myModel.clearAll(project)
}
fun getStateNotifications(project: Project) = myModel.getStateNotifications(project)
fun getNotifications(project: Project?) = myModel.getNotifications(project)
}
override fun isApplicable(project: Project) = ActionCenter.isEnabled()
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
NotificationContent(project, toolWindow)
}
}
internal class NotificationContent(val project: Project,
private val toolWindow: ToolWindow) : Disposable, ToolWindowManagerListener {
private val myMainPanel = JBPanelWithEmptyText(BorderLayout())
private val myNotifications = ArrayList<Notification>()
private val myIconNotifications = ArrayList<Notification>()
private val suggestions: NotificationGroupComponent
private val timeline: NotificationGroupComponent
private val searchController: SearchController
private val singleSelectionHandler = SingleTextSelectionHandler()
private var myVisible = true
private val mySearchUpdateAlarm = Alarm()
init {
myMainPanel.background = NotificationComponent.BG_COLOR
setEmptyState()
handleFocus()
suggestions = NotificationGroupComponent(this, true, project)
timeline = NotificationGroupComponent(this, false, project)
searchController = SearchController(this, suggestions, timeline)
myMainPanel.add(createSearchComponent(toolWindow), BorderLayout.NORTH)
createGearActions()
val splitter = MySplitter()
splitter.firstComponent = suggestions
splitter.secondComponent = timeline
myMainPanel.add(splitter)
suggestions.setRemoveCallback(Consumer(::remove))
timeline.setClearCallback(::clear)
Disposer.register(toolWindow.disposable, this)
val content = ContentFactory.getInstance().createContent(myMainPanel, "", false)
content.preferredFocusableComponent = myMainPanel
val contentManager = toolWindow.contentManager
contentManager.addContent(content)
contentManager.setSelectedContent(content)
project.messageBus.connect(toolWindow.disposable).subscribe(ToolWindowManagerListener.TOPIC, this)
ApplicationManager.getApplication().messageBus.connect(toolWindow.disposable).subscribe(LafManagerListener.TOPIC, LafManagerListener {
suggestions.updateLaf()
timeline.updateLaf()
})
val newNotifications = ArrayList<Notification>()
NotificationsToolWindowFactory.myModel.registerAndGetInitNotifications(this, newNotifications)
for (notification in newNotifications) {
add(notification)
}
}
private fun createSearchComponent(toolWindow: ToolWindow): SearchTextField {
val searchField = object : SearchTextField() {
override fun updateUI() {
super.updateUI()
textEditor?.border = null
}
override fun preprocessEventForTextField(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.VK_ESCAPE && event.id == KeyEvent.KEY_PRESSED) {
isVisible = false
searchController.cancelSearch()
return true
}
return super.preprocessEventForTextField(event)
}
}
searchField.textEditor.border = null
searchField.border = JBUI.Borders.customLineBottom(JBColor.border())
searchField.isVisible = false
if (ExperimentalUI.isNewUI()) {
searchController.background = JBUI.CurrentTheme.ToolWindow.background()
searchField.textEditor.background = searchController.background
}
else {
searchController.background = UIUtil.getTextFieldBackground()
}
searchController.searchField = searchField
searchField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
mySearchUpdateAlarm.cancelAllRequests()
mySearchUpdateAlarm.addRequest(searchController::doSearch, 100, ModalityState.stateForComponent(searchField))
}
})
return searchField
}
private fun createGearActions() {
val gearAction = object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
searchController.startSearch()
}
}
val actionManager = ActionManager.getInstance()
val findAction = actionManager.getAction(IdeActions.ACTION_FIND)
if (findAction == null) {
gearAction.templatePresentation.text = ActionsBundle.actionText(IdeActions.ACTION_FIND)
}
else {
gearAction.copyFrom(findAction)
gearAction.registerCustomShortcutSet(findAction.shortcutSet, myMainPanel)
}
val group = DefaultActionGroup()
group.add(gearAction)
group.addSeparator()
val clearAction = actionManager.getAction(NotificationsToolWindowFactory.CLEAR_ACTION_ID)
if (clearAction != null) {
group.add(clearAction)
}
val markAction = actionManager.getAction("MarkNotificationsAsRead")
if (markAction != null) {
group.add(markAction)
}
(toolWindow as ToolWindowEx).setAdditionalGearActions(group)
}
fun setEmptyState() {
myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.first.line"))
@Suppress("DialogTitleCapitalization")
myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.second.line"))
}
fun clearEmptyState() {
myMainPanel.emptyText.clear()
}
private fun handleFocus() {
val listener = AWTEventListener {
if (it is MouseEvent && it.id == MouseEvent.MOUSE_PRESSED && !toolWindow.isActive && UIUtil.isAncestor(myMainPanel, it.component)) {
it.component.requestFocus()
}
}
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK)
Disposer.register(toolWindow.disposable, Disposable {
Toolkit.getDefaultToolkit().removeAWTEventListener(listener)
})
}
fun add(notification: Notification) {
if (!NotificationsConfigurationImpl.getSettings(notification.groupId).isShouldLog) {
return
}
if (notification.isSuggestionType) {
suggestions.add(notification, singleSelectionHandler)
}
else {
timeline.add(notification, singleSelectionHandler)
}
myNotifications.add(notification)
myIconNotifications.add(notification)
searchController.update()
setStatusMessage(notification)
updateIcon()
}
fun getStateNotifications() = ArrayList(myIconNotifications)
fun getNotifications() = ArrayList(myNotifications)
fun isEmpty() = suggestions.isEmpty() && timeline.isEmpty()
fun expire(notification: Notification?) {
if (notification == null) {
val notifications = ArrayList(myNotifications)
myNotifications.clear()
myIconNotifications.clear()
suggestions.expireAll()
timeline.expireAll()
searchController.update()
setStatusMessage(null)
updateIcon()
for (n in notifications) {
n.expire()
}
}
else {
remove(notification)
}
}
private fun remove(notification: Notification) {
if (notification.isSuggestionType) {
suggestions.remove(notification)
}
else {
timeline.remove(notification)
}
myNotifications.remove(notification)
myIconNotifications.remove(notification)
searchController.update()
setStatusMessage()
updateIcon()
}
private fun clear(notifications: List<Notification>) {
myNotifications.removeAll(notifications)
myIconNotifications.removeAll(notifications)
searchController.update()
setStatusMessage()
updateIcon()
}
fun clearAll() {
project.closeAllBalloons()
myNotifications.clear()
myIconNotifications.clear()
suggestions.clear()
timeline.clear()
searchController.update()
setStatusMessage(null)
updateIcon()
}
override fun stateChanged(toolWindowManager: ToolWindowManager) {
val visible = toolWindow.isVisible
if (myVisible != visible) {
myVisible = visible
if (visible) {
project.closeAllBalloons()
suggestions.updateComponents()
timeline.updateComponents()
}
else {
suggestions.clearNewState()
timeline.clearNewState()
myIconNotifications.clear()
updateIcon()
}
}
}
private fun updateIcon() {
toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(myIconNotifications))
LogModel.fireModelChanged()
}
private fun setStatusMessage() {
setStatusMessage(myNotifications.findLast { it.isImportant || it.isImportantSuggestion })
}
private fun setStatusMessage(notification: Notification?) {
EventLog.getLogModel(project).setStatusMessage(notification)
}
override fun dispose() {
NotificationsToolWindowFactory.myModel.unregister(this)
Disposer.dispose(mySearchUpdateAlarm)
}
fun fullRepaint() {
myMainPanel.doLayout()
myMainPanel.revalidate()
myMainPanel.repaint()
}
}
private class MySplitter : OnePixelSplitter(true, .5f) {
override fun createDivider(): Divider {
return object : OnePixelDivider(true, this) {
override fun setVisible(aFlag: Boolean) {
super.setVisible(aFlag)
setResizeEnabled(aFlag)
if (!aFlag) {
setBounds(0, 0, 0, 0)
}
}
override fun setBackground(bg: Color?) {
super.setBackground(JBColor.border())
}
}
}
}
private fun JComponent.mediumFontFunction() {
font = JBFont.medium()
val f: (JComponent) -> Unit = {
it.font = JBFont.medium()
}
putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}
private fun JComponent.smallFontFunction() {
font = JBFont.smallOrNewUiMedium()
val f: (JComponent) -> Unit = {
it.font = JBFont.smallOrNewUiMedium()
}
putClientProperty(NotificationGroupComponent.FONT_KEY, f)
}
private class SearchController(private val mainContent: NotificationContent,
private val suggestions: NotificationGroupComponent,
private val timeline: NotificationGroupComponent) {
lateinit var searchField: SearchTextField
lateinit var background: Color
fun startSearch() {
searchField.isVisible = true
searchField.selectText()
searchField.requestFocus()
mainContent.clearEmptyState()
if (searchField.text.isNotEmpty()) {
doSearch()
}
}
fun doSearch() {
val query = searchField.text
if (query.isEmpty()) {
searchField.textEditor.background = background
clearSearch()
return
}
var result = false
val function: (NotificationComponent) -> Unit = {
if (it.applySearchQuery(query)) {
result = true
}
}
suggestions.iterateComponents(function)
timeline.iterateComponents(function)
searchField.textEditor.background = if (result) background else LightColors.RED
mainContent.fullRepaint()
}
fun update() {
if (searchField.isVisible && searchField.text.isNotEmpty()) {
doSearch()
}
}
fun cancelSearch() {
mainContent.setEmptyState()
clearSearch()
}
private fun clearSearch() {
val function: (NotificationComponent) -> Unit = { it.applySearchQuery(null) }
suggestions.iterateComponents(function)
timeline.iterateComponents(function)
mainContent.fullRepaint()
}
}
private class NotificationGroupComponent(private val myMainContent: NotificationContent,
private val mySuggestionType: Boolean,
private val myProject: Project) :
JBPanel<NotificationGroupComponent>(BorderLayout()), NullableComponent {
companion object {
const val FONT_KEY = "FontFunction"
}
private val myTitle = JBLabel(
IdeBundle.message(if (mySuggestionType) "notifications.toolwindow.suggestions" else "notifications.toolwindow.timeline"))
private val myList = JPanel(VerticalLayout(JBUI.scale(10)))
private val myScrollPane = object : JBScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
override fun setupCorners() {
super.setupCorners()
border = null
}
override fun updateUI() {
super.updateUI()
border = null
}
}
private var myScrollValue = 0
private val myEventHandler = ComponentEventHandler()
private val myTimeComponents = ArrayList<JLabel>()
private val myTimeAlarm = Alarm(myProject)
private lateinit var myClearCallback: (List<Notification>) -> Unit
private lateinit var myRemoveCallback: Consumer<Notification>
init {
background = NotificationComponent.BG_COLOR
val mainPanel = JPanel(BorderLayout(0, JBUI.scale(8)))
mainPanel.isOpaque = false
mainPanel.border = JBUI.Borders.empty(8, 8, 0, 0)
add(mainPanel)
myTitle.mediumFontFunction()
myTitle.foreground = NotificationComponent.INFO_COLOR
if (mySuggestionType) {
myTitle.border = JBUI.Borders.emptyLeft(10)
mainPanel.add(myTitle, BorderLayout.NORTH)
}
else {
val panel = JPanel(BorderLayout())
panel.isOpaque = false
panel.border = JBUI.Borders.emptyLeft(10)
panel.add(myTitle, BorderLayout.WEST)
val clearAll = LinkLabel(IdeBundle.message("notifications.toolwindow.timeline.clear.all"), null) { _: LinkLabel<Unit>, _: Unit? ->
clearAll()
}
clearAll.mediumFontFunction()
clearAll.border = JBUI.Borders.emptyRight(20)
panel.add(clearAll, BorderLayout.EAST)
mainPanel.add(panel, BorderLayout.NORTH)
}
myList.isOpaque = true
myList.background = NotificationComponent.BG_COLOR
myList.border = JBUI.Borders.emptyRight(10)
myScrollPane.border = null
mainPanel.add(myScrollPane)
myScrollPane.verticalScrollBar.addAdjustmentListener {
val value = it.value
if (myScrollValue == 0 && value > 0 || myScrollValue > 0 && value == 0) {
myScrollValue = value
repaint()
}
else {
myScrollValue = value
}
}
myEventHandler.add(this)
}
fun updateLaf() {
updateComponents()
iterateComponents { it.updateLaf() }
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (myScrollValue > 0) {
g.color = JBColor.border()
val y = myScrollPane.y - 1
g.drawLine(0, y, width, y)
}
}
fun add(notification: Notification, singleSelectionHandler: SingleTextSelectionHandler) {
val component = NotificationComponent(myProject, notification, myTimeComponents, singleSelectionHandler)
component.setNew(true)
myList.add(component, 0)
updateLayout()
myEventHandler.add(component)
updateContent()
if (mySuggestionType) {
component.setDoNotAskHandler { forProject ->
component.myNotificationWrapper.notification!!
.setDoNotAskFor(if (forProject) myProject else null)
.also { myRemoveCallback.accept(it) }
.hideBalloon()
}
component.setRemoveCallback(myRemoveCallback)
}
}
private fun updateLayout() {
val layout = myList.layout
iterateComponents { component ->
layout.removeLayoutComponent(component)
layout.addLayoutComponent(null, component)
}
}
fun isEmpty(): Boolean {
val count = myList.componentCount
for (i in 0 until count) {
if (myList.getComponent(i) is NotificationComponent) {
return false
}
}
return true
}
fun setRemoveCallback(callback: Consumer<Notification>) {
myRemoveCallback = callback
}
fun remove(notification: Notification) {
val count = myList.componentCount
for (i in 0 until count) {
val component = myList.getComponent(i) as NotificationComponent
if (component.myNotificationWrapper.notification === notification) {
if (notification.isSuggestionType) {
component.removeFromParent()
myList.remove(i)
}
else {
component.expire()
}
break
}
}
updateContent()
}
fun setClearCallback(callback: (List<Notification>) -> Unit) {
myClearCallback = callback
}
private fun clearAll() {
myProject.closeAllBalloons()
val notifications = ArrayList<Notification>()
iterateComponents {
val notification = it.myNotificationWrapper.notification
if (notification != null) {
notifications.add(notification)
}
}
clear()
myClearCallback.invoke(notifications)
}
fun expireAll() {
if (mySuggestionType) {
clear()
}
else {
iterateComponents {
if (it.myNotificationWrapper.notification != null) {
it.expire()
}
}
updateContent()
}
}
fun clear() {
iterateComponents { it.removeFromParent() }
myList.removeAll()
updateContent()
}
fun clearNewState() {
iterateComponents { it.setNew(false) }
}
fun updateComponents() {
UIUtil.uiTraverser(this).filter(JComponent::class.java).forEach {
val value = it.getClientProperty(FONT_KEY)
if (value != null) {
(value as (JComponent) -> Unit).invoke(it)
}
}
myMainContent.fullRepaint()
}
inline fun iterateComponents(f: (NotificationComponent) -> Unit) {
val count = myList.componentCount
for (i in 0 until count) {
f.invoke(myList.getComponent(i) as NotificationComponent)
}
}
private fun updateContent() {
if (!mySuggestionType && !myTimeAlarm.isDisposed) {
myTimeAlarm.cancelAllRequests()
object : Runnable {
override fun run() {
for (timeComponent in myTimeComponents) {
timeComponent.text = formatPrettyDateTime(timeComponent.getClientProperty(NotificationComponent.TIME_KEY) as Long)
}
if (myTimeComponents.isNotEmpty() && !myTimeAlarm.isDisposed) {
myTimeAlarm.addRequest(this, 30000)
}
}
}.run()
}
myMainContent.fullRepaint()
}
private fun formatPrettyDateTime(time: Long): @NlsSafe String {
val c = Calendar.getInstance()
c.timeInMillis = Clock.getTime()
val currentYear = c[Calendar.YEAR]
val currentDayOfYear = c[Calendar.DAY_OF_YEAR]
c.timeInMillis = time
val year = c[Calendar.YEAR]
val dayOfYear = c[Calendar.DAY_OF_YEAR]
if (currentYear == year && currentDayOfYear == dayOfYear) {
return DateFormatUtil.formatTime(time)
}
val isYesterdayOnPreviousYear = currentYear == year + 1 && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum(
Calendar.DAY_OF_YEAR)
val isYesterday = isYesterdayOnPreviousYear || currentYear == year && currentDayOfYear == dayOfYear + 1
if (isYesterday) {
return UtilBundle.message("date.format.yesterday")
}
return DateFormatUtil.formatDate(time)
}
override fun isVisible(): Boolean {
if (super.isVisible()) {
val count = myList.componentCount
for (i in 0 until count) {
if (myList.getComponent(i).isVisible) {
return true
}
}
}
return false
}
override fun isNull(): Boolean = !isVisible
}
private class NotificationComponent(val project: Project,
notification: Notification,
timeComponents: ArrayList<JLabel>,
val singleSelectionHandler: SingleTextSelectionHandler) :
JBPanel<NotificationComponent>() {
companion object {
val BG_COLOR: Color
get() {
if (ExperimentalUI.isNewUI()) {
return JBUI.CurrentTheme.ToolWindow.background()
}
return UIUtil.getListBackground()
}
val INFO_COLOR = JBColor.namedColor("Label.infoForeground", JBColor(Gray.x80, Gray.x8C))
internal const val NEW_COLOR_NAME = "NotificationsToolwindow.newNotification.background"
internal val NEW_DEFAULT_COLOR = JBColor(0xE6EEF7, 0x45494A)
val NEW_COLOR = JBColor.namedColor(NEW_COLOR_NAME, NEW_DEFAULT_COLOR)
val NEW_HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.newNotification.hoverBackground", JBColor(0xE6EEF7, 0x45494A))
val HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.Notification.hoverBackground", BG_COLOR)
const val TIME_KEY = "TimestampKey"
}
val myNotificationWrapper = NotificationWrapper(notification)
private var myIsNew = false
private var myHoverState = false
private val myMoreButton: Component?
private var myMorePopupVisible = false
private var myRoundColor = BG_COLOR
private lateinit var myDoNotAskHandler: (Boolean) -> Unit
private lateinit var myRemoveCallback: Consumer<Notification>
private var myMorePopup: JBPopup? = null
var myMoreAwtPopup: JPopupMenu? = null
var myDropDownPopup: JPopupMenu? = null
private var myLafUpdater: Runnable? = null
init {
isOpaque = true
background = BG_COLOR
border = JBUI.Borders.empty(10, 10, 10, 0)
layout = object : BorderLayout(JBUI.scale(7), 0) {
private var myEastComponent: Component? = null
override fun addLayoutComponent(name: String?, comp: Component) {
if (EAST == name) {
myEastComponent = comp
}
else {
super.addLayoutComponent(name, comp)
}
}
override fun layoutContainer(target: Container) {
super.layoutContainer(target)
if (myEastComponent != null && myEastComponent!!.isVisible) {
val insets = target.insets
val height = target.height - insets.bottom - insets.top
val component = myEastComponent!!
component.setSize(component.width, height)
val d = component.preferredSize
component.setBounds(target.width - insets.right - d.width, insets.top, d.width, height)
}
}
}
val iconPanel = JPanel(BorderLayout())
iconPanel.isOpaque = false
iconPanel.add(JBLabel(NotificationsUtil.getIcon(notification)), BorderLayout.NORTH)
add(iconPanel, BorderLayout.WEST)
val centerPanel = JPanel(VerticalLayout(JBUI.scale(8)))
centerPanel.isOpaque = false
centerPanel.border = JBUI.Borders.emptyRight(10)
var titlePanel: JPanel? = null
if (notification.hasTitle()) {
val titleContent = NotificationsUtil.buildHtml(notification, null, false, null, null)
val title = object : JBLabel(titleContent) {
override fun updateUI() {
val oldEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
if (oldEditor != null) {
singleSelectionHandler.remove(oldEditor)
}
super.updateUI()
val newEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java)
if (newEditor != null) {
singleSelectionHandler.add(newEditor, true)
}
}
}
try {
title.setCopyable(true)
}
catch (_: Exception) {
}
NotificationsManagerImpl.setTextAccessibleName(title, titleContent)
val editor = UIUtil.findComponentOfType(title, JEditorPane::class.java)
if (editor != null) {
singleSelectionHandler.add(editor, true)
}
if (notification.isSuggestionType) {
centerPanel.add(title)
}
else {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
titlePanel.add(title)
centerPanel.add(titlePanel)
}
}
if (notification.hasContent()) {
val textContent = NotificationsUtil.buildFullContent(notification)
val textComponent = createTextComponent(textContent)
NotificationsManagerImpl.setTextAccessibleName(textComponent, textContent)
singleSelectionHandler.add(textComponent, true)
if (!notification.hasTitle() && !notification.isSuggestionType) {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
titlePanel.add(textComponent)
centerPanel.add(titlePanel)
}
else {
centerPanel.add(textComponent)
}
}
val actions = notification.actions
val actionsSize = actions.size
val helpAction = notification.contextHelpAction
if (actionsSize > 0 || helpAction != null) {
val layout = HorizontalLayout(JBUIScale.scale(16))
val actionPanel = JPanel(if (!notification.isSuggestionType && actions.size > 1) DropDownActionLayout(layout) else layout)
actionPanel.isOpaque = false
if (notification.isSuggestionType) {
if (actionsSize > 0) {
val button = JButton(actions[0].templateText)
button.isOpaque = false
button.addActionListener {
runAction(actions[0], it.source)
}
actionPanel.add(button)
if (actionsSize == 2) {
actionPanel.add(createAction(actions[1]))
}
else if (actionsSize > 2) {
actionPanel.add(MoreAction(this, actions))
}
}
}
else {
if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST) {
actionPanel.add(MyDropDownAction(this))
}
for (action in actions) {
actionPanel.add(createAction(action))
}
if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_LEFTMOST) {
actionPanel.add(MyDropDownAction(this))
}
}
if (helpAction != null) {
val presentation = helpAction.templatePresentation
val helpLabel = ContextHelpLabel.create(StringUtil.defaultIfEmpty(presentation.text, ""), presentation.description)
helpLabel.foreground = UIUtil.getLabelDisabledForeground()
actionPanel.add(helpLabel)
}
if (!notification.hasTitle() && !notification.hasContent() && !notification.isSuggestionType) {
titlePanel = JPanel(BorderLayout())
titlePanel.isOpaque = false
actionPanel.add(titlePanel, HorizontalLayout.RIGHT)
}
centerPanel.add(actionPanel)
}
add(centerPanel)
if (notification.isSuggestionType) {
val group = DefaultActionGroup()
group.isPopup = true
if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
group.add(object : DumbAwareAction(IdeBundle.message("action.text.settings")) {
override fun actionPerformed(e: AnActionEvent) {
doShowSettings()
}
})
group.addSeparator()
}
val remindAction = RemindLaterManager.createAction(notification, DateFormatUtil.DAY)
if (remindAction != null) {
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.remind.tomorrow")) {
override fun actionPerformed(e: AnActionEvent) {
remindAction.run()
myRemoveCallback.accept(myNotificationWrapper.notification!!)
myNotificationWrapper.notification!!.hideBalloon()
}
})
}
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again.for.this.project")) {
override fun actionPerformed(e: AnActionEvent) {
myDoNotAskHandler.invoke(true)
}
})
@Suppress("DialogTitleCapitalization")
group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again")) {
override fun actionPerformed(e: AnActionEvent) {
myDoNotAskHandler.invoke(false)
}
})
val presentation = Presentation()
presentation.icon = AllIcons.Actions.More
presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, java.lang.Boolean.TRUE)
val button = object : ActionButton(group, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun createAndShowActionGroupPopup(actionGroup: ActionGroup, event: AnActionEvent): JBPopup {
myMorePopupVisible = true
val popup = super.createAndShowActionGroupPopup(actionGroup, event)
myMorePopup = popup
popup.addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
myMorePopup = null
ApplicationManager.getApplication().invokeLater {
myMorePopupVisible = false
isVisible = myHoverState
}
}
})
return popup
}
}
button.border = JBUI.Borders.emptyRight(5)
button.isVisible = false
myMoreButton = button
val eastPanel = JPanel(BorderLayout())
eastPanel.isOpaque = false
eastPanel.add(button, BorderLayout.NORTH)
add(eastPanel, BorderLayout.EAST)
setComponentZOrder(eastPanel, 0)
}
else {
val timeComponent = JBLabel(DateFormatUtil.formatPrettyDateTime(notification.timestamp))
timeComponent.putClientProperty(TIME_KEY, notification.timestamp)
timeComponent.verticalAlignment = SwingConstants.TOP
timeComponent.verticalTextPosition = SwingConstants.TOP
timeComponent.toolTipText = DateFormatUtil.formatDateTime(notification.timestamp)
timeComponent.border = JBUI.Borders.emptyRight(10)
timeComponent.smallFontFunction()
timeComponent.foreground = INFO_COLOR
timeComponents.add(timeComponent)
if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) {
val button = object: InplaceButton(IdeBundle.message("tooltip.turn.notification.off"), AllIcons.Ide.Notification.Gear,
ActionListener { doShowSettings() }) {
override fun setBounds(x: Int, y: Int, width: Int, height: Int) {
super.setBounds(x, y - 1, width, height)
}
}
button.setIcons(AllIcons.Ide.Notification.Gear, null, AllIcons.Ide.Notification.GearHover)
myMoreButton = button
val buttonWrapper = JPanel(BorderLayout())
buttonWrapper.isOpaque = false
buttonWrapper.border = JBUI.Borders.emptyRight(10)
buttonWrapper.add(button, BorderLayout.NORTH)
buttonWrapper.preferredSize = buttonWrapper.preferredSize
button.isVisible = false
val eastPanel = JPanel(BorderLayout())
eastPanel.isOpaque = false
eastPanel.add(buttonWrapper, BorderLayout.WEST)
eastPanel.add(timeComponent, BorderLayout.EAST)
titlePanel!!.add(eastPanel, BorderLayout.EAST)
}
else {
titlePanel!!.add(timeComponent, BorderLayout.EAST)
myMoreButton = null
}
}
}
private fun createAction(action: AnAction): JComponent {
return object : LinkLabel<AnAction>(action.templateText, action.templatePresentation.icon,
{ link, _action -> runAction(_action, link) }, action) {
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
}
private fun doShowSettings() {
NotificationCollector.getInstance().logNotificationSettingsClicked(myNotificationWrapper.id, myNotificationWrapper.displayId,
myNotificationWrapper.groupId)
val configurable = NotificationsConfigurable()
ShowSettingsUtil.getInstance().editConfigurable(project, configurable, Runnable {
val runnable = configurable.enableSearch(myNotificationWrapper.groupId)
runnable?.run()
})
}
private fun runAction(action: AnAction, component: Any) {
setNew(false)
NotificationCollector.getInstance().logNotificationActionInvoked(null, myNotificationWrapper.notification!!, action,
NotificationCollector.NotificationPlace.ACTION_CENTER)
Notification.fire(myNotificationWrapper.notification!!, action, DataManager.getInstance().getDataContext(component as Component))
}
fun expire() {
closePopups()
myNotificationWrapper.notification = null
setNew(false)
for (component in UIUtil.findComponentsOfType(this, LinkLabel::class.java)) {
component.isEnabled = false
}
val dropDownAction = UIUtil.findComponentOfType(this, MyDropDownAction::class.java)
if (dropDownAction != null) {
DataManager.removeDataProvider(dropDownAction)
}
}
fun removeFromParent() {
closePopups()
for (component in UIUtil.findComponentsOfType(this, JTextComponent::class.java)) {
singleSelectionHandler.remove(component)
}
}
private fun closePopups() {
myMorePopup?.cancel()
myMoreAwtPopup?.isVisible = false
myDropDownPopup?.isVisible = false
}
private fun createTextComponent(text: @Nls String): JEditorPane {
val component = JEditorPane()
component.isEditable = false
component.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, java.lang.Boolean.TRUE)
component.contentType = "text/html"
component.isOpaque = false
component.border = null
NotificationsUtil.configureHtmlEditorKit(component, false)
if (myNotificationWrapper.notification!!.listener != null) {
component.addHyperlinkListener { e ->
val notification = myNotificationWrapper.notification
if (notification != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
val listener = notification.listener
if (listener != null) {
NotificationCollector.getInstance().logHyperlinkClicked(notification)
listener.hyperlinkUpdate(notification, e)
}
}
}
}
component.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, StringUtil.unescapeXmlEntities(StringUtil.stripHtml(text, " ")))
component.text = text
component.isEditable = false
if (component.caret != null) {
component.caretPosition = 0
}
myLafUpdater = Runnable {
NotificationsUtil.configureHtmlEditorKit(component, false)
component.text = text
component.revalidate()
component.repaint()
}
return component
}
fun updateLaf() {
myLafUpdater?.run()
updateColor()
}
fun setDoNotAskHandler(handler: (Boolean) -> Unit) {
myDoNotAskHandler = handler
}
fun setRemoveCallback(callback: Consumer<Notification>) {
myRemoveCallback = callback
}
fun isHover(): Boolean = myHoverState
fun setNew(state: Boolean) {
if (myIsNew != state) {
myIsNew = state
updateColor()
}
}
fun setHover(state: Boolean) {
myHoverState = state
if (myMoreButton != null) {
if (!myMorePopupVisible) {
myMoreButton.isVisible = state
}
}
updateColor()
}
private fun updateColor() {
if (myHoverState) {
if (myIsNew) {
setColor(NEW_HOVER_COLOR)
}
else {
setColor(HOVER_COLOR)
}
}
else if (myIsNew) {
if (UIManager.getColor(NEW_COLOR_NAME) != null) {
setColor(NEW_COLOR)
}
else {
setColor(NEW_DEFAULT_COLOR)
}
}
else {
setColor(BG_COLOR)
}
}
private fun setColor(color: Color) {
myRoundColor = color
repaint()
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (myRoundColor !== BG_COLOR) {
g.color = myRoundColor
val config = GraphicsUtil.setupAAPainting(g)
val cornerRadius = NotificationBalloonRoundShadowBorderProvider.CORNER_RADIUS.get()
g.fillRoundRect(0, 0, width, height, cornerRadius, cornerRadius)
config.restore()
}
}
fun applySearchQuery(query: String?): Boolean {
if (query == null) {
isVisible = true
return true
}
val result = matchQuery(query)
isVisible = result
return result
}
private fun matchQuery(query: @NlsSafe String): Boolean {
if (myNotificationWrapper.title.contains(query, true)) {
return true
}
val subtitle = myNotificationWrapper.subtitle
if (subtitle != null && subtitle.contains(query, true)) {
return true
}
if (myNotificationWrapper.content.contains(query, true)) {
return true
}
for (action in myNotificationWrapper.actions) {
if (action != null && action.contains(query, true)) {
return true
}
}
return false
}
}
private class MoreAction(val notificationComponent: NotificationComponent, actions: List<AnAction>) :
NotificationsManagerImpl.DropDownAction(null, null) {
val group = DefaultActionGroup()
init {
val size = actions.size
for (i in 1..size - 1) {
group.add(actions[i])
}
setListener(LinkListener { link, _ ->
val popup = NotificationsManagerImpl.showPopup(link, group)
notificationComponent.myMoreAwtPopup = popup
popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
notificationComponent.myMoreAwtPopup = null
}
})
}, null)
text = IdeBundle.message("notifications.action.more")
Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
}
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
private class MyDropDownAction(val notificationComponent: NotificationComponent) : NotificationsManagerImpl.DropDownAction(null, null) {
var collapseActionsDirection: Notification.CollapseActionsDirection = notificationComponent.myNotificationWrapper.notification!!.collapseDirection
init {
setListener(LinkListener { link, _ ->
val group = DefaultActionGroup()
val layout = link.parent.layout as DropDownActionLayout
for (action in layout.actions) {
if (!action.isVisible) {
group.add(action.linkData)
}
}
val popup = NotificationsManagerImpl.showPopup(link, group)
notificationComponent.myDropDownPopup = popup
popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
notificationComponent.myDropDownPopup = null
}
})
}, null)
text = notificationComponent.myNotificationWrapper.notification!!.dropDownText
isVisible = false
Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this)
}
override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED
}
private class NotificationWrapper(notification: Notification) {
val title = notification.title
val subtitle = notification.subtitle
val content = notification.content
val id = notification.id
val displayId = notification.displayId
val groupId = notification.groupId
val actions: List<String?> = notification.actions.stream().map { it.templateText }.toList()
var notification: Notification? = notification
}
private class DropDownActionLayout(layout: LayoutManager2) : FinalLayoutWrapper(layout) {
val actions = ArrayList<LinkLabel<AnAction>>()
private lateinit var myDropDownAction: MyDropDownAction
override fun addLayoutComponent(comp: Component, constraints: Any?) {
super.addLayoutComponent(comp, constraints)
add(comp)
}
override fun addLayoutComponent(name: String?, comp: Component) {
super.addLayoutComponent(name, comp)
add(comp)
}
private fun add(component: Component) {
if (component is MyDropDownAction) {
myDropDownAction = component
}
else if (component is LinkLabel<*>) {
@Suppress("UNCHECKED_CAST")
actions.add(component as LinkLabel<AnAction>)
}
}
override fun layoutContainer(parent: Container) {
val width = parent.width
myDropDownAction.isVisible = false
for (action in actions) {
action.isVisible = true
}
layout.layoutContainer(parent)
val keepRightmost = myDropDownAction.collapseActionsDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST
val collapseStart = if (keepRightmost) 0 else actions.size - 1
val collapseDelta = if (keepRightmost) 1 else -1
var collapseIndex = collapseStart
if (parent.preferredSize.width > width) {
myDropDownAction.isVisible = true
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
layout.layoutContainer(parent)
while (parent.preferredSize.width > width && collapseIndex >= 0 && collapseIndex < actions.size) {
actions[collapseIndex].isVisible = false
collapseIndex += collapseDelta
layout.layoutContainer(parent)
}
}
}
}
private class ComponentEventHandler {
private var myHoverComponent: NotificationComponent? = null
private val myMouseHandler = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent) {
if (myHoverComponent == null) {
val component = ComponentUtil.getParentOfType(NotificationComponent::class.java, e.component)
if (component != null) {
if (!component.isHover()) {
component.setHover(true)
}
myHoverComponent = component
}
}
}
override fun mouseExited(e: MouseEvent) {
if (myHoverComponent != null) {
val component = myHoverComponent!!
if (component.isHover()) {
component.setHover(false)
}
myHoverComponent = null
}
}
}
fun add(component: Component) {
addAll(component) { c ->
c.addMouseListener(myMouseHandler)
c.addMouseMotionListener(myMouseHandler)
}
}
private fun addAll(component: Component, listener: (Component) -> Unit) {
listener.invoke(component)
if (component is JBOptionButton) {
component.addContainerListener(object : ContainerAdapter() {
override fun componentAdded(e: ContainerEvent) {
addAll(e.child, listener)
}
})
}
for (child in UIUtil.uiChildren(component)) {
addAll(child, listener)
}
}
}
internal class ApplicationNotificationModel {
private val myNotifications = ArrayList<Notification>()
private val myProjectToModel = HashMap<Project, ProjectNotificationModel>()
private val myLock = Object()
internal fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
synchronized(myLock) {
notifications.addAll(myNotifications)
myNotifications.clear()
val model = myProjectToModel.getOrPut(content.project) { ProjectNotificationModel() }
model.registerAndGetInitNotifications(content, notifications)
}
}
internal fun unregister(content: NotificationContent) {
synchronized(myLock) {
myProjectToModel.remove(content.project)
}
}
fun addNotification(project: Project?, notification: Notification) {
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
if (project == null) {
if (myProjectToModel.isEmpty()) {
myNotifications.add(notification)
}
else {
for ((_project, model) in myProjectToModel.entries) {
model.addNotification(_project, notification, myNotifications, runnables)
}
}
}
else {
val model = myProjectToModel.getOrPut(project) {
Disposer.register(project) {
synchronized(myLock) {
myProjectToModel.remove(project)
}
}
ProjectNotificationModel()
}
model.addNotification(project, notification, myNotifications, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
}
fun getStateNotifications(project: Project): List<Notification> {
synchronized(myLock) {
val model = myProjectToModel[project]
if (model != null) {
return model.getStateNotifications()
}
}
return emptyList()
}
fun getNotifications(project: Project?): List<Notification> {
synchronized(myLock) {
if (project == null) {
return ArrayList(myNotifications)
}
val model = myProjectToModel[project]
if (model == null) {
return ArrayList(myNotifications)
}
return model.getNotifications(myNotifications)
}
}
fun isEmptyContent(project: Project): Boolean {
val model = myProjectToModel[project]
return model == null || model.isEmptyContent()
}
fun expire(notification: Notification) {
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
myNotifications.remove(notification)
for ((project , model) in myProjectToModel) {
model.expire(project, notification, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
}
fun expireAll() {
val notifications = ArrayList<Notification>()
val runnables = ArrayList<Runnable>()
synchronized(myLock) {
notifications.addAll(myNotifications)
myNotifications.clear()
for ((project, model) in myProjectToModel) {
model.expireAll(project, notifications, runnables)
}
}
for (runnable in runnables) {
runnable.run()
}
for (notification in notifications) {
notification.expire()
}
}
fun clearAll(project: Project?) {
synchronized(myLock) {
myNotifications.clear()
if (project != null) {
myProjectToModel[project]?.clearAll(project)
}
}
}
}
private class ProjectNotificationModel {
private val myNotifications = ArrayList<Notification>()
private var myContent: NotificationContent? = null
fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) {
notifications.addAll(myNotifications)
myNotifications.clear()
myContent = content
}
fun addNotification(project: Project,
notification: Notification,
appNotifications: List<Notification>,
runnables: MutableList<Runnable>) {
if (myContent == null) {
myNotifications.add(notification)
val notifications = ArrayList(appNotifications)
notifications.addAll(myNotifications)
runnables.add(Runnable {
updateToolWindow(project, notification, notifications, false)
})
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.add(notification) } })
}
}
fun getStateNotifications(): List<Notification> {
if (myContent == null) {
return emptyList()
}
return myContent!!.getStateNotifications()
}
fun isEmptyContent(): Boolean {
return myContent == null || myContent!!.isEmpty()
}
fun getNotifications(appNotifications: List<Notification>): List<Notification> {
if (myContent == null) {
val notifications = ArrayList(appNotifications)
notifications.addAll(myNotifications)
return notifications
}
return myContent!!.getNotifications()
}
fun expire(project: Project, notification: Notification, runnables: MutableList<Runnable>) {
myNotifications.remove(notification)
if (myContent == null) {
runnables.add(Runnable {
updateToolWindow(project, null, myNotifications, false)
})
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(notification) } })
}
}
fun expireAll(project: Project, notifications: MutableList<Notification>, runnables: MutableList<Runnable>) {
notifications.addAll(myNotifications)
myNotifications.clear()
if (myContent == null) {
updateToolWindow(project, null, emptyList(), false)
}
else {
runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(null) } })
}
}
fun clearAll(project: Project) {
myNotifications.clear()
if (myContent == null) {
updateToolWindow(project, null, emptyList(), true)
}
else {
UIUtil.invokeLaterIfNeeded { myContent!!.clearAll() }
}
}
private fun updateToolWindow(project: Project,
stateNotification: Notification?,
notifications: List<Notification>,
closeBalloons: Boolean) {
UIUtil.invokeLaterIfNeeded {
if (project.isDisposed) {
return@invokeLaterIfNeeded
}
EventLog.getLogModel(project).setStatusMessage(stateNotification)
if (closeBalloons) {
project.closeAllBalloons()
}
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID)
toolWindow?.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(notifications))
}
}
}
fun Project.closeAllBalloons() {
val ideFrame = WindowManager.getInstance().getIdeFrame(this)
val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl
balloonLayout.closeAll()
}
class ClearAllNotificationsAction : DumbAwareAction(IdeBundle.message("clear.all.notifications"), null, AllIcons.Actions.GC) {
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabled = NotificationsToolWindowFactory.getNotifications(project).isNotEmpty() ||
(project != null && !NotificationsToolWindowFactory.myModel.isEmptyContent(project))
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun actionPerformed(e: AnActionEvent) {
NotificationsToolWindowFactory.clearAll(e.project)
}
} | apache-2.0 | 2d92396a1c1a1ad60275299bff8fcb42 | 30.43702 | 148 | 0.687635 | 4.976968 | false | false | false | false |
afollestad/assent | rationales/src/test/java/com/afollestad/assent/rationale/MockRequestResponder.kt | 1 | 1784 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.assent.rationale
import com.afollestad.assent.AssentResult
import com.afollestad.assent.GrantResult.DENIED
import com.afollestad.assent.GrantResult.GRANTED
import com.afollestad.assent.Permission
class MockRequestResponder {
private val allow = mutableSetOf<Permission>()
private val requestLog = mutableListOf<Array<out Permission>>()
fun allow(vararg permissions: Permission) {
allow.addAll(permissions)
}
fun deny(vararg permissions: Permission) {
allow.removeAll(permissions)
}
fun reset() {
allow.clear()
requestLog.clear()
}
fun log(): List<Array<out Permission>> {
return requestLog
}
val requester: Requester = { permissions, _, _, callback ->
requestLog.add(permissions)
val grantResults = List(permissions.size) {
val permission: Permission = permissions[it]
if (allow.contains(permission)) {
GRANTED
} else {
DENIED
}
}
val result = AssentResult(
permissions.mapIndexed { index, permission ->
Pair(permission, grantResults[index])
}.toMap()
)
callback(result)
}
}
| apache-2.0 | 356b2055d43613e4e516dfb6697dc483 | 27.31746 | 75 | 0.706839 | 4.247619 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/RewardCardUnselectedViewHolder.kt | 1 | 4620 | package com.kickstarter.ui.viewholders
import android.util.Pair
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import com.kickstarter.R
import com.kickstarter.databinding.ItemRewardUnselectedCardBinding
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.models.Project
import com.kickstarter.models.StoredCard
import com.kickstarter.viewmodels.RewardCardUnselectedViewHolderViewModel
class RewardCardUnselectedViewHolder(val binding: ItemRewardUnselectedCardBinding, val delegate: Delegate) : KSViewHolder(binding.root) {
interface Delegate {
fun cardSelected(storedCard: StoredCard, position: Int)
}
private val viewModel: RewardCardUnselectedViewHolderViewModel.ViewModel = RewardCardUnselectedViewHolderViewModel.ViewModel(environment())
private val ksString = requireNotNull(environment().ksString())
private val creditCardExpirationString = this.context().getString(R.string.Credit_card_expiration)
private val lastFourString = this.context().getString(R.string.payment_method_last_four)
init {
this.viewModel.outputs.expirationDate()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setExpirationDateText(it) }
this.viewModel.outputs.expirationIsGone()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
this.binding.rewardCardDetailsLayout.rewardCardExpirationDate.isGone = it
}
this.viewModel.outputs.isClickable()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.cardContainer.isClickable = it }
this.viewModel.outputs.issuerImage()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.setImageResource(it) }
this.viewModel.outputs.issuer()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.contentDescription = it }
this.viewModel.outputs.issuerImageAlpha()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLogo.alpha = it }
this.viewModel.outputs.lastFour()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setLastFourText(it) }
this.viewModel.outputs.lastFourTextColor()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.binding.rewardCardDetailsLayout.rewardCardLastFour.setTextColor(ContextCompat.getColor(context(), it)) }
this.viewModel.outputs.notAvailableCopyIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(this.binding.cardNotAllowedWarning, !it) }
this.viewModel.outputs.notifyDelegateCardSelected()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { this.delegate.cardSelected(it.first, it.second) }
this.viewModel.outputs.retryCopyIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(this.binding.retryCardWarningLayout.retryCardWarning, !it) }
this.viewModel.outputs.selectImageIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setInvisible(this.binding.selectImageView, !it) }
this.binding.cardContainer.setOnClickListener {
this.viewModel.inputs.cardSelected(adapterPosition)
}
}
override fun bindData(data: Any?) {
@Suppress("UNCHECKED_CAST")
val cardAndProject = requireNotNull(data) as Pair<StoredCard, Project>
this.viewModel.inputs.configureWith(cardAndProject)
}
private fun setExpirationDateText(date: String) {
this.binding.rewardCardDetailsLayout.rewardCardExpirationDate.text = this.ksString.format(
this.creditCardExpirationString,
"expiration_date", date
)
}
private fun setLastFourText(lastFour: String) {
this.binding.rewardCardDetailsLayout.rewardCardLastFour.text = this.ksString.format(
this.lastFourString,
"last_four",
lastFour
)
}
}
| apache-2.0 | d34b223a97c36b013e070ebf3d295996 | 39.173913 | 143 | 0.686797 | 5.133333 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/receivers/BTReceiver.kt | 1 | 1049 | package info.nightscout.androidaps.receivers
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.Intent
import dagger.android.DaggerBroadcastReceiver
import info.nightscout.androidaps.events.EventBTChange
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import javax.inject.Inject
class BTReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var rxBus: RxBusWrapper
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
when (intent.action) {
BluetoothDevice.ACTION_ACL_CONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.CONNECT, deviceName = device.name, deviceAddress = device.address))
BluetoothDevice.ACTION_ACL_DISCONNECTED ->
rxBus.send(EventBTChange(EventBTChange.Change.DISCONNECT, deviceName = device.name, deviceAddress = device.address))
}
}
} | agpl-3.0 | c3604ef7bdf58c7d920f9cbfe826fa45 | 41 | 132 | 0.754051 | 4.856481 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSDirectoryService.kt | 1 | 4321 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.directory.AbstractAWSDirectoryService
import com.amazonaws.services.directory.AWSDirectoryService
import com.amazonaws.services.directory.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAWSDirectoryService(val context: IacContext) : AbstractAWSDirectoryService(), AWSDirectoryService {
override fun addIpRoutes(request: AddIpRoutesRequest): AddIpRoutesResult {
return with (context) {
request.registerWithAutoName()
AddIpRoutesResult().registerWithSameNameAs(request)
}
}
override fun addTagsToResource(request: AddTagsToResourceRequest): AddTagsToResourceResult {
return with (context) {
request.registerWithAutoName()
AddTagsToResourceResult().registerWithSameNameAs(request)
}
}
override fun createAlias(request: CreateAliasRequest): CreateAliasResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateAliasRequest, CreateAliasResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateAliasRequest::getDirectoryId to CreateAliasResult::getDirectoryId,
CreateAliasRequest::getAlias to CreateAliasResult::getAlias
)
)
}
}
override fun createComputer(request: CreateComputerRequest): CreateComputerResult {
return with (context) {
request.registerWithAutoName()
CreateComputerResult().withComputer(
makeProxy<CreateComputerRequest, Computer>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request,
copyFromReq = mapOf(
CreateComputerRequest::getComputerName to Computer::getComputerName,
CreateComputerRequest::getComputerAttributes to Computer::getComputerAttributes
)
)
).registerWithSameNameAs(request)
}
}
override fun createConditionalForwarder(request: CreateConditionalForwarderRequest): CreateConditionalForwarderResult {
return with (context) {
request.registerWithAutoName()
CreateConditionalForwarderResult().registerWithSameNameAs(request)
}
}
override fun createDirectory(request: CreateDirectoryRequest): CreateDirectoryResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateDirectoryRequest, CreateDirectoryResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createMicrosoftAD(request: CreateMicrosoftADRequest): CreateMicrosoftADResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateMicrosoftADRequest, CreateMicrosoftADResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createSnapshot(request: CreateSnapshotRequest): CreateSnapshotResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateSnapshotRequest, CreateSnapshotResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createTrust(request: CreateTrustRequest): CreateTrustResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateTrustRequest, CreateTrustResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredAWSDirectoryService(context: IacContext) : BaseDeferredAWSDirectoryService(context)
| mit | da5dbdf481cd018f16ed251a8f97f2b0 | 37.927928 | 123 | 0.630178 | 6.226225 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findWithStructuralGrouping/kotlinClassAllUsages.1.kt | 4 | 714 | package client
import server.Server
class Client(name: String = Server.NAME): Server() {
var nextServer: Server? = new Server()
val name = Server.NAME
fun foo(s: Server) {
val server: Server = s
println("Server: $server")
}
fun getNextServer(): Server? {
return nextServer
}
override fun work() {
super<Server>.work()
println("Client")
}
companion object: Server() {
}
}
object ClientObject: Server() {
}
fun Client.bar(s: Server = Server.NAME) {
foo(s)
}
fun Client.hasNextServer(): Boolean {
return getNextServer() != null
}
fun Any.asServer(): Server? {
return if (this is Server) this as Server else null
} | apache-2.0 | ccfc9dbb506512e72f9beef25c3a32a6 | 16.02381 | 55 | 0.605042 | 3.71875 | false | false | false | false |
ursjoss/sipamato | common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/AbstractPanel.kt | 2 | 1990 | package ch.difty.scipamato.common.web
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX
import org.apache.wicket.bean.validation.PropertyValidator
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.FormComponent
import org.apache.wicket.markup.html.panel.GenericPanel
import org.apache.wicket.model.IModel
import org.apache.wicket.model.StringResourceModel
abstract class AbstractPanel<T> @JvmOverloads constructor(
id: String,
model: IModel<T>? = null,
open val mode: Mode = Mode.VIEW,
) : GenericPanel<T>(id, model) {
val isSearchMode: Boolean
get() = mode === Mode.SEARCH
val isEditMode: Boolean
get() = mode === Mode.EDIT
val isViewMode: Boolean
get() = mode === Mode.VIEW
val submitLinkResourceLabel: String
get() = when (mode) {
Mode.EDIT -> "button.save.label"
Mode.SEARCH -> "button.search.label"
Mode.VIEW -> "button.disabled.label"
}
@JvmOverloads
fun queueFieldAndLabel(field: FormComponent<*>, pv: PropertyValidator<*>? = null) {
field.labelled().apply {
outputMarkupId = true
}.also {
queue(it)
}
if (isEditMode) pv?.let { field.add(it) }
}
protected fun queueCheckBoxAndLabel(field: CheckBoxX) {
queue(field.labelled())
}
private fun FormComponent<*>.labelled(): FormComponent<*> {
val fieldId = id
val labelModel = StringResourceModel("$fieldId$LABEL_RESOURCE_TAG", this@AbstractPanel, null)
label = labelModel
[email protected](Label("$fieldId$LABEL_TAG", labelModel))
return this
}
companion object {
private const val serialVersionUID = 1L
const val SELECT_ALL_RESOURCE_TAG = "multiselect.selectAll"
const val DESELECT_ALL_RESOURCE_TAG = "multiselect.deselectAll"
}
}
enum class Mode {
EDIT, VIEW, SEARCH
}
| gpl-3.0 | df84f25729b7487a47e183cd0f5340a0 | 31.096774 | 101 | 0.661809 | 4.103093 | false | false | false | false |
nimakro/tornadofx | src/test/kotlin/tornadofx/testapps/AsyncProgressApp.kt | 3 | 1689 | package tornadofx.testapps
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
class AsyncProgressApp : App(AsyncProgressView::class)
class AsyncProgressView : View("Async Progress") {
override val root = borderpane {
setPrefSize(400.0, 300.0)
center {
button("Start") {
action {
runAsync {
updateTitle("Doing some work")
for (i in 1..10) {
updateMessage("Working $i...")
if (i == 5)
updateTitle("Dome something else")
Thread.sleep(200)
updateProgress(i.toLong(), 10)
}
}
}
}
}
bottom {
add<ProgressView>()
}
}
}
class ProgressView : View() {
val status: TaskStatus by inject()
override val root = vbox(4) {
visibleWhen { status.running }
style { borderColor += box(Color.LIGHTGREY, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT) }
label(status.title).style { fontWeight = FontWeight.BOLD }
hbox(4) {
label(status.message)
progressbar(status.progress)
visibleWhen { status.running }
}
}
}
class AsyncProgressButtonView : View() {
override val root = stackpane {
setPrefSize(400.0, 400.0)
button("Click me") {
action {
runAsyncWithProgress {
Thread.sleep(2000)
}
}
}
}
} | apache-2.0 | f4b751cf1f4caa8fe398f97372c511ba | 26.704918 | 110 | 0.485494 | 5.072072 | false | false | false | false |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/network/site/model/UserSmall.kt | 1 | 764 | package com.sedsoftware.yaptalker.data.network.site.model
import com.google.gson.annotations.SerializedName
data class UserSmall(
@SerializedName("avatar_res")
var avatarRes: String? = null,
@SerializedName("avatar_type")
var avatarType: String? = null,
@SerializedName("avatar_url")
var avatarUrl: String? = null,
@SerializedName("id")
var id: String? = null,
@SerializedName("name")
var name: String? = null,
@SerializedName("new_mails")
var newMails: String? = null,
@SerializedName("rank")
var rank: Int? = null,
@SerializedName("read_only")
var readOnly: Int? = null,
@SerializedName("SID")
var sid: String? = null,
@SerializedName("validated")
var validated: String? = null
)
| apache-2.0 | fcadba87a72b555cb436c9da2216898e | 28.384615 | 57 | 0.664921 | 3.839196 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/Border.kt | 3 | 17565 | /*
* 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.foundation
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.CacheDrawScope
import androidx.compose.ui.draw.DrawResult
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSimple
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.ClipOp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageBitmapConfig
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.CanvasDrawScope
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.toSize
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* Modify element to add border with appearance specified with a [border] and a [shape] and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSample()
*
* @param border [BorderStroke] class that specifies border appearance, such as size and color
* @param shape shape of the border
*/
fun Modifier.border(border: BorderStroke, shape: Shape = RectangleShape) =
border(width = border.width, brush = border.brush, shape = shape)
/**
* Modify element to add border with appearance specified with a [width], a [color] and a [shape]
* and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSampleWithDataClass()
*
* @param width width of the border. Use [Dp.Hairline] for a hairline border.
* @param color color to paint the border with
* @param shape shape of the border
*/
fun Modifier.border(width: Dp, color: Color, shape: Shape = RectangleShape) =
border(width, SolidColor(color), shape)
/**
* Modify element to add border with appearance specified with a [width], a [brush] and a [shape]
* and clip it.
*
* @sample androidx.compose.foundation.samples.BorderSampleWithBrush()
*
* @param width width of the border. Use [Dp.Hairline] for a hairline border.
* @param brush brush to paint the border with
* @param shape shape of the border
*/
fun Modifier.border(width: Dp, brush: Brush, shape: Shape): Modifier = composed(
factory = {
// BorderCache object that is lazily allocated depending on the type of shape
// This object is only used for generic shapes and rounded rectangles with different corner
// radius sizes.
val borderCacheRef = remember { Ref<BorderCache>() }
this.then(
Modifier.drawWithCache {
val hasValidBorderParams = width.toPx() >= 0f && size.minDimension > 0f
if (!hasValidBorderParams) {
drawContentWithoutBorder()
} else {
val strokeWidthPx = min(
if (width == Dp.Hairline) 1f else ceil(width.toPx()),
ceil(size.minDimension / 2)
)
val halfStroke = strokeWidthPx / 2
val topLeft = Offset(halfStroke, halfStroke)
val borderSize = Size(
size.width - strokeWidthPx,
size.height - strokeWidthPx
)
// The stroke is larger than the drawing area so just draw a full shape instead
val fillArea = (strokeWidthPx * 2) > size.minDimension
when (val outline = shape.createOutline(size, layoutDirection, this)) {
is Outline.Generic ->
drawGenericBorder(
borderCacheRef,
brush,
outline,
fillArea,
strokeWidthPx
)
is Outline.Rounded ->
drawRoundRectBorder(
borderCacheRef,
brush,
outline,
topLeft,
borderSize,
fillArea,
strokeWidthPx
)
is Outline.Rectangle ->
drawRectBorder(
brush,
topLeft,
borderSize,
fillArea,
strokeWidthPx
)
}
}
}
)
},
inspectorInfo = debugInspectorInfo {
name = "border"
properties["width"] = width
if (brush is SolidColor) {
properties["color"] = brush.value
value = brush.value
} else {
properties["brush"] = brush
}
properties["shape"] = shape
}
)
private fun Ref<BorderCache>.obtain(): BorderCache =
this.value ?: BorderCache().also { value = it }
/**
* Helper object that handles lazily allocating and re-using objects
* to render the border into an offscreen ImageBitmap
*/
private data class BorderCache(
private var imageBitmap: ImageBitmap? = null,
private var canvas: androidx.compose.ui.graphics.Canvas? = null,
private var canvasDrawScope: CanvasDrawScope? = null,
private var borderPath: Path? = null
) {
inline fun CacheDrawScope.drawBorderCache(
borderSize: IntSize,
config: ImageBitmapConfig,
block: DrawScope.() -> Unit
): ImageBitmap {
var targetImageBitmap = imageBitmap
var targetCanvas = canvas
// If we previously had allocated a full Argb888 ImageBitmap but are only requiring
// an alpha mask, just re-use the same ImageBitmap instead of allocating a new one
val compatibleConfig = targetImageBitmap?.config == ImageBitmapConfig.Argb8888 ||
config == targetImageBitmap?.config
if (targetImageBitmap == null ||
targetCanvas == null ||
size.width > targetImageBitmap.width ||
size.height > targetImageBitmap.height ||
!compatibleConfig
) {
targetImageBitmap = ImageBitmap(
borderSize.width,
borderSize.height,
config = config
).also {
imageBitmap = it
}
targetCanvas = androidx.compose.ui.graphics.Canvas(targetImageBitmap).also {
canvas = it
}
}
val targetDrawScope = canvasDrawScope ?: CanvasDrawScope().also { canvasDrawScope = it }
val drawSize = borderSize.toSize()
targetDrawScope.draw(
this,
layoutDirection,
targetCanvas,
drawSize
) {
// Clear the previously rendered portion within this ImageBitmap as we could
// be re-using it
drawRect(
color = Color.Black,
size = drawSize,
blendMode = BlendMode.Clear
)
block()
}
targetImageBitmap.prepareToDraw()
return targetImageBitmap
}
fun obtainPath(): Path =
borderPath ?: Path().also { borderPath = it }
}
/**
* Border implementation for invalid parameters that just draws the content
* as the given border parameters are infeasible (ex. negative border width)
*/
private fun CacheDrawScope.drawContentWithoutBorder(): DrawResult =
onDrawWithContent {
drawContent()
}
/**
* Border implementation for generic paths. Note it is possible to be given paths
* that do not make sense in the context of a border (ex. a figure 8 path or a non-enclosed
* shape) We do not handle that here as we expect developers to give us enclosed, non-overlapping
* paths
*/
private fun CacheDrawScope.drawGenericBorder(
borderCacheRef: Ref<BorderCache>,
brush: Brush,
outline: Outline.Generic,
fillArea: Boolean,
strokeWidth: Float
): DrawResult =
if (fillArea) {
onDrawWithContent {
drawContent()
drawPath(outline.path, brush = brush)
}
} else {
// Optimization, if we are only drawing a solid color border, we only need an alpha8 mask
// as we can draw the mask with a tint.
// Otherwise we need to allocate a full ImageBitmap and draw it normally
val config: ImageBitmapConfig
val colorFilter: ColorFilter?
if (brush is SolidColor) {
config = ImageBitmapConfig.Alpha8
colorFilter = ColorFilter.tint(brush.value)
} else {
config = ImageBitmapConfig.Argb8888
colorFilter = null
}
val pathBounds = outline.path.getBounds()
val borderCache = borderCacheRef.obtain()
// Create a mask path that includes a rectangle with the original path cut out of it
val maskPath = borderCache.obtainPath().apply {
reset()
addRect(pathBounds)
op(this, outline.path, PathOperation.Difference)
}
val cacheImageBitmap: ImageBitmap
val pathBoundsSize = IntSize(
ceil(pathBounds.width).toInt(),
ceil(pathBounds.height).toInt()
)
with(borderCache) {
// Draw into offscreen bitmap with the size of the path
// We need to draw into this intermediate bitmap to act as a layer
// and make sure that the clearing logic does not generate underdraw
// into the target we are rendering into
cacheImageBitmap = drawBorderCache(
pathBoundsSize,
config
) {
// Paths can have offsets, so translate to keep the drawn path
// within the bounds of the mask bitmap
translate(-pathBounds.left, -pathBounds.top) {
// Draw the path with a stroke width twice the provided value.
// Because strokes are centered, this will draw both and inner and outer stroke
// with the desired stroke width
drawPath(path = outline.path, brush = brush, style = Stroke(strokeWidth * 2))
// Scale the canvas slightly to cover the background that may be visible
// after clearing the outer stroke
scale(
(size.width + 1) / size.width,
(size.height + 1) / size.height
) {
// Remove the outer stroke by clearing the inverted mask path
drawPath(path = maskPath, brush = brush, blendMode = BlendMode.Clear)
}
}
}
}
onDrawWithContent {
drawContent()
translate(pathBounds.left, pathBounds.top) {
drawImage(cacheImageBitmap, srcSize = pathBoundsSize, colorFilter = colorFilter)
}
}
}
/**
* Border implementation for simple rounded rects and those with different corner
* radii
*/
private fun CacheDrawScope.drawRoundRectBorder(
borderCacheRef: Ref<BorderCache>,
brush: Brush,
outline: Outline.Rounded,
topLeft: Offset,
borderSize: Size,
fillArea: Boolean,
strokeWidth: Float
): DrawResult {
return if (outline.roundRect.isSimple) {
val cornerRadius = outline.roundRect.topLeftCornerRadius
val halfStroke = strokeWidth / 2
val borderStroke = Stroke(strokeWidth)
onDrawWithContent {
drawContent()
when {
fillArea -> {
// If the drawing area is smaller than the stroke being drawn
// drawn all around it just draw a filled in rounded rect
drawRoundRect(brush, cornerRadius = cornerRadius)
}
cornerRadius.x < halfStroke -> {
// If the corner radius is smaller than half of the stroke width
// then the interior curvature of the stroke will be a sharp edge
// In this case just draw a normal filled in rounded rect with the
// desired corner radius but clipping out the interior rectangle
clipRect(
strokeWidth,
strokeWidth,
size.width - strokeWidth,
size.height - strokeWidth,
clipOp = ClipOp.Difference
) {
drawRoundRect(brush, cornerRadius = cornerRadius)
}
}
else -> {
// Otherwise draw a stroked rounded rect with the corner radius
// shrunk by half of the stroke width. This will ensure that the
// outer curvature of the rounded rectangle will have the desired
// corner radius.
drawRoundRect(
brush = brush,
topLeft = topLeft,
size = borderSize,
cornerRadius = cornerRadius.shrink(halfStroke),
style = borderStroke
)
}
}
}
} else {
val path = borderCacheRef.obtain().obtainPath()
val roundedRectPath = createRoundRectPath(path, outline.roundRect, strokeWidth, fillArea)
onDrawWithContent {
drawContent()
drawPath(roundedRectPath, brush = brush)
}
}
}
/**
* Border implementation for rectangular borders
*/
private fun CacheDrawScope.drawRectBorder(
brush: Brush,
topLeft: Offset,
borderSize: Size,
fillArea: Boolean,
strokeWidthPx: Float
): DrawResult {
// If we are drawing a rectangular stroke, just offset it by half the stroke
// width as strokes are always drawn centered on their geometry.
// If the border is larger than the drawing area, just fill the area with a
// solid rectangle
val rectTopLeft = if (fillArea) Offset.Zero else topLeft
val size = if (fillArea) size else borderSize
val style = if (fillArea) Fill else Stroke(strokeWidthPx)
return onDrawWithContent {
drawContent()
drawRect(
brush = brush,
topLeft = rectTopLeft,
size = size,
style = style
)
}
}
/**
* Helper method that creates a round rect with the inner region removed
* by the given stroke width
*/
private fun createRoundRectPath(
targetPath: Path,
roundedRect: RoundRect,
strokeWidth: Float,
fillArea: Boolean
): Path =
targetPath.apply {
reset()
addRoundRect(roundedRect)
if (!fillArea) {
val insetPath = Path().apply {
addRoundRect(createInsetRoundedRect(strokeWidth, roundedRect))
}
op(this, insetPath, PathOperation.Difference)
}
}
private fun createInsetRoundedRect(
widthPx: Float,
roundedRect: RoundRect
) = RoundRect(
left = widthPx,
top = widthPx,
right = roundedRect.width - widthPx,
bottom = roundedRect.height - widthPx,
topLeftCornerRadius = roundedRect.topLeftCornerRadius.shrink(widthPx),
topRightCornerRadius = roundedRect.topRightCornerRadius.shrink(widthPx),
bottomLeftCornerRadius = roundedRect.bottomLeftCornerRadius.shrink(widthPx),
bottomRightCornerRadius = roundedRect.bottomRightCornerRadius.shrink(widthPx)
)
/**
* Helper method to shrink the corner radius by the given value, clamping to 0
* if the resultant corner radius would be negative
*/
private fun CornerRadius.shrink(value: Float): CornerRadius = CornerRadius(
max(0f, this.x - value),
max(0f, this.y - value)
)
| apache-2.0 | 3c05958721212097af61f3d0e19bba72 | 37.351528 | 100 | 0.604213 | 5.244849 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/k2-fe10-bindings/src/org/jetbrains/kotlin/idea/fir/fe10/binding/CallAndResolverCallWrappers.kt | 2 | 8017 | // 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.fir.fe10.binding
import com.intellij.lang.ASTNode
import org.jetbrains.kotlin.analysis.api.calls.*
import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnostic
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.Fe10WrapperContext
import org.jetbrains.kotlin.idea.fir.fe10.KtSymbolBasedConstructorDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.toDeclarationDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.toKotlinType
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.CallMaker
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver
import org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class CallAndResolverCallWrappers(bindingContext: KtSymbolBasedBindingContext) {
private val context = bindingContext.context
init {
bindingContext.registerGetterByKey(BindingContext.CALL, this::getCall)
bindingContext.registerGetterByKey(BindingContext.RESOLVED_CALL, this::getResolvedCall)
bindingContext.registerGetterByKey(BindingContext.CONSTRUCTOR_RESOLVED_DELEGATION_CALL, this::getConstructorResolvedDelegationCall)
bindingContext.registerGetterByKey(BindingContext.REFERENCE_TARGET, this::getReferenceTarget)
}
private fun getCall(element: KtElement): Call? {
val call = createCall(element) ?: return null
/**
* In FE10 [org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategyImpl.bindCall] happening to the calleeExpression
*/
check(call.calleeExpression == element) {
"${call.calleeExpression} != $element"
}
return call
}
private fun createCall(element: KtElement): Call? {
val parent = element.parent
if (parent is KtCallElement) {
val callParent = parent.parent
val callOperationNode: ASTNode?
val receiver: Receiver?
if (callParent is KtQualifiedExpression) {
callOperationNode = callParent.operationTokenNode
receiver = callParent.receiverExpression.toExpressionReceiverValue(context)
} else {
callOperationNode = null
receiver = null
}
return CallMaker.makeCall(receiver, callOperationNode, parent)
}
if (element is KtSimpleNameExpression && element !is KtOperationReferenceExpression) {
if (parent is KtQualifiedExpression) {
val receiver = parent.receiverExpression.toExpressionReceiverValue(context)
return CallMaker.makePropertyCall(receiver, parent.operationTokenNode, element)
}
return CallMaker.makePropertyCall(null, null, element)
}
if (element is KtArrayAccessExpression) {
val receiver = element.getArrayExpression()?.toExpressionReceiverValue(context) ?: return null
return CallMaker.makeArrayGetCall(receiver, element, Call.CallType.ARRAY_GET_METHOD)
}
when (parent) {
is KtBinaryExpression -> {
val receiver = parent.left?.toExpressionReceiverValue(context) ?: context.errorHandling()
return CallMaker.makeCall(receiver, parent)
}
is KtUnaryExpression -> {
if (element is KtOperationReferenceExpression && element.getReferencedNameElementType() == KtTokens.EXCLEXCL) {
return ControlStructureTypingUtils.createCallForSpecialConstruction(parent, element, listOf(parent.baseExpression))
}
val receiver = parent.baseExpression?.toExpressionReceiverValue(context) ?: context.errorHandling()
return CallMaker.makeCall(receiver, parent)
}
}
// todo support array get/set calls
return null
}
private fun KtExpression.toExpressionReceiverValue(context: Fe10WrapperContext): ExpressionReceiver {
val ktType = context.withAnalysisSession {
[email protected]() ?: context.implementationPostponed()
}
// TODO: implement THIS_TYPE_FOR_SUPER_EXPRESSION Binding slice
return ExpressionReceiver.create(this, ktType.toKotlinType(context), context.bindingContext)
}
private fun getResolvedCall(call: Call): ResolvedCall<*>? {
val ktElement = call.calleeExpression ?: call.callElement
val ktCallInfo = context.withAnalysisSession { ktElement.resolveCall() }
val diagnostic: KtDiagnostic?
val ktCall: KtCall = when (ktCallInfo) {
null -> return null
is KtSuccessCallInfo -> {
diagnostic = null
ktCallInfo.call
}
is KtErrorCallInfo -> {
diagnostic = ktCallInfo.diagnostic
ktCallInfo.candidateCalls.singleOrNull() ?: return null
}
}
when (ktCall) {
is KtFunctionCall<*> -> {
if (ktCall.safeAs<KtSimpleFunctionCall>()?.isImplicitInvoke == true) {
context.implementationPostponed("Variable + invoke resolved call")
}
return FunctionFe10WrapperResolvedCall(call, ktCall, diagnostic, context)
}
is KtVariableAccessCall -> {
return VariableFe10WrapperResolvedCall(call, ktCall, diagnostic, context)
}
is KtCheckNotNullCall -> {
val kotlinType = context.withAnalysisSession { ktCall.baseExpression.getKtType() }?.toKotlinType(context)
return Fe10BindingSpecialConstructionResolvedCall(
call,
kotlinType,
context.fe10BindingSpecialConstructionFunctions.EXCL_EXCL,
context
)
}
else -> context.implementationPostponed(ktCall.javaClass.canonicalName)
}
}
private fun getConstructorResolvedDelegationCall(constructor: ConstructorDescriptor): ResolvedCall<ConstructorDescriptor>? {
val constructorPSI = constructor.safeAs<KtSymbolBasedConstructorDescriptor>()?.ktSymbol?.psi
when (constructorPSI) {
is KtSecondaryConstructor -> {
val delegationCall = constructorPSI.getDelegationCall()
val ktCallInfo = context.withAnalysisSession { delegationCall.resolveCall() }
val diagnostic = ktCallInfo.safeAs<KtErrorCallInfo>()?.diagnostic
val constructorCall = ktCallInfo.calls.singleOrNull() ?: return null
if (constructorCall !is KtFunctionCall<*>) context.errorHandling(constructorCall::class.toString())
val psiCall = CallMaker.makeCall(null, null, delegationCall)
@Suppress("UNCHECKED_CAST")
return FunctionFe10WrapperResolvedCall(psiCall, constructorCall, diagnostic, context) as ResolvedCall<ConstructorDescriptor>
}
null -> return null
else -> context.implementationPlanned() // todo: Primary Constructor delegated call
}
}
private fun getReferenceTarget(key: KtReferenceExpression): DeclarationDescriptor? {
val ktSymbol = context.withAnalysisSession { key.mainReference.resolveToSymbols().singleOrNull() } ?: return null
return ktSymbol.toDeclarationDescriptor(context)
}
}
| apache-2.0 | 6404c1565b28a5d969a1dbfc28731c7e | 45.610465 | 158 | 0.681427 | 5.629916 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/DirectoryPackagingElementEntityImpl.kt | 2 | 16396 | // 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.storage.bridgeEntities
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.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class DirectoryPackagingElementEntityImpl(val dataSource: DirectoryPackagingElementEntityData) : DirectoryPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
ARTIFACT_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val artifact: ArtifactEntity?
get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this)
override val children: List<PackagingElementEntity>
get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val directoryName: String
get() = dataSource.directoryName
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: DirectoryPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<DirectoryPackagingElementEntity, DirectoryPackagingElementEntityData>(
result), DirectoryPackagingElementEntity.Builder {
constructor() : this(DirectoryPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity DirectoryPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// 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().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
if (!getEntityData().isDirectoryNameInitialized()) {
error("Field DirectoryPackagingElementEntity#directoryName should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as DirectoryPackagingElementEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.directoryName != dataSource.directoryName) this.directoryName = dataSource.directoryName
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<CompositePackagingElementEntity?>().singleOrNull()
if ((parentEntityNew == null && this.parentEntity != null) || (parentEntityNew != null && this.parentEntity == null) || (parentEntityNew != null && this.parentEntity != null && (this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id)) {
this.parentEntity = parentEntityNew
}
val artifactNew = parents.filterIsInstance<ArtifactEntity?>().singleOrNull()
if ((artifactNew == null && this.artifact != null) || (artifactNew != null && this.artifact == null) || (artifactNew != null && this.artifact != null && (this.artifact as WorkspaceEntityBase).id != (artifactNew as WorkspaceEntityBase).id)) {
this.artifact = artifactNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var artifact: ArtifactEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
}
else {
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value
}
changedProperty.add("artifact")
}
override var children: List<PackagingElementEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList()
}
}
set(value) {
// Set list of ref types for abstract entities
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store an abstract entity
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var directoryName: String
get() = getEntityData().directoryName
set(value) {
checkModificationAllowed()
getEntityData(true).directoryName = value
changedProperty.add("directoryName")
}
override fun getEntityClass(): Class<DirectoryPackagingElementEntity> = DirectoryPackagingElementEntity::class.java
}
}
class DirectoryPackagingElementEntityData : WorkspaceEntityData<DirectoryPackagingElementEntity>() {
lateinit var directoryName: String
fun isDirectoryNameInitialized(): Boolean = ::directoryName.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<DirectoryPackagingElementEntity> {
val modifiable = DirectoryPackagingElementEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): DirectoryPackagingElementEntity {
return getCached(snapshot) {
val entity = DirectoryPackagingElementEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return DirectoryPackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return DirectoryPackagingElementEntity(directoryName, entitySource) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
this.artifact = parents.filterIsInstance<ArtifactEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as DirectoryPackagingElementEntityData
if (this.entitySource != other.entitySource) return false
if (this.directoryName != other.directoryName) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as DirectoryPackagingElementEntityData
if (this.directoryName != other.directoryName) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + directoryName.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + directoryName.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | ac2bcd650a2062b6d436fac55c4eb0c8 | 44.292818 | 281 | 0.669554 | 5.808006 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/testSources/com/intellij/openapi/roots/LibraryTableTestCase.kt | 2 | 6965 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.rules.ProjectModelRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
abstract class LibraryTableTestCase {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
protected abstract val libraryTable: LibraryTable
protected abstract fun createLibrary(name: String, setup: (LibraryEx.ModifiableModelEx) -> Unit = {}): LibraryEx
protected open fun createLibrary(name: String, model: LibraryTable.ModifiableModel) = model.createLibrary(name) as LibraryEx
@Test
fun `add remove library`() {
assertThat(libraryTable.libraries).isEmpty()
val library = createLibrary("a")
checkConsistency()
assertThat(libraryTable.libraries).containsExactly(library)
assertThat(library.isDisposed).isFalse()
runWriteActionAndWait { libraryTable.removeLibrary(library) }
checkConsistency()
assertThat(libraryTable.libraries).isEmpty()
assertThat(library.isDisposed).isTrue()
}
@Test
fun `rename library`() {
val library = createLibrary("a")
assertThat(libraryTable.getLibraryByName("a")).isSameAs(library)
projectModel.renameLibrary(library, "b")
assertThat(libraryTable.libraries.single()).isSameAs(library)
assertThat(libraryTable.getLibraryByName("a")).isNull()
assertThat(libraryTable.getLibraryByName("b")).isSameAs(library)
}
@Test
fun listener() {
val events = ArrayList<String>()
libraryTable.addListener(object : LibraryTable.Listener {
override fun afterLibraryAdded(newLibrary: Library) {
events += "added ${newLibrary.name}"
}
override fun afterLibraryRenamed(library: Library, oldName: String?) {
events += "renamed ${library.name}"
}
override fun beforeLibraryRemoved(library: Library) {
events += "before removed ${library.name}"
}
override fun afterLibraryRemoved(library: Library) {
events += "removed ${library.name}"
}
})
val library = createLibrary("a")
assertThat(events).containsExactly("added a")
events.clear()
projectModel.renameLibrary(library, "b")
assertThat(events).containsExactly("renamed b")
events.clear()
runWriteActionAndWait { libraryTable.removeLibrary(library) }
assertThat(events).containsExactly("before removed b", "removed b")
}
@Test
fun `remove library before committing`() {
val library = edit {
val library = createLibrary("a", it)
assertThat(it.isChanged).isTrue()
it.removeLibrary(library)
library
}
assertThat(libraryTable.libraries).isEmpty()
assertThat(library.isDisposed).isTrue()
}
@Test
fun `add library and dispose model`() {
val a = createLibrary("a")
val model = libraryTable.modifiableModel
val b = createLibrary("b", model)
Disposer.dispose(model)
assertThat(libraryTable.libraries).containsExactly(a)
assertThat(b.isDisposed).isTrue()
assertThat(a.isDisposed).isFalse()
}
@Test
fun `rename uncommitted library`() {
val library = edit {
val library = createLibrary("a", it)
val libraryModel = library.modifiableModel
libraryModel.name = "b"
assertThat(it.getLibraryByName("a")).isEqualTo(library)
assertThat(it.getLibraryByName("b")).isNull()
runWriteActionAndWait { libraryModel.commit() }
assertThat(it.getLibraryByName("a")).isNull()
assertThat(it.getLibraryByName("b")).isEqualTo(library)
assertThat(libraryTable.getLibraryByName("b")).isNull()
library
}
assertThat(libraryTable.getLibraryByName("b")).isEqualTo(library)
}
@Test
fun `remove library and dispose model`() {
val a = createLibrary("a")
val model = libraryTable.modifiableModel
model.removeLibrary(a)
Disposer.dispose(model)
assertThat(libraryTable.libraries).containsExactly(a)
assertThat(a.isDisposed).isFalse()
}
@Test
fun `merge add remove changes`() {
val a = createLibrary("a")
val model1 = libraryTable.modifiableModel
model1.removeLibrary(a)
val model2 = libraryTable.modifiableModel
val b = createLibrary("b", model2)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).containsExactly(b)
}
@Test
fun `merge add add changes`() {
val a = createLibrary("a")
val model1 = libraryTable.modifiableModel
val b = createLibrary("b", model1)
val model2 = libraryTable.modifiableModel
val c = createLibrary("c", model2)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).containsExactlyInAnyOrder(a, b, c)
}
@Test
fun `merge remove remove changes`() {
val a = createLibrary("a")
val b = createLibrary("b")
val model1 = libraryTable.modifiableModel
model1.removeLibrary(a)
val model2 = libraryTable.modifiableModel
model2.removeLibrary(b)
runWriteActionAndWait {
model1.commit()
model2.commit()
}
assertThat(libraryTable.libraries).isEmpty()
}
private fun <T> edit(action: (LibraryTable.ModifiableModel) -> T): T{
checkConsistency()
val model = libraryTable.modifiableModel
checkConsistency(model)
val result = action(model)
checkConsistency(model)
runWriteActionAndWait { model.commit() }
checkConsistency()
return result
}
private fun checkConsistency() {
val fromIterator = ArrayList<Library>()
libraryTable.libraryIterator.forEach { fromIterator += it }
assertThat(fromIterator).containsExactly(*libraryTable.libraries)
for (library in libraryTable.libraries) {
assertThat(libraryTable.getLibraryByName(library.name!!)).isEqualTo(library)
assertThat((library as LibraryEx).isDisposed).isFalse()
}
}
private fun checkConsistency(model: LibraryTable.ModifiableModel) {
val fromIterator = ArrayList<Library>()
model.libraryIterator.forEach { fromIterator += it }
assertThat(fromIterator).containsExactly(*model.libraries)
for (library in model.libraries) {
assertThat(model.getLibraryByName(library.name!!)).isEqualTo(library)
assertThat((library as LibraryEx).isDisposed).isFalse()
}
}
} | apache-2.0 | 85ec5eac75d839b0656b924a1e53b744 | 31.551402 | 140 | 0.713568 | 4.71564 | false | true | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/com/onyxdevtools/server/entities/Actor.kt | 1 | 540 | package com.onyxdevtools.server.entities
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.*
import com.onyx.persistence.annotations.values.CascadePolicy
import com.onyx.persistence.annotations.values.RelationshipType
@Entity
class Actor : Person(), IManagedEntity {
@Identifier
var actorId: Int = 0
@Relationship(type = RelationshipType.MANY_TO_ONE, cascadePolicy = CascadePolicy.NONE, inverseClass = Movie::class, inverse = "actors")
@Suppress("unused")
var movie: Movie? = null
}
| agpl-3.0 | bf80ef0a945f4bed6adbe8e71ab0013e | 30.764706 | 139 | 0.772222 | 4.186047 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/ContextCollector.kt | 1 | 9656 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.inference.common
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
abstract class ContextCollector(private val resolutionFacade: ResolutionFacade) {
private fun KotlinType.classReference(): ClassReference? =
when (val descriptor = constructor.declarationDescriptor) {
is ClassDescriptor -> descriptor.classReference
is TypeParameterDescriptor -> TypeParameterReference(descriptor)
else -> null
}
private fun KtTypeElement.toData(): TypeElementData? {
val typeReference = parent as? KtTypeReference ?: return null
val type = analyze(resolutionFacade)[BindingContext.TYPE, typeReference] ?: return null
val typeParameterDescriptor = type.constructor
.declarationDescriptor
?.safeAs<TypeParameterDescriptor>() ?: return TypeElementDataImpl(this, type)
return TypeParameterElementData(this, type, typeParameterDescriptor)
}
fun collectTypeVariables(elements: List<KtElement>): InferenceContext {
val declarationToTypeVariable = mutableMapOf<KtNamedDeclaration, TypeVariable>()
val typeElementToTypeVariable = mutableMapOf<KtTypeElement, TypeVariable>()
val typeBasedTypeVariables = mutableListOf<TypeBasedTypeVariable>()
fun KtTypeReference.toBoundType(
owner: TypeVariableOwner,
alreadyCalculatedType: KotlinType? = null,
defaultState: State? = null
): BoundType? {
val typeElement = typeElement ?: return null
val type = alreadyCalculatedType ?: analyze(resolutionFacade, BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]
val classReference = type?.classReference() ?: NoClassReference
val state = defaultState ?: classReference.getState(typeElement)
val typeArguments =
if (classReference is DescriptorClassReference) {
val typeParameters = classReference.descriptor.declaredTypeParameters
typeElement.typeArgumentsAsTypes.mapIndexed { index, typeArgument ->
TypeParameter(
typeArgument?.toBoundType(
owner,
alreadyCalculatedType = type?.arguments?.getOrNull(index)?.type
) ?: BoundType.STAR_PROJECTION,
typeParameters.getOrNull(index)?.variance ?: Variance.INVARIANT
)
}
} else emptyList()
val typeVariable = TypeElementBasedTypeVariable(
classReference,
typeArguments,
typeElement.toData() ?: return null,
owner,
state
)
typeElementToTypeVariable[typeElement] = typeVariable
return typeVariable.asBoundType()
}
fun KotlinType.toBoundType(): BoundType? {
val classReference = classReference() ?: NoClassReference
val state = classReference.getState(typeElement = null)
val typeArguments =
if (classReference is DescriptorClassReference) {
arguments.zip(classReference.descriptor.declaredTypeParameters) { typeArgument, typeParameter ->
TypeParameter(
typeArgument.type.toBoundType() ?: BoundType.STAR_PROJECTION,
typeParameter.variance
)
}
} else emptyList()
val typeVariable = TypeBasedTypeVariable(
classReference,
typeArguments,
this,
state
)
typeBasedTypeVariables += typeVariable
return typeVariable.asBoundType()
}
val substitutors = mutableMapOf<ClassDescriptor, SuperTypesSubstitutor>()
fun isOrAsExpression(typeReference: KtTypeReference) {
val typeElement = typeReference.typeElement ?: return
val typeVariable = typeReference.toBoundType(OtherTarget)?.typeVariable ?: return
typeElementToTypeVariable[typeElement] = typeVariable
}
for (element in elements) {
element.forEachDescendantOfType<KtExpression> { expression ->
if (expression is KtCallableDeclaration
&& (expression is KtParameter
|| expression is KtProperty
|| expression is KtNamedFunction)
) run {
val typeReference = expression.typeReference ?: return@run
val typeVariable = typeReference.toBoundType(
when (expression) {
is KtParameter -> expression.getStrictParentOfType<KtFunction>()?.let(::FunctionParameter)
is KtFunction -> FunctionReturnType(expression)
is KtProperty -> Property(expression)
else -> null
} ?: OtherTarget
)?.typeVariable ?: return@run
declarationToTypeVariable[expression] = typeVariable
}
if (expression is KtTypeParameterListOwner) {
for (typeParameter in expression.typeParameters) {
typeParameter.extendsBound?.toBoundType(OtherTarget, defaultState = State.UPPER)
}
for (constraint in expression.typeConstraints) {
constraint.boundTypeReference?.toBoundType(OtherTarget, defaultState = State.UPPER)
}
}
when (expression) {
is KtClassOrObject -> {
for (entry in expression.superTypeListEntries) {
for (argument in entry.typeReference?.typeElement?.typeArgumentsAsTypes ?: continue) {
argument?.toBoundType(OtherTarget)
}
}
val descriptor =
expression.resolveToDescriptorIfAny(resolutionFacade) ?: return@forEachDescendantOfType
substitutors[descriptor] =
SuperTypesSubstitutor.createFromKtClass(expression, resolutionFacade) ?: return@forEachDescendantOfType
for (typeParameter in expression.typeParameters) {
val typeVariable = typeParameter.resolveToDescriptorIfAny(resolutionFacade)
?.safeAs<TypeParameterDescriptor>()
?.defaultType
?.toBoundType()
?.typeVariable
?: continue
declarationToTypeVariable[typeParameter] = typeVariable
}
}
is KtCallExpression ->
for (typeArgument in expression.typeArguments) {
typeArgument.typeReference?.toBoundType(TypeArgument)
}
is KtLambdaExpression -> {
val context = expression.analyze(resolutionFacade)
val returnType = expression.getType(context)?.arguments?.lastOrNull()?.type ?: return@forEachDescendantOfType
val typeVariable = returnType.toBoundType()?.typeVariable ?: return@forEachDescendantOfType
declarationToTypeVariable[expression.functionLiteral] = typeVariable
}
is KtBinaryExpressionWithTypeRHS -> {
isOrAsExpression(expression.right ?: return@forEachDescendantOfType)
}
is KtIsExpression -> {
isOrAsExpression(expression.typeReference ?: return@forEachDescendantOfType)
}
}
}
}
val typeVariables =
(typeElementToTypeVariable.values + declarationToTypeVariable.values + typeBasedTypeVariables).distinct()
return InferenceContext(
elements,
typeVariables,
typeElementToTypeVariable,
declarationToTypeVariable,
declarationToTypeVariable.mapNotNull { (key, value) ->
key.resolveToDescriptorIfAny(resolutionFacade)?.let { it to value }
}.toMap(),
substitutors
)
}
abstract fun ClassReference.getState(typeElement: KtTypeElement?): State
} | apache-2.0 | f44abac9e056d6ceb0a73d7998bb1581 | 48.523077 | 158 | 0.591964 | 7.173848 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/logging/KotlinLoggerInitializedWithForeignClassInspection.kt | 2 | 8509 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.logging
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ui.ListTable
import com.intellij.codeInspection.ui.ListWrappingTableModel
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilterBase
import com.intellij.util.xmlb.XmlSerializer
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.ui.UiUtils
import org.jdom.Element
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.JComponent
class KotlinLoggerInitializedWithForeignClassInspection : AbstractKotlinInspection() {
companion object {
private val DEFAULT_LOGGER_FACTORIES = listOf(
"java.util.logging.Logger" to "getLogger",
"org.slf4j.LoggerFactory" to "getLogger",
"org.apache.commons.logging.LogFactory" to "getLog",
"org.apache.log4j.Logger" to "getLogger",
"org.apache.logging.log4j.LogManager" to "getLogger",
)
private val DEFAULT_LOGGER_FACTORY_CLASS_NAMES = DEFAULT_LOGGER_FACTORIES.map { it.first }
private val DEFAULT_LOGGER_FACTORY_METHOD_NAMES = DEFAULT_LOGGER_FACTORIES.map { it.second }
private val DEFAULT_LOGGER_FACTORY_CLASS_NAME = BaseInspection.formatString(DEFAULT_LOGGER_FACTORY_CLASS_NAMES)
private val DEFAULT_LOGGER_FACTORY_METHOD_NAME = BaseInspection.formatString(DEFAULT_LOGGER_FACTORY_METHOD_NAMES)
}
@Suppress("MemberVisibilityCanBePrivate")
var loggerFactoryClassName: String = DEFAULT_LOGGER_FACTORY_CLASS_NAME
@Suppress("MemberVisibilityCanBePrivate")
var loggerFactoryMethodName: String = DEFAULT_LOGGER_FACTORY_METHOD_NAME
private val loggerFactoryClassNames = DEFAULT_LOGGER_FACTORY_CLASS_NAMES.toMutableList()
private val loggerFactoryMethodNames = DEFAULT_LOGGER_FACTORY_METHOD_NAMES.toMutableList()
private val loggerFactoryFqNames
get() = loggerFactoryClassNames.zip(loggerFactoryMethodNames).groupBy(
{ (_, methodName) -> methodName },
{ (className, methodName) -> FqName("${className}.${methodName}") }
)
@Suppress("DialogTitleCapitalization")
override fun createOptionsPanel(): JComponent? {
val table = ListTable(
ListWrappingTableModel(
listOf(loggerFactoryClassNames, loggerFactoryMethodNames),
KotlinBundle.message("title.logger.factory.class.name"),
KotlinBundle.message("title.logger.factory.method.name")
)
)
return UiUtils.createAddRemoveTreeClassChooserPanel(table, KotlinBundle.message("title.choose.logger.factory.class"))
}
override fun readSettings(element: Element) {
super.readSettings(element)
BaseInspection.parseString(loggerFactoryClassName, loggerFactoryClassNames)
BaseInspection.parseString(loggerFactoryMethodName, loggerFactoryMethodNames)
if (loggerFactoryClassNames.isEmpty() || loggerFactoryClassNames.size != loggerFactoryMethodNames.size) {
BaseInspection.parseString(DEFAULT_LOGGER_FACTORY_CLASS_NAME, loggerFactoryClassNames)
BaseInspection.parseString(DEFAULT_LOGGER_FACTORY_METHOD_NAME, loggerFactoryMethodNames)
}
}
override fun writeSettings(element: Element) {
loggerFactoryClassName = BaseInspection.formatString(loggerFactoryClassNames)
loggerFactoryMethodName = BaseInspection.formatString(loggerFactoryMethodNames)
XmlSerializer.serializeInto(this, element, object : SerializationFilterBase() {
override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean {
if (accessor.name == "loggerFactoryClassName" && beanValue == DEFAULT_LOGGER_FACTORY_CLASS_NAME) return false
if (accessor.name == "loggerFactoryMethodName" && beanValue == DEFAULT_LOGGER_FACTORY_METHOD_NAME) return false
return true
}
})
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val containingClassNames = call.containingClassNames()
if (containingClassNames.isEmpty()) return
val callee = call.calleeExpression ?: return
val loggerMethodFqNames = loggerFactoryFqNames[callee.text] ?: return
val argument = call.valueArguments.singleOrNull()?.getArgumentExpression() as? KtDotQualifiedExpression ?: return
val argumentSelector = argument.selectorExpression ?: return
val classLiteral = when (val argumentReceiver = argument.receiverExpression) {
// Foo::class.java, Foo::class.qualifiedName, Foo::class.simpleName
is KtClassLiteralExpression -> {
val selectorText = argumentSelector.safeAs<KtNameReferenceExpression>()?.text
if (selectorText !in listOf("java", "qualifiedName", "simpleName")) return
argumentReceiver
}
// Foo::class.java.name, Foo::class.java.simpleName, Foo::class.java.canonicalName
is KtDotQualifiedExpression -> {
val classLiteral = argumentReceiver.receiverExpression as? KtClassLiteralExpression ?: return
if (argumentReceiver.selectorExpression.safeAs<KtNameReferenceExpression>()?.text != "java") return
val selectorText = argumentSelector.safeAs<KtNameReferenceExpression>()?.text
?: argumentSelector.safeAs<KtCallExpression>()?.calleeExpression?.text
if (selectorText !in listOf("name", "simpleName", "canonicalName", "getName", "getSimpleName", "getCanonicalName")) return
classLiteral
}
else -> return
}
val classLiteralName = classLiteral.receiverExpression?.text ?: return
if (classLiteralName in containingClassNames) return
if (call.resolveToCall()?.resultingDescriptor?.fqNameOrNull() !in loggerMethodFqNames) return
holder.registerProblem(
classLiteral,
KotlinBundle.message("logger.initialized.with.foreign.class", "$classLiteralName::class"),
ReplaceForeignFix(containingClassNames.last())
)
})
private fun KtCallExpression.containingClassNames(): List<String> {
val classOrObject = getStrictParentOfType<KtClassOrObject>() ?: return emptyList()
return if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) {
listOfNotNull(classOrObject.name, classOrObject.getStrictParentOfType<KtClass>()?.name)
} else {
listOfNotNull(classOrObject.name)
}
}
private class ReplaceForeignFix(private val containingClassName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.0", "$containingClassName::class")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val argument = descriptor.psiElement.getStrictParentOfType<KtValueArgument>()?.getArgumentExpression()
as? KtDotQualifiedExpression ?: return
val receiver = argument.receiverExpression
val selector = argument.selectorExpression ?: return
val psiFactory = KtPsiFactory(argument)
val newArgument = when (receiver) {
is KtClassLiteralExpression -> {
psiFactory.createExpressionByPattern("${containingClassName}::class.$0", selector)
}
is KtDotQualifiedExpression -> {
psiFactory.createExpressionByPattern("${containingClassName}::class.java.$0", selector)
}
else -> return
}
argument.replace(newArgument)
}
}
}
| apache-2.0 | 846981d63eed468a123c35807432afa2 | 51.850932 | 158 | 0.706076 | 5.464997 | false | false | false | false |
jguerinet/Suitcase | room/src/main/java/AppUpdate.kt | 2 | 1639 | /*
* Copyright 2016-2021 Julien Guerinet
*
* 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.guerinet.room
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
/**
* Logs a date/time the app was updates
* @author Julien Guerinet
* @since 4.4.0
*
* @param version App version that the user has updated to
* @param timestamp Date/time that the user has updated to this version, defaults to now
* @param id Auto-generated Id
*/
@Entity
data class AppUpdate(
val version: String,
val timestamp: Instant = Clock.System.now(),
@PrimaryKey(autoGenerate = true) val id: Int = 0
) {
companion object {
/**
* Saves an [AppUpdate] with the [name] and [code] to the Db using the [updateDao]
*/
fun log(updateDao: UpdateDao, name: String, code: Int) =
updateDao.insert(AppUpdate(getVersion(name, code)))
/**
* Returns the version String to use for the app [name] and [code]
*/
fun getVersion(name: String, code: Int): String = "$name ($code)"
}
}
| apache-2.0 | 360fb4b0a2163d8ccfbaa836d688720b | 30.519231 | 90 | 0.685784 | 4.027027 | false | false | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/certificates/v1/ClassBuilders.kt | 1 | 1806 | // GENERATE
package com.fkorotkov.kubernetes.certificates.v1
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequest as v1_CertificateSigningRequest
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestCondition as v1_CertificateSigningRequestCondition
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestList as v1_CertificateSigningRequestList
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestSpec as v1_CertificateSigningRequestSpec
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestStatus as v1_CertificateSigningRequestStatus
fun newCertificateSigningRequest(block : v1_CertificateSigningRequest.() -> Unit = {}): v1_CertificateSigningRequest {
val instance = v1_CertificateSigningRequest()
instance.block()
return instance
}
fun newCertificateSigningRequestCondition(block : v1_CertificateSigningRequestCondition.() -> Unit = {}): v1_CertificateSigningRequestCondition {
val instance = v1_CertificateSigningRequestCondition()
instance.block()
return instance
}
fun newCertificateSigningRequestList(block : v1_CertificateSigningRequestList.() -> Unit = {}): v1_CertificateSigningRequestList {
val instance = v1_CertificateSigningRequestList()
instance.block()
return instance
}
fun newCertificateSigningRequestSpec(block : v1_CertificateSigningRequestSpec.() -> Unit = {}): v1_CertificateSigningRequestSpec {
val instance = v1_CertificateSigningRequestSpec()
instance.block()
return instance
}
fun newCertificateSigningRequestStatus(block : v1_CertificateSigningRequestStatus.() -> Unit = {}): v1_CertificateSigningRequestStatus {
val instance = v1_CertificateSigningRequestStatus()
instance.block()
return instance
}
| mit | 505e12f16d4a52b1cdd9af96482ada02 | 40.045455 | 145 | 0.824474 | 5.296188 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/ImageDetail/PetalImageDetailActivity.kt | 1 | 16517 | package stan.androiddemo.project.petal.Module.ImageDetail
import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.os.Environment
import android.support.design.widget.FloatingActionButton
import android.support.graphics.drawable.AnimatedVectorDrawableCompat
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.imagepipeline.image.ImageInfo
import kotlinx.android.synthetic.main.activity_petal_image_detail.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.project.petal.API.OperateAPI
import stan.androiddemo.project.petal.Base.BasePetalActivity
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnDialogInteractionListener
import stan.androiddemo.project.petal.Event.OnImageDetailFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.project.petal.Module.BoardDetail.BoardDetailActivity
import stan.androiddemo.project.petal.Module.UserInfo.PetalUserInfoActivity
import stan.androiddemo.project.petal.Observable.AnimatorOnSubscribe
import stan.androiddemo.project.petal.Widget.GatherDialogFragment
import stan.androiddemo.tool.AnimatorUtils
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
import stan.androiddemo.tool.Logger
import stan.androiddemo.tool.SPUtils
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
class PetalImageDetailActivity : BasePetalActivity(), OnDialogInteractionListener,OnImageDetailFragmentInteractionListener {
private val KEYPARCELABLE = "Parcelable"
private var mActionFrom: Int = 0
lateinit var mPinsBean:PinsMainInfo
lateinit var mImageUrl: String//图片地址
lateinit var mImageType: String//图片类型
lateinit var mPinsId: String
private var isLike = false//该图片是否被喜欢操作 默认false 没有被操作过
private var isGathered = false//该图片是否被采集过
var arrBoardId:List<String>? = null
lateinit var mDrawableCancel: Drawable
lateinit var mDrawableRefresh: Drawable
override fun getTag(): String {return this.toString() }
companion object {
val ACTION_KEY = "key"//key值
val ACTION_DEFAULT = -1//默认值
val ACTION_THIS = 0//来自自己的跳转
val ACTION_MAIN = 1//来自主界面的跳转
val ACTION_MODULE = 2//来自模块界面的跳转
val ACTION_BOARD = 3//来自画板界面的跳转
val ACTION_ATTENTION = 4//来自我的关注界面的跳转
val ACTION_SEARCH = 5//来自搜索界面的跳转
fun launch(activity:Activity){
val intent = Intent(activity,PetalImageDetailActivity::class.java)
activity.startActivity(intent)
}
fun launch(activity: Activity,action:Int){
val intent = Intent(activity,PetalImageDetailActivity::class.java)
intent.putExtra("action",action)
activity.startActivity(intent)
}
}
override fun getLayoutId(): Int {
return R.layout.activity_petal_image_detail
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//注册eventbus
setSupportActionBar(toolbar)
title = ""
toolbar.setNavigationOnClickListener { onBackPressed() }
EventBus.getDefault().register(this)
mActionFrom = intent.getIntExtra("action",ACTION_DEFAULT)
recoverData(savedInstanceState)
mDrawableCancel = CompatUtils.getTintDrawable(mContext,R.drawable.ic_cancel_black_24dp,Color.GRAY)
mDrawableRefresh = CompatUtils.getTintDrawable(mContext,R.drawable.ic_refresh_black_24dp,Color.GRAY)
mImageUrl = mPinsBean.file!!.key!!
mImageType = mPinsBean.file!!.type!!
mPinsId = mPinsBean.pin_id.toString()
isLike = mPinsBean.liked
img_image_detail_bg.aspectRatio = mPinsBean.imgRatio
supportFragmentManager.beginTransaction().replace(R.id.frame_layout_petal_with_refresh,
PetalImageDetailFragment.newInstance(mPinsId)).commit()
addSubscription(getGatherInfo())
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putParcelable(KEYPARCELABLE,mPinsBean)
}
fun recoverData(savedInstanceState:Bundle?){
if (savedInstanceState != null){
if (savedInstanceState!!.getParcelable<PinsMainInfo>(KEYPARCELABLE)!=null){
mPinsBean = savedInstanceState!!.getParcelable<PinsMainInfo>(KEYPARCELABLE)
}
}
}
override fun initResAndListener() {
super.initResAndListener()
fab_image_detail.setImageResource(R.drawable.ic_camera_white_24dp)
fab_image_detail.setOnClickListener {
showGatherDialog()
}
}
@Subscribe(sticky = true)
fun onEventReceiveBean(bean: PinsMainInfo) {
//接受EvenBus传过来的数据
Logger.d(TAG + " receive bean")
this.mPinsBean = bean
}
override fun onResume() {
super.onResume()
showImage()
}
fun showImage(){
var objectAnimator: ObjectAnimator? = null
if (mImageType.toLowerCase().contains("fig")){
objectAnimator = AnimatorUtils.getRotationFS(fab_image_detail)
objectAnimator?.start()
}
val url = String.format(mFormatImageUrlBig,mImageUrl)
val url_low = String.format(mFormatImageGeneral,mImageUrl)
ImageLoadBuilder.Start(mContext,img_image_detail_bg,url).setUrlLow(url_low)
.setRetryImage(mDrawableRefresh)
.setFailureImage(mDrawableCancel)
.setControllerListener(object:BaseControllerListener<ImageInfo>(){
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
Logger.d("onFinalImageSet"+Thread.currentThread().toString())
if (animatable != null){
animatable.start()
}
if (objectAnimator!= null && objectAnimator!!.isRunning){
img_image_detail_bg.postDelayed(Runnable {
objectAnimator?.cancel()
},600)
}
}
override fun onSubmit(id: String?, callerContext: Any?) {
super.onSubmit(id, callerContext)
Logger.d("onSubmit"+Thread.currentThread().toString())
}
override fun onFailure(id: String?, throwable: Throwable?) {
super.onFailure(id, throwable)
Logger.d(throwable.toString())
}
}).build()
}
override fun onClickPinsItemImage(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalImageDetailActivity,PetalImageDetailActivity.ACTION_THIS)
}
override fun onClickPinsItemText(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalImageDetailActivity,PetalImageDetailActivity.ACTION_THIS)
}
override fun onClickBoardField(key: String, title: String) {
BoardDetailActivity.launch(this, key, title)
}
override fun onClickUserField(key: String, title: String) {
PetalUserInfoActivity.launch(this, key, title)
}
override fun onClickImageLink(link: String) {
val uri = Uri.parse(link)
val int = Intent(Intent.ACTION_VIEW,uri)
if (int.resolveActivity([email protected]) != null){
startActivity(int)
}
else{
Logger.d("checkResolveIntent = null")
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.petal_image_detail_menu,menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
setMenuIconLikeDynamic(menu?.findItem(R.id.action_like),isLike)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId){
android.R.id.home->{
//这里原代码有一个逻辑要处理
}
R.id.action_like->{
actionLike(item)
}
R.id.action_download->{
downloadItem()
}
R.id.action_gather->{
showGatherDialog()
}
}
return true
}
fun setMenuIconLikeDynamic(item:MenuItem?,like:Boolean){
val drawableCompat = if (like) AnimatedVectorDrawableCompat.create(mContext
,R.drawable.drawable_animation_petal_favorite_undo) else AnimatedVectorDrawableCompat.create(mContext
,R.drawable.drawable_animation_petal_favorite_do)
item?.icon = drawableCompat
}
fun downloadItem(){
if (ContextCompat.checkSelfPermission(this@PetalImageDetailActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this@PetalImageDetailActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1)
return
}
object: AsyncTask<String, Int, File?>(){
override fun doInBackground(vararg p0: String?): File? {
var file: File? = null
try {
val url = String.format(mFormatImageUrlBig,mImageUrl)
val future = Glide.with(this@PetalImageDetailActivity).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
file = future.get()
val pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile
val fileDir = File(pictureFolder,"Petal")
if (!fileDir.exists()){
fileDir.mkdir()
}
val fileName = System.currentTimeMillis().toString() + ".jpg"
val destFile = File(fileDir,fileName)
file.copyTo(destFile)
sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(File(destFile.path))))
}
catch (e:Exception){
e.printStackTrace()
}
return file
}
override fun onPreExecute() {
Toast.makeText(this@PetalImageDetailActivity,"保存图片成功", Toast.LENGTH_LONG).show()
}
}.execute()
}
fun actionLike(menu: MenuItem){
if (!isLogin){
toast("请先登录再操作")
return
}
val operation = if (isLike) Config.OPERATEUNLIKE else Config.OPERATELIKE
RetrofitClient.createService(OperateAPI::class.java).httpsLikeOperate(mAuthorization,mPinsId,operation)
.subscribeOn(Schedulers.io())
.delay(600, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object:Subscriber<LikePinsOperateBean>(){
override fun onStart() {
super.onStart()
menu.isEnabled = false
(menu.icon as AnimatedVectorDrawableCompat)?.start()
}
override fun onCompleted() {
menu.isEnabled = true
}
override fun onNext(t: LikePinsOperateBean?) {
isLike = !isLike
setMenuIconLikeDynamic(menu,isLike)
}
override fun onError(e: Throwable?) {
menu.isEnabled = true
checkException(e!!,appBarLayout_image_detail)
}
})
}
fun showGatherDialog(){
if (!isLogin){
toast("请先登录再操作")
return
}
val arrayBoardTitle = SPUtils.get(mContext,Config.BOARDTILTARRAY,"") as String
val boardId = SPUtils.get(mContext,Config.BOARDIDARRAY,"") as String
val arr = arrayBoardTitle?.split(",")
arrBoardId = boardId?.split(",")
val fragment = GatherDialogFragment.create(mAuthorization,mPinsId,mPinsBean.raw_text!!, ArrayList(arr))
fragment.show(supportFragmentManager,null)
}
fun getGatherInfo(): Subscription {
return RetrofitClient.createService(OperateAPI::class.java).httpsGatherInfo(mAuthorization,mPinsId,true)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object:Subscriber<GatherInfoBean>(){
override fun onNext(t: GatherInfoBean?) {
if (t?.exist_pin != null){
setFabDrawableAnimator(R.drawable.ic_done_white_24dp,fab_image_detail)
isGathered = !isGathered
}
}
override fun onError(e: Throwable?) {
}
override fun onCompleted() {
}
})
}
override fun onDialogClick(option: Boolean, info: HashMap<String, Any>) {
if (option){
val desc = info["describe"] as String
val position = info["position"] as Int
val animation = AnimatorUtils.getRotationAD(fab_image_detail)
Observable.create(AnimatorOnSubscribe(animation)).observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.flatMap {
RetrofitClient.createService(OperateAPI::class.java).httpsGatherPins(mAuthorization,arrBoardId!![position],desc,mPinsId)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object :Subscriber<GatherResultBean>(){
override fun onNext(t: GatherResultBean?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onError(e: Throwable?) {
checkException(e!!,appBarLayout_image_detail)
setFabDrawableAnimator(R.drawable.ic_done_white_24dp,fab_image_detail)
}
override fun onCompleted() {
setFabDrawableAnimator(R.drawable.ic_report_white_24dp,fab_image_detail)
isGathered = !isGathered
}
})
}
}
fun setFabDrawableAnimator(resId:Int,mFabActionBtn:FloatingActionButton){
mFabActionBtn.hide(object:FloatingActionButton.OnVisibilityChangedListener(){
override fun onHidden(fab: FloatingActionButton?) {
super.onHidden(fab)
fab?.setImageResource(resId)
fab?.show()
}
})
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
}
| mit | d43cc99cc3eb76ea7d71d0c7dae2edb3 | 37.591449 | 144 | 0.623561 | 5.083542 | false | false | false | false |
filipproch/reactor-android | library/src/test/java/cz/filipproch/reactor/ui/ReactorViewHelperTest.kt | 1 | 3528 | package cz.filipproch.reactor.ui
import cz.filipproch.reactor.base.view.ReactorUiEvent
import cz.filipproch.reactor.ui.events.TestEvent
import cz.filipproch.reactor.util.FakeReactorView
import cz.filipproch.reactor.util.TestTranslator
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
/**
* @author Filip Prochazka (@filipproch)
*/
class ReactorViewHelperTest {
private var reactorView: FakeReactorView? = null
private var viewHelper: ReactorViewHelper<TestTranslator>? = null
@Before
fun prepareViewHelper() {
reactorView = FakeReactorView()
viewHelper = ReactorViewHelper(checkNotNull(reactorView))
}
@Test
fun onReadyToRegisterEmittersTest() {
assertThat(reactorView?.onEmittersInitCalled).isFalse()
viewHelper?.onReadyToRegisterEmitters()
assertThat(reactorView?.onEmittersInitCalled).isTrue()
}
@Test
fun registerEmitterTest() {
var emitterSubscribed = false
val emitter = Observable.create<ReactorUiEvent> {
emitterSubscribed = true
it.onComplete()
}
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
assertThat(emitterSubscribed).isTrue()
}
@Test(expected = ReactorViewHelper.IllegalLifecycleOperation::class)
fun registerEmitterAtInvalidTimeTest() {
val emitter = Observable.create<ReactorUiEvent> {
it.onComplete()
}
viewHelper?.registerEmitter(emitter)
}
@Test
fun translatorUnbindViewCalledInOnViewNotUsable() {
// prepare for the test
val emitter = PublishSubject.create<ReactorUiEvent>()
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
val translator = TestTranslator()
translator.onCreated()
viewHelper?.bindTranslatorWithView(translator)
// the test
// emit an event
emitter.onNext(TestEvent)
// it should arrive, alone
assertThat(translator.receivedEvents).hasSize(1)
// clear all received events
translator.receivedEvents.clear()
viewHelper?.onViewNotUsable()
// emit an event
emitter.onNext(TestEvent)
assertThat(translator.receivedEvents).hasSize(0)
// rebind view
viewHelper?.bindTranslatorWithView(translator)
// emit an event
emitter.onNext(TestEvent)
// single event should arrive
assertThat(translator.receivedEvents).hasSize(2)
}
@Test
fun eventsAreDeliveredToTranslatorAfterUnbindAndRebind() {
// prepare for the test
val emitter = PublishSubject.create<ReactorUiEvent>()
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
val translator = TestTranslator()
translator.onCreated()
viewHelper?.bindTranslatorWithView(translator)
// the test
viewHelper?.onViewNotUsable()
// emit an event
emitter.onNext(TestEvent)
viewHelper?.bindTranslatorWithView(translator)
// single event should arrive
assertThat(translator.receivedEvents).hasSize(1)
}
} | mit | 39ac05a567543d41714e266501c15f35 | 25.938931 | 72 | 0.678288 | 5.419355 | false | true | false | false |
atlarge-research/opendc-simulator | opendc-model-odc/sc18/src/main/kotlin/com/atlarge/opendc/model/odc/platform/Sc18ExperimentManager.kt | 1 | 5493 | /*
* MIT License
*
* Copyright (c) 2018 atlarge-research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.atlarge.opendc.model.odc.platform
import com.atlarge.opendc.model.odc.integration.csv.Sc18CsvWriter
import com.atlarge.opendc.model.odc.integration.jpa.converter.SchedulerConverter
import com.atlarge.opendc.model.odc.integration.jpa.schema.Experiment
import com.atlarge.opendc.model.odc.integration.jpa.schema.ExperimentState
import com.atlarge.opendc.model.odc.integration.jpa.schema.Path
import com.atlarge.opendc.model.odc.integration.jpa.schema.Simulation
import com.atlarge.opendc.model.odc.integration.jpa.schema.Trace
import java.io.Closeable
import java.time.LocalDateTime
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import kotlin.coroutines.experimental.buildSequence
/**
* This class manages the experiments that are run for the SC18 paper: A Reference Architecture for Datacenter
* Scheduling.
*
* The amount experiments generated is based on the schedulers to test, the amount of repeats per scheduler and the
* amount of warm-up passes.
*
* @property factory The [EntityManagerFactory] in which the data of the experiments is stored.
* @property schedulers The schedulers to simulate.
* @property writer The csv writer to use.
* @property trace The trace to use represented by its identifier.
* @property path The path to use represented by its identifier.
* @property repeat The amount of times to repeat a simulation for a scheduler.
* @property warmUp The amount of warm up passes.
*/
class Sc18ExperimentManager(
private val factory: EntityManagerFactory,
private val writer: Sc18CsvWriter,
private val schedulers: List<String>,
private val trace: Int,
private val path: Int,
private val repeat: Int,
private val warmUp: Int
) : Closeable {
/**
* The internal entity manager for persisting the experiments.
*/
private val manager: EntityManager = factory.createEntityManager()
/**
* The [SchedulerConverter] to use.
*/
private val schedulerConverter = SchedulerConverter()
/**
* A [Sequence] consisting of the generated experiments.
*/
val experiments: Sequence<Sc18Experiment> = buildSequence {
for (scheduler in schedulers) {
val range = 0 until repeat + warmUp
yieldAll(range.map { buildExperiment(scheduler, it) })
}
}
/**
* Build an [Sc18Experiment] for the given scheduler identified by string.
*
* @param schedulerName The scheduler to create an experiment for.
* @param i The index of the experiment.
*/
private fun buildExperiment(schedulerName: String, i: Int): Sc18Experiment {
val isWarmUp = i < warmUp
val name = if (isWarmUp) "WARM-UP" else "EXPERIMENT"
val scheduler = schedulerConverter.convertToEntityAttribute(schedulerName)
val internalManager = factory.createEntityManager()
val simulation = Simulation(null, "Simulation", LocalDateTime.now(), LocalDateTime.now())
val experiment = Experiment(null, name, scheduler, simulation, loadTrace(internalManager), loadPath(internalManager)).apply {
state = ExperimentState.CLAIMED
}
manager.transaction.begin()
manager.persist(simulation)
manager.persist(experiment)
manager.transaction.commit()
return Sc18Experiment(internalManager, writer, experiment, isWarmUp)
}
/**
* Load the [Trace] from the database.
*/
private fun loadTrace(entityManager: EntityManager): Trace = entityManager
.createQuery("SELECT t FROM com.atlarge.opendc.model.odc.integration.jpa.schema.Trace t WHERE t.id = :id", Trace::class.java)
.setParameter("id", trace)
.singleResult
/**
* Load the [Path] from the database.
*/
private fun loadPath(entityManager: EntityManager): Path = entityManager
.createQuery("SELECT p FROM com.atlarge.opendc.model.odc.integration.jpa.schema.Path p WHERE p.id = :id", Path::class.java)
.setParameter("id", path)
.singleResult
/**
* Close this resource, relinquishing any underlying resources.
* This method is invoked automatically on objects managed by the
* `try`-with-resources statement.*
*
* @throws Exception if this resource cannot be closed
*/
override fun close() = manager.close()
}
| mit | 5d39b31f55bf69776821bc6375122856 | 40.300752 | 133 | 0.724194 | 4.473127 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/processor/PojoMethodProcessor.kt | 1 | 1382 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.vo.PojoMethod
import com.google.auto.common.MoreTypes
import javax.lang.model.element.ExecutableElement
import javax.lang.model.type.DeclaredType
/**
* processes an executable element as member of the owning class
*/
class PojoMethodProcessor(
private val context: Context,
private val element: ExecutableElement,
private val owner: DeclaredType) {
fun process(): PojoMethod {
val asMember = context.processingEnv.typeUtils.asMemberOf(owner, element)
val name = element.simpleName.toString()
return PojoMethod(
element = element,
resolvedType = MoreTypes.asExecutable(asMember),
name = name
)
}
} | apache-2.0 | b17f4562330b0571f93223f4cd81a1d2 | 33.575 | 81 | 0.710564 | 4.531148 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/settings/nodeselector/NodeSelectorController.kt | 1 | 7011 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 11/14/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.settings.nodeselector
import android.app.AlertDialog
import android.content.Context
import android.graphics.Typeface
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.breadwallet.R
import com.breadwallet.databinding.ControllerNodeSelectorBinding
import com.breadwallet.mobius.CompositeEffectHandler
import com.breadwallet.tools.util.TrustedNode
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.settings.nodeselector.NodeSelector.E
import com.breadwallet.ui.settings.nodeselector.NodeSelector.F
import com.breadwallet.ui.settings.nodeselector.NodeSelector.M
import com.spotify.mobius.Connectable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.launch
import org.kodein.di.direct
import org.kodein.di.erased.instance
private const val DIALOG_TITLE_PADDING = 16
private const val DIALOG_TITLE_TEXT_SIZE = 18f
private const val DIALOG_INPUT_PADDING = 24
private const val SHOW_KEYBOARD_DELAY = 200L
private const val RESTORE_DIALOG_TITLE_DELAY = 1_000L
class NodeSelectorController : BaseMobiusController<M, E, F>() {
override val defaultModel = M.createDefault()
override val update = NodeSelectorUpdate
override val init = NodeSelectorInit
override val effectHandler = CompositeEffectHandler.from<F, E>(
Connectable { output ->
NodeSelectorHandler(output, direct.instance())
})
private val binding by viewBinding(ControllerNodeSelectorBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return merge(
binding.buttonSwitch.clicks().map { E.OnSwitchButtonClicked }
)
}
override fun M.render() {
val res = checkNotNull(resources)
with(binding) {
ifChanged(M::mode) {
buttonSwitch.text = when (mode) {
NodeSelector.Mode.AUTOMATIC -> res.getString(R.string.NodeSelector_manualButton)
NodeSelector.Mode.MANUAL -> res.getString(R.string.NodeSelector_automaticButton)
else -> ""
}
}
ifChanged(M::currentNode) {
nodeText.text = if (currentNode.isNotBlank()) {
currentNode
} else {
res.getString(R.string.NodeSelector_automatic)
}
}
ifChanged(M::connected) {
nodeStatus.text = if (connected) {
res.getString(R.string.NodeSelector_connected)
} else {
res.getString(R.string.NodeSelector_notConnected)
}
}
}
}
override fun handleViewEffect(effect: ViewEffect) {
when (effect) {
F.ShowNodeDialog -> showNodeDialog()
}
}
private fun showNodeDialog() {
val res = checkNotNull(resources)
val alertDialog = AlertDialog.Builder(activity)
val customTitle = TextView(activity)
customTitle.gravity = Gravity.CENTER
customTitle.textAlignment = View.TEXT_ALIGNMENT_CENTER
val pad16 = Utils.getPixelsFromDps(activity, DIALOG_TITLE_PADDING)
customTitle.setPadding(pad16, pad16, pad16, pad16)
customTitle.text = res.getString(R.string.NodeSelector_enterTitle)
customTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, DIALOG_TITLE_TEXT_SIZE)
customTitle.setTypeface(null, Typeface.BOLD)
alertDialog.setCustomTitle(customTitle)
alertDialog.setMessage(res.getString(R.string.NodeSelector_enterBody))
val input = EditText(activity)
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
val padding = Utils.getPixelsFromDps(activity, DIALOG_INPUT_PADDING)
input.setPadding(padding, 0, padding, padding)
input.layoutParams = lp
alertDialog.setView(input)
alertDialog.setNegativeButton(
res.getString(R.string.Button_cancel)
) { dialog, _ -> dialog.cancel() }
alertDialog.setPositiveButton(
res.getString(R.string.Button_ok)
) { _, _ ->
// this implementation will be overridden
}
val dialog = alertDialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val node = input.text.toString()
if (TrustedNode.isValid(node)) {
eventConsumer.accept(E.SetCustomNode(node))
dialog.dismiss()
} else {
viewAttachScope.launch(Dispatchers.Main) {
customTitle.setText(R.string.NodeSelector_invalid)
customTitle.setTextColor(res.getColor(R.color.warning_color))
delay(RESTORE_DIALOG_TITLE_DELAY)
customTitle.setText(R.string.NodeSelector_enterTitle)
customTitle.setTextColor(res.getColor(R.color.almost_black))
}
}
}
viewAttachScope.launch(Dispatchers.Main) {
delay(SHOW_KEYBOARD_DELAY)
input.requestFocus()
val keyboard =
activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
keyboard.showSoftInput(input, 0)
}
}
}
| mit | 6eae7e4de382f5747cbc9e0c2c124a2f | 38.38764 | 100 | 0.679932 | 4.689632 | false | false | false | false |
sw926/ImageFileSelector | library/src/main/java/com/sw926/imagefileselector/ImageFileSelector.kt | 1 | 3144 | @file:JvmName("ImageFileSelector")
package com.sw926.imagefileselector
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import java.lang.ref.WeakReference
class ImageFileSelector {
private var resultListener: ImageFileResultListener? = null
private val mImagePickHelper: ImagePickHelper
private val mImageCaptureHelper: ImageCaptureHelper
private var compressParams: CompressParams
private val context: WeakReference<Context>
constructor(activity: AppCompatActivity) {
mImageCaptureHelper = ImageCaptureHelper(activity)
mImagePickHelper = ImagePickHelper(activity)
compressParams = CompressParams()
context = WeakReference(activity)
init()
}
constructor(fragment: Fragment) {
mImageCaptureHelper = ImageCaptureHelper(fragment)
mImagePickHelper = ImagePickHelper(fragment)
compressParams = CompressParams()
context = WeakReference(fragment.context)
init()
}
private fun init() {
val listener = object : ImageUriResultListener {
override fun onSuccess(uri: Uri) {
val context = [email protected]()
if (context == null) {
resultListener?.onError()
return
}
ImageUtils.compress(context, uri, compressParams) {
if (it != null) {
resultListener?.onSuccess(it)
} else {
resultListener?.onError()
}
}
}
override fun onCancel() {
}
override fun onError() {
}
}
mImagePickHelper.setListener(listener)
mImageCaptureHelper.setListener(listener)
}
@Suppress("unused")
fun setSelectFileType(type: String) {
mImagePickHelper.setType(type)
}
/**
* 设置压缩后的文件大小
*
* @param maxWidth 压缩后文件宽度
* *
* @param maxHeight 压缩后文件高度
*/
fun setOutPutImageSize(maxWidth: Int, maxHeight: Int) {
compressParams = compressParams.copy(maxWidth = maxWidth, maxHeight = maxHeight)
}
/**
* 设置压缩后保存图片的质量
*
* @param quality 图片质量 0 - 100
*/
@Suppress("unused")
fun setQuality(quality: Int) {
compressParams = compressParams.copy(saveQuality = quality)
}
/**
* set image compress format
*
* @param compressFormat compress format
*/
@Suppress("unused")
fun setCompressFormat(compressFormat: Bitmap.CompressFormat) {
compressParams = compressParams.copy(compressFormat = compressFormat)
}
fun setListener(listenerUri: ImageFileResultListener?) {
resultListener = listenerUri
}
fun selectImage() {
mImagePickHelper.pickImage()
}
fun takePhoto() {
mImageCaptureHelper.takePicture()
}
}
| apache-2.0 | a96ad4459bc259d34983095104522541 | 24.966102 | 88 | 0.617167 | 5.184433 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/processor/FieldProcessor.kt | 1 | 5335 | /*
* Copyright (C) 2016 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.processor
import androidx.room.ColumnInfo
import androidx.room.ext.getAsBoolean
import androidx.room.ext.getAsInt
import androidx.room.ext.getAsString
import androidx.room.parser.Collate
import androidx.room.parser.SQLTypeAffinity
import androidx.room.vo.EmbeddedField
import androidx.room.vo.Field
import com.google.auto.common.AnnotationMirrors
import com.google.auto.common.MoreElements
import com.squareup.javapoet.TypeName
import javax.lang.model.element.Element
import javax.lang.model.type.DeclaredType
class FieldProcessor(baseContext: Context, val containing: DeclaredType, val element: Element,
val bindingScope: BindingScope,
// pass only if this is processed as a child of Embedded field
val fieldParent: EmbeddedField?) {
val context = baseContext.fork(element)
fun process(): Field {
val member = context.processingEnv.typeUtils.asMemberOf(containing, element)
val type = TypeName.get(member)
val columnInfoAnnotation = MoreElements.getAnnotationMirror(element,
ColumnInfo::class.java)
val name = element.simpleName.toString()
val columnName: String
val affinity: SQLTypeAffinity?
val collate: Collate?
val fieldPrefix = fieldParent?.prefix ?: ""
val indexed: Boolean
if (columnInfoAnnotation.isPresent) {
val nameInAnnotation = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "name")
.getAsString(ColumnInfo.INHERIT_FIELD_NAME)
columnName = fieldPrefix + if (nameInAnnotation == ColumnInfo.INHERIT_FIELD_NAME) {
name
} else {
nameInAnnotation
}
affinity = try {
val userDefinedAffinity = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "typeAffinity")
.getAsInt(ColumnInfo.UNDEFINED)!!
SQLTypeAffinity.fromAnnotationValue(userDefinedAffinity)
} catch (ex: NumberFormatException) {
null
}
collate = Collate.fromAnnotationValue(AnnotationMirrors.getAnnotationValue(
columnInfoAnnotation.get(), "collate").getAsInt(ColumnInfo.UNSPECIFIED)!!)
indexed = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "index")
.getAsBoolean(false)
} else {
columnName = fieldPrefix + name
affinity = null
collate = null
indexed = false
}
context.checker.notBlank(columnName, element,
ProcessorErrors.COLUMN_NAME_CANNOT_BE_EMPTY)
context.checker.notUnbound(type, element,
ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS)
val field = Field(name = name,
type = member,
element = element,
columnName = columnName,
affinity = affinity,
collate = collate,
parent = fieldParent,
indexed = indexed)
when (bindingScope) {
BindingScope.TWO_WAY -> {
val adapter = context.typeAdapterStore.findColumnTypeAdapter(field.type,
field.affinity)
field.statementBinder = adapter
field.cursorValueReader = adapter
field.affinity = adapter?.typeAffinity ?: field.affinity
context.checker.check(adapter != null, field.element,
ProcessorErrors.CANNOT_FIND_COLUMN_TYPE_ADAPTER)
}
BindingScope.BIND_TO_STMT -> {
field.statementBinder = context.typeAdapterStore
.findStatementValueBinder(field.type, field.affinity)
context.checker.check(field.statementBinder != null, field.element,
ProcessorErrors.CANNOT_FIND_STMT_BINDER)
}
BindingScope.READ_FROM_CURSOR -> {
field.cursorValueReader = context.typeAdapterStore
.findCursorValueReader(field.type, field.affinity)
context.checker.check(field.cursorValueReader != null, field.element,
ProcessorErrors.CANNOT_FIND_CURSOR_READER)
}
}
return field
}
/**
* Defines what we need to assign
*/
enum class BindingScope {
TWO_WAY, // both bind and read.
BIND_TO_STMT, // just value to statement
READ_FROM_CURSOR // just cursor to value
}
}
| apache-2.0 | 047b8774ff48ec374d313a77cb36ba8b | 40.679688 | 95 | 0.622493 | 5.204878 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/main/SearchViewSetup.kt | 1 | 2917 | package com.orgzly.android.ui.main
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.FragmentActivity
import com.orgzly.R
import com.orgzly.android.db.entity.Book
import com.orgzly.android.query.Condition
import com.orgzly.android.query.Query
import com.orgzly.android.query.user.DottedQueryBuilder
import com.orgzly.android.ui.DisplayManager
import com.orgzly.android.ui.notes.book.BookFragment
/**
* SearchView setup and query text listeners.
* TODO: http://developer.android.com/training/search/setup.html
*/
fun FragmentActivity.setupSearchView(menu: Menu) {
fun getActiveFragmentBook(): Book? {
supportFragmentManager.findFragmentByTag(BookFragment.FRAGMENT_TAG)?.let { bookFragment ->
if (bookFragment is BookFragment && bookFragment.isVisible) {
return bookFragment.currentBook
}
}
return null
}
val activity = this
val searchItem = menu.findItem(R.id.search_view)
// Hide FAB while searching
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
Fab.hide(activity)
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
Fab.show(activity)
return true
}
})
val searchView = searchItem.actionView as SearchView
searchView.queryHint = getString(R.string.search_hint)
searchView.setOnSearchClickListener {
// Make search as wide as possible
searchView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
/*
* When user starts the search, fill the search box with text
* depending on the current fragment.
*/
// For Query fragment, fill the box with full query
DisplayManager.getDisplayedQuery(supportFragmentManager)?.let { query ->
searchView.setQuery("$query ", false)
return@setOnSearchClickListener
}
// If searching from book, add book name to query
getActiveFragmentBook()?.let { book ->
val builder = DottedQueryBuilder()
val query = builder.build(Query(Condition.InBook(book.name)))
searchView.setQuery("$query ", false)
return@setOnSearchClickListener
}
}
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(str: String?): Boolean {
return false
}
override fun onQueryTextSubmit(str: String): Boolean {
// Close search
searchItem.collapseActionView()
DisplayManager.displayQuery(supportFragmentManager, str.trim { it <= ' ' })
return true
}
})
}
| gpl-3.0 | f264d88c88f2d962d3deb5c8a72d3a75 | 31.775281 | 98 | 0.674323 | 5.055459 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/network/ConnectionStateMonitor.kt | 1 | 1904 | /*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.utils.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
class ConnectionStateMonitor(private val listener: OnConnectionChangeListener) : ConnectivityManager.NetworkCallback() {
private val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
var isAvailable = false
private set
fun enable(context: Context) {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
manager.registerNetworkCallback(networkRequest, this)
}
fun disable(context: Context) {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
manager.unregisterNetworkCallback(this)
}
override fun onAvailable(network: Network) {
if (!isAvailable) {
isAvailable = true
listener(true)
}
}
override fun onLost(network: Network) {
if (isAvailable) {
isAvailable = false
listener(false)
}
}
}
typealias OnConnectionChangeListener = (isAvailable: Boolean) -> Unit
| apache-2.0 | d0c34d34c1514be65bdaa7cbfc50adf5 | 31.827586 | 120 | 0.718487 | 4.832487 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/Emulator.kt | 1 | 4549 | package com.soywiz.kpspemu
import com.soywiz.klogger.*
import com.soywiz.korau.format.util.*
import com.soywiz.korinject.*
import com.soywiz.korio.async.*
import com.soywiz.kpspemu.battery.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.cpu.dis.*
import com.soywiz.kpspemu.ctrl.*
import com.soywiz.kpspemu.display.*
import com.soywiz.kpspemu.ge.*
import com.soywiz.kpspemu.hle.manager.*
import com.soywiz.kpspemu.mem.*
import kotlin.coroutines.*
class Emulator constructor(
val coroutineContext: CoroutineContext,
val syscalls: SyscallManager = SyscallManager(),
val mem: Memory = Memory(),
var gpuRenderer: GpuRenderer = DummyGpuRenderer()
) : AsyncDependency {
//val INITIAL_INTERPRETED = false
val INITIAL_INTERPRETED = true
var interpreted = INITIAL_INTERPRETED
val onHomePress = Signal<Unit>()
val onLoadPress = Signal<Unit>()
val logger = Logger("Emulator")
val timeManager = TimeManager(this)
val nameProvider = AddressInfo()
val breakpoints = Breakpoints()
val globalCpuState = GlobalCpuState(mem)
var output = StringBuilder()
val ge: Ge = Ge(this)
val gpu: Gpu = Gpu(this)
val battery: PspBattery = PspBattery(this)
val interruptManager: InterruptManager = InterruptManager(this)
val display: PspDisplay = PspDisplay(this)
val deviceManager = DeviceManager(this)
val configManager = ConfigManager()
val memoryManager = MemoryManager(this)
val threadManager = ThreadManager(this)
val moduleManager = ModuleManager(this)
val callbackManager = CallbackManager(this)
val controller = PspController(this)
val fileManager = FileManager(this)
val imem = object : IMemory {
override fun read8(addr: Int): Int = mem.lbu(addr)
}
override suspend fun init() {
configManager.init()
deviceManager.init()
configManager.storage.subscribe {
deviceManager.setStorage(it)
}
}
val running: Boolean get() = threadManager.aliveThreadCount >= 1
var globalTrace: Boolean = false
var sdkVersion: Int = 150
init {
CpuBreakException.initialize(mem)
}
fun invalidateInstructionCache(ptr: Int = 0, size: Int = Int.MAX_VALUE) {
logger.trace { "invalidateInstructionCache($ptr, $size)" }
globalCpuState.mcache.invalidateInstructionCache(ptr, size)
}
fun dataCache(ptr: Int = 0, size: Int = Int.MAX_VALUE, writeback: Boolean, invalidate: Boolean) {
logger.trace { "writebackDataCache($ptr, $size, writeback=$writeback, invalidate=$invalidate)" }
}
suspend fun reset() {
globalTrace = false
sdkVersion = 150
syscalls.reset()
mem.reset()
CpuBreakException.initialize(mem)
gpuRenderer.reset()
timeManager.reset()
nameProvider.reset()
//breakpoints.reset() // Do not reset breakpoints?
globalCpuState.reset()
output = StringBuilder()
ge.reset()
gpu.reset()
battery.reset()
interruptManager.reset()
display.reset()
deviceManager.reset()
memoryManager.reset()
threadManager.reset()
moduleManager.reset()
callbackManager.reset()
controller.reset()
fileManager.reset()
}
}
interface WithEmulator {
val emulator: Emulator
}
class AddressInfo : NameProvider {
val names = hashMapOf<Int, String>()
override fun getName(addr: Int): String? = names[addr]
fun reset() {
names.clear()
}
}
val WithEmulator.mem: Memory get() = emulator.mem
val WithEmulator.imem: IMemory get() = emulator.imem
val WithEmulator.ge: Ge get() = emulator.ge
val WithEmulator.gpu: Gpu get() = emulator.gpu
val WithEmulator.controller: PspController get() = emulator.controller
val WithEmulator.coroutineContext: CoroutineContext get() = emulator.coroutineContext
val WithEmulator.display: PspDisplay get() = emulator.display
val WithEmulator.deviceManager: DeviceManager get() = emulator.deviceManager
val WithEmulator.memoryManager: MemoryManager get() = emulator.memoryManager
val WithEmulator.timeManager: TimeManager get() = emulator.timeManager
val WithEmulator.fileManager: FileManager get() = emulator.fileManager
val WithEmulator.rtc: TimeManager get() = emulator.timeManager
val WithEmulator.threadManager: ThreadManager get() = emulator.threadManager
val WithEmulator.callbackManager: CallbackManager get() = emulator.callbackManager
val WithEmulator.breakpoints: Breakpoints get() = emulator.breakpoints
| mit | 8df8740e28806506dab769a4c9ce9f8b | 33.462121 | 104 | 0.703891 | 4.369837 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/run/jvm/interpret/Interpreter.kt | 1 | 41276 | package asmble.run.jvm.interpret
import asmble.ast.Node
import asmble.compile.jvm.*
import asmble.run.jvm.RunErr
import asmble.util.Either
import asmble.util.Logger
import asmble.util.toUnsignedInt
import asmble.util.toUnsignedLong
import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.nio.ByteBuffer
import java.nio.ByteOrder
// This is not intended to be fast, rather clear and easy to read. Very little cached/memoized, lots of extra cycles.
open class Interpreter {
open fun execFunc(
ctx: Context,
funcIndex: Int = ctx.mod.startFuncIndex ?: error("No start func index"),
vararg funcArgs: Number
): Number? {
// Check params
val funcType = ctx.funcTypeAtIndex(funcIndex)
funcArgs.mapNotNull { it.valueType }.let {
if (it != funcType.params) throw InterpretErr.StartFuncParamMismatch(funcType.params, it)
}
// Import functions are executed inline and returned
ctx.importFuncs.getOrNull(funcIndex)?.also {
return ctx.imports.invokeFunction(it.module, it.field, funcType, funcArgs.toList())
}
// This is the call stack we need to stop at
val startingCallStackSize = ctx.callStack.size
// Make the call on the context
var lastStep: StepResult = StepResult.Call(funcIndex, funcArgs.toList(), funcType)
// Run until done
while (lastStep !is StepResult.Return || ctx.callStack.size > startingCallStackSize + 1) {
next(ctx, lastStep)
lastStep = step(ctx)
}
ctx.callStack.subList(startingCallStackSize, ctx.callStack.size).clear()
return lastStep.v
}
open fun step(ctx: Context): StepResult = ctx.currFuncCtx.run {
// If the insn is out of bounds, it's an implicit return, otherwise just execute the insn
if (insnIndex >= func.instructions.size) StepResult.Return(func.type.ret?.let { pop(it) })
else invokeSingle(ctx)
}
// Errors with InterpretErr.EndReached if there is no next step to be had
open fun next(ctx: Context, step: StepResult) {
ctx.logger.trace {
val fnName = ctx.maybeCurrFuncCtx?.funcIndex?.let { ctx.mod.names?.funcNames?.get(it) ?: it.toString() }
"NEXT ON $fnName(${ctx.maybeCurrFuncCtx?.funcIndex}:${ctx.maybeCurrFuncCtx?.insnIndex}): $step " +
"[VAL STACK: ${ctx.maybeCurrFuncCtx?.valueStack}] " +
"[CALL STACK DEPTH: ${ctx.callStack.size}]"
}
when (step) {
// Next just moves the counter
is StepResult.Next -> ctx.currFuncCtx.insnIndex++
// Branch updates the stack and moves the insn index
is StepResult.Branch -> ctx.currFuncCtx.run {
// A failed if just jumps to the else or end
if (step.failedIf) {
require(step.blockDepth == 0)
val block = blockStack.last()
if (block.elseIndex != null) insnIndex = block.elseIndex + 1
else {
insnIndex = block.endIndex + 1
blockStack.removeAt(blockStack.size - 1)
}
} else {
// Remove all blocks until the depth requested
blockStack.subList(blockStack.size - step.blockDepth, blockStack.size).clear()
// This can break out of the entire function
if (blockStack.isEmpty()) {
// Grab the stack item if present, blow away stack, put back, and move to end of func
val retVal = func.type.ret?.let { pop(it) }
valueStack.clear()
retVal?.also { push(it) }
insnIndex = func.instructions.size
} else if (blockStack.last().insn is Node.Instr.Loop && !step.forceEndOnLoop) {
// It's just a loop continuation, go back to top
insnIndex = blockStack.last().startIndex + 1
} else {
// Remove the one at the depth requested
val block = blockStack.removeAt(blockStack.size - 1)
// Pop value if applicable
val blockVal = block.insn.type?.let { pop(it) }
// Trim the stack down to required size
valueStack.subList(block.stackSizeAtStart, valueStack.size).clear()
// Put the value back on if applicable
blockVal?.also { push(it) }
// Jump past the end
insnIndex = block.endIndex + 1
}
}
}
// Call, if import, invokes it and puts result on stack. If not, just pushes a new func context.
is StepResult.Call -> ctx.funcAtIndex(step.funcIndex).let {
when (it) {
// If import, call and just put on stack and advance insn if came from insn
is Either.Left ->
ctx.imports.invokeFunction(it.v.module, it.v.field, step.type, step.args).also {
// Make sure result type is accurate
if (it.valueType != step.type.ret)
throw InterpretErr.InvalidCallResult(step.type.ret, it)
it?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
// If inside the module, create new context to continue
is Either.Right -> ctx.callStack += FuncContext(step.funcIndex, it.v).also { funcCtx ->
ctx.logger.debug {
">".repeat(ctx.callStack.size) + " " + ctx.mod.names?.funcNames?.get(funcCtx.funcIndex) +
":${funcCtx.funcIndex} - args: " + step.args
}
// Set the args
step.args.forEachIndexed { index, arg -> funcCtx.locals[index] = arg }
}
}
}
// Call indirect is just an MH invocation
is StepResult.CallIndirect -> {
val mh = ctx.table?.getOrNull(step.tableIndex) ?: error("Missing table entry")
val res = mh.invokeWithArguments(step.args) as? Number?
if (res.valueType != step.type.ret) throw InterpretErr.InvalidCallResult(step.type.ret, res)
res?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
// Unreachable throws
is StepResult.Unreachable -> throw UnsupportedOperationException("Unreachable")
// Return pops curr func from the call stack, push ret and move insn on prev one
is StepResult.Return -> ctx.callStack.removeAt(ctx.callStack.lastIndex).let { returnedFrom ->
if (ctx.callStack.isEmpty()) throw InterpretErr.EndReached(step.v)
if (returnedFrom.valueStack.isNotEmpty())
throw CompileErr.UnusedStackOnReturn(returnedFrom.valueStack.map { it::class.ref } )
step.v?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
}
}
open fun invokeSingle(ctx: Context): StepResult = ctx.currFuncCtx.run {
// TODO: validation?
func.instructions[insnIndex].let { insn ->
ctx.logger.trace { "INSN #$insnIndex: $insn [STACK: $valueStack]" }
when (insn) {
is Node.Instr.Unreachable -> StepResult.Unreachable
is Node.Instr.Nop -> next { }
is Node.Instr.Block, is Node.Instr.Loop -> next {
blockStack += Block(insnIndex, insn as Node.Instr.Args.Type, valueStack.size, currentBlockEnd()!!)
}
is Node.Instr.If -> {
blockStack += Block(insnIndex, insn, valueStack.size - 1, currentBlockEnd()!!, currentBlockElse())
if (popInt() == 0) StepResult.Branch(0, failedIf = true) else StepResult.Next
}
is Node.Instr.Else ->
// Jump over the whole thing and to the end, this can only be gotten here via if
StepResult.Branch(0)
is Node.Instr.End ->
// Since we reached the end by manually running through it, jump to end even on loop
StepResult.Branch(0, forceEndOnLoop = true)
is Node.Instr.Br -> StepResult.Branch(insn.relativeDepth)
is Node.Instr.BrIf -> if (popInt() != 0) StepResult.Branch(insn.relativeDepth) else StepResult.Next
is Node.Instr.BrTable -> StepResult.Branch(insn.targetTable.getOrNull(popInt())
?: insn.default)
is Node.Instr.Return ->
StepResult.Return(func.type.ret?.let { pop(it) })
is Node.Instr.Call -> ctx.funcTypeAtIndex(insn.index).let {
ctx.checkNextIsntStackOverflow()
StepResult.Call(insn.index, popCallArgs(it), it)
}
is Node.Instr.CallIndirect -> {
ctx.checkNextIsntStackOverflow()
val tableIndex = popInt()
val expectedType = ctx.typeAtIndex(insn.index).also {
val tableMh = ctx.table?.getOrNull(tableIndex) ?:
throw InterpretErr.UndefinedElement(tableIndex)
val actualType = Node.Type.Func(
params = tableMh.type().parameterList().map { it.valueType!! },
ret = tableMh.type().returnType().valueType
)
if (it != actualType) throw InterpretErr.IndirectCallTypeMismatch(it, actualType)
}
StepResult.CallIndirect(tableIndex, popCallArgs(expectedType), expectedType)
}
is Node.Instr.Drop -> next { pop() }
is Node.Instr.Select -> next {
popInt().also {
val v2 = pop()
val v1 = pop()
if (v1::class != v2::class)
throw CompileErr.SelectMismatch(v1.valueType!!.typeRef, v2.valueType!!.typeRef)
if (it != 0) push(v1) else push(v2)
}
}
is Node.Instr.GetLocal -> next { push(locals[insn.index]) }
is Node.Instr.SetLocal -> next { locals[insn.index] = pop()}
is Node.Instr.TeeLocal -> next { locals[insn.index] = peek() }
is Node.Instr.GetGlobal -> next { push(ctx.getGlobal(insn.index)) }
is Node.Instr.SetGlobal -> next { ctx.setGlobal(insn.index, pop()) }
is Node.Instr.I32Load -> next { push(ctx.mem.getInt(insn.popMemAddr())) }
is Node.Instr.I64Load -> next { push(ctx.mem.getLong(insn.popMemAddr())) }
is Node.Instr.F32Load -> next { push(ctx.mem.getFloat(insn.popMemAddr())) }
is Node.Instr.F64Load -> next { push(ctx.mem.getDouble(insn.popMemAddr())) }
is Node.Instr.I32Load8S -> next { push(ctx.mem.get(insn.popMemAddr()).toInt()) }
is Node.Instr.I32Load8U -> next { push(ctx.mem.get(insn.popMemAddr()).toUnsignedInt()) }
is Node.Instr.I32Load16S -> next { push(ctx.mem.getShort(insn.popMemAddr()).toInt()) }
is Node.Instr.I32Load16U -> next { push(ctx.mem.getShort(insn.popMemAddr()).toUnsignedInt()) }
is Node.Instr.I64Load8S -> next { push(ctx.mem.get(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load8U -> next { push(ctx.mem.get(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I64Load16S -> next { push(ctx.mem.getShort(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load16U -> next { push(ctx.mem.getShort(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I64Load32S -> next { push(ctx.mem.getInt(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load32U -> next { push(ctx.mem.getInt(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I32Store -> next { popInt().let { ctx.mem.putInt(insn.popMemAddr(), it) } }
is Node.Instr.I64Store -> next { popLong().let { ctx.mem.putLong(insn.popMemAddr(), it) } }
is Node.Instr.F32Store -> next { popFloat().let { ctx.mem.putFloat(insn.popMemAddr(), it) } }
is Node.Instr.F64Store -> next { popDouble().let { ctx.mem.putDouble(insn.popMemAddr(), it) } }
is Node.Instr.I32Store8 -> next { popInt().let { ctx.mem.put(insn.popMemAddr(), it.toByte()) } }
is Node.Instr.I32Store16 -> next { popInt().let { ctx.mem.putShort(insn.popMemAddr(), it.toShort()) } }
is Node.Instr.I64Store8 -> next { popLong().let { ctx.mem.put(insn.popMemAddr(), it.toByte()) } }
is Node.Instr.I64Store16 -> next { popLong().let { ctx.mem.putShort(insn.popMemAddr(), it.toShort()) } }
is Node.Instr.I64Store32 -> next { popLong().let { ctx.mem.putInt(insn.popMemAddr(), it.toInt()) } }
is Node.Instr.MemorySize -> next { push(ctx.mem.limit() / Mem.PAGE_SIZE) }
is Node.Instr.MemoryGrow -> next {
val newLim = ctx.mem.limit().toLong() + (popInt().toLong() * Mem.PAGE_SIZE)
if (newLim > ctx.mem.capacity()) push(-1)
else (ctx.mem.limit() / Mem.PAGE_SIZE).also {
push(it)
ctx.mem.limit(newLim.toInt())
}
}
is Node.Instr.I32Const -> next { push(insn.value) }
is Node.Instr.I64Const -> next { push(insn.value) }
is Node.Instr.F32Const -> next { push(insn.value) }
is Node.Instr.F64Const -> next { push(insn.value) }
is Node.Instr.I32Eqz -> next { push(popInt() == 0) }
is Node.Instr.I32Eq -> nextBinOp(popInt(), popInt()) { a, b -> a == b }
is Node.Instr.I32Ne -> nextBinOp(popInt(), popInt()) { a, b -> a != b }
is Node.Instr.I32LtS -> nextBinOp(popInt(), popInt()) { a, b -> a < b }
is Node.Instr.I32LtU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) < 0 }
is Node.Instr.I32GtS -> nextBinOp(popInt(), popInt()) { a, b -> a > b }
is Node.Instr.I32GtU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) > 0 }
is Node.Instr.I32LeS -> nextBinOp(popInt(), popInt()) { a, b -> a <= b }
is Node.Instr.I32LeU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) <= 0 }
is Node.Instr.I32GeS -> nextBinOp(popInt(), popInt()) { a, b -> a >= b }
is Node.Instr.I32GeU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) >= 0 }
is Node.Instr.I64Eqz -> next { push(popLong() == 0L) }
is Node.Instr.I64Eq -> nextBinOp(popLong(), popLong()) { a, b -> a == b }
is Node.Instr.I64Ne -> nextBinOp(popLong(), popLong()) { a, b -> a != b }
is Node.Instr.I64LtS -> nextBinOp(popLong(), popLong()) { a, b -> a < b }
is Node.Instr.I64LtU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) < 0 }
is Node.Instr.I64GtS -> nextBinOp(popLong(), popLong()) { a, b -> a > b }
is Node.Instr.I64GtU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) > 0 }
is Node.Instr.I64LeS -> nextBinOp(popLong(), popLong()) { a, b -> a <= b }
is Node.Instr.I64LeU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) <= 0 }
is Node.Instr.I64GeS -> nextBinOp(popLong(), popLong()) { a, b -> a >= b }
is Node.Instr.I64GeU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) >= 0 }
is Node.Instr.F32Eq -> nextBinOp(popFloat(), popFloat()) { a, b -> a == b }
is Node.Instr.F32Ne -> nextBinOp(popFloat(), popFloat()) { a, b -> a != b }
is Node.Instr.F32Lt -> nextBinOp(popFloat(), popFloat()) { a, b -> a < b }
is Node.Instr.F32Gt -> nextBinOp(popFloat(), popFloat()) { a, b -> a > b }
is Node.Instr.F32Le -> nextBinOp(popFloat(), popFloat()) { a, b -> a <= b }
is Node.Instr.F32Ge -> nextBinOp(popFloat(), popFloat()) { a, b -> a >= b }
is Node.Instr.F64Eq -> nextBinOp(popDouble(), popDouble()) { a, b -> a == b }
is Node.Instr.F64Ne -> nextBinOp(popDouble(), popDouble()) { a, b -> a != b }
is Node.Instr.F64Lt -> nextBinOp(popDouble(), popDouble()) { a, b -> a < b }
is Node.Instr.F64Gt -> nextBinOp(popDouble(), popDouble()) { a, b -> a > b }
is Node.Instr.F64Le -> nextBinOp(popDouble(), popDouble()) { a, b -> a <= b }
is Node.Instr.F64Ge -> nextBinOp(popDouble(), popDouble()) { a, b -> a >= b }
is Node.Instr.I32Clz -> next { push(Integer.numberOfLeadingZeros(popInt())) }
is Node.Instr.I32Ctz -> next { push(Integer.numberOfTrailingZeros(popInt())) }
is Node.Instr.I32Popcnt -> next { push(Integer.bitCount(popInt())) }
is Node.Instr.I32Add -> nextBinOp(popInt(), popInt()) { a, b -> a + b }
is Node.Instr.I32Sub -> nextBinOp(popInt(), popInt()) { a, b -> a - b }
is Node.Instr.I32Mul -> nextBinOp(popInt(), popInt()) { a, b -> a * b }
is Node.Instr.I32DivS -> nextBinOp(popInt(), popInt()) { a, b ->
ctx.checkedSignedDivInteger(a, b)
a / b
}
is Node.Instr.I32DivU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.divideUnsigned(a, b) }
is Node.Instr.I32RemS -> nextBinOp(popInt(), popInt()) { a, b -> a % b }
is Node.Instr.I32RemU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.remainderUnsigned(a, b) }
is Node.Instr.I32And -> nextBinOp(popInt(), popInt()) { a, b -> a and b }
is Node.Instr.I32Or -> nextBinOp(popInt(), popInt()) { a, b -> a or b }
is Node.Instr.I32Xor -> nextBinOp(popInt(), popInt()) { a, b -> a xor b }
is Node.Instr.I32Shl -> nextBinOp(popInt(), popInt()) { a, b -> a shl b }
is Node.Instr.I32ShrS -> nextBinOp(popInt(), popInt()) { a, b -> a shr b }
is Node.Instr.I32ShrU -> nextBinOp(popInt(), popInt()) { a, b -> a ushr b }
is Node.Instr.I32Rotl -> nextBinOp(popInt(), popInt()) { a, b -> Integer.rotateLeft(a, b) }
is Node.Instr.I32Rotr -> nextBinOp(popInt(), popInt()) { a, b -> Integer.rotateRight(a, b) }
is Node.Instr.I64Clz -> next { push(java.lang.Long.numberOfLeadingZeros(popLong()).toLong()) }
is Node.Instr.I64Ctz -> next { push(java.lang.Long.numberOfTrailingZeros(popLong()).toLong()) }
is Node.Instr.I64Popcnt -> next { push(java.lang.Long.bitCount(popLong()).toLong()) }
is Node.Instr.I64Add -> nextBinOp(popLong(), popLong()) { a, b -> a + b }
is Node.Instr.I64Sub -> nextBinOp(popLong(), popLong()) { a, b -> a - b }
is Node.Instr.I64Mul -> nextBinOp(popLong(), popLong()) { a, b -> a * b }
is Node.Instr.I64DivS -> nextBinOp(popLong(), popLong()) { a, b ->
ctx.checkedSignedDivInteger(a, b)
a / b
}
is Node.Instr.I64DivU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.divideUnsigned(a, b) }
is Node.Instr.I64RemS -> nextBinOp(popLong(), popLong()) { a, b -> a % b }
is Node.Instr.I64RemU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.remainderUnsigned(a, b) }
is Node.Instr.I64And -> nextBinOp(popLong(), popLong()) { a, b -> a and b }
is Node.Instr.I64Or -> nextBinOp(popLong(), popLong()) { a, b -> a or b }
is Node.Instr.I64Xor -> nextBinOp(popLong(), popLong()) { a, b -> a xor b }
is Node.Instr.I64Shl -> nextBinOp(popLong(), popLong()) { a, b -> a shl b.toInt() }
is Node.Instr.I64ShrS -> nextBinOp(popLong(), popLong()) { a, b -> a shr b.toInt() }
is Node.Instr.I64ShrU -> nextBinOp(popLong(), popLong()) { a, b -> a ushr b.toInt() }
is Node.Instr.I64Rotl -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.rotateLeft(a, b.toInt()) }
is Node.Instr.I64Rotr -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.rotateRight(a, b.toInt()) }
is Node.Instr.F32Abs -> next { push(Math.abs(popFloat())) }
is Node.Instr.F32Neg -> next { push(-popFloat()) }
is Node.Instr.F32Ceil -> next { push(Math.ceil(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Floor -> next { push(Math.floor(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Trunc -> next {
popFloat().toDouble().let { push((if (it >= 0.0) Math.floor(it) else Math.ceil(it)).toFloat()) }
}
is Node.Instr.F32Nearest -> next { push(Math.rint(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Sqrt -> next { push(Math.sqrt(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Add -> nextBinOp(popFloat(), popFloat()) { a, b -> a + b }
is Node.Instr.F32Sub -> nextBinOp(popFloat(), popFloat()) { a, b -> a - b }
is Node.Instr.F32Mul -> nextBinOp(popFloat(), popFloat()) { a, b -> a * b }
is Node.Instr.F32Div -> nextBinOp(popFloat(), popFloat()) { a, b -> a / b }
is Node.Instr.F32Min -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.min(a, b) }
is Node.Instr.F32Max -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.max(a, b) }
is Node.Instr.F32CopySign -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.copySign(a, b) }
is Node.Instr.F64Abs -> next { push(Math.abs(popDouble())) }
is Node.Instr.F64Neg -> next { push(-popDouble()) }
is Node.Instr.F64Ceil -> next { push(Math.ceil(popDouble())) }
is Node.Instr.F64Floor -> next { push(Math.floor(popDouble())) }
is Node.Instr.F64Trunc -> next {
popDouble().let { push((if (it >= 0.0) Math.floor(it) else Math.ceil(it))) }
}
is Node.Instr.F64Nearest -> next { push(Math.rint(popDouble())) }
is Node.Instr.F64Sqrt -> next { push(Math.sqrt(popDouble())) }
is Node.Instr.F64Add -> nextBinOp(popDouble(), popDouble()) { a, b -> a + b }
is Node.Instr.F64Sub -> nextBinOp(popDouble(), popDouble()) { a, b -> a - b }
is Node.Instr.F64Mul -> nextBinOp(popDouble(), popDouble()) { a, b -> a * b }
is Node.Instr.F64Div -> nextBinOp(popDouble(), popDouble()) { a, b -> a / b }
is Node.Instr.F64Min -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.min(a, b) }
is Node.Instr.F64Max -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.max(a, b) }
is Node.Instr.F64CopySign -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.copySign(a, b) }
is Node.Instr.I32WrapI64 -> next { push(popLong().toInt()) }
// TODO: trunc traps on overflow!
is Node.Instr.I32TruncSF32 -> next {
push(ctx.checkedTrunc(popFloat(), true) { it.toInt() })
}
is Node.Instr.I32TruncUF32 -> next {
push(ctx.checkedTrunc(popFloat(), false) { it.toLong().toInt() })
}
is Node.Instr.I32TruncSF64 -> next {
push(ctx.checkedTrunc(popDouble(), true) { it.toInt() })
}
is Node.Instr.I32TruncUF64 -> next {
push(ctx.checkedTrunc(popDouble(), false) { it.toLong().toInt() })
}
is Node.Instr.I64ExtendSI32 -> next { push(popInt().toLong()) }
is Node.Instr.I64ExtendUI32 -> next { push(popInt().toUnsignedLong()) }
is Node.Instr.I64TruncSF32 -> next {
push(ctx.checkedTrunc(popFloat(), true) { it.toLong() })
}
is Node.Instr.I64TruncUF32 -> next {
push(ctx.checkedTrunc(popFloat(), false) {
// If over max long, subtract and negate
if (it < 9223372036854775807f) it.toLong()
else (-9223372036854775808f + (it - 9223372036854775807f)).toLong()
})
}
is Node.Instr.I64TruncSF64 -> next {
push(ctx.checkedTrunc(popDouble(), true) { it.toLong() })
}
is Node.Instr.I64TruncUF64 -> next {
push(ctx.checkedTrunc(popDouble(), false) {
// If over max long, subtract and negate
if (it < 9223372036854775807.0) it.toLong()
else (-9223372036854775808.0 + (it - 9223372036854775807.0)).toLong()
})
}
is Node.Instr.F32ConvertSI32 -> next { push(popInt().toFloat()) }
is Node.Instr.F32ConvertUI32 -> next { push(popInt().toUnsignedLong().toFloat()) }
is Node.Instr.F32ConvertSI64 -> next { push(popLong().toFloat()) }
is Node.Instr.F32ConvertUI64 -> next {
push(popLong().let { if (it >= 0) it.toFloat() else (it ushr 1).toFloat() * 2f })
}
is Node.Instr.F32DemoteF64 -> next { push(popDouble().toFloat()) }
is Node.Instr.F64ConvertSI32 -> next { push(popInt().toDouble()) }
is Node.Instr.F64ConvertUI32 -> next { push(popInt().toUnsignedLong().toDouble()) }
is Node.Instr.F64ConvertSI64 -> next { push(popLong().toDouble()) }
is Node.Instr.F64ConvertUI64 -> next {
push(popLong().let { if (it >= 0) it.toDouble() else ((it ushr 1) or (it and 1)) * 2.0 })
}
is Node.Instr.F64PromoteF32 -> next { push(popFloat().toDouble()) }
is Node.Instr.I32ReinterpretF32 -> next { push(java.lang.Float.floatToRawIntBits(popFloat())) }
is Node.Instr.I64ReinterpretF64 -> next { push(java.lang.Double.doubleToRawLongBits(popDouble())) }
is Node.Instr.F32ReinterpretI32 -> next { push(java.lang.Float.intBitsToFloat(popInt())) }
is Node.Instr.F64ReinterpretI64 -> next { push(java.lang.Double.longBitsToDouble(popLong())) }
}
}
}
companion object : Interpreter()
// Creating this does all the initialization except execute the start function
data class Context(
val mod: Node.Module,
val logger: Logger = Logger.Print(Logger.Level.OFF),
val interpreter: Interpreter = Interpreter.Companion,
val imports: Imports = Imports.None,
val defaultMaxMemPages: Int = 1,
val memByteBufferDirect: Boolean = true,
val checkTruncOverflow: Boolean = true,
val checkSignedDivIntegerOverflow: Boolean = true,
val maximumCallStackDepth: Int = 3000
) {
val callStack = mutableListOf<FuncContext>()
val currFuncCtx get() = callStack.last()
val maybeCurrFuncCtx get() = callStack.lastOrNull()
val exportsByName = mod.exports.map { it.field to it }.toMap()
fun exportIndex(field: String, kind: Node.ExternalKind) =
exportsByName[field]?.takeIf { it.kind == kind }?.index
val importGlobals = mod.imports.filter { it.kind is Node.Import.Kind.Global }
fun singleConstant(instrs: List<Node.Instr>): Number? = instrs.singleOrNull().let { instr ->
when (instr) {
is Node.Instr.Args.Const<*> -> instr.value
is Node.Instr.GetGlobal -> importGlobals.getOrNull(instr.index).let {
it ?: throw CompileErr.UnknownGlobal(instr.index)
imports.getGlobal(it.module, it.field, (it.kind as Node.Import.Kind.Global).type)
}
else -> null
}
}
val maybeMem = run {
// Import it if we can, otherwise make it
val memImport = mod.imports.singleOrNull { it.kind is Node.Import.Kind.Memory }
// TODO: validate imported memory
val mem =
if (memImport != null) imports.getMemory(
memImport.module,
memImport.field,
(memImport.kind as Node.Import.Kind.Memory).type
) else mod.memories.singleOrNull()?.let { memType ->
val max = (memType.limits.maximum ?: defaultMaxMemPages) * Mem.PAGE_SIZE
val mem = if (memByteBufferDirect) ByteBuffer.allocateDirect(max) else ByteBuffer.allocate(max)
mem.apply {
order(ByteOrder.LITTLE_ENDIAN)
limit(memType.limits.initial * Mem.PAGE_SIZE)
}
}
mem?.also { mem ->
// Load all data
mod.data.forEach { data ->
val pos = singleConstant(data.offset) as? Int ?: throw CompileErr.OffsetNotConstant()
if (pos < 0 || pos + data.data.size > mem.limit())
throw RunErr.InvalidDataIndex(pos, data.data.size, mem.limit())
mem.duplicate().apply { position(pos) }.put(data.data)
}
}
}
val mem get() = maybeMem ?: throw CompileErr.UnknownMemory(0)
// TODO: some of this shares with the compiler's context, so how about some code reuse?
val importFuncs = mod.imports.filter { it.kind is Node.Import.Kind.Func }
fun typeAtIndex(index: Int) = mod.types.getOrNull(index) ?: throw CompileErr.UnknownType(index)
fun funcAtIndex(index: Int) = importFuncs.getOrNull(index).let {
when (it) {
null -> Either.Right(mod.funcs.getOrNull(index - importFuncs.size) ?: throw CompileErr.UnknownFunc(index))
else -> Either.Left(it)
}
}
fun funcTypeAtIndex(index: Int) = funcAtIndex(index).let {
when (it) {
is Either.Left -> typeAtIndex((it.v.kind as Node.Import.Kind.Func).typeIndex)
is Either.Right -> it.v.type
}
}
fun boundFuncMethodHandleAtIndex(index: Int): MethodHandle {
val type = funcTypeAtIndex(index).let {
MethodType.methodType(it.ret?.jclass ?: Void.TYPE, it.params.map { it.jclass })
}
val origMh = MethodHandles.lookup().bind(interpreter, "execFunc", MethodType.methodType(
Number::class.java, Context::class.java, Int::class.java, Array<Number>::class.java))
return MethodHandles.insertArguments(origMh, 0, this, index).
asVarargsCollector(Array<Number>::class.java).asType(type)
}
val moduleGlobals = mod.globals.mapIndexed { index, global ->
// In MVP all globals have an init, it's either a const or an import read
val initVal = singleConstant(global.init) ?: throw CompileErr.GlobalInitNotConstant(index)
if (initVal.valueType != global.type.contentType)
throw CompileErr.GlobalConstantMismatch(index, global.type.contentType.typeRef, initVal::class.ref)
initVal
}.toMutableList()
fun globalTypeAtIndex(index: Int) =
(importGlobals.getOrNull(index)?.kind as? Node.Import.Kind.Global)?.type ?:
mod.globals[index - importGlobals.size].type
fun getGlobal(index: Int): Number = importGlobals.getOrNull(index).let { importGlobal ->
if (importGlobal != null) imports.getGlobal(
importGlobal.module,
importGlobal.field,
(importGlobal.kind as Node.Import.Kind.Global).type
) else moduleGlobals.getOrNull(index - importGlobals.size) ?: error("No global")
}
fun setGlobal(index: Int, v: Number) {
val importGlobal = importGlobals.getOrNull(index)
if (importGlobal != null) imports.setGlobal(
importGlobal.module,
importGlobal.field,
(importGlobal.kind as Node.Import.Kind.Global).type,
v
) else (index - importGlobals.size).also { index ->
require(index < moduleGlobals.size)
moduleGlobals[index] = v
}
}
val table = run {
val importTable = mod.imports.singleOrNull { it.kind is Node.Import.Kind.Table }
val table = (importTable?.kind as? Node.Import.Kind.Table)?.type ?: mod.tables.singleOrNull()
if (table == null && mod.elems.isNotEmpty()) throw CompileErr.UnknownTable(0)
table?.let { table ->
// Create array either cloned from import or fresh
val arr = importTable?.let { imports.getTable(it.module, it.field, table) } ?:
arrayOfNulls(table.limits.initial)
// Now put all the elements in there
mod.elems.forEach { elem ->
require(elem.index == 0)
// Offset index always a constant or import
val offsetVal = singleConstant(elem.offset) as? Int ?: throw CompileErr.OffsetNotConstant()
// Still have to validate offset even if no func indexes
if (offsetVal < 0 || offsetVal + elem.funcIndices.size > arr.size)
throw RunErr.InvalidElemIndex(offsetVal, elem.funcIndices.size, arr.size)
elem.funcIndices.forEachIndexed { index, funcIndex ->
arr[offsetVal + index] = boundFuncMethodHandleAtIndex(funcIndex)
}
}
arr
}
}
fun <T : Number> checkedTrunc(orig: Float, signed: Boolean, to: (Float) -> T) = to(orig).also {
if (checkTruncOverflow) {
if (orig.isNaN()) throw InterpretErr.TruncIntegerNaN(orig, it.valueType!!, signed)
val invalid =
(it is Int && signed && (orig < -2147483648f || orig >= 2147483648f)) ||
(it is Int && !signed && (orig.toInt() < 0 || orig >= 4294967296f)) ||
(it is Long && signed && (orig < -9223372036854775807f || orig >= 9223372036854775807f)) ||
(it is Long && !signed && (orig.toInt() < 0 || orig >= 18446744073709551616f))
if (invalid) throw InterpretErr.TruncIntegerOverflow(orig, it.valueType!!, signed)
}
}
fun <T : Number> checkedTrunc(orig: Double, signed: Boolean, to: (Double) -> T) = to(orig).also {
if (checkTruncOverflow) {
if (orig.isNaN()) throw InterpretErr.TruncIntegerNaN(orig, it.valueType!!, signed)
val invalid =
(it is Int && signed && (orig < -2147483648.0 || orig >= 2147483648.0)) ||
(it is Int && !signed && (orig.toInt() < 0 || orig >= 4294967296.0)) ||
(it is Long && signed && (orig < -9223372036854775807.0 || orig >= 9223372036854775807.0)) ||
(it is Long && !signed && (orig.toInt() < 0 || orig >= 18446744073709551616.0))
if (invalid) throw InterpretErr.TruncIntegerOverflow(orig, it.valueType!!, signed)
}
}
fun checkedSignedDivInteger(a: Int, b: Int) {
if (checkSignedDivIntegerOverflow && (a == Int.MIN_VALUE && b == -1))
throw InterpretErr.SignedDivOverflow(a, b)
}
fun checkedSignedDivInteger(a: Long, b: Long) {
if (checkSignedDivIntegerOverflow && (a == Long.MIN_VALUE && b == -1L))
throw InterpretErr.SignedDivOverflow(a, b)
}
fun checkNextIsntStackOverflow() {
// TODO: note this doesn't keep count of imports and their call stack
if (callStack.size + 1 >= maximumCallStackDepth) {
// We blow away the entire stack here so code can continue...could provide stack to
// exception if we wanted
callStack.clear()
throw InterpretErr.StackOverflow(maximumCallStackDepth)
}
}
}
data class FuncContext(
val funcIndex: Int,
val func: Node.Func,
val valueStack: MutableList<Number> = mutableListOf(),
val blockStack: MutableList<Block> = mutableListOf(),
var insnIndex: Int = 0
) {
val locals = (func.type.params + func.locals).map {
when (it) {
is Node.Type.Value.I32 -> 0 as Number
is Node.Type.Value.I64 -> 0L as Number
is Node.Type.Value.F32 -> 0f as Number
is Node.Type.Value.F64 -> 0.0 as Number
}
}.toMutableList()
fun peek() = valueStack.last()
fun pop() = valueStack.removeAt(valueStack.size - 1)
fun popInt() = pop() as Int
fun popLong() = pop() as Long
fun popFloat() = pop() as Float
fun popDouble() = pop() as Double
fun Node.Instr.Args.AlignOffset.popMemAddr(): Int {
val v = popInt()
if (offset > Int.MAX_VALUE || offset + v > Int.MAX_VALUE) throw InterpretErr.OutOfBoundsMemory(v, offset)
return v + offset.toInt()
}
fun pop(type: Node.Type.Value): Number = when (type) {
is Node.Type.Value.I32 -> popInt()
is Node.Type.Value.I64 -> popLong()
is Node.Type.Value.F32 -> popFloat()
is Node.Type.Value.F64 -> popDouble()
}
fun popCallArgs(type: Node.Type.Func) = type.params.reversed().map(::pop).reversed()
fun push(v: Number) { valueStack += v }
fun push(v: Boolean) { valueStack += if (v) 1 else 0 }
fun currentBlockEndOrElse(end: Boolean): Int? {
// Find the next end/else
var blockDepth = 0
val index = func.instructions.drop(insnIndex + 1).indexOfFirst { insn ->
// Increase block depth if necessary
when (insn) { is Node.Instr.Block, is Node.Instr.Loop, is Node.Instr.If -> blockDepth++ }
// If we're at the end of ourself but not looking for end, short-circuit a failure
if (blockDepth == 0 && !end && insn is Node.Instr.End) return null
// Did we find an end or an else on ourself?
val found = blockDepth == 0 && ((end && insn is Node.Instr.End) || (!end && insn is Node.Instr.Else))
if (blockDepth > 0 && insn is Node.Instr.End) blockDepth--
found
}
return if (index == -1) null else index + insnIndex + 1
}
fun currentBlockEnd() = currentBlockEndOrElse(true)
fun currentBlockElse(): Int? = currentBlockEndOrElse(false)
inline fun next(crossinline f: () -> Unit) = StepResult.Next.also { f() }
inline fun <T, U> nextBinOp(second: T, first: U, crossinline f: (U, T) -> Any) = StepResult.Next.also {
val v = f(first, second)
if (v is Boolean) push(v) else push(v as Number)
}
}
data class Block(
val startIndex: Int,
val insn: Node.Instr.Args.Type,
val stackSizeAtStart: Int,
val endIndex: Int,
val elseIndex: Int? = null
)
sealed class StepResult {
object Next : StepResult()
data class Branch(
val blockDepth: Int,
val failedIf: Boolean = false,
val forceEndOnLoop: Boolean = false
) : StepResult()
data class Call(
val funcIndex: Int,
val args: List<Number>,
val type: Node.Type.Func
) : StepResult()
data class CallIndirect(
val tableIndex: Int,
val args: List<Number>,
val type: Node.Type.Func
) : StepResult()
object Unreachable : StepResult()
data class Return(val v: Number?) : StepResult()
}
} | mit | f9171c4ed7a32f8100ba2d42988873d9 | 59.434846 | 125 | 0.541889 | 4.247813 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/run/jvm/interpret/RunModule.kt | 1 | 4035 | package asmble.run.jvm.interpret
import asmble.ast.Node
import asmble.compile.jvm.jclass
import asmble.run.jvm.Module
import asmble.run.jvm.ModuleBuilder
import asmble.util.Logger
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.nio.ByteBuffer
class RunModule(
override val name: String?,
val ctx: Interpreter.Context
) : Module {
override fun exportedFunc(field: String) =
ctx.exportIndex(field, Node.ExternalKind.FUNCTION)?.let { ctx.boundFuncMethodHandleAtIndex(it) }
override fun exportedGlobal(field: String) = ctx.exportIndex(field, Node.ExternalKind.GLOBAL)?.let { index ->
val type = ctx.globalTypeAtIndex(index)
val lookup = MethodHandles.lookup()
var getter = lookup.bind(ctx, "getGlobal",
MethodType.methodType(Number::class.java, Int::class.javaPrimitiveType))
var setter = if (!type.mutable) null else lookup.bind(ctx, "setGlobal", MethodType.methodType(
Void::class.javaPrimitiveType, Int::class.javaPrimitiveType, Number::class.java))
// Cast number to specific type
getter = MethodHandles.explicitCastArguments(getter,
MethodType.methodType(type.contentType.jclass, Int::class.javaPrimitiveType))
if (setter != null)
setter = MethodHandles.explicitCastArguments(setter, MethodType.methodType(
Void::class.javaPrimitiveType, Int::class.javaPrimitiveType, type.contentType.jclass))
// Insert the index argument up front
getter = MethodHandles.insertArguments(getter, 0, index)
if (setter != null) setter = MethodHandles.insertArguments(setter, 0, index)
getter to setter
}
@SuppressWarnings("UNCHECKED_CAST")
override fun <T> exportedMemory(field: String, memClass: Class<T>) =
ctx.exportIndex(field, Node.ExternalKind.MEMORY)?.let { index ->
require(index == 0 && memClass == ByteBuffer::class.java)
ctx.maybeMem as? T?
}
override fun exportedTable(field: String) =
ctx.exportIndex(field, Node.ExternalKind.TABLE)?.let { index ->
require(index == 0)
ctx.table
}
class Builder(
val logger: Logger = Logger.Print(Logger.Level.OFF),
val defaultMaxMemPages: Int = 1,
val memByteBufferDirect: Boolean = true
) : ModuleBuilder<RunModule> {
override fun build(
imports: Module.ImportResolver,
mod: Node.Module,
className: String,
name: String?
) = RunModule(
name = name,
ctx = Interpreter.Context(
mod = mod,
logger = logger,
imports = ResolverImports(imports),
defaultMaxMemPages = defaultMaxMemPages,
memByteBufferDirect = memByteBufferDirect
).also { ctx ->
// Run start function if present
mod.startFuncIndex?.also { Interpreter.execFunc(ctx, it) }
}
)
}
class ResolverImports(val res: Module.ImportResolver) : Imports {
override fun invokeFunction(module: String, field: String, type: Node.Type.Func, args: List<Number>) =
res.resolveImportFunc(module, field, type).invokeWithArguments(args) as Number?
override fun getGlobal(module: String, field: String, type: Node.Type.Global) =
res.resolveImportGlobal(module, field, type).first.invokeWithArguments() as Number
override fun setGlobal(module: String, field: String, type: Node.Type.Global, value: Number) {
res.resolveImportGlobal(module, field, type).second!!.invokeWithArguments(value)
}
override fun getMemory(module: String, field: String, type: Node.Type.Memory) =
res.resolveImportMemory(module, field, type, ByteBuffer::class.java)
override fun getTable(module: String, field: String, type: Node.Type.Table) =
res.resolveImportTable(module, field, type)
}
} | mit | 864a52a1ed79a698d904f81e17abc6d0 | 42.397849 | 113 | 0.653532 | 4.554176 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/DependenciesExtensions.kt | 2 | 7560 | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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:Incubating
@file:Suppress("EXTENSION_SHADOWED_BY_MEMBER")
package org.gradle.kotlin.dsl
import org.gradle.api.Action
import org.gradle.api.Incubating
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.FileCollectionDependency
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.Dependencies
import org.gradle.api.artifacts.dsl.DependencyAdder
import org.gradle.api.artifacts.dsl.DependencyFactory
import org.gradle.api.artifacts.dsl.DependencyModifier
import org.gradle.api.artifacts.dsl.GradleDependencies
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderConvertible
/**
* This file is used to add [Kotlin extension functions](https://kotlinlang.org/docs/extensions.html) to [Dependencies], [DependencyAdder] and [DependencyModifier] to make the Kotlin DSL more idiomatic.
*
* These extension functions allow an interface to implement a dependencies block in the Kotlin DSL by
* - exposing an instance of [DependencyAdder] to add dependencies without explicitly calling [DependencyAdder.add]
* - exposing an instance of [DependencyModifier] to modify dependencies without explicitly calling [DependencyModifier.modify]
*
* There are `invoke(...)` equivalents for all the `add(...)` methods in [DependencyAdder].
*
* There are `invoke(...)` equivalents for all the `modify(...)` methods in [DependencyModifier].
*
* @since 8.0
*
* @see org.gradle.api.internal.artifacts.dsl.dependencies.DependenciesExtensionModule
* @see Dependencies
* @see DependencyAdder
* @see DependencyModifier
* @see DependencyFactory
*
* @sample DependenciesExtensions.sample
*/
@Suppress("unused")
private
class DependenciesExtensions {
interface MyDependencies : GradleDependencies {
val implementation: DependencyAdder
val testFixtures: DependencyModifier
operator fun invoke(action: Action<in MyDependencies>)
}
fun sample(dependencies: MyDependencies) {
// In a Kotlin DSL build script
dependencies {
// Add a dependency by String
implementation("org:foo:1.0") // is getImplementation().add("org:foo:1.0")
// Add a dependency with explicit coordinate parameters
implementation(module(group = "org", name = "foo", version = "1.0")) // is getImplementation().add(module("org", "foo", "1.0"))
// Add dependencies on projects
implementation(project(":path")) // is getImplementation().add(project(":path"))
implementation(project()) // is getImplementation().add(project())
// Add a dependency on the Gradle API
implementation(gradleApi()) // is getImplementation().add(gradleApi())
// Modify a dependency to select test fixtures
implementation(testFixtures("org:foo:1.0")) // is getImplementation().add(getTestFixtures().modify("org:foo:1.0"))
}
}
}
/**
* Creates a dependency based on the group, name and version (GAV) coordinates.
*
* @since 8.0
*/
fun Dependencies.module(group: String?, name: String, version: String?): ExternalModuleDependency = module(group, name, version)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun <D : ModuleDependency> DependencyModifier.invoke(dependency: D): D = modify(dependency)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependencyNotation: CharSequence): ExternalModuleDependency = modify(dependencyNotation)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependency: ProviderConvertible<out MinimalExternalModuleDependency>): Provider<out MinimalExternalModuleDependency> = modify(dependency)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependency: Provider<out ModuleDependency>): Provider<out ModuleDependency> = modify(dependency)
/**
* Add a dependency.
*
* @param dependencyNotation dependency to add
* @see DependencyFactory.create
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependencyNotation: CharSequence) = add(dependencyNotation)
/**
* Add a dependency.
*
* @param dependencyNotation dependency to add
* @param configuration an action to configure the dependency
* @see DependencyFactory.create
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependencyNotation: CharSequence, configuration: Action<in ExternalModuleDependency>) = add(dependencyNotation, configuration)
/**
* Add a dependency.
*
* @param files files to add as a dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(files: FileCollection) = add(files)
/**
* Add a dependency.
*
* @param files files to add as a dependency
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(files: FileCollection, configuration: Action<in FileCollectionDependency>) = add(files, configuration)
/**
* Add a dependency.
*
* @param externalModule external module to add as a dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(externalModule: ProviderConvertible<out MinimalExternalModuleDependency>) = add(externalModule)
/**
* Add a dependency.
*
* @param externalModule external module to add as a dependency
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(externalModule: ProviderConvertible<out MinimalExternalModuleDependency>, configuration: Action<in ExternalModuleDependency>) = add(externalModule, configuration)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependency: Dependency) = add(dependency)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun <D : Dependency> DependencyAdder.invoke(dependency: D, configuration: Action<in D>) = add(dependency, configuration)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependency: Provider<out Dependency>) = add(dependency)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun <D : Dependency> DependencyAdder.invoke(dependency: Provider<out D>, configuration: Action<in D>) = add(dependency, configuration)
| apache-2.0 | 4b5b4f4bfd3ec6bb1ccb4894decec5d2 | 31.869565 | 202 | 0.742593 | 4.434018 | false | true | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/listener/RequestLoggingListener.kt | 1 | 6669 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.listener
import android.os.SystemClock
import android.util.Pair
import com.facebook.common.logging.FLog
import com.facebook.imagepipeline.request.ImageRequest
import java.util.HashMap
import javax.annotation.concurrent.GuardedBy
/** Logging for [ImageRequest]s. */
class RequestLoggingListener : RequestListener {
@GuardedBy("this")
private val producerStartTimeMap: MutableMap<Pair<String, String>, Long> = HashMap()
@GuardedBy("this") private val requestStartTimeMap: MutableMap<String, Long> = HashMap()
@Synchronized
override fun onRequestStart(
request: ImageRequest,
callerContextObject: Any,
requestId: String,
isPrefetch: Boolean
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"time %d: onRequestSubmit: {requestId: %s, callerContext: %s, isPrefetch: %b}",
time,
requestId,
callerContextObject,
isPrefetch)
requestStartTimeMap[requestId] = time
}
}
@Synchronized
override fun onProducerStart(requestId: String, producerName: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = time
producerStartTimeMap[mapKey] = startTime
FLog.v(
TAG,
"time %d: onProducerStart: {requestId: %s, producer: %s}",
startTime,
requestId,
producerName)
}
}
@Synchronized
override fun onProducerFinishWithSuccess(
requestId: String,
producerName: String,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerFinishWithSuccess: {requestId: %s, producer: %s, elapsedTime: %d ms, extraMap: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap)
}
}
@Synchronized
override fun onProducerFinishWithFailure(
requestId: String,
producerName: String,
throwable: Throwable,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.WARN)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.w(
TAG,
throwable,
"time %d: onProducerFinishWithFailure: {requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s, throwable: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap,
throwable.toString())
}
}
@Synchronized
override fun onProducerFinishWithCancellation(
requestId: String,
producerName: String,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerFinishWithCancellation: {requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap)
}
}
@Synchronized
override fun onProducerEvent(requestId: String, producerName: String, producerEventName: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap[mapKey]
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerEvent: {requestId: %s, stage: %s, eventName: %s; elapsedTime: %d ms}",
time,
requestId,
producerName,
producerEventName,
getElapsedTime(startTime, currentTime))
}
}
@Synchronized
override fun onUltimateProducerReached(
requestId: String,
producerName: String,
successful: Boolean
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onUltimateProducerReached: {requestId: %s, producer: %s, elapsedTime: %d ms, success: %b}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
successful)
}
}
@Synchronized
override fun onRequestSuccess(request: ImageRequest, requestId: String, isPrefetch: Boolean) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.v(
TAG,
"time %d: onRequestSuccess: {requestId: %s, elapsedTime: %d ms}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime))
}
}
@Synchronized
override fun onRequestFailure(
request: ImageRequest,
requestId: String,
throwable: Throwable,
isPrefetch: Boolean
) {
if (FLog.isLoggable(FLog.WARN)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.w(
TAG,
"time %d: onRequestFailure: {requestId: %s, elapsedTime: %d ms, throwable: %s}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime),
throwable.toString())
}
}
@Synchronized
override fun onRequestCancellation(requestId: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.v(
TAG,
"time %d: onRequestCancellation: {requestId: %s, elapsedTime: %d ms}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime))
}
}
override fun requiresExtraMap(id: String): Boolean = FLog.isLoggable(FLog.VERBOSE)
companion object {
private const val TAG = "RequestLoggingListener"
private fun getElapsedTime(startTime: Long?, endTime: Long): Long =
if (startTime != null) {
endTime - startTime
} else {
-1
}
private val time: Long
get() = SystemClock.uptimeMillis()
}
}
| mit | 6a94349232d0700baeae218210d4ec4e | 28.64 | 126 | 0.633528 | 4.683287 | false | false | false | false |
frendyxzc/KotlinNews | app/src/main/java/vip/frendy/news/activity/BaseFragmentActivity.kt | 1 | 1893 | package vip.frendy.news.activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import vip.frendy.news.R
/**
* Created by iimedia on 2017/3/23.
*/
open class BaseFragmentActivity : AppCompatActivity() {
protected var currentFragment: Fragment ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment_base)
}
protected fun setDefaultFragment(fragment: Fragment) {
// 开启Fragment事务
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 使用fragment的布局替代frame_layout的控件并提交事务
fragmentTransaction.replace(R.id.frame_layout, fragment).commit()
currentFragment = fragment
}
protected fun switchFragment(fragment: Fragment) {
if (fragment !== currentFragment) {
if (!fragment.isAdded) {
supportFragmentManager.beginTransaction().hide(currentFragment)
.add(R.id.frame_layout, fragment).commit()
} else {
supportFragmentManager.beginTransaction().hide(currentFragment)
.show(fragment).commit()
}
currentFragment = fragment
}
}
override fun onResume() {
super.onResume()
currentFragment?.userVisibleHint = true
}
override fun onPause() {
super.onPause()
currentFragment?.userVisibleHint = false
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
currentFragment?.onActivityResult(requestCode, resultCode, data)
}
override fun onDestroy() {
super.onDestroy()
}
}
| mit | 19584c395e1d77cfd3b193af79c55295 | 29.916667 | 84 | 0.662534 | 5.040761 | false | false | false | false |
AlmasB/FXGL | fxgl-entity/src/main/kotlin/com/almasb/fxgl/physics/box2d/dynamics/Definitions.kt | 1 | 4900 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.physics.box2d.dynamics
import com.almasb.fxgl.core.math.Vec2
import com.almasb.fxgl.physics.box2d.collision.shapes.Shape
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
enum class BodyType {
/**
* Zero mass, zero velocity, may be manually moved.
*/
STATIC,
/**
* Zero mass, non-zero velocity set by user, moved by solver.
*/
KINEMATIC,
/**
* Positive mass, non-zero velocity determined by forces, moved by solver.
*/
DYNAMIC
}
/**
* A body definition holds all the data needed to construct a rigid body.
* You can safely re-use body definitions.
* Shapes are added to a body after construction.
*/
class BodyDef {
/**
* The body type: static, kinematic, or dynamic.
* Note: if a dynamic body would have zero mass, the mass is set to one.
*/
var type = BodyType.STATIC
/**
* The world position of the body.
* Avoid creating bodies at the origin since this can lead to many overlapping shapes.
*/
var position = Vec2()
/**
* The world angle of the body in radians.
*/
var angle = 0f
/**
* The linear velocity of the body in world co-ordinates.
*/
var linearVelocity = Vec2()
/**
* The angular velocity of the body.
*/
var angularVelocity = 0f
/**
* Linear damping is used to reduce the linear velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
var linearDamping = 0f
/**
* Angular damping is use to reduce the angular velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
var angularDamping = 0f
/**
* Set this flag to false if this body should never fall asleep. Note that this increases CPU
* usage.
*/
var isAllowSleep = true
/**
* Is this body initially sleeping?
*/
var isAwake = true
/**
* Should this body be prevented from rotating? Useful for characters.
*/
var isFixedRotation = false
/**
* Is this a fast moving body that should be prevented from tunneling through other moving bodies?
* Note that all bodies are prevented from tunneling through kinematic and static bodies. This
* setting is only considered on dynamic bodies.
* You should use this flag sparingly since it increases processing time.
*/
var isBullet = false
/**
* Does this body start out active?
*/
var isActive = true
/**
* Experimental: scales the inertia tensor.
*/
var gravityScale = 1f
var userData: Any? = null
}
/**
* A fixture definition is used to create a fixture.
* This class defines an abstract fixture definition.
* You can reuse fixture definitions safely.
*/
class FixtureDef {
/**
* The friction coefficient, usually in the range [0,1].
*/
var friction = 0.2f
/**
* The restitution (elasticity) usually in the range [0,1].
*/
var restitution = 0.0f
/**
* The density, usually in kg/m^2
*/
var density = 0.0f
/**
* A sensor shape collects contact information but never generates a collision response.
*/
var isSensor = false
/**
* Contact filtering data
*/
var filter = Filter()
/**
* The shape, this must be set. The shape will be cloned, so you can create the shape on the
* stack.
*/
var shape: Shape? = null
var userData: Any? = null
fun copy(): FixtureDef {
val def = FixtureDef()
def.friction = friction
def.restitution = restitution
def.density = density
def.isSensor = isSensor
def.filter.set(filter)
def.shape = shape!!.clone()
def.userData = userData
return def
}
/* FLUENT API */
fun friction(friction: Float): FixtureDef {
this.friction = friction
return this
}
fun restitution(restitution: Float): FixtureDef {
this.restitution = restitution
return this
}
fun density(density: Float): FixtureDef {
this.density = density
return this
}
fun filter(filter: Filter): FixtureDef {
this.filter = filter
return this
}
fun shape(shape: Shape): FixtureDef {
this.shape = shape
return this
}
fun sensor(isSensor: Boolean): FixtureDef {
this.isSensor = isSensor
return this
}
fun userData(userData: Any): FixtureDef {
this.userData = userData
return this
}
} | mit | b4fc4f28eb9b6e72badbc2c139b99384 | 22.338095 | 102 | 0.618163 | 4.309587 | false | false | false | false |
crunchersaspire/worshipsongs | app/src/main/java/org/worshipsongs/service/PopupMenuService.kt | 1 | 11282 | package org.worshipsongs.service
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context.PRINT_SERVICE
import android.content.Intent
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.print.PrintAttributes
import android.print.pdf.PrintedPdfDocument
import androidx.core.content.FileProvider
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity
import org.apache.commons.lang3.StringUtils
import org.worshipsongs.BuildConfig
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.WorshipSongApplication.Companion.context
import org.worshipsongs.activity.CustomYoutubeBoxActivity
import org.worshipsongs.activity.PresentSongActivity
import org.worshipsongs.dialog.FavouritesDialogFragment
import org.worshipsongs.domain.Song
import org.worshipsongs.utils.PermissionUtils
import java.io.File
import java.io.FileOutputStream
import java.util.*
/**
* author: Madasamy,Seenivasan, Vignesh Palanisamy
* version: 1.0.0
*/
class PopupMenuService
{
private val customTagColorService = CustomTagColorService()
private val preferenceSettingService = UserPreferenceSettingService()
private val favouriteService = FavouriteService()
private val songService = SongService(context!!)
fun showPopupmenu(activity: AppCompatActivity, view: View, songName: String, hidePlay: Boolean)
{
val wrapper = ContextThemeWrapper(context, R.style.PopupMenu_Theme)
val popupMenu: PopupMenu
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
popupMenu = PopupMenu(wrapper, view, Gravity.RIGHT)
} else
{
popupMenu = PopupMenu(wrapper, view)
}
popupMenu.menuInflater.inflate(R.menu.favourite_share_option_menu, popupMenu.menu)
val song = songService.findContentsByTitle(songName)
val urlKey = song!!.urlKey
val menuItem = popupMenu.menu.findItem(R.id.play_song)
menuItem.isVisible = urlKey != null && urlKey.length > 0 && preferenceSettingService.isPlayVideo && hidePlay
val exportMenuItem = popupMenu.menu.findItem(R.id.export_pdf)
exportMenuItem.isVisible = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
val presentSongMenuItem = popupMenu.menu.findItem(R.id.present_song)
presentSongMenuItem.isVisible = false
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId)
{
R.id.addToList ->
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, songName)
bundle.putString(CommonConstants.LOCALISED_TITLE_KEY, song.tamilTitle)
bundle.putInt(CommonConstants.ID, song.id)
val favouritesDialogFragment = FavouritesDialogFragment.newInstance(bundle)
favouritesDialogFragment.show(activity.supportFragmentManager, "FavouritesDialogFragment")
true
}
R.id.share_whatsapp ->
{
shareSongInSocialMedia(songName, song)
true
}
R.id.play_song ->
{
showYouTube(urlKey, songName)
true
}
R.id.present_song ->
{
startPresentActivity(songName)
true
}
R.id.export_pdf ->
{
if (PermissionUtils.isStoragePermissionGranted(activity))
{
exportSongToPDF(songName, Arrays.asList(song))
}
true
}
else -> false
}
}
popupMenu.show()
}
private fun shareSongInSocialMedia(songName: String, song: Song)
{
val builder = StringBuilder()
builder.append(songName).append("\n").append("\n")
for (content in song.contents!!)
{
builder.append(customTagColorService.getFormattedLines(content))
builder.append("\n")
}
builder.append(context!!.getString(R.string.share_info))
Log.i([email protected], builder.toString())
val textShareIntent = Intent(Intent.ACTION_SEND)
textShareIntent.putExtra(Intent.EXTRA_TEXT, builder.toString())
textShareIntent.type = "text/plain"
val intent = Intent.createChooser(textShareIntent, "Share $songName with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private fun exportSongToPDF(songName: String, songs: List<Song>)
{
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "$songName.pdf")
val printAttrs = PrintAttributes.Builder().setColorMode(PrintAttributes.COLOR_MODE_COLOR).setMediaSize(PrintAttributes.MediaSize.ISO_A4).setResolution(PrintAttributes.Resolution("zooey", PRINT_SERVICE, 450, 700)).setMinMargins(PrintAttributes.Margins.NO_MARGINS).build()
val document = PrintedPdfDocument(WorshipSongApplication.context, printAttrs)
for (i in songs.indices)
{
val song = songs[i]
val pageInfo = PdfDocument.PageInfo.Builder(450, 700, i).create()
var page: PdfDocument.Page? = document.startPage(pageInfo)
if (page != null)
{
val titleDesign = Paint()
titleDesign.textAlign = Paint.Align.LEFT
titleDesign.textSize = 18f
val title = getTamilTitle(song) + song.title!!
val titleLength = titleDesign.measureText(title)
var yPos = 50f
if (page.canvas.width > titleLength)
{
val xPos = page.canvas.width / 2 - titleLength.toInt() / 2
page.canvas.drawText(title, xPos.toFloat(), 20f, titleDesign)
} else
{
var xPos = page.canvas.width / 2 - titleDesign.measureText(song.tamilTitle).toInt() / 2
page.canvas.drawText(song.tamilTitle!! + "/", xPos.toFloat(), 20f, titleDesign)
xPos = page.canvas.width / 2 - titleDesign.measureText(song.title).toInt() / 2
page.canvas.drawText(song.title!!, xPos.toFloat(), 45f, titleDesign)
yPos = 75f
}
for (content in song.contents!!)
{
if (yPos > 620)
{
document.finishPage(page)
page = document.startPage(pageInfo)
yPos = 40f
}
yPos = customTagColorService.getFormattedPage(content, page!!, 10f, yPos)
yPos = yPos + 20
}
}
document.finishPage(page)
}
try
{
val os = FileOutputStream(file)
document.writeTo(os)
document.close()
os.close()
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "application/pdf"
val uriForFile = FileProvider.getUriForFile(context!!, BuildConfig.APPLICATION_ID + ".provider", file)
shareIntent.putExtra(Intent.EXTRA_STREAM, uriForFile)
val intent = Intent.createChooser(shareIntent, "Share $songName with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
Log.i("done", file.absolutePath.toString())
} catch (ex: Exception)
{
Log.e(PopupMenuService::class.java.simpleName, "Error occurred while exporting to PDF", ex)
}
}
private fun getTamilTitle(song: Song): String
{
return if (StringUtils.isNotBlank(song.tamilTitle)) song.tamilTitle!! + "/" else ""
}
private fun showYouTube(urlKey: String?, songName: String)
{
Log.i(this.javaClass.simpleName, "Url key: " + urlKey!!)
val youTubeIntent = Intent(context, CustomYoutubeBoxActivity::class.java)
youTubeIntent.putExtra(CustomYoutubeBoxActivity.KEY_VIDEO_ID, urlKey)
youTubeIntent.putExtra(CommonConstants.TITLE_KEY, songName)
youTubeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(youTubeIntent)
}
private fun startPresentActivity(title: String)
{
val intent = Intent(context, PresentSongActivity::class.java)
intent.putExtra(CommonConstants.TITLE_KEY, title)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
fun shareFavouritesInSocialMedia(activity: Activity, view: View, favouriteName: String)
{
val wrapper = ContextThemeWrapper(context, R.style.PopupMenu_Theme)
val popupMenu: PopupMenu
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
popupMenu = PopupMenu(wrapper, view, Gravity.RIGHT)
} else
{
popupMenu = PopupMenu(wrapper, view)
}
popupMenu.menuInflater.inflate(R.menu.favourite_share_option_menu, popupMenu.menu)
popupMenu.menu.findItem(R.id.play_song).isVisible = false
popupMenu.menu.findItem(R.id.present_song).isVisible = false
popupMenu.menu.findItem(R.id.addToList).isVisible = false
popupMenu.setOnMenuItemClickListener(getPopupMenuItemListener(activity, favouriteName))
popupMenu.show()
}
private fun getPopupMenuItemListener(activity: Activity, text: String): PopupMenu.OnMenuItemClickListener
{
return PopupMenu.OnMenuItemClickListener { item ->
when (item.itemId)
{
R.id.share_whatsapp ->
{
shareFavouritesInSocialMedia(text)
true
}
R.id.export_pdf ->
{
if (PermissionUtils.isStoragePermissionGranted(activity))
{
exportSongToPDF(text, favouriteService.findSongsByFavouriteName(text))
}
false
}
else -> false
}
}
}
private fun shareFavouritesInSocialMedia(text: String)
{
val textShareIntent = Intent(Intent.ACTION_SEND)
textShareIntent.putExtra(Intent.EXTRA_TEXT, favouriteService.buildShareFavouriteFormat(text))
textShareIntent.type = "text/plain"
val intent = Intent.createChooser(textShareIntent, "Share with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
}
| apache-2.0 | 318c5015ea7bbba58e4dae8cd6091b82 | 40.175182 | 278 | 0.620901 | 4.930944 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut03/vertCalcOffset.kt | 2 | 2224 | package glNext.tut03
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.programOf
/**
* Created by elect on 21/02/17.
*/
fun main(args: Array<String>) {
VertCalcOffset_Next().setup("Tutorial 03 - Shader Calc Offset")
}
class VertCalcOffset_Next : Framework() {
var theProgram = 0
var elapsedTimeUniform = 0
val positionBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexPositions = floatBufferOf(
+0.25f, +0.25f, 0.0f, 1.0f,
+0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f)
var startingTime = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
startingTime = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut03", "calc-offset.vert", "standard.frag")
withProgram(theProgram) {
elapsedTimeUniform = "time".location
use { "loopDuration".location.float = 5f }
}
}
fun initializeVertexBuffer(gl: GL3) =
gl.initArrayBuffer(positionBufferObject) { data(vertexPositions, GL_STATIC_DRAW) }
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
elapsedTimeUniform.float = (System.currentTimeMillis() - startingTime) / 1_000.0f
withVertexLayout(positionBufferObject, glf.pos4) { glDrawArrays(3) }
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(positionBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(positionBufferObject, vao)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
}
| mit | 7af4ead12cdecc08dc667801a8b25d88 | 23.711111 | 94 | 0.635342 | 3.847751 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/cameraViewer/AutoFitTextureView.kt | 1 | 2290 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itachi1706.cheesecakeutilities.modules.cameraViewer
import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
/**
* A [TextureView] that can be adjusted to a specified aspect ratio.
*/
class AutoFitTextureView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : TextureView(context, attrs, defStyle) {
private var ratioWidth = 0
private var ratioHeight = 0
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
if (width < 0 || height < 0) throw IllegalArgumentException("Size cannot be negative.")
ratioWidth = width
ratioHeight = height
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
if (ratioWidth == 0 || ratioHeight == 0) setMeasuredDimension(width, height)
else {
if (width < height * ratioWidth / ratioHeight) setMeasuredDimension(width, width * ratioHeight / ratioWidth)
else setMeasuredDimension(height * ratioWidth / ratioHeight, height)
}
}
}
| mit | 1f2d26f835b38b585a995eed4190f970 | 39.175439 | 158 | 0.71048 | 4.692623 | false | false | false | false |
konrad-jamrozik/droidmate | dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/ApkSummary.kt | 1 | 7042 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// 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/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import com.konradjamrozik.Resource
import com.konradjamrozik.uniqueItemsWithFirstOccurrenceIndex
import org.droidmate.android_sdk.DeviceException
import org.droidmate.apis.IApiLogcatMessage
import org.droidmate.exploration.actions.DeviceExceptionMissing
import org.droidmate.exploration.actions.RunnableExplorationActionWithResult
import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2
import org.droidmate.logging.LogbackConstants
import java.time.Duration
class ApkSummary() {
companion object {
fun build(data: IApkExplorationOutput2): String {
return build(Payload(data))
}
fun build(payload: Payload): String {
return with(payload) {
// @formatter:off
StringBuilder(template)
.replaceVariable("exploration_title" , "droidmate-run:" + appPackageName)
.replaceVariable("total_run_time" , totalRunTime.minutesAndSeconds)
.replaceVariable("total_actions_count" , totalActionsCount.toString().padStart(4, ' '))
.replaceVariable("total_resets_count" , totalResetsCount.toString().padStart(4, ' '))
.replaceVariable("exception" , exception.messageIfAny())
.replaceVariable("unique_apis_count" , uniqueApisCount.toString())
.replaceVariable("api_entries" , apiEntries.joinToString(separator = "\n"))
.replaceVariable("unique_api_event_pairs_count" , uniqueEventApiPairsCount.toString())
.replaceVariable("api_event_entries" , apiEventEntries.joinToString(separator = "\n"))
.toString()
}
// @formatter:on
}
val template: String by lazy {
Resource("apk_exploration_summary_template.txt").text
}
private fun DeviceException.messageIfAny(): String {
return if (this is DeviceExceptionMissing)
""
else {
"\n* * * * * * * * * *\n" +
"WARNING! This exploration threw an exception.\n\n" +
"Exception message: '${this.message}'.\n\n" +
LogbackConstants.err_log_msg + "\n" +
"* * * * * * * * * *\n"
}
}
}
@Suppress("unused") // Kotlin BUG on private constructor(data: IApkExplorationOutput2, uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int>)
data class Payload(
val appPackageName: String,
val totalRunTime: Duration,
val totalActionsCount: Int,
val totalResetsCount: Int,
val exception: DeviceException,
val uniqueApisCount: Int,
val apiEntries: List<ApiEntry>,
val uniqueEventApiPairsCount: Int,
val apiEventEntries: List<ApiEventEntry>
) {
constructor(data: IApkExplorationOutput2) : this(
data,
data.uniqueApiLogsWithFirstTriggeringActionIndex,
data.uniqueEventApiPairsWithFirstTriggeringActionIndex
)
private constructor(
data: IApkExplorationOutput2,
uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int>,
uniqueEventApiPairsWithFirstTriggeringActionIndex: Map<EventApiPair, Int>
) : this(
appPackageName = data.packageName,
totalRunTime = data.explorationDuration,
totalActionsCount = data.actRess.size,
totalResetsCount = data.resetActionsCount,
exception = data.exception,
uniqueApisCount = uniqueApiLogsWithFirstTriggeringActionIndex.keys.size,
apiEntries = uniqueApiLogsWithFirstTriggeringActionIndex.map {
val (apiLog: IApiLogcatMessage, firstIndex: Int) = it
ApiEntry(
time = Duration.between(data.explorationStartTime, apiLog.time),
actionIndex = firstIndex,
threadId = apiLog.threadId.toInt(),
apiSignature = apiLog.uniqueString
)
},
uniqueEventApiPairsCount = uniqueEventApiPairsWithFirstTriggeringActionIndex.keys.size,
apiEventEntries = uniqueEventApiPairsWithFirstTriggeringActionIndex.map {
val (eventApiPair, firstIndex: Int) = it
val (event: String, apiLog: IApiLogcatMessage) = eventApiPair
ApiEventEntry(
ApiEntry(
time = Duration.between(data.explorationStartTime, apiLog.time),
actionIndex = firstIndex,
threadId = apiLog.threadId.toInt(),
apiSignature = apiLog.uniqueString
),
event = event
)
}
)
companion object {
val IApkExplorationOutput2.uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int> get() {
return this.actRess.uniqueItemsWithFirstOccurrenceIndex(
extractItems = { it.result.deviceLogs.apiLogsOrEmpty },
extractUniqueString = { it.uniqueString }
)
}
val IApkExplorationOutput2.uniqueEventApiPairsWithFirstTriggeringActionIndex: Map<EventApiPair, Int> get() {
return this.actRess.uniqueItemsWithFirstOccurrenceIndex(
extractItems = RunnableExplorationActionWithResult::extractEventApiPairs,
extractUniqueString = EventApiPair::uniqueString
)
}
}
}
data class ApiEntry(val time: Duration, val actionIndex: Int, val threadId: Int, val apiSignature: String) {
companion object {
private val actionIndexPad: Int = 7
private val threadIdPad: Int = 7
}
override fun toString(): String {
val actionIndexFormatted = "$actionIndex".padStart(actionIndexPad)
val threadIdFormatted = "$threadId".padStart(threadIdPad)
return "${time.minutesAndSeconds} $actionIndexFormatted $threadIdFormatted $apiSignature"
}
}
data class ApiEventEntry(val apiEntry: ApiEntry, val event: String) {
companion object {
private val actionIndexPad: Int = 7
private val threadIdPad: Int = 7
private val eventPadEnd: Int = 69
}
override fun toString(): String {
val actionIndexFormatted = "${apiEntry.actionIndex}".padStart(actionIndexPad)
val eventFormatted = event.padEnd(eventPadEnd)
val threadIdFormatted = "${apiEntry.threadId}".padStart(threadIdPad)
return "${apiEntry.time.minutesAndSeconds} $actionIndexFormatted $eventFormatted $threadIdFormatted ${apiEntry.apiSignature}"
}
}
} | gpl-3.0 | 63a0563ac6d4a7b49eeed02ddd3e6226 | 38.79096 | 162 | 0.693837 | 4.78072 | false | false | false | false |
owntracks/android | project/app/src/gms/java/org/owntracks/android/ui/map/LocationLiveData.kt | 1 | 3027 | package org.owntracks.android.ui.map
import android.content.Context
import android.location.Location
import android.os.Looper
import androidx.lifecycle.LiveData
import com.google.android.gms.location.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import org.owntracks.android.gms.location.toGMSLocationRequest
import org.owntracks.android.location.LocationRequest
import timber.log.Timber
import java.util.concurrent.TimeUnit
class LocationLiveData(
private val locationProviderClient: FusedLocationProviderClient,
private val coroutineScope: CoroutineScope,
) :
LiveData<Location>() {
constructor(
context: Context,
coroutineScope: CoroutineScope,
) : this(LocationServices.getFusedLocationProviderClient(context), coroutineScope)
private val locationCallback = Callback()
private val lock = Semaphore(1)
suspend fun requestLocationUpdates() {
// We don't want to kick off another request while we're doing this one
lock.acquire()
locationProviderClient.removeLocationUpdates(locationCallback).continueWith { task ->
Timber.d("Removing previous locationupdate task complete. Success=${task.isSuccessful} Cancelled=${task.isCanceled}")
locationProviderClient.requestLocationUpdates(
LocationRequest(
smallestDisplacement = 1f,
priority = LocationRequest.PRIORITY_HIGH_ACCURACY,
interval = TimeUnit.SECONDS.toMillis(2),
waitForAccurateLocation = false
).toGMSLocationRequest(),
locationCallback, Looper.getMainLooper()
).addOnCompleteListener {
Timber.d("LocationLiveData location update request completed: Success=${it.isSuccessful} Cancelled=${it.isCanceled}")
lock.release()
}
}
}
private suspend fun removeLocationUpdates() {
lock.acquire()
locationProviderClient.removeLocationUpdates(locationCallback).addOnCompleteListener {
Timber.d("LocationLiveData removing location updates completed: Success=${it.isSuccessful} Cancelled=${it.isCanceled}")
lock.release()
}
}
override fun onActive() {
super.onActive()
coroutineScope.launch { requestLocationUpdates() }
}
override fun onInactive() {
coroutineScope.launch { removeLocationUpdates() }
super.onInactive()
}
inner class Callback : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
value = locationResult.lastLocation
}
override fun onLocationAvailability(locationAvailability: LocationAvailability) {
Timber.d("LocationLiveData location availability: $locationAvailability")
super.onLocationAvailability(locationAvailability)
}
}
}
| epl-1.0 | f9721fbd257aae2140d0f745f85f0ae2 | 37.807692 | 133 | 0.695738 | 5.711321 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/AnnotationSpacingRule.kt | 1 | 6546 | package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType
import com.pinterest.ktlint.core.ast.isPartOf
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.isWhiteSpace
import com.pinterest.ktlint.core.ast.isWhiteSpaceWithNewline
import com.pinterest.ktlint.core.ast.nextCodeSibling
import com.pinterest.ktlint.core.ast.nextLeaf
import com.pinterest.ktlint.core.ast.nextSibling
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.endOffset
/**
* Ensures annotations occur immediately prior to the annotated construct
*
* https://kotlinlang.org/docs/reference/coding-conventions.html#annotation-formatting
*/
class AnnotationSpacingRule : Rule("annotation-spacing") {
companion object {
const val ERROR_MESSAGE = "Annotations should occur immediately before the annotated construct"
}
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.elementType != ElementType.MODIFIER_LIST && node.elementType != ElementType.FILE_ANNOTATION_LIST) {
return
}
val annotations =
node.children()
.mapNotNull { it.psi as? KtAnnotationEntry }
.toList()
if (annotations.isEmpty()) {
return
}
// Join the nodes that immediately follow the annotations (whitespace), then add the final whitespace
// if it's not a child of root. This happens when a new line separates the annotations from the annotated
// construct. In the following example, there are no whitespace children of root, but root's next sibling is the
// new line whitespace.
//
// @JvmField
// val s: Any
//
val whiteSpaces = (annotations.asSequence().map { it.nextSibling } + node.treeNext)
.filterIsInstance<PsiWhiteSpace>()
.take(annotations.size)
.toList()
val next = node.nextSiblingWithAtLeastOneOf(
{
!it.isWhiteSpace() &&
it.textLength > 0 &&
!it.isPartOf(ElementType.FILE_ANNOTATION_LIST)
},
{
// Disallow multiple white spaces as well as comments
if (it.psi is PsiWhiteSpace) {
val s = it.text
// Ensure at least one occurrence of two line breaks
s.indexOf("\n") != s.lastIndexOf("\n")
} else it.isPartOfComment()
}
)
if (next != null) {
if (node.elementType != ElementType.FILE_ANNOTATION_LIST) {
val psi = node.psi
emit(psi.endOffset - 1, ERROR_MESSAGE, true)
if (autoCorrect) {
// Special-case autocorrection when the annotation is separated from the annotated construct
// by a comment: we need to swap the order of the comment and the annotation
if (next.isPartOfComment()) {
// Remove the annotation and the following whitespace
val nextSibling = node.nextSibling { it.isWhiteSpace() }
node.treeParent.removeChild(node)
nextSibling?.treeParent?.removeChild(nextSibling)
// Insert the annotation prior to the annotated construct
val space = PsiWhiteSpaceImpl("\n")
next.treeParent.addChild(space, next.nextCodeSibling())
next.treeParent.addChild(node, space)
} else {
removeExtraLineBreaks(node)
}
}
}
}
if (whiteSpaces.isNotEmpty() && annotations.size > 1 && node.elementType != ElementType.FILE_ANNOTATION_LIST) {
// Check to make sure there are multi breaks between annotations
if (whiteSpaces.any { psi -> psi.textToCharArray().filter { it == '\n' }.count() > 1 }) {
val psi = node.psi
emit(psi.endOffset - 1, ERROR_MESSAGE, true)
if (autoCorrect) {
removeIntraLineBreaks(node, annotations.last())
}
}
}
}
private inline fun ASTNode.nextSiblingWithAtLeastOneOf(
p: (ASTNode) -> Boolean,
needsToOccur: (ASTNode) -> Boolean
): ASTNode? {
var n = this.treeNext
var occurrenceCount = 0
while (n != null) {
if (needsToOccur(n)) {
occurrenceCount++
}
if (p(n)) {
return if (occurrenceCount > 0) {
n
} else {
null
}
}
n = n.treeNext
}
return null
}
private fun removeExtraLineBreaks(node: ASTNode) {
val next = node.nextSibling {
it.isWhiteSpaceWithNewline()
} as? LeafPsiElement
if (next != null) {
rawReplaceExtraLineBreaks(next)
}
}
private fun rawReplaceExtraLineBreaks(leaf: LeafPsiElement) {
// Replace the extra white space with a single break
val text = leaf.text
val firstIndex = text.indexOf("\n") + 1
val replacementText = text.substring(0, firstIndex) +
text.substringAfter("\n").replace("\n", "")
leaf.rawReplaceWithText(replacementText)
}
private fun removeIntraLineBreaks(
node: ASTNode,
last: KtAnnotationEntry
) {
val txt = node.text
// Pull the next before raw replace or it will blow up
val lNext = node.nextLeaf()
if (node is PsiWhiteSpaceImpl) {
if (txt.toCharArray().count { it == '\n' } > 1) {
rawReplaceExtraLineBreaks(node)
}
}
if (lNext != null && !last.text.endsWith(lNext.text)) {
removeIntraLineBreaks(lNext, last)
}
}
}
| mit | 9cfb6ac5fee248e8f1a55b829915d481 | 37.964286 | 120 | 0.581882 | 4.907046 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/goods/types/RandomPortal.kt | 1 | 1233 | package cn.luo.yuan.maze.model.goods.types
import cn.luo.yuan.maze.model.Parameter
import cn.luo.yuan.maze.model.goods.GoodsProperties
import cn.luo.yuan.maze.model.goods.UsableGoods
import cn.luo.yuan.maze.service.InfoControlInterface
import cn.luo.yuan.maze.utils.Field
import cn.luo.yuan.maze.utils.StringUtils
/**
* Created by luoyuan on 2017/9/4.
*/
class RandomPortal: UsableGoods() {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
override fun perform(properties: GoodsProperties): Boolean {
val context:InfoControlInterface? = properties[Parameter.CONTEXT] as InfoControlInterface
if(context!=null){
val maze = context.maze
val level = context.random.randomRange((maze.level * 0.4f).toLong(), (maze.maxLevel * 0.8f).toLong()) + 1
maze.level = level
context.showPopup("传送到了第 ${StringUtils.formatNumber(level)} 层")
return true
}
return false
}
override var desc: String = "使用后随机传送。传送范围为(当前层数40%)至(最高层数80%)之间"
override var name: String = "随机传送"
override var price: Long = 300000L
} | bsd-3-clause | c8ca23b8400acc88507b647a66320571 | 35.1875 | 117 | 0.689715 | 3.593168 | false | false | false | false |
skydoves/WaterDrink | app/src/main/java/com/skydoves/waterdays/persistence/preference/PreferenceManager.kt | 1 | 2056 | /*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.persistence.preference
import android.content.Context
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-08-17.
* Copyright (c) 2017 skydoves rights reserved.
*/
class PreferenceManager(private val mContext: Context) {
fun getBoolean(key: String, default_value: Boolean): Boolean {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getBoolean(key, default_value)
}
fun getInt(key: String, default_value: Int): Int {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getInt(key, default_value)
}
fun getString(key: String, default_value: String): String {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getString(key, default_value)
}
fun putBoolean(key: String, default_value: Boolean) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putBoolean(key, default_value).apply()
}
fun putInt(key: String, default_value: Int) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putInt(key, default_value).apply()
}
fun putString(key: String, default_value: String) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putString(key, default_value).apply()
}
companion object {
private val preferenceKey = "waterdays"
}
}
| apache-2.0 | 37ad3e877a24910bedef8323c301cdaf | 30.630769 | 75 | 0.723249 | 4.063241 | false | false | false | false |
GiuseppeGiacoppo/Android-Clean-Architecture-with-Kotlin | core/src/main/java/me/giacoppo/examples/kotlin/mvp/bean/Show.kt | 1 | 214 | package me.giacoppo.examples.kotlin.mvp.bean
data class Show(val id: Int,val title: String = "", val description: String = "", val originCountry: String = "", val coverUrl: String = "", val posterUrl: String = "") | apache-2.0 | 8a721f32612d605e9d43c39810423220 | 70.666667 | 168 | 0.700935 | 3.821429 | false | false | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt | 1 | 18914 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.import
class AutoImportFixTest : AutoImportFixTestBase() {
fun `test import struct`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
pub struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test import enum variant 1`() = checkAutoImportFixByText("""
mod foo {
pub enum Foo { A }
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo::A/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
pub enum Foo { A }
}
fn main() {
Foo::A/*caret*/;
}
""")
fun `test import enum variant 2`() = checkAutoImportFixByText("""
mod foo {
pub enum Foo { A }
}
fn main() {
let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>;
}
""", """
use foo::Foo::A;
mod foo {
pub enum Foo { A }
}
fn main() {
let a = A/*caret*/;
}
""")
fun `test import function`() = checkAutoImportFixByText("""
mod foo {
pub fn bar() -> i32 { unimplemented!() }
}
fn main() {
let f = <error descr="Unresolved reference: `bar`">bar/*caret*/</error>();
}
""", """
use foo::bar;
mod foo {
pub fn bar() -> i32 { unimplemented!() }
}
fn main() {
let f = bar/*caret*/();
}
""")
fun `test import function method`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo::foo/*caret*/</error>();
}
""", """
use foo::Foo;
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
Foo::foo/*caret*/();
}
""")
fun `test import generic item`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo<T>(T);
}
fn f<T>(foo: <error descr="Unresolved reference: `Foo`">Foo/*caret*/<T></error>) {}
""", """
use foo::Foo;
mod foo {
pub struct Foo<T>(T);
}
fn f<T>(foo: Foo/*caret*/<T>) {}
""")
fun `test import module`() = checkAutoImportFixByText("""
mod foo {
pub mod bar {
pub fn foo_bar() -> i32 { unimplemented!() }
}
}
fn main() {
let f = <error descr="Unresolved reference: `bar`">bar/*caret*/::foo_bar</error>();
}
""", """
use foo::bar;
mod foo {
pub mod bar {
pub fn foo_bar() -> i32 { unimplemented!() }
}
}
fn main() {
let f = bar/*caret*/::foo_bar();
}
""")
fun `test insert use item after existing use items`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
pub struct Bar;
}
use foo::Bar;
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
mod foo {
pub struct Foo;
pub struct Bar;
}
use foo::Bar;
use foo::Foo;
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test insert use item after inner attributes`() = checkAutoImportFixByText("""
#![allow(non_snake_case)]
mod foo {
pub struct Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
#![allow(non_snake_case)]
use foo::Foo;
mod foo {
pub struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test import item from nested module`() = checkAutoImportFixByText("""
mod foo {
pub mod bar {
pub struct Foo;
}
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::bar::Foo;
mod foo {
pub mod bar {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test don't try to import private item`() = checkAutoImportFixIsUnavailable("""
mod foo {
struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test don't try to import from private mod`() = checkAutoImportFixIsUnavailable("""
mod foo {
mod bar {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test complex module structure`() = checkAutoImportFixByText("""
mod aaa {
mod bbb {
fn foo() {
let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
}
}
mod ccc {
pub mod ddd {
pub struct Foo;
}
mod eee {
struct Foo;
}
}
""", """
mod aaa {
mod bbb {
use ccc::ddd::Foo;
fn foo() {
let x = Foo/*caret*/;
}
}
}
mod ccc {
pub mod ddd {
pub struct Foo;
}
mod eee {
struct Foo;
}
}
""")
fun `test complex module structure with file modules`() = checkAutoImportFixByFileTree("""
//- aaa/mod.rs
mod bbb;
//- aaa/bbb/mod.rs
fn foo() {
let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
//- ccc/mod.rs
pub mod ddd;
mod eee;
//- ccc/ddd/mod.rs
pub struct Foo;
//- ccc/eee/mod.rs
struct Foo;
//- main.rs
mod aaa;
mod ccc;
""", """
use ccc::ddd::Foo;
fn foo() {
let x = Foo/*caret*/;
}
""")
fun `test import module declared via module declaration`() = checkAutoImportFixByFileTree("""
//- foo/bar.rs
fn foo_bar() {}
//- main.rs
mod foo {
pub mod bar;
}
fn main() {
<error descr="Unresolved reference: `bar`">bar::foo_bar/*caret*/</error>();
}
""", """
use foo::bar;
mod foo {
pub mod bar;
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test filter import candidates 1`() = checkAutoImportFixByText("""
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
<error descr="Unresolved reference: `bar`">bar/*caret*/</error>();
}
""", """
use foo1::bar;
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
bar/*caret*/();
}
""")
fun `test filter import candidates 2`() = checkAutoImportFixByText("""
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
<error descr="Unresolved reference: `bar`">bar::foo_bar/*caret*/</error>();
}
""", """
use foo2::bar;
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test filter members without owner prefix`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
foo/*caret*/();
}
""")
fun `test don't try to import item if it can't be resolved`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub mod bar {
}
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test don't import trait method`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub trait Bar {
fn bar();
}
}
fn main() {
Bar::bar/*caret*/();
}
""")
fun `test don't import trait const`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub trait Bar {
const BAR: i32;
}
}
fn main() {
Bar::BAR/*caret*/();
}
""")
fun `test import reexported item`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar;
}
fn main() {
<error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>;
}
""", """
use foo::Bar;
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar;
}
fn main() {
Bar/*caret*/;
}
""")
fun `test import reexported item with alias`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar as Foo;
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar as Foo;
}
fn main() {
Foo/*caret*/;
}
""")
fun `test import reexported item via use group`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz, Qwe};
}
fn main() {
let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>;
}
""", """
use foo::Baz;
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz, Qwe};
}
fn main() {
let a = Baz/*caret*/;
}
""")
fun `test import reexported item via 'self'`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
}
pub use self::bar::Baz::{self};
}
fn main() {
let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>;
}
""", """
use foo::Baz;
mod foo {
mod bar {
pub struct Baz;
}
pub use self::bar::Baz::{self};
}
fn main() {
let a = Baz/*caret*/;
}
""")
fun `test import reexported item with complex reexport`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz as Foo, Qwe};
}
fn main() {
let a = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz as Foo, Qwe};
}
fn main() {
let a = Foo/*caret*/;
}
""")
fun `test module reexport`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub mod baz {
pub struct FooBar;
}
}
pub use self::bar::baz;
}
fn main() {
let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", """
use foo::baz::FooBar;
mod foo {
mod bar {
pub mod baz {
pub struct FooBar;
}
}
pub use self::bar::baz;
}
fn main() {
let x = FooBar/*caret*/;
}
""")
fun `test multiple import`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub struct Foo;
pub mod bar {
pub struct Foo;
}
}
mod baz {
pub struct Foo;
mod qwe {
pub struct Foo;
}
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", setOf("foo::Foo", "foo::bar::Foo", "baz::Foo"), "foo::bar::Foo", """
use foo::bar::Foo;
mod foo {
pub struct Foo;
pub mod bar {
pub struct Foo;
}
}
mod baz {
pub struct Foo;
mod qwe {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test multiple import with reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub struct Foo;
}
mod bar {
mod baz {
pub struct Foo;
}
pub use self::baz::Foo;
}
mod qwe {
mod xyz {
pub struct Bar;
}
pub use self::xyz::Bar as Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", setOf("foo::Foo", "bar::Foo", "qwe::Foo"), "qwe::Foo", """
use qwe::Foo;
mod foo {
pub struct Foo;
}
mod bar {
mod baz {
pub struct Foo;
}
pub use self::baz::Foo;
}
mod qwe {
mod xyz {
pub struct Bar;
}
pub use self::xyz::Bar as Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test double module reexport`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub mod bar {
pub struct FooBar;
}
}
mod baz {
pub mod qqq {
pub use foo::bar;
}
}
mod xxx {
pub use baz::qqq;
}
fn main() {
let a = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", setOf("foo::bar::FooBar", "baz::qqq::bar::FooBar", "xxx::qqq::bar::FooBar"), "baz::qqq::bar::FooBar", """
use baz::qqq::bar::FooBar;
mod foo {
pub mod bar {
pub struct FooBar;
}
}
mod baz {
pub mod qqq {
pub use foo::bar;
}
}
mod xxx {
pub use baz::qqq;
}
fn main() {
let a = FooBar/*caret*/;
}
""")
fun `test cyclic module reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
pub mod x {
pub struct Z;
pub use y;
}
pub mod y {
pub use x;
}
fn main() {
let x = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>;
}
""", setOf("x::Z", "y::x::Z", "x::y::x::Z"), "x::Z", """
use x::Z;
pub mod x {
pub struct Z;
pub use y;
}
pub mod y {
pub use x;
}
fn main() {
let x = Z/*caret*/;
}
""")
fun `test crazy cyclic module reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
pub mod x {
pub use u;
pub mod y {
pub use u::v;
pub struct Z;
}
}
pub mod u {
pub use x::y;
pub mod v {
pub use x;
}
}
fn main() {
let z = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>;
}
""", setOf(
"x::y::Z",
"x::u::y::Z",
"x::u::v::x::y::Z",
"x::u::y::v::x::y::Z",
"x::y::v::x::u::y::Z",
"x::y::v::x::y::Z",
"u::y::Z",
"u::v::x::y::Z",
"u::y::v::x::y::Z",
"u::v::x::u::y::Z"
), "u::y::Z", """
use u::y::Z;
pub mod x {
pub use u;
pub mod y {
pub use u::v;
pub struct Z;
}
}
pub mod u {
pub use x::y;
pub mod v {
pub use x;
}
}
fn main() {
let z = Z/*caret*/;
}
""")
fun `test filter imports`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub mod bar {
pub struct FooBar;
}
pub use self::bar::FooBar;
}
mod baz {
pub use foo::bar::FooBar;
}
mod quuz {
pub use foo::bar;
}
fn main() {
let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", setOf("foo::FooBar", "baz::FooBar", "quuz::bar::FooBar"), "baz::FooBar", """
use baz::FooBar;
mod foo {
pub mod bar {
pub struct FooBar;
}
pub use self::bar::FooBar;
}
mod baz {
pub use foo::bar::FooBar;
}
mod quuz {
pub use foo::bar;
}
fn main() {
let x = FooBar/*caret*/;
}
""")
}
| mit | af3341ed3473897dd3e9a421af5affd9 | 20.493182 | 114 | 0.387596 | 4.670123 | false | false | false | false |
jeffbanks/Lotto-Sessions | lotto-session-3/src/main/kotlin/com/jjbanks/lotto/service/LottoData.kt | 1 | 2169 |
/*
* MIT License
*
* Copyright (c) 2017 Jeff Banks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*/
package com.jjbanks.lotto.service
import com.jjbanks.lotto.model.Drawing
import com.jjbanks.lotto.model.PowerDrawing
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.util.*
@Component
class LottoData {
fun getPowerDrawing(): Drawing {
// Simulation of drawing retrieval from some source.
val date: LocalDate = LocalDate.of(2017, 10, 1)
val powerPick: Int = (1..PowerDrawing.MAX_POWER_PICK).random()
val corePicks: HashSet<Int> = HashSet()
for (n in 1..5) {
while (true) {
val pick: Int = (1..PowerDrawing.MAX_CORE_PICK).random()
if (!corePicks.contains(pick)) {
corePicks.add(pick)
break
}
}
}
val powerDrawing = PowerDrawing(date, corePicks, powerPick)
powerDrawing.validate()
return powerDrawing
}
private fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
} | mit | f9a9e3e4888e03227f0989b0b294306c | 34.57377 | 90 | 0.687414 | 4.29505 | false | false | false | false |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/DrawDetectionTest.kt | 1 | 1809 | package karballo
import karballo.pgn.PgnFile
import karballo.pgn.PgnImportExport
import org.junit.Assert.*
import org.junit.Test
class DrawDetectionTest {
@Test
fun test3FoldDraw() {
val b = Board()
val `is` = this.javaClass.getResourceAsStream("/draw.pgn")
val pgnGame = PgnFile.getGameNumber(`is`, 0)
PgnImportExport.setBoard(b, pgnGame!!)
System.out.println(b.toString())
System.out.println("draw = " + b.isDraw)
assertTrue(b.isDraw)
}
@Test
fun test3FoldDrawNo() {
val b = Board()
val `is` = this.javaClass.getResourceAsStream("/draw.pgn")
val pgnGame = PgnFile.getGameNumber(`is`, 0)
PgnImportExport.setBoard(b, pgnGame!!)
b.undoMove()
System.out.println(b.toString())
System.out.println("draw = " + b.isDraw)
assertFalse(b.isDraw)
}
@Test
fun testDrawDetection() {
val b = Board()
b.fen = "7k/8/8/8/8/8/8/7K w - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/8/8/8/8/8/6BK b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/8/8/8/8/8/6NK b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/nn6/8/8/8/8/8K b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/Nn6/8/8/8/8/8K b - - 0 0"
assertEquals(b.isDraw, false)
b.fen = "7k/7p/8/8/8/8/8/6NK b - - 0 0"
assertEquals(b.isDraw, false)
}
@Test
fun testKBbkDraw() {
val b = Board()
// Different bishop color is NOT draw
b.fen = "6bk/8/8/8/8/8/8/6BK b - - 0 0"
assertEquals(b.isDraw, false)
// Both bishops in the same color is draw
b.fen = "6bk/8/8/8/8/8/8/5B1K b - - 0 0"
assertEquals(b.isDraw, true)
}
} | mit | d807f1693d99b79a39808c13afc2dd9b | 25.617647 | 66 | 0.559425 | 2.899038 | false | true | false | false |
SUPERCILEX/Robot-Scouter | feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/TemplateListFragment.kt | 1 | 8144 | package com.supercilex.robotscouter.feature.templates
import android.animation.FloatEvaluator
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Guideline
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.LayoutParams
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
import com.supercilex.robotscouter.Bridge
import com.supercilex.robotscouter.Refreshable
import com.supercilex.robotscouter.SignInResolver
import com.supercilex.robotscouter.TemplateListFragmentCompanion
import com.supercilex.robotscouter.TemplateListFragmentCompanion.Companion.TAG
import com.supercilex.robotscouter.core.data.TAB_KEY
import com.supercilex.robotscouter.core.data.defaultTemplateId
import com.supercilex.robotscouter.core.data.getTabId
import com.supercilex.robotscouter.core.data.getTabIdBundle
import com.supercilex.robotscouter.core.data.isSignedIn
import com.supercilex.robotscouter.core.data.model.addTemplate
import com.supercilex.robotscouter.core.model.TemplateType
import com.supercilex.robotscouter.core.ui.FragmentBase
import com.supercilex.robotscouter.core.ui.LifecycleAwareLazy
import com.supercilex.robotscouter.core.ui.RecyclerPoolHolder
import com.supercilex.robotscouter.core.ui.animateChange
import com.supercilex.robotscouter.core.ui.isInTabletMode
import com.supercilex.robotscouter.core.ui.longSnackbar
import com.supercilex.robotscouter.core.ui.onDestroy
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.shared.SharedLifecycleResource
import kotlinx.android.synthetic.main.fragment_template_list.*
import com.supercilex.robotscouter.R as RC
@Bridge
internal class TemplateListFragment : FragmentBase(R.layout.fragment_template_list), Refreshable,
View.OnClickListener, RecyclerPoolHolder {
override val recyclerPool by LifecycleAwareLazy { RecyclerView.RecycledViewPool() }
val pagerAdapter by unsafeLazy {
object : TemplatePagerAdapter(this@TemplateListFragment) {
override fun onDataChanged() {
super.onDataChanged()
if (currentScouts.isEmpty()) {
fab.hide()
} else {
fab.show()
}
}
}
}
private val sharedResources by activityViewModels<SharedLifecycleResource>()
val fab: FloatingActionButton by unsafeLazy {
requireActivity().findViewById(RC.id.fab)
}
private val appBar: AppBarLayout by unsafeLazy {
requireActivity().findViewById(RC.id.appBar)
}
private val tabs by LifecycleAwareLazy {
val tabs = TabLayout(ContextThemeWrapper(
requireContext(),
RC.style.ThemeOverlay_AppCompat_Dark_ActionBar
)).apply {
id = R.id.tabs
tabMode = TabLayout.MODE_SCROLLABLE
}
appBar.addView(
tabs, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
scrollFlags = LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED
})
tabs
} onDestroy {
appBar.removeView(it)
}
private val homeDivider: Guideline? by unsafeLazy {
val activity = requireActivity()
if (activity.isInTabletMode()) activity.findViewById<Guideline>(RC.id.guideline) else null
}
private var savedState: Bundle? = null
init {
setHasOptionsMenu(true)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedState = savedInstanceState
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
sharedResources.onCreate(fab)
animateContainerMorph(2f / 3)
tabs // Force init
viewPager.adapter = pagerAdapter
tabs.setupWithViewPager(viewPager)
fab.setOnClickListener(this)
handleArgs(arguments, savedInstanceState)
}
override fun refresh() {
childFragmentManager.fragments
.filterIsInstance<TemplateFragment>()
.singleOrNull { pagerAdapter.currentTabId == it.dataId }
?.refresh()
}
override fun onStop() {
super.onStop()
// This has to be done in onStop so fragment transactions from the view pager can be
// committed. Only reset the adapter if the user is switching destinations.
if (isDetached) pagerAdapter.reset()
}
override fun onDestroyView() {
super.onDestroyView()
viewPager.adapter = null
animateContainerMorph(1f / 3)
sharedResources.onDestroy(fab) {
setOnClickListener(null)
hide()
}
}
fun handleArgs(args: Bundle) {
if (view == null) {
arguments = (arguments ?: Bundle()).apply { putAll(args) }
} else {
handleArgs(args, null)
}
}
private fun handleArgs(args: Bundle?, savedInstanceState: Bundle?) {
val templateId = getTabId(args)
if (templateId == null) {
getTabId(savedInstanceState)?.let { pagerAdapter.currentTabId = it }
} else {
pagerAdapter.currentTabId = TemplateType.coerce(templateId)?.let {
viewPager.longSnackbar(R.string.template_added_message)
addTemplate(it).also { defaultTemplateId = it }
} ?: templateId
args?.remove(TAB_KEY)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) =
inflater.inflate(R.menu.template_list_menu, menu)
override fun onSaveInstanceState(outState: Bundle) =
outState.putAll(getTabIdBundle(pagerAdapter.currentTabId ?: getTabId(savedState)))
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (!isSignedIn) {
(activity as SignInResolver).showSignInResolution()
return false
}
when (item.itemId) {
R.id.action_new_template -> NewTemplateDialog.show(childFragmentManager)
R.id.action_share -> TemplateSharer.shareTemplate(
this,
checkNotNull(pagerAdapter.currentTabId),
checkNotNull(pagerAdapter.currentTab?.text?.toString())
)
else -> return false
}
return true
}
override fun onClick(v: View) {
if (v.id == RC.id.fab) {
AddMetricDialog.show(childFragmentManager)
} else {
childFragmentManager.fragments
.filterIsInstance<TemplateFragment>()
.singleOrNull { pagerAdapter.currentTabId == it.dataId }
?.onClick(v)
}
}
fun onTemplateCreated(id: String) {
pagerAdapter.currentTabId = id
viewPager.longSnackbar(
R.string.template_added_title,
RC.string.template_set_default_title
) { defaultTemplateId = id }
}
private fun animateContainerMorph(new: Float) {
val div = homeDivider ?: return
val current = (div.layoutParams as ConstraintLayout.LayoutParams).guidePercent
animateChange(FloatEvaluator(), current, new) {
div.setGuidelinePercent(it.animatedValue as Float)
}
}
companion object : TemplateListFragmentCompanion {
override fun getInstance(
manager: FragmentManager,
args: Bundle?
): TemplateListFragment {
val instance = manager.findFragmentByTag(TAG) as TemplateListFragment?
?: TemplateListFragment()
args?.let { instance.handleArgs(args) }
return instance
}
}
}
| gpl-3.0 | 04ed1a0e99627f5cc1f7cbc4c2cef29c | 36.187215 | 98 | 0.675589 | 5.093183 | false | false | false | false |
Subsets and Splits